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.

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

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

import api from 'lib/api'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { AccessControlLevel, ActivityScope, Breadcrumb, ExperimentsTabs } from '~/types'
import type { UserBasicType } from '~/types'

import type { ExperimentSavedMetricLinkedExperimentApi } from 'products/experiments/frontend/generated/api.schemas'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { ExperimentMetricUnion } from '../../../queries/schema/schema-general'
import type { BillingType } from '../../../types'
import { getDefaultFunnelMetric } from '../utils'
import { sharedMetricsLogic } from './sharedMetricsLogic'

export interface SharedMetricLogicProps {
    sharedMetricId?: number | null
    action: 'create' | 'update' | 'duplicate'
}

export interface SharedMetric {
    id: number
    name: string
    description?: string
    query: Record<string, any>
    created_by: UserBasicType | null
    created_at: string | null
    updated_at: string | null
    tags: string[]
    metadata?: Record<string, any>
    user_access_level: AccessControlLevel
    // Populated only when the metric is fetched by id; empty in list responses
    linked_experiments?: readonly ExperimentSavedMetricLinkedExperimentApi[]
}

export const NEW_SHARED_METRIC: Partial<SharedMetric> = {
    name: '',
    description: '',
    query: undefined,
    tags: [],
    user_access_level: AccessControlLevel.Editor,
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharedMetricLogicValues {
    billing: BillingType | null // billingLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentProjectId: number | string // teamLogic
    action: 'create' | 'duplicate' | 'update'
    breadcrumbs: Breadcrumb[]
    metricSaving: boolean
    newSharedMetric: {
        created_at?: string | null | undefined
        created_by?: UserBasicType | null | undefined
        description?: string | undefined
        id?: number | undefined
        linked_experiments?: readonly ExperimentSavedMetricLinkedExperimentApi[] | undefined
        metadata?: Record<string, any> | undefined
        name?: string | undefined
        query: ExperimentMetricUnion
        tags?: string[] | undefined
        updated_at?: string | null | undefined
        user_access_level?: AccessControlLevel | undefined
    }
    sharedMetric: Partial<SharedMetric>
    sharedMetricId: number | string
    sharedMetricLoading: boolean
    sidePanelContext: SidePanelSceneContext | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharedMetricLogicActions {
    reportExperimentSharedMetricCreated: (sharedMetric: SharedMetric) => {
        sharedMetric: SharedMetric
    } // eventUsageLogic
    loadSharedMetrics: (_?: void | undefined) => void // sharedMetricsLogic
    createSharedMetric: () => {
        value: true
    }
    deleteSharedMetric: () => {
        value: true
    }
    loadSharedMetric: () => any
    loadSharedMetricFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSharedMetricSuccess: (
        sharedMetric:
            | SharedMetric
            | {
                  created_at?: string | null | undefined
                  created_by?: UserBasicType | null | undefined
                  description?: string | undefined
                  id?: number | undefined
                  linked_experiments?: readonly ExperimentSavedMetricLinkedExperimentApi[] | undefined
                  metadata?: Record<string, any> | undefined
                  name?: string | undefined
                  query: ExperimentMetricUnion
                  tags?: string[] | undefined
                  updated_at?: string | null | undefined
                  user_access_level?: AccessControlLevel | undefined
              },
        payload?: any
    ) => {
        sharedMetric:
            | SharedMetric
            | {
                  created_at?: string | null | undefined
                  created_by?: UserBasicType | null | undefined
                  description?: string | undefined
                  id?: number | undefined
                  linked_experiments?: readonly ExperimentSavedMetricLinkedExperimentApi[] | undefined
                  metadata?: Record<string, any> | undefined
                  name?: string | undefined
                  query: ExperimentMetricUnion
                  tags?: string[] | undefined
                  updated_at?: string | null | undefined
                  user_access_level?: AccessControlLevel | undefined
              }
        payload?: any
    }
    setMetricSaving: (saving: boolean) => {
        saving: boolean
    }
    setSharedMetric: (metric: Partial<SharedMetric>) => {
        metric: Partial<SharedMetric>
    }
    updateSharedMetric: (redirect?: boolean) => {
        redirect: boolean | undefined
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharedMetricLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        sharedMetricId: (arg: any) => number | string
        action: (action: 'create' | 'duplicate' | 'update') => 'create' | 'duplicate' | 'update'
        breadcrumbs: (sharedMetric: Partial<SharedMetric>, sharedMetricId: number | string) => Breadcrumb[]
        sidePanelContext: (
            sharedMetric: Partial<SharedMetric>,
            sharedMetricId: number | string
        ) => SidePanelSceneContext | null
    }
}

export type sharedMetricLogicType = MakeLogicType<
    sharedMetricLogicValues,
    sharedMetricLogicActions,
    SharedMetricLogicProps,
    sharedMetricLogicMeta
>

export const sharedMetricLogic = kea<sharedMetricLogicType>([
    props({} as SharedMetricLogicProps),
    path((key) => ['scenes', 'experiments', 'sharedMetricLogic', key]),
    key((props) => `${props.sharedMetricId ?? 'new'}-${props.action}`),

    connect(() => ({
        actions: [sharedMetricsLogic, ['loadSharedMetrics'], eventUsageLogic, ['reportExperimentSharedMetricCreated']],
        values: [featureFlagLogic, ['featureFlags'], billingLogic, ['billing'], teamLogic, ['currentProjectId']],
    })),

    actions({
        setSharedMetric: (metric: Partial<SharedMetric>) => ({ metric }),
        createSharedMetric: true,
        updateSharedMetric: (redirect?: boolean) => ({ redirect }),
        deleteSharedMetric: true,
        setMetricSaving: (saving: boolean) => ({ saving }),
    }),

    loaders(({ props, values }) => ({
        sharedMetric: {
            loadSharedMetric: async () => {
                const { sharedMetricId } = props

                if (sharedMetricId) {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentSavedMetricsRetrieve() from 'products/experiments/frontend/generated/api' instead.
                    const response = await api.get(
                        `api/projects/${values.currentProjectId}/experiment_saved_metrics/${sharedMetricId}`
                    )
                    return response as SharedMetric
                }

                return {
                    ...values.newSharedMetric,
                }
            },
        },
    })),

    listeners(({ actions, props, values, cache }) => ({
        /**
         * we need to wait for the metric to load to check if we need to modify the name and id
         */
        loadSharedMetricSuccess: () => {
            if (props.action === 'duplicate' && values.sharedMetric) {
                // Generate a new UUID for the duplicated metric's query
                const duplicatedQuery = {
                    ...values.sharedMetric.query,
                    uuid: crypto.randomUUID(),
                }

                actions.setSharedMetric({
                    ...values.sharedMetric,
                    query: duplicatedQuery,
                    name: `${values.sharedMetric.name} (duplicate)`,
                    id: undefined,
                })
            }
        },
        createSharedMetric: async () => {
            if (values.metricSaving) {
                return
            }
            actions.setMetricSaving(true)
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentSavedMetricsCreate() from 'products/experiments/frontend/generated/api' instead.
                const response = await api.create(
                    `api/projects/${values.currentProjectId}/experiment_saved_metrics/`,
                    values.sharedMetric
                )
                if (response.id) {
                    lemonToast.success('Shared metric created successfully')
                    actions.reportExperimentSharedMetricCreated(response as SharedMetric)
                    actions.loadSharedMetrics()
                    router.actions.push('/experiments?tab=shared-metrics')
                }
            } catch (error: any) {
                lemonToast.error(error.detail || error.data?.name?.[0] || 'Failed to create shared metric')
            } finally {
                actions.setMetricSaving(false)
            }
        },
        updateSharedMetric: async ({ redirect = true }: { redirect?: boolean } = {}) => {
            if (values.metricSaving) {
                // Queue a trailing rerun instead of dropping the call: the request reads
                // values.sharedMetric at send time, so one rerun persists the newest state
                // (e.g. a tag edit made while an explicit save was in flight)
                cache.queuedUpdateRedirect = Boolean(cache.queuedUpdateRedirect) || redirect
                cache.updateQueued = true
                return
            }
            actions.setMetricSaving(true)
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentSavedMetricsPartialUpdate() from 'products/experiments/frontend/generated/api' instead.
                const response = await api.update(
                    `api/projects/${values.currentProjectId}/experiment_saved_metrics/${values.sharedMetricId}`,
                    values.sharedMetric
                )
                if (response.id) {
                    lemonToast.success('Shared metric updated successfully')
                    actions.loadSharedMetrics()
                    if (redirect && !cache.updateQueued) {
                        router.actions.push('/experiments?tab=shared-metrics')
                    }
                }
            } catch (error: any) {
                lemonToast.error(error.detail || error.data?.name?.[0] || 'Failed to update shared metric')
            } finally {
                actions.setMetricSaving(false)
                if (cache.updateQueued) {
                    const queuedRedirect = Boolean(cache.queuedUpdateRedirect) || redirect
                    cache.updateQueued = false
                    cache.queuedUpdateRedirect = false
                    actions.updateSharedMetric(queuedRedirect)
                }
            }
        },
        deleteSharedMetric: async () => {
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. experimentSavedMetricsDestroy() from 'products/experiments/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                await api.delete(
                    `api/projects/${values.currentProjectId}/experiment_saved_metrics/${values.sharedMetricId}`
                )
                lemonToast.success('Shared metric deleted successfully')
                actions.loadSharedMetrics()
                router.actions.push('/experiments?tab=shared-metrics')
            } catch (error) {
                lemonToast.error('Failed to delete shared metric')
                console.error(error)
            }
        },
    })),

    reducers({
        sharedMetric: [
            { ...NEW_SHARED_METRIC } as Partial<SharedMetric>,
            {
                setSharedMetric: (state, { metric }) => ({ ...state, ...metric }),
            },
        ],
        metricSaving: [
            false,
            {
                setMetricSaving: (_, { saving }) => saving,
            },
        ],
    }),

    selectors({
        sharedMetricId: [
            () => [(_, props) => props.sharedMetricId ?? 'new'],
            (sharedMetricId): string | number => sharedMetricId,
        ],
        action: [(_, p) => [p.action], (action: 'create' | 'duplicate' | 'update') => action],
        newSharedMetric: [
            () => [],
            () => ({
                ...NEW_SHARED_METRIC,
                query: getDefaultFunnelMetric(),
            }),
        ],
        breadcrumbs: [
            (s) => [s.sharedMetric, s.sharedMetricId],
            (sharedMetric: Partial<SharedMetric>, sharedMetricId: string | number): Breadcrumb[] => {
                const isNew = sharedMetricId === 'new'
                return [
                    {
                        key: Scene.Experiments,
                        name: sceneConfigurations[Scene.Experiments].name || 'Experiments',
                        path: `${urls.experiments()}?tab=${ExperimentsTabs.SharedMetrics}`,
                    },
                    {
                        key: [Scene.ExperimentsSharedMetric, sharedMetricId],
                        name: isNew ? 'New shared metric' : sharedMetric?.name || '',
                    },
                ]
            },
        ],
        [SIDE_PANEL_CONTEXT_KEY]: [
            (s) => [s.sharedMetric, s.sharedMetricId],
            (sharedMetric: Partial<SharedMetric>, sharedMetricId: string | number): SidePanelSceneContext | null => {
                return sharedMetric?.id && sharedMetricId !== 'new'
                    ? {
                          activity_scope: ActivityScope.EXPERIMENT,
                          activity_item_id: `${sharedMetric.id}`,
                          access_control_resource: 'experiment_saved_metric',
                          access_control_resource_id: `${sharedMetric.id}`,
                      }
                    : null
            },
        ],
    }),

    urlToAction(({ actions, values }) => ({
        '/experiments/shared-metrics/:id': ({ id }, _, __, currentLocation, previousLocation) => {
            const didPathChange = currentLocation.initial || currentLocation.pathname !== previousLocation?.pathname

            if (id && didPathChange) {
                const parsedId = id === 'new' ? 'new' : parseInt(id)
                if (parsedId === 'new') {
                    actions.setSharedMetric({ ...values.newSharedMetric, query: getDefaultFunnelMetric() })
                }

                if (parsedId !== 'new' && parsedId === values.sharedMetricId) {
                    actions.loadSharedMetric()
                }
            }
        },
        '/experiments/shared-metrics/:id/:action': ({ id }, _, __, currentLocation, previousLocation) => {
            const didPathChange = currentLocation.initial || currentLocation.pathname !== previousLocation?.pathname

            if (id && didPathChange) {
                actions.loadSharedMetric()
            }
        },
    })),
])