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

import api from 'lib/api'
import { Scene } from 'scenes/sceneTypes'

import { ActorsQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { AnyPersonScopeFilter, AnyPropertyFilter } from '~/types'

import {
    BroadcastEmailValue,
    BroadcastPushValue,
    BroadcastWizardLogicProps,
    broadcastWizardLogic,
} from './broadcastWizardLogic'
import { EmailPreviewPerson, renderEmailPreview } from './emailPreview'

const PREVIEW_PERSON_LIMIT = 25

export interface BroadcastPreviewPerson extends EmailPreviewPerson {
    displayName: string
}

// The properties column arrives as a JSON string over the query API, but tolerate an object in case
// a caller hands one over already parsed.
function parseProperties(raw: unknown): Record<string, any> {
    if (raw && typeof raw === 'object') {
        return raw as Record<string, any>
    }
    if (typeof raw === 'string') {
        try {
            return JSON.parse(raw)
        } catch {
            return {}
        }
    }
    return {}
}

function parsePerson(row: any[]): BroadcastPreviewPerson {
    const properties = parseProperties(row[2])
    return {
        id: String(row[0]),
        displayName: row[1]?.display_name || properties.email || String(row[0]),
        properties,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPreviewLogicValues {
    audienceProperties: AnyPropertyFilter[] // broadcastWizardLogic
    email: BroadcastEmailValue // broadcastWizardLogic
    push: BroadcastPushValue // broadcastWizardLogic
    persons: BroadcastPreviewPerson[]
    personsFailed: boolean
    personsLoading: boolean
    previewHtml: string
    previewPerson: BroadcastPreviewPerson | null
    previewPushBody: string
    previewPushTitle: string
    previewSubject: string
    previewText: string
    previewTo: string
    selectedPersonId: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPreviewLogicActions {
    loadPersons: () => any
    loadPersonsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPersonsSuccess: (
        persons: BroadcastPreviewPerson[],
        payload?: any
    ) => {
        persons: BroadcastPreviewPerson[]
        payload?: any
    }
    selectPerson: (personId: string | null) => {
        personId: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPreviewLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        previewPerson: (
            persons: BroadcastPreviewPerson[],
            selectedPersonId: string | null
        ) => BroadcastPreviewPerson | null
        previewSubject: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
        previewHtml: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
        previewText: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
        previewPushTitle: (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null) => string
        previewPushBody: (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null) => string
        previewTo: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
    }
}

export type broadcastPreviewLogicType = MakeLogicType<
    broadcastPreviewLogicValues,
    broadcastPreviewLogicActions,
    BroadcastWizardLogicProps,
    broadcastPreviewLogicMeta
>

export const broadcastPreviewLogic = kea<broadcastPreviewLogicType>([
    path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastPreviewLogic']),
    props({} as BroadcastWizardLogicProps),
    key((props) => props.id),

    connect((props: BroadcastWizardLogicProps) => ({
        values: [broadcastWizardLogic(props), ['audienceProperties', 'email', 'push']],
    })),

    actions({
        selectPerson: (personId: string | null) => ({ personId }),
    }),

    loaders(({ values }) => ({
        persons: [
            [] as BroadcastPreviewPerson[],
            {
                loadPersons: async () => {
                    const query: ActorsQuery = {
                        kind: NodeKind.ActorsQuery,
                        // Attributes the query in the ClickHouse query log. Without it the backend
                        // rejects the query outright when DEBUG is on, so the picker stays empty
                        // for anyone running locally.
                        tags: { productKey: ProductKey.WORKFLOWS, scene: Scene.Broadcast },
                        // The recipients step only offers person-scoped filters, which is all an
                        // actors query accepts.
                        properties: values.audienceProperties as AnyPersonScopeFilter[],
                        select: ['id', 'person_display_name -- Person', 'properties'],
                        limit: PREVIEW_PERSON_LIMIT,
                    }
                    const response = await api.query<ActorsQuery>(query)
                    return (response.results ?? []).map(parsePerson)
                },
            },
        ],
    })),

    reducers({
        selectedPersonId: [
            null as string | null,
            {
                selectPerson: (_, { personId }) => personId,
                // The audience decides who is on offer, so a reload invalidates the old pick.
                loadPersons: () => null,
            },
        ],
        // An empty list and a failed lookup both leave the picker empty, but they mean
        // different things to a sender, so keep them apart.
        personsFailed: [
            false,
            {
                loadPersons: () => false,
                loadPersonsSuccess: () => false,
                loadPersonsFailure: () => true,
            },
        ],
    }),

    selectors({
        previewPerson: [
            (s) => [s.persons, s.selectedPersonId],
            (persons: BroadcastPreviewPerson[], selectedPersonId: string | null): BroadcastPreviewPerson | null =>
                persons.find((person) => person.id === selectedPersonId) ??
                // Default to someone the broadcast can reach. An audience filter that does not mention
                // email can put a person with no email address first, and that person renders every
                // merge tag blank, so the preview reads as broken rather than as an empty value.
                persons.find((person) => !!person.properties.email) ??
                persons[0] ??
                null,
        ],
        previewSubject: [
            (s) => [s.email, s.previewPerson],
            (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>
                renderEmailPreview(email.subject, previewPerson),
        ],
        previewHtml: [
            (s) => [s.email, s.previewPerson],
            (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>
                renderEmailPreview(email.html, previewPerson),
        ],
        // The worker renders liquid in every string of the email input, `text` included, so a
        // text-only broadcast has to preview through the same renderer as the html one.
        previewText: [
            (s) => [s.email, s.previewPerson],
            (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>
                renderEmailPreview(email.text, previewPerson),
        ],
        previewPushTitle: [
            (s) => [s.push, s.previewPerson],
            (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null): string =>
                renderEmailPreview(push.title, previewPerson),
        ],
        previewPushBody: [
            (s) => [s.push, s.previewPerson],
            (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null): string =>
                renderEmailPreview(push.body, previewPerson),
        ],
        previewTo: [
            (s) => [s.email, s.previewPerson],
            (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>
                renderEmailPreview(email.to?.email ?? '', previewPerson),
        ],
    }),

    // Reload on the value rather than on the edit action, so resuming a saved draft loads against
    // the audience it hydrates with instead of the empty one the logic mounted on.
    subscriptions(({ actions }) => ({
        audienceProperties: () => {
            actions.loadPersons()
        },
    })),
])