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.

8.4 KB
Raw Blame
import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'

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

import api, { ApiConfig } from 'lib/api'
import { urls } from 'scenes/urls'

import { conversationsTicketsComposeCreate } from '../../generated/api'
import type { EmailConfigStatus } from '../../scenes/settings/supportSettingsLogic'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface composeTicketLogicValues {
    composingLoading: boolean
    emailConfigId: string
    emailConfigs: EmailConfigStatus[]
    emailConfigsLoading: boolean
    emailSubject: string
    isOpen: boolean
    recipientDistinctId: string
    recipientEmail: string
    senderManuallySelected: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface composeTicketLogicActions {
    closeComposeModal: () => {
        value: true
    }
    loadEmailConfigs: () => any
    loadEmailConfigsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEmailConfigsSuccess: (
        emailConfigs: EmailConfigStatus[],
        payload?: any
    ) => {
        emailConfigs: EmailConfigStatus[]
        payload?: any
    }
    openComposeModal: (prefill?: { distinctId?: string; email?: string }) => {
        prefill:
            | {
                  distinctId?: string | undefined
                  email?: string | undefined
              }
            | undefined
    }
    resetForm: () => {
        value: true
    }
    setEmailConfigId: (
        configId: string,
        isManual?: boolean
    ) => {
        configId: string
        isManual: boolean
    }
    setEmailSubject: (subject: string) => {
        subject: string
    }
    setRecipientDistinctId: (distinctId: string) => {
        distinctId: string
    }
    setRecipientEmail: (email: string) => {
        email: string
    }
    submitCompose: (
        message: string,
        richContent: Record<string, unknown> | null
    ) => {
        message: string
        richContent: Record<string, unknown> | null
    }
    submitComposeFinished: () => {
        value: true
    }
}

export type composeTicketLogicType = MakeLogicType<composeTicketLogicValues, composeTicketLogicActions>

export const composeTicketLogic = kea<composeTicketLogicType>([
    path(['products', 'conversations', 'frontend', 'components', 'ComposeTicket', 'composeTicketLogic']),
    actions({
        openComposeModal: (prefill?: { distinctId?: string; email?: string }) => ({ prefill }),
        closeComposeModal: true,
        setRecipientEmail: (email: string) => ({ email }),
        setRecipientDistinctId: (distinctId: string) => ({ distinctId }),
        setEmailSubject: (subject: string) => ({ subject }),
        setEmailConfigId: (configId: string, isManual: boolean = true) => ({ configId, isManual }),
        resetForm: true,
        submitCompose: (message: string, richContent: Record<string, unknown> | null) => ({ message, richContent }),
        submitComposeFinished: true,
    }),
    reducers({
        isOpen: [
            false,
            {
                openComposeModal: () => true,
                closeComposeModal: () => false,
                resetForm: () => false,
            },
        ],
        recipientEmail: [
            '',
            {
                setRecipientEmail: (_, { email }) => email,
                openComposeModal: () => '',
                resetForm: () => '',
            },
        ],
        recipientDistinctId: [
            '',
            {
                setRecipientDistinctId: (_, { distinctId }) => distinctId,
                openComposeModal: () => '',
                resetForm: () => '',
            },
        ],
        emailSubject: [
            '',
            {
                setEmailSubject: (_, { subject }) => subject,
                openComposeModal: () => '',
                resetForm: () => '',
            },
        ],
        emailConfigId: [
            '',
            {
                setEmailConfigId: (_, { configId }) => configId,
                openComposeModal: () => '',
                resetForm: () => '',
            },
        ],
        senderManuallySelected: [
            false,
            {
                setEmailConfigId: (_, { isManual }) => isManual,
                openComposeModal: () => false,
                resetForm: () => false,
            },
        ],
        composingLoading: [
            false,
            {
                submitCompose: () => true,
                submitComposeFinished: () => false,
                openComposeModal: () => false,
                resetForm: () => false,
            },
        ],
    }),
    loaders({
        emailConfigs: [
            [] as EmailConfigStatus[],
            {
                loadEmailConfigs: async (): Promise<EmailConfigStatus[]> => {
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        const response = await api.get('api/conversations/v1/email/status')
                        return response.configs || []
                    } catch {
                        return []
                    }
                },
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        openComposeModal: ({ prefill }) => {
            if (prefill?.distinctId) {
                actions.setRecipientDistinctId(prefill.distinctId)
            }
            if (prefill?.email) {
                actions.setRecipientEmail(prefill.email)
            }
            actions.loadEmailConfigs()
        },
        loadEmailConfigsSuccess: ({ emailConfigs }) => {
            // Default the "From" address to the team's primary channel (falling back to the first verified one).
            // Skip only when the user picked a sender themselves — a newer response can still re-apply the default,
            // so a stale in-flight request can't lock in an outdated sender.
            if (values.senderManuallySelected) {
                return
            }
            const verified = emailConfigs.filter((c) => c.domain_verified)
            const defaultConfig = verified.find((c) => c.is_default) ?? verified[0]
            if (defaultConfig) {
                actions.setEmailConfigId(defaultConfig.id, false)
            }
        },
        submitCompose: async ({ message, richContent }) => {
            const { recipientEmail, recipientDistinctId, emailSubject, emailConfigId } = values

            if (!message.trim()) {
                lemonToast.error('Message is required.')
                actions.submitComposeFinished()
                return
            }

            if (!recipientEmail) {
                lemonToast.error('Recipient email is required.')
                actions.submitComposeFinished()
                return
            }

            if (!emailConfigId) {
                lemonToast.error('Please select a "From" email address.')
                actions.submitComposeFinished()
                return
            }

            try {
                const result = await conversationsTicketsComposeCreate(String(ApiConfig.getCurrentProjectId()), {
                    message,
                    recipient_email: recipientEmail,
                    email_config_id: emailConfigId,
                    ...(recipientDistinctId ? { recipient_distinct_id: recipientDistinctId } : {}),
                    ...(emailSubject ? { email_subject: emailSubject } : {}),
                    ...(richContent ? { rich_content: richContent } : {}),
                })

                lemonToast.success('Ticket created successfully.')
                actions.resetForm()
                router.actions.push(urls.supportTicketDetail(result.ticket_number))
            } catch (error: unknown) {
                const detail =
                    error && typeof error === 'object' && 'detail' in error
                        ? (error as { detail: string }).detail
                        : 'Failed to create ticket.'
                lemonToast.error(detail)
                actions.submitComposeFinished()
            }
        },
    })),
])