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.

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

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

import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'

import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import {
    CyclotronJobFiltersType,
    HogFunctionConfigurationContextId,
    HogFunctionType,
    HogFunctionTypeType,
    UserType,
} from '~/types'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { AvailableFeature } from '../../../types'
import { eventToHogFunctionContextId } from '../sub-templates/sub-templates'

export const CDP_TEST_HIDDEN_FLAG = '[CDP-TEST-HIDDEN]'
const EMPTY_MANUAL_FUNCTIONS: HogFunctionType[] = []

export type HogFunctionListFilters = {
    search?: string
    showPaused?: boolean
    createdBy?: string | null
    /** Which PostHog product an `internal_destination` delivers notifications for. */
    notificationSource?: HogFunctionConfigurationContextId
}

export type HogFunctionListLogicProps = {
    logicKey?: string
    type: HogFunctionTypeType
    additionalTypes?: HogFunctionTypeType[]
    forceFilterGroups?: CyclotronJobFiltersType[]
    syncFiltersWithUrl?: boolean
    manualFunctions?: HogFunctionType[]
}

export const shouldShowHogFunction = (hogFunction: HogFunctionType, user?: UserType | null): boolean => {
    if (!user) {
        return false
    }
    if (hogFunction.name.includes(CDP_TEST_HIDDEN_FLAG) && !user.is_impersonated && !user.is_staff) {
        return false
    }
    return true
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFunctionsListLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentProjectId: number | null // projectLogic
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    user: UserType | null // userLogic
    enabledHogFunctions: HogFunctionType[]
    filteredHogFunctions: HogFunctionType[]
    filters: HogFunctionListFilters
    hiddenHogFunctions: HogFunctionType[]
    hogFunctions: HogFunctionType[]
    hogFunctionsLoading: boolean
    loading: boolean
    notificationSources: HogFunctionConfigurationContextId[]
    reorderModalOpen: boolean
    sortedHogFunctions: HogFunctionType[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFunctionsListLogicActions {
    addHogFunction: (hogFunction: HogFunctionType) => {
        hogFunction: HogFunctionType
    }
    addHogFunctionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    addHogFunctionSuccess: (
        hogFunctions: HogFunctionType[],
        payload?: {
            hogFunction: HogFunctionType
        }
    ) => {
        hogFunctions: HogFunctionType[]
        payload?: {
            hogFunction: HogFunctionType
        }
    }
    deleteHogFunction: (hogFunction: HogFunctionType) => {
        hogFunction: HogFunctionType
    }
    deleteHogFunctionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteHogFunctionSuccess: (
        hogFunctions: HogFunctionType[],
        payload?: {
            hogFunction: HogFunctionType
        }
    ) => {
        hogFunctions: HogFunctionType[]
        payload?: {
            hogFunction: HogFunctionType
        }
    }
    loadHogFunctions: () => any
    loadHogFunctionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadHogFunctionsSuccess: (
        hogFunctions: HogFunctionType[],
        payload?: any
    ) => {
        hogFunctions: HogFunctionType[]
        payload?: any
    }
    resetFilters: () => {
        value: true
    }
    saveHogFunctionOrder: (newOrders: Record<string, number>) => {
        newOrders: Record<string, number>
    }
    saveHogFunctionOrderFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveHogFunctionOrderSuccess: (
        hogFunctions: HogFunctionType[],
        payload?: {
            newOrders: Record<string, number>
        }
    ) => {
        hogFunctions: HogFunctionType[]
        payload?: {
            newOrders: Record<string, number>
        }
    }
    setFilters: (filters: Partial<HogFunctionListFilters>) => {
        filters: Partial<HogFunctionListFilters>
    }
    setReorderModalOpen: (open: boolean) => {
        open: boolean
    }
    toggleEnabled: (
        hogFunction: HogFunctionType,
        enabled: boolean
    ) => {
        enabled: boolean
        hogFunction: HogFunctionType
    }
    toggleEnabledFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    toggleEnabledSuccess: (
        hogFunctions: HogFunctionType[],
        payload?: {
            enabled: boolean
            hogFunction: HogFunctionType
        }
    ) => {
        hogFunctions: HogFunctionType[]
        payload?: {
            enabled: boolean
            hogFunction: HogFunctionType
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFunctionsListLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        loading: (hogFunctionsLoading: boolean) => boolean
        sortedHogFunctions: (
            hogFunctions: HogFunctionType[],
            filters: HogFunctionListFilters,
            arg: any
        ) => HogFunctionType[]
        enabledHogFunctions: (sortedHogFunctions: HogFunctionType[]) => HogFunctionType[]
        filteredHogFunctions: (
            filters: HogFunctionListFilters,
            sortedHogFunctions: HogFunctionType[],
            user: UserType | null
        ) => HogFunctionType[]
        hiddenHogFunctions: (
            sortedHogFunctions: HogFunctionType[],
            filteredHogFunctions: HogFunctionType[]
        ) => HogFunctionType[]
        notificationSources: (
            sortedHogFunctions: HogFunctionType[],
            filters: HogFunctionListFilters
        ) => HogFunctionConfigurationContextId[]
    }
}

export type hogFunctionsListLogicType = MakeLogicType<
    hogFunctionsListLogicValues,
    hogFunctionsListLogicActions,
    HogFunctionListLogicProps,
    hogFunctionsListLogicMeta
>

export const hogFunctionsListLogic = kea<hogFunctionsListLogicType>([
    props({} as HogFunctionListLogicProps),
    key((props) =>
        JSON.stringify({
            ...props,
            manualFunctions: null, // We don't care about these
        })
    ),
    path((id) => ['scenes', 'pipeline', 'hogFunctionsListLogic', id]),
    connect(() => ({
        values: [
            projectLogic,
            ['currentProjectId'],
            userLogic,
            ['user', 'hasAvailableFeature'],
            featureFlagLogic,
            ['featureFlags'],
        ],
    })),
    actions({
        toggleEnabled: (hogFunction: HogFunctionType, enabled: boolean) => ({ hogFunction, enabled }),
        deleteHogFunction: (hogFunction: HogFunctionType) => ({ hogFunction }),
        setFilters: (filters: Partial<HogFunctionListFilters>) => ({ filters }),
        resetFilters: true,
        addHogFunction: (hogFunction: HogFunctionType) => ({ hogFunction }),
        setReorderModalOpen: (open: boolean) => ({ open }),
        saveHogFunctionOrder: (newOrders: Record<string, number>) => ({ newOrders }),
    }),
    reducers(() => ({
        filters: [
            {} as HogFunctionListFilters,
            {
                setFilters: (state, { filters }) => ({
                    ...state,
                    ...filters,
                }),
                resetFilters: () => ({}),
            },
        ],
        reorderModalOpen: [
            false as boolean,
            {
                setReorderModalOpen: (_, { open }) => open,
            },
        ],
    })),
    loaders(({ values, actions, props }) => ({
        hogFunctions: [
            [] as HogFunctionType[],
            {
                loadHogFunctions: async () => {
                    const search = values.filters.search?.trim() || undefined
                    return (
                        await api.hogFunctions.list({
                            filter_groups: props.forceFilterGroups,
                            types: [props.type, ...(props.additionalTypes || [])],
                            search,
                            // TODO: This is a temporary fix. We need proper server-side pagination.
                            limit: 300,
                        })
                    ).results
                },
                saveHogFunctionOrder: async ({ newOrders }) => {
                    return await api.hogFunctions.rearrange(newOrders)
                },
                deleteHogFunction: async ({ hogFunction }) => {
                    // deleteWithUndo turns an API rejection into a toast, so the callback firing is
                    // the only signal that the row really went. Destinations a product manages are
                    // refused, and dropping those rows here makes the table disagree with the server.
                    let deleted = false
                    await deleteWithUndo({
                        endpoint: `projects/${values.currentProjectId}/hog_functions`,
                        object: {
                            id: hogFunction.id,
                            name: hogFunction.name,
                        },
                        callback: (undo) => {
                            if (undo) {
                                actions.loadHogFunctions()
                                refreshTreeItem('hog_function/', hogFunction.id)
                            } else {
                                deleted = true
                                deleteFromTree('hog_function/', hogFunction.id)
                            }
                        },
                    })

                    return deleted ? values.hogFunctions.filter((x) => x.id !== hogFunction.id) : values.hogFunctions
                },
                toggleEnabled: async ({ hogFunction, enabled }) => {
                    const { hogFunctions } = values
                    const hogFunctionIndex = hogFunctions.findIndex((hf) => hf.id === hogFunction.id)
                    const response = await api.hogFunctions.update(hogFunction.id, {
                        enabled,
                    })
                    return [
                        ...hogFunctions.slice(0, hogFunctionIndex),
                        response,
                        ...hogFunctions.slice(hogFunctionIndex + 1),
                    ]
                },
                addHogFunction: ({ hogFunction }) => {
                    return [hogFunction, ...values.hogFunctions]
                },
            },
        ],
    })),
    selectors({
        loading: [(s) => [s.hogFunctionsLoading], (hogFunctionsLoading: boolean) => hogFunctionsLoading],
        sortedHogFunctions: [
            (s) => [s.hogFunctions, s.filters, (_, props) => props.manualFunctions ?? EMPTY_MANUAL_FUNCTIONS],
            (
                hogFunctions: HogFunctionType[],
                filters: HogFunctionListFilters,
                manualFunctions: HogFunctionType[]
            ): HogFunctionType[] => {
                const search = filters.search?.trim().toLowerCase()
                const filteredManual = search
                    ? manualFunctions.filter(
                          (f) => f.name?.toLowerCase().includes(search) || f.description?.toLowerCase().includes(search)
                      )
                    : manualFunctions
                const enabledFirst = [...hogFunctions, ...filteredManual].sort(
                    (a, b) => Number(b.enabled) - Number(a.enabled)
                )
                return enabledFirst
            },
        ],
        enabledHogFunctions: [
            (s) => [s.sortedHogFunctions],
            (hogFunctions: HogFunctionType[]): HogFunctionType[] => {
                return hogFunctions.filter((hogFunction) => hogFunction.enabled)
            },
        ],
        filteredHogFunctions: [
            (s) => [s.filters, s.sortedHogFunctions, s.user],
            (
                filters: HogFunctionListFilters,
                hogFunctions: HogFunctionType[],
                user: UserType | null
            ): HogFunctionType[] => {
                const { showPaused, createdBy, notificationSource } = filters

                return hogFunctions.filter((x) => {
                    if (!shouldShowHogFunction(x, user)) {
                        return false
                    }

                    if (!showPaused && !x.enabled) {
                        return false
                    }

                    if (createdBy && x.created_by?.uuid !== createdBy) {
                        return false
                    }

                    if (
                        notificationSource &&
                        eventToHogFunctionContextId(x.filters?.events?.[0]?.id) !== notificationSource
                    ) {
                        return false
                    }

                    return true
                })
            },
        ],

        hiddenHogFunctions: [
            (s) => [s.sortedHogFunctions, s.filteredHogFunctions],
            (sortedHogFunctions: HogFunctionType[], filteredHogFunctions: HogFunctionType[]): HogFunctionType[] => {
                return sortedHogFunctions.filter((hogFunction) => !filteredHogFunctions.includes(hogFunction))
            },
        ],

        // The products that the listed notifications deliver for. The selected source stays in the list even
        // when a search removed its notifications, so the filter never shows a value it cannot list.
        notificationSources: [
            (s) => [s.sortedHogFunctions, s.filters],
            (
                sortedHogFunctions: HogFunctionType[],
                filters: HogFunctionListFilters
            ): HogFunctionConfigurationContextId[] => {
                const sources = new Set(
                    sortedHogFunctions
                        .filter((hogFunction) => hogFunction.type === 'internal_destination')
                        .map((hogFunction) => eventToHogFunctionContextId(hogFunction.filters?.events?.[0]?.id))
                )
                if (filters.notificationSource) {
                    sources.add(filters.notificationSource)
                }
                return Array.from(sources)
            },
        ],
    }),

    listeners(({ actions }) => ({
        setFilters: async ({ filters }, breakpoint) => {
            if (filters.search === undefined) {
                return
            }
            await breakpoint(250)
            actions.loadHogFunctions()
        },
        resetFilters: () => {
            actions.loadHogFunctions()
        },
        saveHogFunctionOrderSuccess: () => {
            actions.setReorderModalOpen(false)
            lemonToast.success('Order updated successfully')
        },
        saveHogFunctionOrderFailure: () => {
            lemonToast.error('Failed to update order')
        },
    })),

    actionToUrl(({ props, values }) => {
        if (!props.syncFiltersWithUrl) {
            return {}
        }
        const urlFromFilters = (): [
            string,
            Record<string, any>,
            Record<string, any>,
            {
                replace: boolean
            },
        ] => [
            router.values.location.pathname,

            values.filters,
            router.values.hashParams,
            {
                replace: true,
            },
        ]

        return {
            setFilters: () => urlFromFilters(),
            resetFilters: () => urlFromFilters(),
        }
    }),

    urlToAction(({ props, actions, values }) => ({
        '*': (_, searchParams) => {
            if (!props.syncFiltersWithUrl) {
                return
            }

            if (!objectsEqual(values.filters, searchParams)) {
                actions.setFilters(searchParams)
            }
        },
    })),
])