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.

13.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import {
    coerceListVariableValue,
    getListVariableValues,
} from '~/queries/nodes/DataVisualization/Components/Variables/VariableFields'
import { getListVariableSelectedValues } from '~/queries/nodes/DataVisualization/Components/Variables/variableUtils'
import { ListVariable, Variable, VariableType } from '~/queries/nodes/DataVisualization/types'
import { InsightModel } from '~/types'

import type { Node } from '../../../queries/schema/schema-general'
import { fetchInsightsUsingVariable } from './insightsLoader'

export interface SqlVariableEditSceneLogicProps {
    id: string
}

const NEW_VARIABLE_DEFAULTS: Partial<Variable> = {
    name: '',
    type: 'String',
    default_value: '',
    code_name: '',
}

// List `values` come from a JSONField and may hold non-string entries (e.g. objects
// from API-created variables), which crash React if rendered — sanitize on the way
// into the form so editing and saving repairs them.
export const variableToFormValues = (variable: Variable): Partial<Variable> =>
    ({
        name: variable.name,
        type: variable.type,
        default_value:
            variable.type === 'List'
                ? variable.is_multi
                    ? getListVariableSelectedValues({ ...variable, value: undefined })
                    : (coerceListVariableValue(variable.default_value) ?? '')
                : variable.default_value,
        code_name: variable.code_name,
        ...(variable.type === 'List' && {
            values: getListVariableValues(variable as ListVariable),
            is_multi: Boolean(variable.is_multi),
            values_query: variable.values_query ?? null,
            values_query_connection_id: variable.values_query_connection_id ?? null,
        }),
    }) as Partial<Variable>

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sqlVariableEditSceneLogicValues {
    currentTeamId: number | null // teamLogic
    breadcrumbs: (
        | {
              key: string
              name: string
              path: string
          }
        | {
              key: string
              name: string
              path?: undefined
          }
    )[]
    hasChanges: boolean
    insightsUsingVariable: InsightModel[]
    insightsUsingVariableLoading: boolean
    isNew: boolean
    isVariableFormSubmitting: boolean
    isVariableFormValid: boolean
    showVariableFormErrors: boolean
    variable: Variable | null
    variableForm: Partial<Variable>
    variableFormAllErrors: Record<string, any>
    variableFormChanged: boolean
    variableFormErrors: DeepPartialMap<Partial<Variable>, ValidationErrorType>
    variableFormHasErrors: boolean
    variableFormManualErrors: Record<string, any>
    variableFormTouched: boolean
    variableFormTouches: Record<string, boolean>
    variableFormValidationErrors: DeepPartialMap<Partial<Variable>, ValidationErrorType>
    variableLoading: boolean
    variableType: VariableType
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sqlVariableEditSceneLogicActions {
    loadInsightsUsingVariable: () => any
    loadInsightsUsingVariableFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInsightsUsingVariableSuccess: (
        insightsUsingVariable: InsightModel<Node<Record<string, any>>>[],
        payload?: any
    ) => {
        insightsUsingVariable: InsightModel<Node<Record<string, any>>>[]
        payload?: any
    }
    loadVariable: () => any
    loadVariableFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadVariableSuccess: (
        variable: Variable | null,
        payload?: any
    ) => {
        variable: Variable | null
        payload?: any
    }
    resetVariableForm: (values?: Partial<Variable>) => {
        values?: Partial<Variable>
    }
    setVariableFormManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setVariableFormValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setVariableFormValues: (values: DeepPartial<Partial<Variable>>) => {
        values: DeepPartial<Partial<Variable>>
    }
    setVariableType: (type: VariableType) => {
        type: VariableType
    }
    submitVariableForm: () => {
        value: boolean
    }
    submitVariableFormFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitVariableFormRequest: (variableForm: Partial<Variable>) => {
        variableForm: Partial<Variable>
    }
    submitVariableFormSuccess: (variableForm: Partial<Variable>) => {
        variableForm: Partial<Variable>
    }
    touchVariableFormField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sqlVariableEditSceneLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        isNew: (id: string) => boolean
        hasChanges: (
            variableForm: Partial<Variable>,
            variableType: VariableType,
            variable: Variable | null,
            variableLoading: boolean
        ) => boolean
        breadcrumbs: (
            variable: Variable | null,
            id: string
        ) => (
            | {
                  key: string
                  name: string
                  path: string
              }
            | {
                  key: string
                  name: string
                  path?: undefined
              }
        )[]
    }
}

export type sqlVariableEditSceneLogicType = MakeLogicType<
    sqlVariableEditSceneLogicValues,
    sqlVariableEditSceneLogicActions,
    SqlVariableEditSceneLogicProps,
    sqlVariableEditSceneLogicMeta
>

export const sqlVariableEditSceneLogic = kea<sqlVariableEditSceneLogicType>([
    props({} as SqlVariableEditSceneLogicProps),
    path(['scenes', 'data-management', 'variables', 'sqlVariableEditSceneLogic']),
    key((props: SqlVariableEditSceneLogicProps) => props.id),
    connect({
        values: [teamLogic, ['currentTeamId']],
    }),
    actions({
        setVariableType: (type: VariableType) => ({ type }),
    }),
    loaders(({ props }) => ({
        variable: [
            null as Variable | null,
            {
                loadVariable: async () => {
                    if (props.id === 'new') {
                        return null
                    }
                    try {
                        const response = await api.insightVariables.list()
                        return response.results.find((v: Variable) => v.id === props.id) ?? null
                    } catch {
                        return null
                    }
                },
            },
        ],
        insightsUsingVariable: [
            [] as InsightModel[],
            {
                loadInsightsUsingVariable: async () => {
                    if (props.id === 'new') {
                        return []
                    }

                    const currentTeamId = teamLogic.values.currentTeamId
                    if (!currentTeamId) {
                        return []
                    }

                    try {
                        return await fetchInsightsUsingVariable(currentTeamId, props.id)
                    } catch {
                        // Error already handled by fetchInsightsUsingVariable
                        return []
                    }
                },
            },
        ],
    })),
    reducers({
        variableType: [
            'String' as VariableType,
            {
                setVariableType: (_, { type }: { type: VariableType }) => type,
                loadVariableSuccess: (state: VariableType, { variable }: { variable: Variable | null }) =>
                    variable?.type ?? state,
            },
        ],
    }),
    forms(({ props, values, actions }) => ({
        variableForm: {
            defaults: NEW_VARIABLE_DEFAULTS as Partial<Variable>,
            errors: ({ name }: { name?: string }) => ({
                name: !name?.trim() ? 'Name is required' : undefined,
            }),
            submit: async (formValues: Partial<Variable>) => {
                // TypeScript struggles with discriminated unions in Partial types,
                // but the form validation ensures this data is valid
                const data = {
                    ...formValues,
                    type: values.variableType,
                } as Partial<Variable>

                try {
                    if (props.id === 'new') {
                        const created = await api.insightVariables.create(data)
                        lemonToast.success('Variable created')
                        router.actions.push(urls.variableEdit(created.id))
                    } else {
                        await api.insightVariables.update(props.id, data)
                        lemonToast.success('Variable updated')
                        actions.loadVariable()
                    }
                } catch (error: unknown) {
                    const apiError = error as { data?: { detail?: string } }
                    if (apiError.data?.detail) {
                        lemonToast.error(apiError.data.detail)
                    } else {
                        lemonToast.error('Failed to save variable')
                    }
                    throw error
                }
            },
        },
    })),
    selectors({
        isNew: [(_, p) => [p.id], (id: string): boolean => id === 'new'],
        hasChanges: [
            (s) => [s.variableForm, s.variableType, s.variable, s.variableLoading],
            (
                variableForm: Partial<Variable>,
                variableType: VariableType,
                variable: Variable | null,
                variableLoading: boolean
            ): boolean => {
                if (!variable || variableLoading) {
                    return false
                }
                // Normalize the saved side exactly as `variableToFormValues` normalizes the
                // form, otherwise a freshly loaded List variable holding legacy (non-string)
                // values compares unequal to its own coerced form and reports perpetual changes.
                const isList = variable.type === 'List'
                const defaultValueForm = variableForm.default_value ?? ''
                const defaultValueSaved = isList
                    ? variable.is_multi
                        ? getListVariableSelectedValues({ ...(variable as ListVariable), value: undefined })
                        : (coerceListVariableValue(variable.default_value) ?? '')
                    : (variable.default_value ?? '')
                const valuesForm = (variableForm as any).values ?? null
                const valuesSaved = isList
                    ? getListVariableValues(variable as ListVariable)
                    : ((variable as any).values ?? null)
                const isMultiForm = isList ? Boolean(variableForm.is_multi) : false
                const valuesQueryForm = isList ? (variableForm.values_query ?? null) : null
                const valuesQueryConnectionForm = isList ? (variableForm.values_query_connection_id ?? null) : null
                return (
                    (variableForm.name ?? '') !== (variable.name ?? '') ||
                    variableType !== variable.type ||
                    JSON.stringify(defaultValueForm) !== JSON.stringify(defaultValueSaved) ||
                    JSON.stringify(valuesForm) !== JSON.stringify(valuesSaved) ||
                    isMultiForm !== Boolean(variable.is_multi) ||
                    valuesQueryForm !== (variable.values_query ?? null) ||
                    valuesQueryConnectionForm !== (variable.values_query_connection_id ?? null)
                )
            },
        ],
        breadcrumbs: [
            (s, p) => [s.variable, p.id],
            (variable: Variable | null, id: string) => [
                {
                    key: 'variables',
                    name: 'SQL variables',
                    path: urls.variables(),
                },
                {
                    key: 'variable',
                    name: id === 'new' ? 'New variable' : (variable?.name ?? 'Loading...'),
                },
            ],
        ],
    }),
    listeners(({ actions }) => ({
        loadVariableSuccess: ({ variable }: { variable: Variable | null }) => {
            if (variable) {
                actions.resetVariableForm(variableToFormValues(variable))
                actions.loadInsightsUsingVariable()
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadVariable()
    }),
])