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.

feat(workflows): tag transactional emails and filter the list (#124807)

Meikel Ratz82b1ee599a8d
diff --git a/products/workflows/frontend/Transactional/TransactionalEmailsTable.tsx b/products/workflows/frontend/Transactional/TransactionalEmailsTable.tsx
index 45e2b3dbe671..44b0d9e0bbfd 100644
--- a/products/workflows/frontend/Transactional/TransactionalEmailsTable.tsx
+++ b/products/workflows/frontend/Transactional/TransactionalEmailsTable.tsx
@@ -1,25 +1,41 @@
-import { useMountedLogic, useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { IconLock } from '@posthog/icons'
-import { LemonTag, Link } from '@posthog/lemon-ui'
+import { LemonInput, LemonTag, Link } from '@posthog/lemon-ui'
import { AppMetricsSparkline } from 'lib/components/AppMetrics/AppMetricsSparkline'
+import { MemberSelect } from 'lib/components/MemberSelect'
+import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
+import { TagSelect } from 'lib/components/TagSelect'
import { LemonTable, LemonTableColumn } from 'lib/lemon-ui/LemonTable'
-import { updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
+import { createdByColumn, updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { urls } from 'scenes/urls'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
-import { messageTemplatesLogic } from '../TemplateLibrary/messageTemplatesLogic'
import { MessageTemplate } from '../TemplateLibrary/types'
+import { transactionalEmailsLogic } from './transactionalEmailsLogic'
export function TransactionalEmailsTable(): JSX.Element {
- useMountedLogic(messageTemplatesLogic)
- const { transactionalTemplates, templatesLoading } = useValues(messageTemplatesLogic)
+ const {
+ transactionalTemplates,
+ filteredTransactionalTemplates,
+ templatesLoading,
+ filters,
+ isFiltered,
+ tags: allTags,
+ savingTagsFor,
+ } = useValues(transactionalEmailsLogic)
+ const { setFilters, saveTransactionalTags } = useActions(transactionalEmailsLogic)
+ // Same check as the "New transactional email" button: changing a template needs Editor access.
+ const editDisabledReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Workflow,
+ AccessControlLevel.Editor
+ )
if (!templatesLoading && transactionalTemplates.length === 0) {
return (
@@ -28,84 +44,136 @@ export function TransactionalEmailsTable(): JSX.Element {
description="Send emails from your code with one API call. Use them for emails a person triggers, like password resets, receipts and sign-in codes. This tab shows how many were sent, delivered and failed in the last 7 days."
docsURL="https://posthog.com/docs/workflows"
action={() => router.actions.push(urls.transactionalNew())}
- disabledReason={
- getAccessControlDisabledReason(AccessControlResourceType.Workflow, AccessControlLevel.Editor) ??
- undefined
- }
+ disabledReason={editDisabledReason ?? undefined}
isEmpty
/>
)
}
return (
- <LemonTable<MessageTemplate>
- dataSource={transactionalTemplates}
- loading={templatesLoading}
- rowKey="id"
- data-attr="transactional-emails-table"
- columns={[
- {
- title: 'Name',
- key: 'name',
- sorter: (a, b) => (a.name || '').localeCompare(b.name || ''),
- render: (_, template) => (
- <LemonTableLink
- to={urls.transactionalTemplate(template.id)}
- title={
- <span className="flex items-center gap-1">
- {template.name || 'Unnamed template'}
- {template.sensitive && (
- <LemonTag type="highlight" size="small" icon={<IconLock />}>
- Sensitive
- </LemonTag>
- )}
- {template.draft_content && (
- <LemonTag type="warning" size="small">
- Unpublished changes
- </LemonTag>
- )}
- </span>
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <LemonInput
+ type="search"
+ placeholder="Search emails"
+ onChange={(search) => setFilters({ search })}
+ value={filters.search}
+ data-attr="transactional-emails-search"
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <b>Created by</b>
+ <MemberSelect
+ value={filters.createdBy}
+ onChange={(user) => setFilters({ createdBy: user?.id ?? null })}
+ />
+ <b className="ml-1">Tags</b>
+ <TagSelect
+ size="small"
+ defaultLabel="Any tags"
+ value={filters.tags}
+ onChange={(tags) => setFilters({ tags })}
+ listDataAttr="transactional-emails-tags-filter-list"
+ />
+ </div>
+ </div>
+ <LemonTable<MessageTemplate>
+ dataSource={filteredTransactionalTemplates}
+ loading={templatesLoading}
+ rowKey="id"
+ data-attr="transactional-emails-table"
+ columns={[
+ {
+ title: 'Name',
+ key: 'name',
+ sorter: (a, b) => (a.name || '').localeCompare(b.name || ''),
+ render: (_, template) => (
+ <LemonTableLink
+ to={urls.transactionalTemplate(template.id)}
+ title={
+ <span className="flex items-center gap-1">
+ {template.name || 'Unnamed template'}
+ {template.sensitive && (
+ <LemonTag type="highlight" size="small" icon={<IconLock />}>
+ Sensitive
+ </LemonTag>
+ )}
+ {template.draft_content && (
+ <LemonTag type="warning" size="small">
+ Unpublished changes
+ </LemonTag>
+ )}
+ </span>
+ }
+ description={template.description}
+ />
+ ),
+ },
+ {
+ title: 'Tags',
+ key: 'tags',
+ width: 220,
+ render: function Render(_, template) {
+ const shown = {
+ tags: [...(template.tags ?? [])],
+ onTagClick: (tag: string) => {
+ if (!filters.tags.includes(tag)) {
+ setFilters({ tags: [...filters.tags, tag] })
+ }
+ },
+ wrap: true,
+ maxVisibleTags: 2,
+ 'data-attr': 'transactional-email-tags',
}
- description={template.description}
- />
- ),
- },
- {
- title: 'Last 7 days',
- width: 0,
- render: (_, template) =>
- template.transactional_hog_flow_id ? (
- <Link to={urls.transactionalTemplate(template.id)}>
- <AppMetricsSparkline
- logicKey={`transactional-${template.id}`}
- // Lines, not stacked bars: a delivered or failed email was also counted as sent.
- type="line"
- metricLabels={{
- email_sent: 'Sent',
- email_delivered: 'Delivered',
- email_failed: 'Failed',
- }}
- metricColors={{
- email_sent: 'blue',
- email_delivered: 'success',
- email_failed: 'danger',
- }}
- forceParams={{
- appSource: 'hog_flow',
- appSourceId: template.transactional_hog_flow_id,
- metricName: ['email_sent', 'email_delivered', 'email_failed'],
- breakdownBy: 'metric_name',
- interval: 'day',
- dateFrom: '-7d',
- }}
+ return editDisabledReason ? (
+ <ObjectTags {...shown} staticOnly />
+ ) : (
+ <ObjectTags
+ {...shown}
+ onChange={(tags) => saveTransactionalTags(template, tags)}
+ saving={savingTagsFor === template.id}
+ tagsAvailable={allTags}
/>
- </Link>
- ) : null,
- },
- { ...(updatedAtColumn() as LemonTableColumn<MessageTemplate, any>), width: 0 },
- ]}
- defaultSorting={{ columnKey: 'updated_at', order: -1 }}
- emptyState="No transactional emails match"
- />
+ )
+ },
+ },
+ {
+ title: 'Last 7 days',
+ width: 0,
+ render: (_, template) =>
+ template.transactional_hog_flow_id ? (
+ <Link to={urls.transactionalTemplate(template.id)}>
+ <AppMetricsSparkline
+ logicKey={`transactional-${template.id}`}
+ // Lines, not stacked bars: a delivered or failed email was also counted as sent.
+ type="line"
+ metricLabels={{
+ email_sent: 'Sent',
+ email_delivered: 'Delivered',
+ email_failed: 'Failed',
+ }}
+ metricColors={{
+ email_sent: 'blue',
+ email_delivered: 'success',
+ email_failed: 'danger',
+ }}
+ forceParams={{
+ appSource: 'hog_flow',
+ appSourceId: template.transactional_hog_flow_id,
+ metricName: ['email_sent', 'email_delivered', 'email_failed'],
+ breakdownBy: 'metric_name',
+ interval: 'day',
+ dateFrom: '-7d',
+ }}
+ />
+ </Link>
+ ) : null,
+ },
+ createdByColumn() as LemonTableColumn<MessageTemplate, any>,
+ { ...(updatedAtColumn() as LemonTableColumn<MessageTemplate, any>), width: 0 },
+ ]}
+ defaultSorting={{ columnKey: 'updated_at', order: -1 }}
+ emptyState={isFiltered ? 'No transactional emails match these filters' : 'No transactional emails'}
+ />
+ </div>
)
}
diff --git a/products/workflows/frontend/Transactional/transactionalEmailsLogic.test.ts b/products/workflows/frontend/Transactional/transactionalEmailsLogic.test.ts
new file mode 100644
index 000000000000..b16b41e31f1d
--- /dev/null
+++ b/products/workflows/frontend/Transactional/transactionalEmailsLogic.test.ts
@@ -0,0 +1,101 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { MessageTemplate } from '../TemplateLibrary/types'
+import { transactionalEmailsLogic } from './transactionalEmailsLogic'
+
+const template = (id: string, name: string, tags: string[], createdBy: number, transactional = true): MessageTemplate =>
+ ({
+ id,
+ name,
+ description: '',
+ tags,
+ created_by: { id: createdBy },
+ transactional_hog_flow_id: transactional ? `flow-${id}` : null,
+ }) as unknown as MessageTemplate
+
+describe('transactionalEmailsLogic', () => {
+ let logic: ReturnType<typeof transactionalEmailsLogic.build>
+ let writes: { id: string; tags: string[] }[]
+
+ beforeEach(async () => {
+ writes = []
+ useMocks({
+ patch: {
+ '/api/projects/:team_id/messaging_templates/:id/': async ({ request, params }) => {
+ const { tags } = (await request.json()) as { tags: string[] }
+ const id = String(params.id)
+ writes.push({ id, tags })
+ return [200, { ...template(id, 'Password reset', [], 1), tags }]
+ },
+ },
+ get: {
+ '/api/projects/:team_id/messaging_templates/': {
+ results: [
+ template('a', 'Password reset', ['auth'], 1),
+ template('b', 'Receipt', ['billing'], 2),
+ template('c', 'Sign-in code', ['auth'], 2),
+ template('d', 'Newsletter', ['auth'], 1, false),
+ ],
+ },
+ '/api/projects/:team_id/tags': ['auth', 'billing'],
+ },
+ })
+ initKeaTests()
+ logic = transactionalEmailsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => logic.unmount())
+
+ it.each([
+ ['a tag', `/transactional?tags=${encodeURIComponent('["auth"]')}`, ['Password reset', 'Sign-in code']],
+ ['the creator', '/transactional?created_by=2', ['Receipt', 'Sign-in code']],
+ ['a search', '/transactional?search=receipt', ['Receipt']],
+ ])('filters transactional emails by %s from the url', async (_name, url, expected) => {
+ router.actions.push(url)
+
+ await expectLogic(logic).toMatchValues({
+ filteredTransactionalTemplates: expected.map((name) => expect.objectContaining({ name })),
+ })
+ })
+
+ it('keeps the filters when a link back to the list carries no query params', () => {
+ router.actions.push('/transactional?search=reset&created_by=1')
+
+ router.actions.push('/transactional')
+
+ expect(logic.values.filters).toMatchObject({ search: 'reset', createdBy: 1 })
+ expect(router.values.searchParams).toMatchObject({ search: 'reset' })
+ })
+
+ it('saves two quick tag edits as one write that keeps both tags', async () => {
+ const reset = logic.values.filteredTransactionalTemplates.find((t) => t.name === 'Password reset')!
+
+ logic.actions.saveTransactionalTags(reset, ['auth', 'security'])
+ const shown = logic.values.filteredTransactionalTemplates.find((t) => t.name === 'Password reset')!
+ logic.actions.saveTransactionalTags(shown, [...shown.tags!, 'urgent'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(writes).toEqual([{ id: 'a', tags: ['auth', 'security', 'urgent'] }])
+ })
+
+ it('saves tag edits made on two rows within the same pause', async () => {
+ const [reset, receipt] = ['Password reset', 'Receipt'].map(
+ (name) => logic.values.transactionalTemplates.find((t) => t.name === name)!
+ )
+
+ logic.actions.saveTransactionalTags(reset, ['auth', 'security'])
+ logic.actions.saveTransactionalTags(receipt, ['billing', 'urgent'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(writes).toEqual([
+ { id: 'a', tags: ['auth', 'security'] },
+ { id: 'b', tags: ['billing', 'urgent'] },
+ ])
+ })
+})
diff --git a/products/workflows/frontend/Transactional/transactionalEmailsLogic.ts b/products/workflows/frontend/Transactional/transactionalEmailsLogic.ts
new file mode 100644
index 000000000000..857767557be7
--- /dev/null
+++ b/products/workflows/frontend/Transactional/transactionalEmailsLogic.ts
@@ -0,0 +1,206 @@
+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()
+ })
+ })
+}