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.

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

import api from 'lib/api'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { tryDecodeURIComponent } from 'lib/utils/url'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { updatePropertyDefinitions } from '~/models/propertyDefinitionsModel'
import { getFilterLabel, getVirtualPropertyDefinition } from '~/taxonomy/helpers'
import { Breadcrumb, Definition, EventDefinitionMetrics, ObjectMediaPreview, PropertyDefinition } from '~/types'

import type { SchemaEnforcementMode, UserBasicType } from '../../../types'
import { DataManagementTab } from '../DataManagementScene'
import { eventDefinitionsTableLogic } from '../events/eventDefinitionsTableLogic'
import { propertyDefinitionsTableLogic } from '../properties/propertyDefinitionsTableLogic'

export const createNewDefinition = (isEvent: boolean): Definition => ({
    id: 'new',
    name: `New ${isEvent ? 'Event' : 'Event property'}`,
    verified: false,
    hidden: false,
})

export interface SetDefinitionProps {
    merge?: boolean
}

export interface DefinitionLogicProps {
    id?: Definition['id']
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface definitionLogicValues {
    breadcrumbs: Breadcrumb[]
    definition: Definition
    definitionLoading: boolean
    definitionMissing: boolean
    isEvent: boolean
    isProperty: boolean
    metrics: EventDefinitionMetrics | null
    metricsLoading: boolean
    previews: ObjectMediaPreview[]
    previewsLoading: boolean
    singular: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface definitionLogicActions {
    createMediaPreview: (
        uploadedMediaId: string,
        metadata?: Record<string, any>
    ) => {
        metadata: Record<string, any> | undefined
        uploadedMediaId: string
    }
    createMediaPreviewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createMediaPreviewSuccess: (
        previews: ObjectMediaPreview[],
        payload?: {
            metadata: Record<string, any> | undefined
            uploadedMediaId: string
        }
    ) => {
        previews: ObjectMediaPreview[]
        payload?: {
            metadata: Record<string, any> | undefined
            uploadedMediaId: string
        }
    }
    deleteDefinition: () => any
    deleteDefinitionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteDefinitionSuccess: (
        definition: Definition,
        payload?: any
    ) => {
        definition: Definition
        payload?: any
    }
    deleteMediaPreview: (previewId: string) => {
        previewId: string
    }
    deleteMediaPreviewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteMediaPreviewSuccess: (
        previews: ObjectMediaPreview[],
        payload?: {
            previewId: string
        }
    ) => {
        previews: ObjectMediaPreview[]
        payload?: {
            previewId: string
        }
    }
    loadDefinition: (id: Definition['id']) => {
        id: string
    }
    loadDefinitionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDefinitionSuccess: (
        definition:
            | PropertyDefinition
            | {
                  created_at?: string | undefined
                  default_columns?: string[] | undefined
                  description?: string | undefined
                  enforcement_mode?: SchemaEnforcementMode | undefined
                  hidden?: boolean | undefined
                  id: string
                  is_action?: boolean | undefined
                  is_data_warehouse?: boolean | undefined
                  last_seen_at?: string | undefined
                  last_updated_at?: string | undefined
                  media_preview_urls?: string[] | undefined
                  name: string
                  owner?: UserBasicType | null | undefined
                  primary_property?: string | null | undefined
                  tags?: string[] | undefined
                  updated_at?: string | undefined
                  updated_by?: UserBasicType | null | undefined
                  verified?: boolean | undefined
                  verified_at?: string | undefined
                  verified_by?: string | undefined
              },
        payload?: {
            id: string
        }
    ) => {
        definition:
            | PropertyDefinition
            | {
                  created_at?: string | undefined
                  default_columns?: string[] | undefined
                  description?: string | undefined
                  enforcement_mode?: SchemaEnforcementMode | undefined
                  hidden?: boolean | undefined
                  id: string
                  is_action?: boolean | undefined
                  is_data_warehouse?: boolean | undefined
                  last_seen_at?: string | undefined
                  last_updated_at?: string | undefined
                  media_preview_urls?: string[] | undefined
                  name: string
                  owner?: UserBasicType | null | undefined
                  primary_property?: string | null | undefined
                  tags?: string[] | undefined
                  updated_at?: string | undefined
                  updated_by?: UserBasicType | null | undefined
                  verified?: boolean | undefined
                  verified_at?: string | undefined
                  verified_by?: string | undefined
              }
        payload?: {
            id: string
        }
    }
    loadMetrics: (id: Definition['id']) => {
        id: string
    }
    loadMetricsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMetricsSuccess: (
        metrics: EventDefinitionMetrics | null,
        payload?: {
            id: string
        }
    ) => {
        metrics: EventDefinitionMetrics | null
        payload?: {
            id: string
        }
    }
    loadPreviews: () => {
        value: true
    }
    loadPreviewsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPreviewsSuccess: (
        previews: ObjectMediaPreview[],
        payload?: {
            value: true
        }
    ) => {
        previews: ObjectMediaPreview[]
        payload?: {
            value: true
        }
    }
    setDefinition: (
        definition: Partial<Definition>,
        options?: SetDefinitionProps
    ) => {
        definition: Partial<Definition>
        options: SetDefinitionProps
    }
    setDefinitionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    setDefinitionMissing: () => {
        value: true
    }
    setDefinitionSuccess: (
        definition: Definition,
        payload?: {
            definition: Partial<Definition>
            options: SetDefinitionProps
        }
    ) => {
        definition: Definition
        payload?: {
            definition: Partial<Definition>
            options: SetDefinitionProps
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface definitionLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        isEvent: (location: { hash: string; pathname: string; search: string }) => boolean
        isProperty: (isEvent: boolean) => boolean
        singular: (isEvent: boolean) => string
        breadcrumbs: (definition: Definition, isEvent: boolean) => Breadcrumb[]
    }
}

export type definitionLogicType = MakeLogicType<
    definitionLogicValues,
    definitionLogicActions,
    DefinitionLogicProps,
    definitionLogicMeta
>

// Route params arrive percent-encoded (virtual ids contain `$`); tryDecodeURIComponent keeps malformed ids
// from throwing, letting them fall through to the API's graceful 404. Both the scenes' paramsToProps and the
// component bodies must use this so the two definitionLogic build paths agree on one logic key.
export function decodeDefinitionId(id: string | undefined): string | undefined {
    return id ? tryDecodeURIComponent(id) : id
}

export const definitionLogic = kea<definitionLogicType>([
    path(['scenes', 'data-management', 'definition', 'definitionViewLogic']),
    props({} as DefinitionLogicProps),
    key((props) => props.id || 'new'),
    actions({
        setDefinition: (definition: Partial<Definition>, options: SetDefinitionProps = {}) => ({ definition, options }),
        loadDefinition: (id: Definition['id']) => ({ id }),
        loadMetrics: (id: Definition['id']) => ({ id }),
        setDefinitionMissing: true,
        loadPreviews: true,
        createMediaPreview: (uploadedMediaId: string, metadata?: Record<string, any>) => ({
            uploadedMediaId,
            metadata,
        }),
        deleteMediaPreview: (previewId: string) => ({ previewId }),
    }),
    reducers(() => ({
        definitionMissing: [
            false,
            {
                setDefinitionMissing: () => true,
            },
        ],
    })),
    loaders(({ values, actions }) => ({
        definition: [
            createNewDefinition(values.isEvent),
            {
                setDefinition: ({ definition, options: { merge } }) =>
                    (merge ? { ...values.definition, ...definition } : definition) as Definition,
                loadDefinition: async ({ id }, breakpoint) => {
                    let definition = { ...values.definition }
                    if (values.isProperty) {
                        // Virtual properties have no database row to fetch, so resolve them from the taxonomy
                        const virtualProperty = getVirtualPropertyDefinition(id)
                        if (virtualProperty) {
                            return virtualProperty.definition
                        }
                    }
                    try {
                        if (values.isEvent) {
                            // Event Definition
                            definition = await api.eventDefinitions.get({
                                eventDefinitionId: id,
                            })
                        } else {
                            // Event Property Definition
                            definition = await api.propertyDefinitions.get({
                                propertyDefinitionId: id,
                            })
                            updatePropertyDefinitions({
                                [`event/${definition.name}`]: definition as PropertyDefinition,
                            })
                        }
                        breakpoint()
                    } catch (response: any) {
                        actions.setDefinitionMissing()
                        throw response
                    }

                    return definition
                },
                deleteDefinition: async () => {
                    if (values.isEvent) {
                        await api.eventDefinitions.delete({ eventDefinitionId: values.definition.id })
                    } else {
                        await api.propertyDefinitions.delete({ propertyDefinitionId: values.definition.id })
                    }
                    router.actions.push(values.isEvent ? urls.eventDefinitions() : urls.propertyDefinitions())
                    if (values.isEvent) {
                        eventDefinitionsTableLogic.findMounted()?.actions.loadEventDefinitions()
                    } else {
                        propertyDefinitionsTableLogic.findMounted()?.actions.loadPropertyDefinitions()
                    }
                    return values.definition
                },
            },
        ],
        metrics: [
            null as EventDefinitionMetrics | null,
            {
                loadMetrics: async ({ id }) => {
                    if (values.isEvent) {
                        return await api.eventDefinitions.getMetrics({ eventDefinitionId: id })
                    }

                    // For properties, we currently don't have metrics in the same way as events.
                    return null
                },
            },
        ],
        previews: [
            [] as ObjectMediaPreview[],
            {
                loadPreviews: async () => {
                    if (!values.isEvent || !values.definition.id || values.definition.id === 'new') {
                        return []
                    }
                    try {
                        const response = await api.objectMediaPreviews.list(values.definition.id)
                        return response.results
                    } catch {
                        return []
                    }
                },
                createMediaPreview: async ({ uploadedMediaId, metadata }) => {
                    const preview = await api.objectMediaPreviews.create({
                        uploaded_media_id: uploadedMediaId,
                        event_definition_id: values.definition.id,
                        metadata,
                    })
                    return [preview, ...values.previews]
                },
                deleteMediaPreview: async ({ previewId }) => {
                    await api.objectMediaPreviews.delete(previewId)
                    return values.previews.filter((p) => p.id !== previewId)
                },
            },
        ],
    })),
    selectors({
        isEvent: [() => [router.selectors.location], ({ pathname }) => pathname.includes(urls.eventDefinitions())],
        isProperty: [(s) => [s.isEvent], (isEvent: boolean) => !isEvent],
        singular: [(s) => [s.isEvent], (isEvent: boolean): string => (isEvent ? 'event' : 'property')],
        breadcrumbs: [
            (s) => [s.definition, s.isEvent],
            (definition: Definition, isEvent: boolean): Breadcrumb[] => {
                // Resolve virtual definitions' label from the same taxonomy group the definition came from
                const propertyLabelGroup =
                    ('virtual' in definition &&
                        definition.virtual &&
                        getVirtualPropertyDefinition(definition.id)?.group) ||
                    TaxonomicFilterGroupType.EventProperties
                return [
                    {
                        key: Scene.DataManagement,
                        name: `Data management`,
                        path: isEvent ? urls.eventDefinitions() : urls.propertyDefinitions(),
                        iconType: 'event_definition',
                    },
                    {
                        key: isEvent ? DataManagementTab.EventDefinitions : DataManagementTab.PropertyDefinitions,
                        name: isEvent ? 'Events' : 'Properties',
                        path: isEvent ? urls.eventDefinitions() : urls.propertyDefinitions(),
                        iconType: isEvent ? 'event_definition' : 'property_definition',
                    },
                    {
                        key: [isEvent ? Scene.EventDefinition : Scene.PropertyDefinition, definition?.id || 'new'],
                        name:
                            definition?.id !== 'new'
                                ? getFilterLabel(
                                      definition?.name,
                                      isEvent ? TaxonomicFilterGroupType.Events : propertyLabelGroup
                                  ) || 'Untitled'
                                : 'Untitled',
                        iconType: isEvent ? 'event_definition' : 'property_definition',
                    },
                ]
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        loadDefinitionSuccess: () => {
            // Virtual definitions are taxonomy-defined and read-only, so bounce off the edit page
            if (
                'virtual' in values.definition &&
                values.definition.virtual &&
                router.values.location.pathname.endsWith('/edit')
            ) {
                router.actions.replace(urls.propertyDefinition(values.definition.id))
                return
            }
            if (values.isEvent && values.definition.id && values.definition.id !== 'new') {
                actions.loadPreviews()
            }
        },
        createMediaPreviewSuccess: () => {
            lemonToast.success('Preview image added')
        },
        createMediaPreviewFailure: () => {
            lemonToast.error('Failed to add image')
        },
        deleteMediaPreviewSuccess: () => {
            lemonToast.success('Image deleted')
        },
        deleteMediaPreviewFailure: () => {
            lemonToast.error('Failed to delete image')
        },
    })),
    // Covers client-side navigation to the edit URL while this logic is already mounted, where
    // loadDefinition (and therefore the loadDefinitionSuccess bounce above) does not re-fire
    urlToAction(({ values, props }) => ({
        [urls.propertyDefinitionEdit(':id')]: ({ id }) => {
            if (
                id &&
                decodeDefinitionId(id) === props.id &&
                'virtual' in values.definition &&
                values.definition.virtual
            ) {
                router.actions.replace(urls.propertyDefinition(values.definition.id))
            }
        },
    })),
    afterMount(({ actions, values, props }) => {
        if (!props.id || props.id === 'new') {
            actions.setDefinition(createNewDefinition(values.isEvent))
        } else {
            actions.loadDefinition(props.id)
            actions.loadMetrics(props.id)
        }
    }),
])