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.

11.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, path, reducers } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { router } from 'kea-router'

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

import api from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { errorTrackingIssueLinkHogTemplate } from 'scenes/hog-functions/sub-templates/sub-templates'

import { HogFunctionConfigurationType } from '~/types'

import type { IntegrationType } from '../../../types'
import { onboardingLogic } from '../onboardingLogic'

export type ErrorTrackingAlertIntegrationType = 'slack' | 'microsoft-teams' | 'discord'

const DEFAULT_HOG_FUNCTION_CONFIGURATION: Partial<HogFunctionConfigurationType> = {
    type: 'internal_destination',
    filters: { events: [{ id: '$error_tracking_issue_created', type: 'events' }] },
    enabled: true,
    masking: null,
}

const DEFAULT_SLACK_INPUTS: Record<string, any> = {
    icon_emoji: { value: ':hedgehog:' },
    username: { value: 'PostHog' },
    blocks: {
        value: [
            { type: 'header', text: { type: 'plain_text', text: '🔴 {event.properties.name}' } },
            { type: 'section', text: { type: 'plain_text', text: 'New issue created' } },
            {
                type: 'section',
                text: { type: 'mrkdwn', text: '```{substring(event.properties.description, 1, 150)}```' },
            },
            {
                type: 'context',
                elements: [
                    { type: 'plain_text', text: 'Status: {event.properties.status}' },
                    { type: 'mrkdwn', text: 'Project: <{project.url}|{project.name}>' },
                    {
                        type: 'mrkdwn',
                        text: 'Alert: <{source.url}|{source.name}>',
                    },
                ],
            },
            { type: 'divider' },
            {
                type: 'actions',
                elements: [
                    {
                        url: errorTrackingIssueLinkHogTemplate('slack'),
                        text: { text: 'View Issue', type: 'plain_text' },
                        type: 'button',
                    },
                ],
            },
        ],
    },
    text: { value: 'New issue created: {event.properties.name}' },
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface onboardingErrorTrackingAlertsLogicValues {
    slackAvailable: boolean | undefined // integrationsLogic
    slackIntegrations: IntegrationType[] | undefined // integrationsLogic
    connectionConfig: {
        discordWebhookUrl: string | undefined
        microsoftTeamsWebhookUrl: string | undefined
        slackChannelId: string | undefined
        slackWorkspaceId: number | undefined
    }
    connectionConfigAllErrors: Record<string, any>
    connectionConfigChanged: boolean
    connectionConfigErrors: DeepPartialMap<
        {
            discordWebhookUrl: string | undefined
            microsoftTeamsWebhookUrl: string | undefined
            slackChannelId: string | undefined
            slackWorkspaceId: number | undefined
        },
        ValidationErrorType
    >
    connectionConfigHasErrors: boolean
    connectionConfigManualErrors: Record<string, any>
    connectionConfigTouched: boolean
    connectionConfigTouches: Record<string, boolean>
    connectionConfigValidationErrors: DeepPartialMap<
        {
            discordWebhookUrl: string | undefined
            microsoftTeamsWebhookUrl: string | undefined
            slackChannelId: string | undefined
            slackWorkspaceId: number | undefined
        },
        ValidationErrorType
    >
    integration: ErrorTrackingAlertIntegrationType | null
    isConnectionConfigSubmitting: boolean
    isConnectionConfigValid: boolean
    showConnectionConfigErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface onboardingErrorTrackingAlertsLogicActions {
    goToNextStep: () => {
        value: true
    } // onboardingLogic
    resetConnectionConfig: (values?: {
        discordWebhookUrl: string | undefined
        microsoftTeamsWebhookUrl: string | undefined
        slackChannelId: string | undefined
        slackWorkspaceId: number | undefined
    }) => {
        values?: {
            discordWebhookUrl: string | undefined
            microsoftTeamsWebhookUrl: string | undefined
            slackChannelId: string | undefined
            slackWorkspaceId: number | undefined
        }
    }
    setConnectionConfigManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setConnectionConfigValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setConnectionConfigValues: (
        values: DeepPartial<{
            discordWebhookUrl: string | undefined
            microsoftTeamsWebhookUrl: string | undefined
            slackChannelId: string | undefined
            slackWorkspaceId: number | undefined
        }>
    ) => {
        values: DeepPartial<{
            discordWebhookUrl: string | undefined
            microsoftTeamsWebhookUrl: string | undefined
            slackChannelId: string | undefined
            slackWorkspaceId: number | undefined
        }>
    }
    setIntegration: (integration: ErrorTrackingAlertIntegrationType | null) => {
        integration: ErrorTrackingAlertIntegrationType | null
    }
    submitConnectionConfig: () => {
        value: boolean
    }
    submitConnectionConfigFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitConnectionConfigRequest: (connectionConfig: {
        discordWebhookUrl: string | undefined
        microsoftTeamsWebhookUrl: string | undefined
        slackChannelId: string | undefined
        slackWorkspaceId: number | undefined
    }) => {
        connectionConfig: {
            discordWebhookUrl: string | undefined
            microsoftTeamsWebhookUrl: string | undefined
            slackChannelId: string | undefined
            slackWorkspaceId: number | undefined
        }
    }
    submitConnectionConfigSuccess: (connectionConfig: {
        discordWebhookUrl: string | undefined
        microsoftTeamsWebhookUrl: string | undefined
        slackChannelId: string | undefined
        slackWorkspaceId: number | undefined
    }) => {
        connectionConfig: {
            discordWebhookUrl: string | undefined
            microsoftTeamsWebhookUrl: string | undefined
            slackChannelId: string | undefined
            slackWorkspaceId: number | undefined
        }
    }
    touchConnectionConfigField: (key: string) => {
        key: string
    }
}

export type onboardingErrorTrackingAlertsLogicType = MakeLogicType<
    onboardingErrorTrackingAlertsLogicValues,
    onboardingErrorTrackingAlertsLogicActions
>

export const onboardingErrorTrackingAlertsLogic = kea<onboardingErrorTrackingAlertsLogicType>([
    path(['scenes', 'onboarding', 'error-tracking', 'onboardingErrorTrackingAlertsLogic']),
    connect(() => ({
        values: [integrationsLogic, ['slackIntegrations', 'slackAvailable']],
        actions: [onboardingLogic, ['goToNextStep']],
    })),
    actions({
        setIntegration: (integration: ErrorTrackingAlertIntegrationType | null) => ({ integration }),
    }),
    reducers({
        integration: [
            null as ErrorTrackingAlertIntegrationType | null,
            {
                setIntegration: (_, { integration }) => integration,
            },
        ],
    }),
    forms(({ values, actions }) => ({
        connectionConfig: {
            defaults: {
                discordWebhookUrl: undefined as string | undefined,
                microsoftTeamsWebhookUrl: undefined as string | undefined,
                slackWorkspaceId: undefined as number | undefined,
                slackChannelId: undefined as string | undefined,
            },

            errors: ({ discordWebhookUrl, microsoftTeamsWebhookUrl, slackChannelId }) => {
                return {
                    discordWebhookUrl:
                        values.integration === 'discord' && !discordWebhookUrl
                            ? 'Please enter a Discord webhook URL'
                            : undefined,
                    microsoftTeamsWebhookUrl:
                        values.integration === 'microsoft-teams' && !microsoftTeamsWebhookUrl
                            ? 'Please enter a Microsoft Teams webhook URL'
                            : undefined,
                    slackChannelId:
                        values.integration === 'slack' && !slackChannelId ? 'Please choose a Slack channel' : undefined,
                }
            },

            submit: async (formValues) => {
                const configuration = {
                    ...DEFAULT_HOG_FUNCTION_CONFIGURATION,
                    template_id: `template-${values.integration}`,
                }

                if (values.integration === 'microsoft-teams') {
                    configuration.inputs = {
                        webhookUrl: { value: formValues.microsoftTeamsWebhookUrl },
                        text: {
                            value: `**🔴 {event.properties.name} created:** {event.properties.description} (View in [PostHog](${errorTrackingIssueLinkHogTemplate(
                                'microsoft_teams'
                            )}))`,
                        },
                    }
                } else if (values.integration === 'discord') {
                    configuration.inputs = {
                        webhookUrl: { value: formValues.discordWebhookUrl },
                        content: {
                            value: `**🔴 {event.properties.name} created:** {event.properties.description}\n\n[View in PostHog](${errorTrackingIssueLinkHogTemplate(
                                'discord'
                            )})`,
                        },
                    }
                } else if (values.integration === 'slack') {
                    configuration.inputs = {
                        ...DEFAULT_SLACK_INPUTS,
                        slack_workspace: { value: formValues.slackWorkspaceId },
                        channel: { value: formValues.slackChannelId },
                    }
                }

                try {
                    await api.hogFunctions.create(configuration)
                } catch (e: any) {
                    // Without this, kea-forms swallows the API error and the "Next" button
                    // appears to do nothing
                    lemonToast.error(e?.detail || e?.message || 'Failed to create alert')
                    throw e
                }
                actions.goToNextStep()
            },
        },
    })),
    afterMount(({ actions }) => {
        const { kind, integration_id } = router.values.searchParams

        if (kind && kind === 'slack_callback') {
            actions.setIntegration('slack')

            if (integration_id) {
                actions.setConnectionConfigValue('slackWorkspaceId', integration_id)
            }
        }
    }),
])