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.2 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { lazyLoaders } from 'kea-loaders'

import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { CdpFilterEntities } from 'scenes/hog-functions/filters/cdpFilterSeries'
import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'

import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { AnyPropertyFilter } from '~/types'

import {
    groupsTypesMetricsCreate,
    groupsTypesMetricsDestroy,
    groupsTypesMetricsList,
    groupsTypesMetricsUpdate,
} from 'products/customer_analytics/frontend/generated/api'
import type { GroupUsageMetricApi } from 'products/customer_analytics/frontend/generated/api.schemas'

import type { ProductIntentProperties } from '../../../lib/utils/product-intents'

export type UsageMetricSource = 'events' | 'data_warehouse'

export type UsageMetricFiltersDataWarehouse = {
    source: 'data_warehouse'
    table_name?: string | null
    timestamp_field?: string | null
    key_field?: string | null
}

export type UsageMetricEventFilters = Partial<CdpFilterEntities> & {
    properties?: AnyPropertyFilter[]
    filter_test_accounts?: boolean
}

export type UsageMetricFormData = Omit<GroupUsageMetricApi, 'id' | 'filters'> & {
    id?: string
    filters: UsageMetricEventFilters | UsageMetricFiltersDataWarehouse
}

const NEW_USAGE_METRIC: UsageMetricFormData = {
    name: '',
    format: 'numeric',
    interval: 7,
    display: 'number',
    filters: {},
    math: 'count',
    math_property: null,
}

export function getMetricSource(filters: UsageMetricFormData['filters']): UsageMetricSource {
    if (
        filters &&
        typeof filters === 'object' &&
        'source' in filters &&
        (filters as UsageMetricFiltersDataWarehouse).source === 'data_warehouse'
    ) {
        return 'data_warehouse'
    }
    return 'events'
}

/**
 * Render the saved filters in the matcher shape the event picker reads.
 * DW metrics get hoisted into a single `data_warehouse` entry; events metrics pass through.
 */
export function savedFiltersToActionFilterValue(filters: UsageMetricFormData['filters']): UsageMetricEventFilters {
    if (getMetricSource(filters) === 'data_warehouse') {
        const dw = filters as UsageMetricFiltersDataWarehouse
        return {
            data_warehouse: [
                {
                    type: 'data_warehouse',
                    id: dw.table_name ?? '',
                    name: dw.table_name ?? '',
                    table_name: dw.table_name ?? '',
                    timestamp_field: dw.timestamp_field,
                    key_field: dw.key_field,
                },
            ],
        }
    }
    return (filters ?? {}) as UsageMetricEventFilters
}

/**
 * Translate the event picker's matcher payload back into our saved shape (events shape or DW shape).
 * If both branches are populated (the user just added an entry of the opposite type), resolve by
 * switching to whichever side just received the new entry — using `prevSource` as the reference.
 */
export function actionFilterValueToSavedFilters(
    payload: UsageMetricEventFilters,
    prevSource: UsageMetricSource
): UsageMetricFormData['filters'] {
    const dwEntries = (payload.data_warehouse ?? []) as Array<Record<string, any>>
    const eventEntries = payload.events ?? []
    const actionEntries = payload.actions ?? []

    const switchedToDw = prevSource === 'events' && dwEntries.length > 0
    const onlyDw = dwEntries.length > 0 && eventEntries.length === 0 && actionEntries.length === 0

    if (onlyDw || switchedToDw) {
        const dw = dwEntries[0] ?? {}
        return {
            source: 'data_warehouse',
            table_name: dw.table_name ?? dw.name ?? null,
            timestamp_field: dw.timestamp_field ?? null,
            key_field: dw.key_field ?? null,
        }
    }

    return {
        events: eventEntries,
        actions: actionEntries,
        properties: payload.properties ?? [],
        filter_test_accounts: payload.filter_test_accounts,
    }
}

// Hardcoded to 0 — the backend model is coupled to groups but will be refactored to be group-agnostic
const GROUP_TYPE_INDEX = 0

export interface UsageMetricsConfigLogicProps {
    logicKey?: string
    onMetricsChanged?: () => void
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface usageMetricsConfigLogicValues {
    currentProjectId: number | null // projectLogic
    isModalOpen: boolean
    isUsageMetricSubmitting: boolean
    isUsageMetricValid: boolean
    showUsageMetricErrors: boolean
    usageMetric: UsageMetricFormData
    usageMetricAllErrors: Record<string, any>
    usageMetricChanged: boolean
    usageMetricErrors: DeepPartialMap<UsageMetricFormData, ValidationErrorType>
    usageMetricHasErrors: boolean
    usageMetricManualErrors: Record<string, any>
    usageMetricTouched: boolean
    usageMetricTouches: Record<string, boolean>
    usageMetricValidationErrors: DeepPartialMap<UsageMetricFormData, ValidationErrorType>
    usageMetrics: GroupUsageMetricApi[]
    usageMetricsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface usageMetricsConfigLogicActions {
    reportUsageMetricCreated: () => boolean // eventUsageLogic
    reportUsageMetricDeleted: () => boolean // eventUsageLogic
    reportUsageMetricUpdated: () => boolean // eventUsageLogic
    addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
    addUsageMetric: (metric: UsageMetricFormData) => {
        metric: UsageMetricFormData
    }
    addUsageMetricFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    addUsageMetricSuccess: (
        usageMetrics: GroupUsageMetricApi[],
        payload?: {
            metric: UsageMetricFormData
        }
    ) => {
        usageMetrics: GroupUsageMetricApi[]
        payload?: {
            metric: UsageMetricFormData
        }
    }
    closeModal: () => {
        value: true
    }
    loadUsageMetrics: () => any
    loadUsageMetricsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadUsageMetricsSuccess: (
        usageMetrics: GroupUsageMetricApi[],
        payload?: any
    ) => {
        usageMetrics: GroupUsageMetricApi[]
        payload?: any
    }
    openModal: () => {
        value: true
    }
    removeUsageMetric: (id: string) => {
        id: string
    }
    removeUsageMetricFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    removeUsageMetricSuccess: (
        usageMetrics: GroupUsageMetricApi[],
        payload?: {
            id: string
        }
    ) => {
        usageMetrics: GroupUsageMetricApi[]
        payload?: {
            id: string
        }
    }
    resetUsageMetric: (values?: UsageMetricFormData) => {
        values?: UsageMetricFormData
    }
    setUsageMetricManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setUsageMetricValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setUsageMetricValues: (values: DeepPartial<UsageMetricFormData>) => {
        values: DeepPartial<UsageMetricFormData>
    }
    submitUsageMetric: () => {
        value: boolean
    }
    submitUsageMetricFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitUsageMetricRequest: (usageMetric: UsageMetricFormData) => {
        usageMetric: UsageMetricFormData
    }
    submitUsageMetricSuccess: (usageMetric: UsageMetricFormData) => {
        usageMetric: UsageMetricFormData
    }
    touchUsageMetricField: (key: string) => {
        key: string
    }
    updateUsageMetric: (metric: UsageMetricFormData) => {
        metric: UsageMetricFormData
    }
    updateUsageMetricFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateUsageMetricSuccess: (
        usageMetrics: GroupUsageMetricApi[],
        payload?: {
            metric: UsageMetricFormData
        }
    ) => {
        usageMetrics: GroupUsageMetricApi[]
        payload?: {
            metric: UsageMetricFormData
        }
    }
}

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

export type usageMetricsConfigLogicType = MakeLogicType<
    usageMetricsConfigLogicValues,
    usageMetricsConfigLogicActions,
    UsageMetricsConfigLogicProps,
    usageMetricsConfigLogicMeta
>

export const usageMetricsConfigLogic = kea<usageMetricsConfigLogicType>([
    path(['scenes', 'settings', 'environment', 'usageMetricsConfigLogic']),
    props({} as UsageMetricsConfigLogicProps),
    key(({ logicKey }) => logicKey || 'defaultKey'),
    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
        actions: [
            eventUsageLogic,
            ['reportUsageMetricCreated', 'reportUsageMetricUpdated', 'reportUsageMetricDeleted'],
            teamLogic,
            ['addProductIntent'],
        ],
    })),

    actions(() => ({
        addUsageMetric: (metric: UsageMetricFormData) => ({ metric }),
        updateUsageMetric: (metric: UsageMetricFormData) => ({ metric }),
        removeUsageMetric: (id: string) => ({ id }),
        openModal: true,
        closeModal: true,
    })),

    reducers({
        isModalOpen: [
            false,
            {
                openModal: () => true,
                closeModal: () => false,
            },
        ],
    }),

    lazyLoaders(({ values }) => ({
        usageMetrics: [
            [] as GroupUsageMetricApi[],
            {
                loadUsageMetrics: async () => {
                    const response = await groupsTypesMetricsList(String(values.currentProjectId), GROUP_TYPE_INDEX)
                    return response.results
                },
                addUsageMetric: async ({ metric }) => {
                    const { id: _id, ...payload } = metric
                    const newMetric = await groupsTypesMetricsCreate(
                        String(values.currentProjectId),
                        GROUP_TYPE_INDEX,
                        payload as GroupUsageMetricApi
                    )
                    return [...values.usageMetrics, newMetric]
                },
                updateUsageMetric: async ({ metric }) => {
                    if (!metric.id) {
                        throw new Error('Cannot update a metric without an id')
                    }
                    const updatedMetric = await groupsTypesMetricsUpdate(
                        String(values.currentProjectId),
                        GROUP_TYPE_INDEX,
                        metric.id,
                        metric as GroupUsageMetricApi
                    )
                    return [...values.usageMetrics.filter((m) => m.id !== metric.id), updatedMetric]
                },
                removeUsageMetric: async ({ id }) => {
                    await groupsTypesMetricsDestroy(String(values.currentProjectId), GROUP_TYPE_INDEX, id)
                    return values.usageMetrics.filter((m) => m.id !== id)
                },
            },
        ],
    })),

    forms(({ actions }) => ({
        usageMetric: {
            defaults: NEW_USAGE_METRIC,
            errors: ({ name, math, math_property, filters }) => ({
                name: !name ? 'Name is required' : undefined,
                math_property:
                    math === 'sum' && !math_property
                        ? getMetricSource(filters) === 'data_warehouse'
                            ? 'Column to sum is required'
                            : 'Property is required for sum'
                        : undefined,
            }),
            submit: (formData) => {
                if (formData?.id) {
                    actions.updateUsageMetric(formData)
                } else {
                    actions.addUsageMetric(formData)
                }
            },
        },
    })),

    listeners(({ actions, props }) => ({
        closeModal: () => {
            actions.resetUsageMetric()
        },
        submitUsageMetricSuccess: () => {
            actions.loadUsageMetrics()
            actions.closeModal()
        },
        addUsageMetricSuccess: () => {
            actions.loadUsageMetrics()
            actions.reportUsageMetricCreated()
            actions.addProductIntent({
                product_type: ProductKey.CUSTOMER_ANALYTICS,
                intent_context: ProductIntentContext.CUSTOMER_ANALYTICS_USAGE_METRIC_CREATED,
            })
            props.onMetricsChanged?.()
        },
        updateUsageMetricSuccess: () => {
            actions.loadUsageMetrics()
            actions.reportUsageMetricUpdated()
            props.onMetricsChanged?.()
        },
        removeUsageMetricSuccess: () => {
            actions.loadUsageMetrics()
            actions.reportUsageMetricDeleted()
            props.onMetricsChanged?.()
        },
    })),
])