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

import api from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { isEmail } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

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

import {
    senderFrom,
    senderIntegrationFor,
} from '../../../../frontend/src/scenes/hog-functions/email-templater/emailSenderFields'
import { findTestSendSkipReason } from '../Workflows/hogflows/steps/testSendSkipReason'
import { HogflowTestResult } from '../Workflows/hogflows/steps/types'
import { createExampleEvent } from '../Workflows/hogflows/testEventFactory'
import type { HogFlow, HogFlowAction, HogFlowEdge } from '../Workflows/hogflows/types'
import { EXIT_NODE_ID, NEW_WORKFLOW, TRIGGER_NODE_ID } from '../Workflows/workflowLogic'
import { MessageTemplateLogicProps, messageTemplateLogic } from './messageTemplateLogic'
import { MessageTemplate } from './types'

// Fixed id for the single email action in the synthetic test flow - referenced by the edges
// below and passed as `current_action_id` so the CDP worker executes just this one node.
const TEST_EMAIL_ACTION_ID = 'send_test_email'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageTemplateTestSendLogicValues {
    integrations: IntegrationType[] | null // integrationsLogic
    integrationsLoading: boolean // integrationsLogic
    template: MessageTemplate // messageTemplateLogic
    currentTeamId: number | null // teamLogic
    user: UserType | null // userLogic
    emailIntegrations: IntegrationType[]
    isModalOpen: boolean
    recipientEmail: string
    sendDisabledReason: string | undefined
    senderIntegrationId: number | null
    senderIntegrationIdOverride: number | null
    testSendResult: HogflowTestResult | null
    testSendResultLoading: boolean
    testSendSkipReason: string | undefined
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageTemplateTestSendLogicActions {
    clearTestSendResult: () => {
        value: true
    }
    clearTestSendResultFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    clearTestSendResultSuccess: (
        testSendResult: null,
        payload?: {
            value: true
        }
    ) => {
        testSendResult: null
        payload?: {
            value: true
        }
    }
    sendTestEmail: () => any
    sendTestEmailFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    sendTestEmailSuccess: (
        testSendResult: HogflowTestResult,
        payload?: any
    ) => {
        testSendResult: HogflowTestResult
        payload?: any
    }
    setModalOpen: (open: boolean) => {
        open: boolean
    }
    setRecipientEmail: (email: string) => {
        email: string
    }
    setSenderIntegrationId: (id: number | null) => {
        id: number | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageTemplateTestSendLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        emailIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[]
        senderIntegrationId: (
            senderIntegrationIdOverride: number | null,
            emailIntegrations: IntegrationType[],
            template: MessageTemplate
        ) => number | null
        testSendSkipReason: (testSendResult: HogflowTestResult | null) => string | undefined
        sendDisabledReason: (
            template: MessageTemplate,
            recipientEmail: string,
            senderIntegrationId: number | null
        ) => string | undefined
    }
}

export type messageTemplateTestSendLogicType = MakeLogicType<
    messageTemplateTestSendLogicValues,
    messageTemplateTestSendLogicActions,
    MessageTemplateLogicProps,
    messageTemplateTestSendLogicMeta
>

export const messageTemplateTestSendLogic = kea<messageTemplateTestSendLogicType>([
    path((key) => ['products', 'workflows', 'frontend', 'TemplateLibrary', 'messageTemplateTestSendLogic', key]),
    props({} as MessageTemplateLogicProps),
    key(({ id }) => id ?? 'new'),
    connect((props: MessageTemplateLogicProps) => ({
        values: [
            messageTemplateLogic(props),
            ['template'],
            userLogic,
            ['user'],
            teamLogic,
            ['currentTeamId'],
            integrationsLogic,
            ['integrations', 'integrationsLoading'],
        ],
    })),
    actions({
        setModalOpen: (open: boolean) => ({ open }),
        setRecipientEmail: (email: string) => ({ email }),
        setSenderIntegrationId: (id: number | null) => ({ id }),
        clearTestSendResult: true,
    }),
    reducers({
        isModalOpen: [false, { setModalOpen: (_, { open }) => open }],
        recipientEmail: ['', { setRecipientEmail: (_, { email }) => email }],
        senderIntegrationIdOverride: [null as number | null, { setSenderIntegrationId: (_, { id }) => id }],
    }),
    loaders(({ values }) => ({
        testSendResult: [
            null as HogflowTestResult | null,
            {
                clearTestSendResult: () => null,
                sendTestEmail: async (): Promise<HogflowTestResult> => {
                    const { template, recipientEmail, senderIntegrationId, currentTeamId } = values

                    const emailAction: HogFlowAction = {
                        id: TEST_EMAIL_ACTION_ID,
                        type: 'function_email',
                        name: 'Send test email',
                        description: '',
                        created_at: 0,
                        updated_at: 0,
                        config: {
                            template_id: 'template-email',
                            inputs: {
                                email: {
                                    value: {
                                        ...template.content.email,
                                        // A test send has exactly one visible recipient - never carry over a
                                        // cc/bcc that happened to be on the copied source content.
                                        cc: '',
                                        bcc: '',
                                        // A custom name and address carry over, so the test shows what a send shows.
                                        from: {
                                            ...senderFrom(template.content.email ?? {}),
                                            integrationIds: undefined,
                                            integrationId: senderIntegrationId ?? undefined,
                                        },
                                        to: { email: recipientEmail, name: '' },
                                    },
                                    templating: template.content.templating === 'hog' ? 'hog' : 'liquid',
                                },
                            },
                        },
                    }

                    const edges: HogFlowEdge[] = [
                        { from: TRIGGER_NODE_ID, to: TEST_EMAIL_ACTION_ID, type: 'continue' },
                        { from: TEST_EMAIL_ACTION_ID, to: EXIT_NODE_ID, type: 'continue' },
                    ]

                    const configuration: HogFlow = {
                        ...NEW_WORKFLOW,
                        team_id: currentTeamId ?? NEW_WORKFLOW.team_id,
                        name: template.name || 'Test email',
                        actions: [NEW_WORKFLOW.actions[0], emailAction, NEW_WORKFLOW.actions[1]],
                        edges,
                    }

                    return await api.hogFlows.createTestInvocation('new', {
                        configuration,
                        globals: createExampleEvent(
                            currentTeamId ?? undefined,
                            configuration.name,
                            '$pageview',
                            recipientEmail
                        ),
                        mock_async_functions: false,
                        current_action_id: TEST_EMAIL_ACTION_ID,
                    })
                },
            },
        ],
    })),
    selectors({
        emailIntegrations: [
            (s) => [s.integrations],
            (integrations: IntegrationType[] | null): IntegrationType[] =>
                integrations?.filter(
                    (integration) => integration.kind === 'email' && integration.config?.verified === true
                ) ?? [],
        ],
        senderIntegrationId: [
            (s) => [s.senderIntegrationIdOverride, s.emailIntegrations, s.template],
            (override: number | null, emailIntegrations: IntegrationType[], template: MessageTemplate): number | null =>
                override ??
                senderIntegrationFor(template.content.email ?? {}, emailIntegrations)?.id ??
                emailIntegrations[0]?.id ??
                null,
        ],
        testSendSkipReason: [
            (s) => [s.testSendResult],
            (testSendResult: HogflowTestResult | null): string | undefined =>
                findTestSendSkipReason(testSendResult) ??
                (testSendResult?.status === 'skipped'
                    ? testSendResult.logs?.map((log) => log.message).join(' ') ||
                      'The send was skipped for this recipient.'
                    : undefined),
        ],
        sendDisabledReason: [
            (s) => [s.template, s.recipientEmail, s.senderIntegrationId],
            (
                template: MessageTemplate,
                recipientEmail: string,
                senderIntegrationId: number | null
            ): string | undefined => {
                if (!template.content.email?.subject) {
                    return 'Add a subject first'
                }
                if (!template.content.email.text && !template.content.email.html) {
                    return 'Add email content first'
                }
                if (!recipientEmail || !isEmail(recipientEmail)) {
                    return 'Enter a valid email address'
                }
                if (!senderIntegrationId) {
                    return 'Connect an email sender first'
                }
                return undefined
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        setModalOpen: ({ open }) => {
            if (!open) {
                return
            }
            actions.clearTestSendResult()
            if (!values.recipientEmail && values.user?.email) {
                actions.setRecipientEmail(values.user.email)
            }
        },
        sendTestEmailSuccess: ({ testSendResult }) => {
            if (values.testSendSkipReason) {
                lemonToast.warning('Test email skipped, see details below')
            } else if (testSendResult.status === 'success') {
                lemonToast.success(`Test email sent to ${values.recipientEmail}`)
                actions.setModalOpen(false)
                actions.clearTestSendResult()
            } else {
                lemonToast.error('Failed to send test email')
            }
        },
        sendTestEmailFailure: () => {
            lemonToast.error('Failed to send test email')
        },
    })),
])