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.

14.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'

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

import api from 'lib/api'
import { openTakeOwnershipDialog, ownerUnavailableCause } from 'lib/components/openTakeOwnershipDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { objectClean } from 'lib/utils/objects'
import { urls } from 'scenes/urls'

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

import { alertsTakeOwnershipCreate } from 'products/alerts/frontend/generated/api'

import { AlertType } from '../types'
import { AlertLogicProps } from './alertLogic'
import { buildAlertFilterConfig } from './alertNotifications'

export interface AlertsLogicProps extends AlertLogicProps {}

export const ALERTS_PER_PAGE = 30

export interface AlertsFilters {
    search: string
    createdBy: string
}

export const DEFAULT_ALERTS_FILTERS: AlertsFilters = {
    search: '',
    createdBy: 'All users',
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertsLogicValues {
    alertDestinationCounts: Record<string, number>
    alertDestinationCountsLoading: boolean
    alerts: AlertType[]
    alertsCount: number
    alertsResponse: {
        count: number
        results: AlertType[]
    }
    alertsResponseLoading: boolean
    alertsSortedByState: AlertType[]
    deletedAlertIds: Set<string>
    deletingAlertIds: Set<string>
    filters: AlertsFilters
    isFiltering: boolean
    page: number
    pagination: PaginationManual
    togglingAlertIds: Set<string>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertsLogicActions {
    deleteAlert: (alert: AlertType) => {
        alert: AlertType
    }
    loadAlertDestinationCounts: (alerts: AlertType[]) => AlertType[]
    loadAlertDestinationCountsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAlertDestinationCountsSuccess: (
        alertDestinationCounts: Record<string, number>,
        payload?: AlertType[]
    ) => {
        alertDestinationCounts: Record<string, number>
        payload?: AlertType[]
    }
    loadAlerts: () => any
    loadAlertsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAlertsSuccess: (
        alertsResponse: {
            count: number
            results: AlertType[]
        },
        payload?: any
    ) => {
        alertsResponse: {
            count: number
            results: AlertType[]
        }
        payload?: any
    }
    removeAlertFromList: (alertId: string) => {
        alertId: string
    }
    setAlertDeleting: (
        alertId: string,
        isDeleting: boolean
    ) => {
        alertId: string
        isDeleting: boolean
    }
    setAlertToggling: (
        alertId: string,
        isToggling: boolean
    ) => {
        alertId: string
        isToggling: boolean
    }
    setFilters: (filters: Partial<AlertsFilters>) => {
        filters: Partial<AlertsFilters>
    }
    setPage: (page: number) => {
        page: number
    }
    toggleAlertEnabled: (alert: AlertType) => {
        alert: AlertType
    }
    updateAlertInList: (alert: AlertType) => {
        alert: AlertType
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        alerts: (alertsResponse: { count: number; results: AlertType[] }) => AlertType[]
        alertsCount: (alertsResponse: { count: number; results: AlertType[] }) => number
        isFiltering: (filters: AlertsFilters) => boolean
        alertsSortedByState: (alerts: AlertType[]) => AlertType[]
        pagination: (page: number, alertsCount: number) => PaginationManual
    }
}

export type alertsLogicType = MakeLogicType<alertsLogicValues, alertsLogicActions, Record<string, any>, alertsLogicMeta>

export const alertsLogic = kea<alertsLogicType>([
    path(['lib', 'components', 'Alerts', 'alertsLogic']),
    actions({
        setPage: (page: number) => ({ page }),
        setFilters: (filters: Partial<AlertsFilters>) => ({ filters }),
        setAlertToggling: (alertId: string, isToggling: boolean) => ({ alertId, isToggling }),
        deleteAlert: (alert: AlertType) => ({ alert }),
        setAlertDeleting: (alertId: string, isDeleting: boolean) => ({ alertId, isDeleting }),
        removeAlertFromList: (alertId: string) => ({ alertId }),
        toggleAlertEnabled: (alert: AlertType) => ({ alert }),
        updateAlertInList: (alert: AlertType) => ({ alert }),
    }),

    reducers({
        alertsResponse: [
            { results: [], count: 0 } as { results: AlertType[]; count: number },
            {
                updateAlertInList: (state, { alert }) => ({
                    ...state,
                    results: state.results.map((currentAlert) => (currentAlert.id === alert.id ? alert : currentAlert)),
                }),
                removeAlertFromList: (state, { alertId }) => {
                    const results = state.results.filter((alert) => alert.id !== alertId)
                    if (results.length === state.results.length) {
                        return state
                    }
                    return { results, count: Math.max(0, state.count - 1) }
                },
            },
        ],
        page: [
            1,
            {
                setPage: (_, { page }) => page,
            },
        ],
        deletingAlertIds: [
            new Set<string>(),
            {
                setAlertDeleting: (state, { alertId, isDeleting }) => {
                    const nextState = new Set(state)
                    if (isDeleting) {
                        nextState.add(alertId)
                    } else {
                        nextState.delete(alertId)
                    }
                    return nextState
                },
            },
        ],
        deletedAlertIds: [
            new Set<string>(),
            {
                removeAlertFromList: (state, { alertId }) => new Set(state).add(alertId),
            },
        ],
        togglingAlertIds: [
            new Set<string>(),
            {
                setAlertToggling: (state, { alertId, isToggling }) => {
                    const nextState = new Set(state)
                    if (isToggling) {
                        nextState.add(alertId)
                    } else {
                        nextState.delete(alertId)
                    }
                    return nextState
                },
            },
        ],
        filters: [
            DEFAULT_ALERTS_FILTERS,
            {
                setFilters: (state, { filters }) =>
                    objectClean({
                        ...state,
                        ...filters,
                    }),
            },
        ],
    }),

    loaders(({ values }) => ({
        alertsResponse: [
            { results: [], count: 0 } as { results: AlertType[]; count: number },
            {
                loadAlerts: async () => {
                    const search = values.filters.search.trim()

                    const response = await api.alerts.list(undefined, {
                        limit: ALERTS_PER_PAGE,
                        offset: (values.page - 1) * ALERTS_PER_PAGE,
                        ...(search ? { search } : {}),
                        ...(values.filters.createdBy !== 'All users' ? { created_by: values.filters.createdBy } : {}),
                    })
                    const results = response.results.filter((alert) => !values.deletedAlertIds.has(alert.id))
                    return {
                        results,
                        count: Math.max(
                            0,
                            (response.count ?? response.results.length) - (response.results.length - results.length)
                        ),
                    }
                },
            },
        ],
        alertDestinationCounts: [
            {} as Record<string, number>,
            {
                loadAlertDestinationCounts: async (alerts: AlertType[]) => {
                    if (alerts.length === 0) {
                        return {}
                    }
                    const alertIds = new Set(alerts.map((alert) => alert.id))
                    const response = await api.hogFunctions.list({
                        types: ['internal_destination'],
                        filter_groups: alerts.map((alert) => buildAlertFilterConfig(alert.id)),
                        full: true,
                        limit: 500,
                    })
                    return response.results.reduce<Record<string, number>>((counts, hogFunction) => {
                        if (!hogFunction.enabled) {
                            return counts
                        }
                        const alertIdProperty = hogFunction.filters?.properties?.find(
                            (property) => property.key === 'alert_id'
                        )
                        const alertId = alertIdProperty?.value
                        if (typeof alertId === 'string' && alertIds.has(alertId)) {
                            counts[alertId] = (counts[alertId] ?? 0) + 1
                        }
                        return counts
                    }, {})
                },
            },
        ],
    })),

    selectors(({ actions }) => ({
        alerts: [
            (s) => [s.alertsResponse],
            (response: { count: number; results: AlertType[] }): AlertType[] => response.results,
        ],
        alertsCount: [
            (s) => [s.alertsResponse],
            (response: { count: number; results: AlertType[] }): number => response.count,
        ],
        isFiltering: [
            (s) => [s.filters],
            (filters: AlertsFilters): boolean =>
                filters.search !== DEFAULT_ALERTS_FILTERS.search ||
                filters.createdBy !== DEFAULT_ALERTS_FILTERS.createdBy,
        ],
        alertsSortedByState: [
            (s) => [s.alerts],
            (alerts: AlertType[]): AlertType[] =>
                [...alerts].sort((a, b) => alertComparatorKey(a) - alertComparatorKey(b)),
        ],
        pagination: [
            (s) => [s.page, s.alertsCount],
            (page: number, count: number): PaginationManual => ({
                controlled: true,
                pageSize: ALERTS_PER_PAGE,
                currentPage: page,
                entryCount: count,
                onBackward: () => actions.setPage(page - 1),
                onForward: () => actions.setPage(page + 1),
            }),
        ],
    })),

    listeners(({ actions, values }) => ({
        deleteAlert: async ({ alert }) => {
            actions.setAlertDeleting(alert.id, true)
            try {
                await api.alerts.delete(alert.id)
                actions.removeAlertFromList(alert.id)
                actions.loadAlerts()
                lemonToast.success(`${alert.name || 'Unnamed alert'} has been deleted`)
            } catch {
                lemonToast.error("Couldn't delete the alert. Try again.")
            } finally {
                actions.setAlertDeleting(alert.id, false)
            }
        },
        setPage: () => {
            actions.loadAlerts()
        },
        setFilters: async ({ filters }, breakpoint) => {
            if ('search' in filters && filters.search?.trim()) {
                await breakpoint(300)
            }
            if (values.page !== 1) {
                actions.setPage(1)
            } else {
                actions.loadAlerts()
            }
        },
        toggleAlertEnabled: async ({ alert }) => {
            actions.setAlertToggling(alert.id, true)
            try {
                const updatedAlert = await api.alerts.update(alert.id, { enabled: !alert.enabled })
                actions.updateAlertInList(updatedAlert)
            } catch (error) {
                const cause = alert.enabled ? null : ownerUnavailableCause(error)
                if (cause) {
                    // Not awaited, so the row's switch stops loading while the dialog is open.
                    void openTakeOwnershipDialog({
                        resourceLabel: 'alert',
                        resourceId: alert.id,
                        owner: alert.created_by ?? null,
                        cause,
                        takeOwnership: async () => {
                            await alertsTakeOwnershipCreate(String(getCurrentTeamId()), alert.id)
                            lemonToast.success('Alert enabled')
                        },
                    }).then((taken) => {
                        if (taken) {
                            actions.loadAlerts()
                        }
                    })
                } else {
                    lemonToast.error('Failed to update alert')
                }
            } finally {
                actions.setAlertToggling(alert.id, false)
            }
        },
        loadAlertsSuccess: ({ alertsResponse }) => {
            actions.loadAlertDestinationCounts(alertsResponse.results)
        },
    })),

    actionToUrl(({ values }) => ({
        setFilters: ({ filters }) => {
            if (!('createdBy' in filters)) {
                return
            }
            const { pathname, searchParams, hashParams } = router.values.currentLocation
            if (!pathname.endsWith(urls.alerts())) {
                return
            }
            return [
                pathname,
                {
                    ...searchParams,
                    created_by:
                        values.filters.createdBy === DEFAULT_ALERTS_FILTERS.createdBy
                            ? undefined
                            : values.filters.createdBy,
                },
                hashParams,
                { replace: true },
            ]
        },
    })),
    urlToAction(({ actions, values }) => ({
        [urls.alerts()]: (_, searchParams) => {
            const createdBy = searchParams.created_by || DEFAULT_ALERTS_FILTERS.createdBy
            if (createdBy !== values.filters.createdBy) {
                actions.setFilters({ createdBy })
            }
        },
    })),
    afterMount(({ actions, values }) => {
        if (!values.alertsResponseLoading) {
            actions.loadAlerts()
        }
    }),
])

const alertComparatorKey = (alert: AlertType): number => {
    if (!alert.enabled) {
        return 100
    }

    switch (alert.state) {
        case AlertState.FIRING:
            return 1
        case AlertState.ERRORED:
            return 2
        case AlertState.SNOOZED:
            return 3
        case AlertState.NOT_FIRING:
            return 4
    }
}