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.

19.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 { lemonToast } from 'lib/lemon-ui/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
import { isEmail } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

import { UserType } from '~/types'

import type { HogFlowApi } from '../generated/api.schemas'
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 { BroadcastPreviewPerson, broadcastPreviewLogic } from './broadcastPreviewLogic'
import { BroadcastChannel } from './broadcastsLogic'
import {
    BroadcastEmailSettings,
    BroadcastEmailValue,
    BroadcastPushValue,
    BroadcastWizardLogicProps,
    broadcastWizardLogic,
    findPushInputs,
    pushInputs,
} from './broadcastWizardLogic'

// Fixed id for the single email action in the synthetic test flow. The edges below reference it,
// and it goes over as `current_action_id` so the worker runs just this node.
const TEST_EMAIL_ACTION_ID = 'send_test_email'
const TEST_PUSH_ACTION_ID = 'send_test_push'

// The push worker logs this once per app that took the notification
// (nodejs/src/cdp/services/messaging/push-notification.service.ts).
const PUSH_ACCEPTED_LOG = /accepted by (FCM|APNs)/

/** Why a push test reached no device. A push with no registered device still finishes cleanly. */
export function findPushTestSkipReason(result: HogflowTestResult | null): string | undefined {
    if (result?.status !== 'success' || result.logs?.some((log) => PUSH_ACCEPTED_LOG.test(log.message ?? ''))) {
        return undefined
    }
    const warnings = result.logs
        ?.filter((log) => String(log.level).toLowerCase().startsWith('warn'))
        .map((log) => log.message)
    return warnings?.length
        ? warnings.join(' ')
        : 'No device took the notification. Check that this person has push turned on in your app.'
}

// Per-app delivery errors from the same worker. A missing token on one app is not one of them.
const PUSH_APP_FAILURE_LOG = /(FCM|APNs): /

export function findPushTestPartialFailure(result: HogflowTestResult | null): string | undefined {
    if (result?.status !== 'success' || !result.logs?.some((log) => PUSH_ACCEPTED_LOG.test(log.message ?? ''))) {
        return undefined
    }
    const failures = result.logs
        .filter((log) => String(log.level).toLowerCase() === 'error' || PUSH_APP_FAILURE_LOG.test(log.message ?? ''))
        .map((log) => log.message)
    return failures.length ? failures.join(' ') : undefined
}

/** Liquid prints a raw block as typed, so braces in a distinct ID never run as a template. */
export function literalDistinctIdInput(distinctId: string): { value: string; templating: 'liquid' } {
    return { value: `{% raw %}${distinctId}{% endraw %}`, templating: 'liquid' }
}

type TestedContent = BroadcastEmailValue | BroadcastPushValue

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastTestSendLogicValues {
    previewPerson: BroadcastPreviewPerson | null // broadcastPreviewLogic
    broadcast: HogFlowApi | null // broadcastWizardLogic
    channel: BroadcastChannel // broadcastWizardLogic
    email: BroadcastEmailValue // broadcastWizardLogic
    emailSettings: BroadcastEmailSettings // broadcastWizardLogic
    name: string // broadcastWizardLogic
    push: BroadcastPushValue // broadcastWizardLogic
    currentTeamId: number | null // teamLogic
    user: UserType | null // userLogic
    isModalOpen: boolean
    lastTestSent: {
        content: TestedContent
        to: string
    } | null
    lastTestSentTo: string | null
    recipientDistinctId: string
    recipientEmail: string
    sendDisabledReason: string | undefined
    testSendPartialFailure: string | undefined
    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 broadcastTestSendLogicActions {
    clearTestSendResult: () => {
        value: true
    }
    clearTestSendResultFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    clearTestSendResultSuccess: (
        testSendResult: null,
        payload?: {
            value: true
        }
    ) => {
        testSendResult: null
        payload?: {
            value: true
        }
    }
    markTestSent: (
        to: string,
        content: TestedContent
    ) => {
        content: TestedContent
        to: string
    }
    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
    }
    setRecipientDistinctId: (distinctId: string) => {
        distinctId: string
    }
    setRecipientEmail: (email: string) => {
        email: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastTestSendLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        lastTestSentTo: (
            lastTestSent: {
                content: TestedContent
                to: string
            } | null,
            email: BroadcastEmailValue,
            push: BroadcastPushValue,
            channel: BroadcastChannel
        ) => string | null
        testSendPartialFailure: (
            testSendResult: HogflowTestResult | null,
            channel: BroadcastChannel
        ) => string | undefined
        testSendSkipReason: (testSendResult: HogflowTestResult | null, channel: BroadcastChannel) => string | undefined
        sendDisabledReason: (
            email: BroadcastEmailValue,
            recipientEmail: string,
            channel: BroadcastChannel,
            push: BroadcastPushValue,
            recipientDistinctId: string
        ) => string | undefined
    }
}

export type broadcastTestSendLogicType = MakeLogicType<
    broadcastTestSendLogicValues,
    broadcastTestSendLogicActions,
    BroadcastWizardLogicProps,
    broadcastTestSendLogicMeta
>

/**
 * Sends one real email to an address the user names, so they can read the broadcast in an inbox
 * before it reaches the audience. The send runs the same email step the broadcast will, through a
 * throwaway flow that exists only for this invocation.
 */
export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
    path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastTestSendLogic']),
    props({} as BroadcastWizardLogicProps),
    key((props) => props.id),

    connect((props: BroadcastWizardLogicProps) => ({
        values: [
            broadcastWizardLogic(props),
            ['broadcast', 'email', 'emailSettings', 'name', 'channel', 'push'],
            broadcastPreviewLogic(props),
            ['previewPerson'],
            teamLogic,
            ['currentTeamId'],
            userLogic,
            ['user'],
        ],
    })),

    actions({
        setModalOpen: (open: boolean) => ({ open }),
        setRecipientEmail: (email: string) => ({ email }),
        setRecipientDistinctId: (distinctId: string) => ({ distinctId }),
        clearTestSendResult: true,
        markTestSent: (to: string, content: TestedContent) => ({ to, content }),
    }),

    reducers({
        isModalOpen: [false, { setModalOpen: (_, { open }) => open }],
        recipientEmail: ['', { setRecipientEmail: (_, { email }) => email }],
        recipientDistinctId: ['', { setRecipientDistinctId: (_, { distinctId }) => distinctId }],
        lastTestSent: [
            null as { to: string; content: TestedContent } | null,
            { markTestSent: (_, { to, content }) => ({ to, content }) },
        ],
    }),

    loaders(({ values, cache }) => ({
        testSendResult: [
            null as HogflowTestResult | null,
            {
                clearTestSendResult: () => null,
                sendTestEmail: async (): Promise<HogflowTestResult> => {
                    const { broadcast, email, emailSettings, name, previewPerson, recipientEmail, currentTeamId } =
                        values
                    if (values.channel === 'push') {
                        return await sendTestPush(values, cache)
                    }
                    // The recipient field stays editable while the send runs, so remember what this send used.
                    cache.pendingTest = { to: recipientEmail, content: email }

                    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',
                            // The test shows the links as the audience gets them.
                            utm_tags_enabled: emailSettings.utmTagsEnabled,
                            // The default content tag is the email step's name, so the test uses the real step's name.
                            utm_params: {
                                utm_content:
                                    broadcast?.actions?.find((action) => action.type === 'function_email')?.name ??
                                    'Send email',
                                ...emailSettings.utmParams,
                            },
                            inputs: {
                                email: {
                                    value: {
                                        ...email,
                                        // One visible recipient on a test, whatever the broadcast carries.
                                        cc: '',
                                        bcc: '',
                                        to: { email: recipientEmail, name: '' },
                                    },
                                    templating: '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: name || 'Test broadcast',
                        actions: [NEW_WORKFLOW.actions[0], emailAction, NEW_WORKFLOW.actions[1]],
                        edges,
                    }

                    const globals = createExampleEvent(
                        currentTeamId ?? undefined,
                        configuration.name,
                        '$pageview',
                        recipientEmail
                    )
                    if (previewPerson) {
                        // Render against the person the preview is showing, so the test email that
                        // lands is the one that person would have received.
                        globals.person = {
                            id: previewPerson.id,
                            properties: previewPerson.properties,
                            name: previewPerson.displayName,
                            url: globals.person?.url ?? '',
                        }
                    }

                    return await api.hogFlows.createTestInvocation('new', {
                        configuration,
                        globals,
                        // A test send is a real send. Mocking it would defeat the point.
                        mock_async_functions: false,
                        current_action_id: TEST_EMAIL_ACTION_ID,
                    })
                },
            },
        ],
    })),

    selectors({
        // Only vouches for the email as it was tested. Any later change, typed or from another editor, clears it.
        lastTestSentTo: [
            (s) => [s.lastTestSent, s.email, s.push, s.channel],
            (
                lastTestSent: { to: string; content: TestedContent } | null,
                email: BroadcastEmailValue,
                push: BroadcastPushValue,
                channel: BroadcastChannel
            ): string | null =>
                lastTestSent && objectsEqual(lastTestSent.content, channel === 'push' ? push : email)
                    ? lastTestSent.to
                    : null,
        ],
        testSendPartialFailure: [
            (s) => [s.testSendResult, s.channel],
            (testSendResult: HogflowTestResult | null, channel: BroadcastChannel): string | undefined =>
                channel === 'push' ? findPushTestPartialFailure(testSendResult) : undefined,
        ],
        testSendSkipReason: [
            (s) => [s.testSendResult, s.channel],
            (testSendResult: HogflowTestResult | null, channel: BroadcastChannel): string | undefined =>
                channel === 'push' ? findPushTestSkipReason(testSendResult) : findTestSendSkipReason(testSendResult),
        ],
        sendDisabledReason: [
            (s) => [s.email, s.recipientEmail, s.channel, s.push, s.recipientDistinctId],
            (
                email: BroadcastEmailValue,
                recipientEmail: string,
                channel: BroadcastChannel,
                push: BroadcastPushValue,
                recipientDistinctId: string
            ): string | undefined => {
                if (channel === 'push') {
                    if (push.channels.length === 0) {
                        return 'Choose a push channel first'
                    }
                    if (!push.title.trim()) {
                        return 'Add a notification title first'
                    }
                    if (recipientDistinctId.includes('{% endraw')) {
                        return 'This distinct ID contains text that cannot be sent'
                    }
                    return recipientDistinctId.trim() ? undefined : 'Enter a distinct ID'
                }
                if (!email.from?.integrationId) {
                    return 'Choose an email sender first'
                }
                if (!email.subject) {
                    return 'Add a subject first'
                }
                if (!email.html && !email.text) {
                    return 'Add email content first'
                }
                if (!recipientEmail || !isEmail(recipientEmail)) {
                    return 'Enter a valid email address'
                }
                return undefined
            },
        ],
    }),

    listeners(({ actions, values, cache }) => ({
        setModalOpen: ({ open }) => {
            // A stale result from a previous attempt must not greet the next one.
            actions.clearTestSendResult()
            if (open && !values.recipientEmail && values.user?.email) {
                actions.setRecipientEmail(values.user.email)
            }
            if (open && !values.recipientDistinctId && values.user?.distinct_id) {
                actions.setRecipientDistinctId(values.user.distinct_id)
            }
        },
        sendTestEmailSuccess: ({ testSendResult }) => {
            // A declined send finishes the step cleanly, so check the reason before the status.
            if (values.testSendSkipReason) {
                lemonToast.warning('Nothing was sent, see why below')
            } else if (values.testSendPartialFailure) {
                lemonToast.warning('Sent through some apps only, see the errors below')
                if (cache.pendingTest) {
                    actions.markTestSent(cache.pendingTest.to, cache.pendingTest.content)
                }
            } else if (testSendResult?.status === 'success') {
                const to = cache.pendingTest?.to ?? values.recipientEmail
                lemonToast.success(
                    values.channel === 'push' ? `Test notification sent to ${to}'s devices` : `Test email sent to ${to}`
                )
                if (cache.pendingTest) {
                    actions.markTestSent(cache.pendingTest.to, cache.pendingTest.content)
                }
                actions.setModalOpen(false)
            } else if (testSendResult?.status === 'skipped') {
                lemonToast.warning(
                    `The ${values.channel === 'push' ? 'push' : 'email'} step was skipped, so nothing was sent`
                )
            } else {
                lemonToast.error(`Could not send the test ${values.channel === 'push' ? 'notification' : 'email'}`)
            }
        },
        sendTestEmailFailure: () => {
            lemonToast.error(`Could not send the test ${values.channel === 'push' ? 'notification' : 'email'}`)
        },
    })),
])

/** Runs the push step once against one person, so the sender sees it on their own phone first. */
async function sendTestPush(
    values: broadcastTestSendLogicType['values'],
    cache: Record<string, any>
): Promise<HogflowTestResult> {
    const { push, name, currentTeamId } = values
    const distinctId = values.recipientDistinctId.trim()
    cache.pendingTest = { to: distinctId, content: push }
    const pushAction: HogFlowAction = {
        id: TEST_PUSH_ACTION_ID,
        type: 'function_push',
        name: 'Send test push',
        description: '',
        created_at: 0,
        updated_at: 0,
        config: {
            template_id: 'template-native-push',
            inputs: {
                ...pushInputs(push, findPushInputs(values.broadcast)),
                // Not the example event's distinct id, so the worker looks up this person's own devices.
                distinctId: literalDistinctIdInput(distinctId),
            },
        },
    } as HogFlowAction
    const configuration: HogFlow = {
        ...NEW_WORKFLOW,
        team_id: currentTeamId ?? NEW_WORKFLOW.team_id,
        name: name || 'Test broadcast',
        actions: [NEW_WORKFLOW.actions[0], pushAction, NEW_WORKFLOW.actions[1]],
        edges: [
            { from: TRIGGER_NODE_ID, to: TEST_PUSH_ACTION_ID, type: 'continue' },
            { from: TEST_PUSH_ACTION_ID, to: EXIT_NODE_ID, type: 'continue' },
        ],
    }
    const globals = createExampleEvent(currentTeamId ?? undefined, configuration.name, '$pageview')
    if (values.previewPerson) {
        // Variables render as they do in the preview.
        globals.person = {
            id: values.previewPerson.id,
            properties: values.previewPerson.properties,
            name: values.previewPerson.displayName,
            url: globals.person?.url ?? '',
        }
    }
    // nosemgrep: prefer-codegen-api-namespaced-workflows -- The generated hogFlowsInvocationsCreate returns void, and this caller needs the test result.
    return await api.hogFlows.createTestInvocation('new', {
        configuration,
        globals,
        mock_async_functions: false,
        current_action_id: TEST_PUSH_ACTION_ID,
    })
}