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.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import api from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { projectLogic } from 'scenes/projectLogic'

import { HogFunctionType, IntegrationType } from '~/types'

import { alertsTestDeliveryCreate } from 'products/alerts/frontend/generated/api'
import type { AlertTestDeliveryResponseApi } from 'products/alerts/frontend/generated/api.schemas'
import {
    ALERT_NOTIFICATION_TYPE_DISCORD,
    ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS,
    ALERT_NOTIFICATION_TYPE_SLACK,
    ALERT_NOTIFICATION_TYPE_WEBHOOK,
    AlertNotificationType,
    PendingAlertNotification,
    buildAlertFilterConfig,
    buildHogFunctionPayload,
    notificationTypeFromTemplateId,
} from 'products/alerts/frontend/logic/alertNotifications'

export const ALERT_NOTIFICATION_TYPE_OPTIONS = [
    { label: 'Slack', value: ALERT_NOTIFICATION_TYPE_SLACK },
    { label: 'Discord', value: ALERT_NOTIFICATION_TYPE_DISCORD },
    { label: 'Microsoft Teams', value: ALERT_NOTIFICATION_TYPE_MICROSOFT_TEAMS },
    { label: 'Webhook', value: ALERT_NOTIFICATION_TYPE_WEBHOOK },
]

export interface AlertNotificationLogicProps {
    alertId?: string
    loadDestinations?: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertNotificationLogicValues {
    integrationsLoading: boolean // integrationsLogic
    slackIntegrations: IntegrationType[] | undefined // integrationsLogic
    currentProjectId: number | null // projectLogic
    existingHogFunctions: HogFunctionType[]
    existingHogFunctionsLoading: boolean
    integrationsFailed: boolean
    pendingNotifications: PendingAlertNotification[]
    selectedSlackIntegration: IntegrationType | undefined
    selectedSlackIntegrationId: number | null
    selectedType: AlertNotificationType
    slackChannelValue: string | null
    testDeliveryResult: AlertTestDeliveryResponseApi | null
    testDeliveryResultLoading: boolean
    webhookUrl: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertNotificationLogicActions {
    loadIntegrations: (_?: any) => any // integrationsLogic
    loadIntegrationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // integrationsLogic
    loadIntegrationsSuccess: (
        integrations: IntegrationType[],
        payload?: any
    ) => {
        integrations: IntegrationType[]
        payload?: any
    } // integrationsLogic
    addPendingNotification: (notification: PendingAlertNotification) => {
        notification: PendingAlertNotification
    }
    clearPendingNotifications: () => {
        value: true
    }
    createPendingHogFunctions: (
        alertId: string,
        alertName?: string
    ) => {
        alertId: string
        alertName: string | undefined
    }
    deleteExistingHogFunction: (hogFunction: HogFunctionType) => {
        hogFunction: HogFunctionType
    }
    loadExistingHogFunctions: () => any
    loadExistingHogFunctionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadExistingHogFunctionsSuccess: (
        existingHogFunctions: HogFunctionType[],
        payload?: any
    ) => {
        existingHogFunctions: HogFunctionType[]
        payload?: any
    }
    removePendingNotification: (index: number) => {
        index: number
    }
    sendTestDelivery: () => any
    sendTestDeliveryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    sendTestDeliverySuccess: (
        testDeliveryResult: AlertTestDeliveryResponseApi,
        payload?: any
    ) => {
        testDeliveryResult: AlertTestDeliveryResponseApi
        payload?: any
    }
    setPendingNotifications: (notifications: PendingAlertNotification[]) => {
        notifications: PendingAlertNotification[]
    }
    setSelectedSlackIntegrationId: (selectedSlackIntegrationId: number | null) => {
        selectedSlackIntegrationId: number | null
    }
    setSelectedType: (selectedType: AlertNotificationType) => {
        selectedType: AlertNotificationType
    }
    setSlackChannelValue: (slackChannelValue: string | null) => {
        slackChannelValue: string | null
    }
    setWebhookUrl: (webhookUrl: string) => {
        webhookUrl: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertNotificationLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        selectedSlackIntegration: (
            slackIntegrations: IntegrationType[] | undefined,
            selectedSlackIntegrationId: number | null
        ) => IntegrationType | undefined
    }
}

export type alertNotificationLogicType = MakeLogicType<
    alertNotificationLogicValues,
    alertNotificationLogicActions,
    AlertNotificationLogicProps,
    alertNotificationLogicMeta
>

export const alertNotificationLogic = kea<alertNotificationLogicType>([
    path(['lib', 'components', 'Alerts', 'alertNotificationLogic']),
    props({} as AlertNotificationLogicProps),
    key(({ alertId, loadDestinations = true }) => `${alertId ?? 'new'}-${loadDestinations ? 'full' : 'test-only'}`),

    connect({
        values: [projectLogic, ['currentProjectId'], integrationsLogic, ['integrationsLoading', 'slackIntegrations']],
        actions: [integrationsLogic, ['loadIntegrations', 'loadIntegrationsFailure', 'loadIntegrationsSuccess']],
    }),

    actions({
        addPendingNotification: (notification: PendingAlertNotification) => ({ notification }),
        removePendingNotification: (index: number) => ({ index }),
        clearPendingNotifications: true,
        setPendingNotifications: (notifications: PendingAlertNotification[]) => ({ notifications }),
        deleteExistingHogFunction: (hogFunction: HogFunctionType) => ({ hogFunction }),
        createPendingHogFunctions: (alertId: string, alertName?: string) => ({ alertId, alertName }),
        setSelectedType: (selectedType: AlertNotificationType) => ({ selectedType }),
        setSelectedSlackIntegrationId: (selectedSlackIntegrationId: number | null) => ({
            selectedSlackIntegrationId,
        }),
        setSlackChannelValue: (slackChannelValue: string | null) => ({ slackChannelValue }),
        setWebhookUrl: (webhookUrl: string) => ({ webhookUrl }),
    }),

    reducers({
        pendingNotifications: [
            [] as PendingAlertNotification[],
            {
                addPendingNotification: (state, { notification }) => [...state, notification],
                removePendingNotification: (state, { index }) => state.filter((_, i) => i !== index),
                clearPendingNotifications: () => [],
                setPendingNotifications: (_, { notifications }) => notifications,
            },
        ],
        integrationsFailed: [
            false,
            {
                loadIntegrations: () => false,
                loadIntegrationsFailure: () => true,
                loadIntegrationsSuccess: () => false,
            },
        ],
        slackChannelValue: [
            null as string | null,
            {
                setSlackChannelValue: (_, { slackChannelValue }) => slackChannelValue,
                // Reset the input when switching destination type so stale values don't carry over.
                setSelectedType: () => null,
                setSelectedSlackIntegrationId: () => null,
            },
        ],
        selectedSlackIntegrationId: [
            null as number | null,
            {
                setSelectedSlackIntegrationId: (_, { selectedSlackIntegrationId }) => selectedSlackIntegrationId,
            },
        ],
        webhookUrl: [
            '' as string,
            {
                setWebhookUrl: (_, { webhookUrl }) => webhookUrl,
                setSelectedType: () => '',
            },
        ],
        selectedType: [
            ALERT_NOTIFICATION_TYPE_SLACK as AlertNotificationType,
            {
                setSelectedType: (_, { selectedType }) => selectedType,
            },
        ],
        existingHogFunctions: [
            [] as HogFunctionType[],
            {
                // Optimistic removal so the item disappears immediately
                deleteExistingHogFunction: (state, { hogFunction }) => state.filter((hf) => hf.id !== hogFunction.id),
            },
        ],
    }),

    selectors({
        selectedSlackIntegration: [
            (s) => [s.slackIntegrations, s.selectedSlackIntegrationId],
            (
                slackIntegrations: IntegrationType[] | undefined,
                selectedSlackIntegrationId: number | null
            ): IntegrationType | undefined =>
                slackIntegrations?.find((integration) => integration.id === selectedSlackIntegrationId) ??
                slackIntegrations?.[0],
        ],
    }),

    loaders(({ props, values }) => ({
        existingHogFunctions: [
            [] as HogFunctionType[],
            {
                loadExistingHogFunctions: async () => {
                    if (!props.alertId) {
                        return []
                    }
                    const response = await api.hogFunctions.list({
                        types: ['internal_destination'],
                        filter_groups: [buildAlertFilterConfig(props.alertId)],
                        full: true,
                    })
                    return response.results
                },
            },
        ],
        testDeliveryResult: [
            null as AlertTestDeliveryResponseApi | null,
            {
                sendTestDelivery: async () => {
                    if (!props.alertId || values.currentProjectId === null) {
                        throw new Error('Save the alert before sending a test.')
                    }
                    return alertsTestDeliveryCreate(String(values.currentProjectId), props.alertId)
                },
            },
        ],
    })),

    listeners(({ actions, values, props }) => ({
        loadIntegrationsSuccess: ({ integrations }) => {
            const availableSlackIntegrations = integrations.filter((integration) => integration.kind === 'slack')
            const selectedIntegrationIsAvailable = availableSlackIntegrations.some(
                (integration) => integration.id === values.selectedSlackIntegrationId
            )

            if (!selectedIntegrationIsAvailable) {
                actions.setSelectedSlackIntegrationId(availableSlackIntegrations[0]?.id ?? null)
            }
            if (availableSlackIntegrations.length === 0) {
                actions.setSelectedType(ALERT_NOTIFICATION_TYPE_WEBHOOK)
            }

            // Drop any staged Slack notifications pointing at a workspace that's no longer
            // connected — saving them would create a destination referencing a dead integration.
            const availableIds = new Set(availableSlackIntegrations.map((integration) => integration.id))
            const stillValidPending = values.pendingNotifications.filter(
                (notification) =>
                    notification.type !== ALERT_NOTIFICATION_TYPE_SLACK ||
                    availableIds.has(notification.slackWorkspaceId)
            )
            if (stillValidPending.length !== values.pendingNotifications.length) {
                actions.setPendingNotifications(stillValidPending)
            }
        },
        deleteExistingHogFunction: async ({ hogFunction }) => {
            // Resolve the type from the closure up front — after the delete the HogFunction is
            // removed from state, so we can't derive it later.
            const type = notificationTypeFromTemplateId(hogFunction.template_id)
            await deleteWithUndo({
                endpoint: `projects/${values.currentProjectId}/hog_functions`,
                object: {
                    id: hogFunction.id,
                    name: hogFunction.name,
                },
                callback: (undo) => {
                    if (undo) {
                        actions.loadExistingHogFunctions()
                        return
                    }
                    // Skip on undo and on unrecognized templates so this only counts confirmed deletes with a known type.
                    if (type) {
                        posthog.capture('insight alert destination deleted', {
                            alert_id: props.alertId,
                            type,
                        })
                    }
                },
            })
        },

        createPendingHogFunctions: async ({ alertId, alertName }) => {
            const pending = values.pendingNotifications
            if (pending.length === 0) {
                return
            }

            const results = await Promise.allSettled(
                pending.map((notification) => {
                    const payload = buildHogFunctionPayload(alertId, alertName, notification)
                    return api.hogFunctions.create(payload)
                })
            )

            // No `alert created`/`alert updated` event captures destination type, so this is emitted per created destination instead.
            results.forEach((result, i) => {
                if (result.status === 'fulfilled') {
                    posthog.capture('insight alert destination created', {
                        alert_id: alertId,
                        type: pending[i].type,
                    })
                }
            })

            const failures = results
                .map((result, i) => ({ result, notification: pending[i] }))
                .filter(
                    (item): item is { result: PromiseRejectedResult; notification: PendingAlertNotification } =>
                        item.result.status === 'rejected'
                )

            if (failures.length > 0) {
                const labelForType = (type: AlertNotificationType): string =>
                    ALERT_NOTIFICATION_TYPE_OPTIONS.find((option) => option.value === type)?.label ?? type
                failures.forEach(({ result, notification }) => {
                    console.error(
                        `Failed to create ${labelForType(notification.type)} alert notification`,
                        result.reason
                    )
                })
                const failedTypes = Array.from(
                    new Set(failures.map(({ notification }) => labelForType(notification.type)))
                )
                lemonToast.error(
                    `Alert saved, but failed to create: ${failedTypes.join(', ')}. Reopen the alert to add them again.`
                )
                actions.setPendingNotifications(failures.map(({ notification }) => notification))
            } else {
                if (results.length > 0) {
                    lemonToast.success(`${results.length} notification destination(s) created.`)
                }
                actions.clearPendingNotifications()
            }

            actions.loadExistingHogFunctions()
        },
        sendTestDeliverySuccess: ({ testDeliveryResult }) => {
            const destinationCount = testDeliveryResult.destination_count
            const emailCount = testDeliveryResult.email_recipient_count
            const deliveryTargets: string[] = []
            if (emailCount > 0) {
                deliveryTargets.push(`${emailCount} email ${emailCount === 1 ? 'recipient' : 'recipients'}`)
            }
            if (destinationCount > 0) {
                deliveryTargets.push(`${destinationCount} ${destinationCount === 1 ? 'destination' : 'destinations'}`)
            }
            if (testDeliveryResult.failed_delivery_channels.length > 0) {
                lemonToast.warning(
                    `Test delivery started for ${deliveryTargets.join(' and ')}, but failed for ${testDeliveryResult.failed_delivery_channels.join(' and ')}.`
                )
                return
            }
            lemonToast.success(`Test delivery started for ${deliveryTargets.join(' and ')}.`)
        },
    })),

    afterMount(({ actions, props }) => {
        if (props.alertId && props.loadDestinations !== false) {
            actions.loadExistingHogFunctions()
        }
    }),
])