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.

5.8 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'

import { HogQLQuery } from '~/queries/schema/schema-general'

import type { BIConfig } from '../../../frontend/src/queries/schema/schema-business-intelligence'
import { biEditorLogic } from './biEditorLogic'

type ParameterDraft = { name: string; type: 'string' | 'number' | 'boolean'; value: string | boolean }

export function metricParameterDrafts(query?: HogQLQuery): ParameterDraft[] {
    return Object.entries(query?.values ?? {}).flatMap<ParameterDraft>(([name, value]) => {
        if (typeof value === 'boolean') {
            return [{ name, type: 'boolean' as const, value }]
        }
        if (typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value))) {
            return [{ name, type: typeof value as 'string' | 'number', value: String(value) }]
        }
        return []
    })
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biMetricParametersLogicValues {
    config: BIConfig // biEditorLogic
    applyDisabledReason: string | undefined
    parameterErrors: Record<string, string>
    parameters: ParameterDraft[]
    source: HogQLQuery | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biMetricParametersLogicActions {
    setSnapshotParameters: (
        source: HogQLQuery,
        parameters: Record<string, boolean | number | string>
    ) => {
        parameters: Record<string, boolean | number | string>
        source: HogQLQuery
    } // biEditorLogic
    apply: () => {
        value: true
    }
    changeParameter: (
        name: string,
        value: boolean | string
    ) => {
        name: string
        value: boolean | string
    }
    close: () => {
        value: true
    }
    open: () => {
        value: true
    }
    setDraft: (
        source: HogQLQuery,
        parameters: ParameterDraft[]
    ) => {
        parameters: ParameterDraft[]
        source: HogQLQuery
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biMetricParametersLogicProps {
    tabId: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biMetricParametersLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        parameterErrors: (parameters: ParameterDraft[]) => Record<string, string>
        applyDisabledReason: (
            source: HogQLQuery | null,
            config: BIConfig,
            parameterErrors: Record<string, string>
        ) => string | undefined
    }
}

export type biMetricParametersLogicType = MakeLogicType<
    biMetricParametersLogicValues,
    biMetricParametersLogicActions,
    biMetricParametersLogicProps,
    biMetricParametersLogicMeta
>

export const biMetricParametersLogic = kea<biMetricParametersLogicType>([
    path(['products', 'business_intelligence', 'frontend', 'biMetricParametersLogic']),
    props({} as { tabId: string }),
    key((props) => props.tabId),
    connect((props: { tabId: string }) => ({
        values: [biEditorLogic(props), ['config']],
        actions: [biEditorLogic(props), ['setSnapshotParameters']],
    })),
    actions({
        open: true,
        close: true,
        setDraft: (source: HogQLQuery, parameters: ParameterDraft[]) => ({ source, parameters }),
        changeParameter: (name: string, value: string | boolean) => ({ name, value }),
        apply: true,
    }),
    reducers({
        source: [null as HogQLQuery | null, { setDraft: (_, { source }) => source, close: () => null }],
        parameters: [
            [] as ParameterDraft[],
            {
                setDraft: (_, { parameters }) => parameters,
                changeParameter: (parameters, { name, value }) =>
                    parameters.map((parameter) => (parameter.name === name ? { ...parameter, value } : parameter)),
                close: () => [],
            },
        ],
    }),
    selectors({
        parameterErrors: [
            (s) => [s.parameters],
            (parameters: ParameterDraft[]): Record<string, string> =>
                Object.assign(
                    Object.create(null) as Record<string, string>,
                    Object.fromEntries(
                        parameters.flatMap(({ name, type, value }) =>
                            type === 'number' && (String(value).trim() === '' || !Number.isFinite(Number(value)))
                                ? [[name, 'Enter a valid number']]
                                : []
                        )
                    )
                ),
        ],
        applyDisabledReason: [
            (s) => [s.source, s.config, s.parameterErrors],
            (source: HogQLQuery | null, config: BIConfig, errors: Record<string, string>): string | undefined =>
                source !== config.querySnapshot
                    ? 'The worksheet changed. Close this dialog and try again.'
                    : Object.keys(errors).length
                      ? 'Fix the invalid parameters first'
                      : undefined,
        ],
    }),
    listeners(({ actions, values }) => ({
        open: () => {
            if (values.config.querySnapshot) {
                actions.setDraft(values.config.querySnapshot, metricParameterDrafts(values.config.querySnapshot))
            }
        },
        apply: () => {
            if (!values.source || values.applyDisabledReason) {
                return
            }
            actions.setSnapshotParameters(
                values.source,
                Object.fromEntries(
                    values.parameters.map(({ name, type, value }) => [name, type === 'number' ? Number(value) : value])
                )
            )
            actions.close()
        },
    })),
])