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.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'

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

import { buildUserScopedPersistenceConfig } from 'lib/logic/persistence'
import { objectsEqual } from 'lib/utils/objects'
import { urls } from 'scenes/urls'

import { filterMessageTemplates } from '../TemplateLibrary/filterMessageTemplates'
import { messageTemplatesLogic, saveTemplateTags } from '../TemplateLibrary/messageTemplatesLogic'
import { MessageTemplate } from '../TemplateLibrary/types'

export interface TransactionalEmailsFilters {
    search: string
    createdBy: number | null
    tags: string[]
}

const DEFAULT_FILTERS: TransactionalEmailsFilters = { search: '', createdBy: null, tags: [] }

// The search params actionToUrl writes below. A URL that carries none of them states no filters at all,
// which is different from stating that every filter is off.
const FILTER_URL_PARAMS = ['search', 'created_by', 'tags']

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface transactionalEmailsLogicValues {
    tags: string[] // messageTemplatesLogic
    templatesLoading: boolean // messageTemplatesLogic
    transactionalTemplates: MessageTemplate[] // messageTemplatesLogic
    filteredTransactionalTemplates: MessageTemplate[]
    filters: TransactionalEmailsFilters
    isFiltered: boolean
    savingTagsFor: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface transactionalEmailsLogicActions {
    loadTagsIfNeeded: () => {
        value: true
    } // messageTemplatesLogic
    loadTemplates: () => any // messageTemplatesLogic
    templateTagsSaved: (template: MessageTemplate) => {
        template: MessageTemplate
    } // messageTemplatesLogic
    saveTransactionalTags: (
        template: MessageTemplate,
        tags: string[]
    ) => {
        tags: string[]
        template: MessageTemplate
    }
    setFilters: (filters: Partial<TransactionalEmailsFilters>) => {
        filters: Partial<TransactionalEmailsFilters>
    }
    setFiltersFromUrl: (filters: TransactionalEmailsFilters) => {
        filters: TransactionalEmailsFilters
    }
    transactionalTagsSaved: (templateId: string) => {
        templateId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface transactionalEmailsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        filteredTransactionalTemplates: (
            transactionalTemplates: MessageTemplate[],
            filters: TransactionalEmailsFilters
        ) => MessageTemplate[]
        isFiltered: (filters: TransactionalEmailsFilters) => boolean
    }
}

export type transactionalEmailsLogicType = MakeLogicType<
    transactionalEmailsLogicValues,
    transactionalEmailsLogicActions,
    Record<string, any>,
    transactionalEmailsLogicMeta
>

export const transactionalEmailsLogic = kea<transactionalEmailsLogicType>([
    path(['products', 'workflows', 'frontend', 'Transactional', 'transactionalEmailsLogic']),
    connect(() => ({
        values: [messageTemplatesLogic, ['transactionalTemplates', 'templatesLoading', 'tags']],
        actions: [messageTemplatesLogic, ['loadTagsIfNeeded', 'loadTemplates', 'templateTagsSaved']],
    })),
    actions({
        setFilters: (filters: Partial<TransactionalEmailsFilters>) => ({ filters }),
        setFiltersFromUrl: (filters: TransactionalEmailsFilters) => ({ filters }),
        saveTransactionalTags: (template: MessageTemplate, tags: string[]) => ({ template, tags }),
        transactionalTagsSaved: (templateId: string) => ({ templateId }),
    }),
    reducers(() => ({
        filters: [
            DEFAULT_FILTERS,
            // The list unmounts when an email opens, so the filters are persisted to survive that and be
            // restored when the user comes back to the list. The key carries the user and the team, so
            // another account or another project never reads these filters.
            buildUserScopedPersistenceConfig('transactional_emails_list_filters__'),
            {
                setFilters: (state, { filters }) => ({ ...state, ...filters }),
                setFiltersFromUrl: (_, { filters }) => filters,
            },
        ],
        savingTagsFor: [
            null as string | null,
            {
                saveTransactionalTags: (_, { template }) => template.id,
                transactionalTagsSaved: (state, { templateId }) => (state === templateId ? null : state),
            },
        ],
    })),
    selectors({
        filteredTransactionalTemplates: [
            (s) => [s.transactionalTemplates, s.filters],
            (templates: MessageTemplate[], filters: TransactionalEmailsFilters): MessageTemplate[] =>
                filterMessageTemplates(templates, filters),
        ],
        isFiltered: [
            (s) => [s.filters],
            (filters: TransactionalEmailsFilters): boolean => !objectsEqual(filters, DEFAULT_FILTERS),
        ],
    }),
    listeners(({ actions }) => ({
        saveTransactionalTags: async ({ template, tags }) => {
            // The editor builds each payload from the row's tags, so a second edit made while the first
            // is in flight would be built from the stored list and drop the first one. Showing the new
            // tags at once gives that second edit the right starting point.
            actions.templateTagsSaved({ ...template, tags })
            try {
                await saveTagsAfterPause(template, tags)
            } catch (error: any) {
                lemonToast.error(`Couldn't save tags: ${error?.detail || error?.message || 'unknown error'}`)
                // The row is showing tags that were never stored, so the stored ones are read back.
                actions.loadTemplates()
            } finally {
                if (!pendingTagSaves.has(template.id)) {
                    actions.transactionalTagsSaved(template.id)
                }
            }
        },
    })),
    actionToUrl(({ values }) => ({
        setFilters: () => {
            const { search, createdBy, tags } = values.filters
            const searchParams = {
                ...router.values.searchParams,
                search: search || undefined,
                created_by: createdBy ?? undefined,
                tags: tags.length ? tags : undefined,
            }
            return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
        },
    })),
    urlToAction(({ actions, values }) => ({
        [urls.transactional()]: (_, searchParams) => {
            // An in-app link back to the list, such as the breadcrumb out of an email, carries no filter
            // params. Parsing that URL would clear every filter, so the filters held in state are restored
            // and written back into the URL instead.
            if (!FILTER_URL_PARAMS.some((param) => param in searchParams)) {
                if (!objectsEqual(values.filters, DEFAULT_FILTERS)) {
                    actions.setFilters(values.filters)
                }
                return
            }
            const rawTags = searchParams['tags']
            const createdBy = parseInt(String(searchParams['created_by']))
            const parsed: TransactionalEmailsFilters = {
                search: searchParams['search'] ? String(searchParams['search']) : '',
                createdBy: Number.isNaN(createdBy) ? null : createdBy,
                // kea-router parses a JSON array in the URL back into an array.
                tags: Array.isArray(rawTags)
                    ? rawTags.map(String)
                    : typeof rawTags === 'string' && rawTags
                      ? [rawTags]
                      : [],
            }
            if (!objectsEqual(parsed, values.filters)) {
                actions.setFiltersFromUrl(parsed)
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadTagsIfNeeded()
    }),
])

// Tag writes waiting out their pause, keyed by template. They are held here rather than behind a
// listener breakpoint, which would also cancel them when another row is edited or the list unmounts.
const pendingTagSaves = new Map<string, () => void>()

// One write per burst of clicks on a row, so two quick edits become a single save that keeps both tags.
function saveTagsAfterPause(template: MessageTemplate, tags: string[]): Promise<void> {
    pendingTagSaves.get(template.id)?.()
    return new Promise<void>((resolve, reject) => {
        const timer = setTimeout(() => {
            pendingTagSaves.delete(template.id)
            saveTemplateTags(template, tags).then(resolve, reject)
        }, 300)
        pendingTagSaves.set(template.id, () => {
            clearTimeout(timer)
            resolve()
        })
    })
}