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.

7.6 KB
Raw Blame
import { MakeLogicType, actions, kea, key, listeners, path, props } from 'kea'

import { LemonDialog, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'

import { ApiError } from 'lib/api'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { urls } from 'scenes/urls'

import { BIConfig } from '~/queries/schema/schema-business-intelligence'
import { NodeKind } from '~/queries/schema/schema-general'

import {
    existingMetricFromNameConflict,
    METRIC_FIELD_COPY,
    validateMetricDescription,
    validateMetricName,
} from 'products/data_catalog/frontend/common'
import { createMetricAsUser } from 'products/data_catalog/frontend/createMetricAsUser'
import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
import { openOverwriteMetricDialog } from 'products/data_catalog/frontend/openOverwriteMetricDialog'

import { captureBIEditorQuerySaved, captureBIWorksheetAction } from './biEditorAnalytics'
import { BIEditorView } from './biEditorTypes'

interface BIMetricProposalProps {
    tabId: string
    config: BIConfig
    snapshot: string | null
    name: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biMetricProposalLogicActions {
    proposeMetric: () => {
        value: true
    }
}

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

export type biMetricProposalLogicType = MakeLogicType<
    {},
    biMetricProposalLogicActions,
    BIMetricProposalProps,
    biMetricProposalLogicMeta
>

export const biMetricProposalLogic = kea<biMetricProposalLogicType>([
    props({} as BIMetricProposalProps),
    key((props) => props.tabId),
    path((key) => ['products', 'business_intelligence', 'biMetricProposalLogic', key]),
    actions({ proposeMetric: true }),
    listeners(({ props }) => ({
        proposeMetric: () => {
            if (!props.snapshot || props.config.source?.connectionId) {
                return
            }
            const snapshot = props.snapshot
            const config = props.config
            let submission: Promise<void> | null = null
            let formClosed = false
            let cancelConfirmation: (() => void) | undefined
            LemonDialog.openForm({
                title: 'Propose as catalog metric',
                description:
                    'Saves this query with the date window and filters from its last run. Shelves and worksheet history are not part of the metric. If the name already exists, you can confirm an overwrite. Changes go through catalog review.',
                onAfterClose: () => {
                    formClosed = true
                    cancelConfirmation?.()
                },
                shouldAwaitSubmit: true,
                primaryButtonProps: { children: 'Propose metric' },
                initialValues: { name: '', display_name: props.name, description: '', unit: '' },
                content: (
                    <>
                        <LemonField name="name" label={METRIC_FIELD_COPY.name.label}>
                            <LemonInput placeholder={METRIC_FIELD_COPY.name.placeholder} autoFocus />
                        </LemonField>
                        <LemonField name="display_name" label={METRIC_FIELD_COPY.displayName.label}>
                            <LemonInput placeholder={METRIC_FIELD_COPY.displayName.placeholder} />
                        </LemonField>
                        <LemonField name="description" label={METRIC_FIELD_COPY.description.label}>
                            <LemonTextArea
                                placeholder={METRIC_FIELD_COPY.description.placeholder}
                                minRows={2}
                                stopPropagation
                            />
                        </LemonField>
                        <LemonField name="unit" label={METRIC_FIELD_COPY.unit.label}>
                            <LemonInput placeholder={METRIC_FIELD_COPY.unit.placeholder} />
                        </LemonField>
                    </>
                ),
                errors: {
                    name: (value) => validateMetricName((value ?? '').trim()),
                    description: (value) =>
                        !value?.trim() ? 'Add a description' : validateMetricDescription(value.trim()),
                },
                onSubmit: async (fields) => {
                    if (formClosed) {
                        return
                    }
                    if (submission) {
                        return submission
                    }
                    let canceled = false
                    submission = (async () => {
                        const request = {
                            name: fields.name.trim(),
                            display_name: (fields.display_name ?? '').trim(),
                            description: fields.description.trim(),
                            unit: (fields.unit ?? '').trim(),
                            definition: { kind: NodeKind.HogQLQuery, query: snapshot },
                        }
                        const created = await createMetricAsUser(request, false).catch(async (error) => {
                            if (formClosed) {
                                canceled = true
                                throw error
                            }
                            const existing = existingMetricFromNameConflict(error)
                            if (!existing) {
                                throw error
                            }
                            const confirmed = await new Promise<boolean>((resolve) => {
                                cancelConfirmation = () => resolve(false)
                                openOverwriteMetricDialog({
                                    existing,
                                    onOverwrite: () => resolve(true),
                                    onCancel: cancelConfirmation,
                                })
                            })
                            cancelConfirmation = undefined
                            if (!confirmed || formClosed) {
                                canceled = true
                                throw error
                            }
                            return createMetricAsUser({ ...request, overwrite: true }, false)
                        })
                        const metric = created.metric
                        metricsLogic.findMounted()?.actions.loadMetrics()
                        captureBIEditorQuerySaved({ editorView: BIEditorView.BI, config }, 'metric', 'create')
                        captureBIWorksheetAction('catalog_metric_proposed', config)
                        lemonToast.success(
                            <>
                                Metric proposed. <Link to={urls.dataCatalogMetric(metric.name)}>Review in catalog</Link>
                            </>
                        )
                    })()
                        .catch((error) => {
                            if (!canceled) {
                                lemonToast.error(
                                    error instanceof ApiError && error.detail
                                        ? error.detail
                                        : 'Could not propose the metric. Try again.'
                                )
                            }
                            throw error
                        })
                        .finally(() => {
                            submission = null
                        })
                    return submission
                },
            })
        },
    })),
])