: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): show what the person did around a transactional email (#129261)
Daniel Marchuk40f1808cb3c2
diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivity.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivity.tsxnew file mode 100644index 000000000000..589bf67c05eb--- /dev/null+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivity.tsx@@ -0,0 +1,85 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'++import type { TransactionalEmailLogDetailApi } from 'products/messaging/frontend/generated/api.schemas'++import { emailSentAt } from './emailActivity'+import { TransactionalEmailActivityTimeline } from './TransactionalEmailActivityTimeline'+import { transactionalEmailLogEntryLogic } from './transactionalEmailLogEntryLogic'++export function TransactionalEmailActivity({ email }: { email: TransactionalEmailLogDetailApi }): JSX.Element {+ const { person, personLoading, personFailed, activity, activityLoading, activityFailed } = useValues(+ transactionalEmailLogEntryLogic+ )+ const { loadActivity, loadPerson } = useActions(transactionalEmailLogEntryLogic)++ const firstName = person?.properties?.name ? String(person.properties.name).split(' ')[0] : null+ const title = firstName ? `What ${firstName} did around this email` : 'Activity around this email'++ let content: JSX.Element+ if (!email.distinct_id) {+ content = (+ <p className="text-sm text-secondary m-0">+ This send has no person attached. Pass a <code>distinct_id</code> when you send, and the person's+ activity before and after the email shows up here.+ </p>+ )+ } else if (personFailed && !personLoading) {+ const distinctId = email.distinct_id+ content = (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: () => loadPerson(distinctId),+ 'data-attr': 'transactional-email-person-retry',+ }}+ >+ The person behind this send couldn't load. Check your connection and try again.+ </LemonBanner>+ )+ } else if (person === null) {+ content = (+ <p className="text-sm text-secondary m-0">+ No events from this person yet. Once your app captures events for them, what they did before and after+ the email shows up here.+ </p>+ )+ } else if (activityFailed && !activityLoading && person) {+ content = (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: () => loadActivity({ personId: person.id, sentAt: emailSentAt(email) }),+ 'data-attr': 'transactional-email-activity-retry',+ }}+ >+ The activity couldn't load. Check your connection and try again.+ </LemonBanner>+ )+ } else if (!activity || activityLoading || personLoading) {+ content = (+ <div className="flex flex-col gap-3">+ {Array.from({ length: 6 }).map((_, index) => (+ <LemonSkeleton key={index} className="h-5" />+ ))}+ </div>+ )+ } else {+ content = <TransactionalEmailActivityTimeline email={email} activity={activity} />+ }++ return (+ <section className="ph-no-capture border rounded bg-surface-primary p-4 flex flex-col gap-3">+ <div className="flex flex-col gap-0.5">+ <h3 className="text-base font-semibold m-0">{title}</h3>+ <p className="text-xs text-secondary m-0">+ The person's events in your product, with this email's delivery and engagement in between.+ </p>+ </div>+ {content}+ </section>+ )+}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRow.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRow.tsxnew file mode 100644index 000000000000..c56996b2c248--- /dev/null+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRow.tsx@@ -0,0 +1,131 @@+import clsx from 'clsx'++import { IconBolt, IconCursorClick, IconEye, IconLetter } from '@posthog/icons'+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { urls } from 'scenes/urls'++import type { EmailLogEventKindEnumApi } from 'products/messaging/frontend/generated/api.schemas'++import { ActivityEvent, ActivityRow, describeActivityEvent, isCustomEvent, relativeToSend } from './emailActivity'+import { EMAIL_STATUS_LABEL, EMAIL_STATUS_TAG, emailReasonText } from './emailLogStatus'++const EMAIL_EVENT_LABEL: Record<EmailLogEventKindEnumApi, string> = {+ queued: 'Email queued',+ sent: 'Email sent',+ delivered: 'Email delivered',+ opened: 'Opened the email',+ clicked: 'Clicked a link in the email',+ bounced: 'Email bounced',+ complained: 'Marked the email as spam',+ failed: "Email wasn't sent",+}++const FAILED_KINDS: EmailLogEventKindEnumApi[] = ['bounced', 'complained', 'failed']++function EventIcon({ event }: { event: ActivityEvent }): JSX.Element {+ if (event.event === '$pageview' || event.event === '$screen') {+ return <IconEye />+ }+ if (event.event === '$autocapture' || event.event === '$rageclick') {+ return <IconCursorClick />+ }+ return <IconBolt />+}++function TimeCell({ at, sentAt }: { at: string; sentAt: string }): JSX.Element {+ return (+ <Tooltip title={<TZLabel time={at} formatDate="MMM D, YYYY" formatTime="HH:mm:ss" noStyles />}>+ <span className="text-xs text-secondary whitespace-nowrap tabular-nums">{relativeToSend(at, sentAt)}</span>+ </Tooltip>+ )+}++export function TransactionalEmailActivityRow({ row, sentAt }: { row: ActivityRow; sentAt: string }): JSX.Element {+ if (row.kind === 'session') {+ return (+ <li className="flex items-center gap-3 pt-3 first:pt-0">+ <span className="text-xs font-semibold uppercase tracking-wide text-secondary">Session</span>+ <TZLabel time={row.at} className="text-xs text-secondary" />+ <span className="h-px flex-1 bg-border" />+ <ViewRecordingButton+ sessionId={row.sessionId}+ timestamp={row.at}+ checkRecordingExists+ openPlayerIn={RecordingPlayerType.Modal}+ size="xsmall"+ type="secondary"+ label="Watch"+ data-attr="transactional-email-activity-recording"+ />+ </li>+ )+ }+ if (row.kind === 'emailGroup') {+ return (+ <li className="flex flex-col gap-1 rounded border border-l-2 border-l-accent bg-surface-secondary px-3 py-2">+ {row.rows.map((emailRow) => {+ const failed = FAILED_KINDS.includes(emailRow.event.kind)+ const reason = emailReasonText(emailRow.event.reason)+ return (+ <div key={emailRow.key} className="flex items-center gap-3 min-w-0">+ <span className={clsx('flex shrink-0 text-base', failed ? 'text-danger' : 'text-accent')}>+ <IconLetter />+ </span>+ <span+ className={clsx(+ 'flex-1 min-w-0 text-sm font-semibold truncate',+ failed && 'text-danger'+ )}+ >+ {EMAIL_EVENT_LABEL[emailRow.event.kind]}+ {reason && <span className="font-normal text-secondary"> · {reason}</span>}+ </span>+ <TimeCell at={emailRow.at} sentAt={sentAt} />+ </div>+ )+ })}+ </li>+ )+ }+ if (row.kind === 'otherEmail') {+ return (+ <li className="flex items-center gap-3 px-2 -mx-2 py-1">+ <span className="flex shrink-0 text-base text-secondary">+ <IconLetter />+ </span>+ <span className="flex-1 min-w-0 flex items-center gap-2 text-sm">+ <span className="truncate">+ Got{' '}+ <Link+ to={urls.transactionalEmailLogEntry(row.entry.message_id)}+ data-attr="transactional-email-activity-other-email"+ >+ {row.entry.template_name || 'a deleted email'}+ </Link>+ </span>+ <LemonTag size="small" type={EMAIL_STATUS_TAG[row.entry.status]} className="shrink-0">+ {EMAIL_STATUS_LABEL[row.entry.status]}+ </LemonTag>+ </span>+ <TimeCell at={row.at} sentAt={sentAt} />+ </li>+ )+ }+ const custom = isCustomEvent(row.event)+ const description = describeActivityEvent(row.event)+ return (+ <li className="flex items-center gap-3 px-2 -mx-2 py-1">+ <span className={clsx('flex shrink-0 text-base', custom ? 'text-warning' : 'text-secondary')}>+ <EventIcon event={row.event} />+ </span>+ <span className={clsx('flex-1 min-w-0 text-sm truncate', custom && 'font-semibold')} title={description}>+ {description}+ {row.count > 1 && <span className="font-normal text-secondary"> ×{row.count}</span>}+ </span>+ <TimeCell at={row.at} sentAt={sentAt} />+ </li>+ )+}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivitySummary.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivitySummary.tsxnew file mode 100644index 000000000000..bce14bf7947f--- /dev/null+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivitySummary.tsx@@ -0,0 +1,39 @@+import { IconBolt } from '@posthog/icons'+import { LemonTag } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'++import type { TransactionalEmailLogEventApi } from 'products/messaging/frontend/generated/api.schemas'++import { ActivityEvent, summarizeAfter } from './emailActivity'++/** How many custom events the summary names before it stops. */+const MAX_OUTCOMES = 4++export function TransactionalEmailActivitySummary({+ after,+ timeline,+}: {+ after: ActivityEvent[]+ timeline: readonly TransactionalEmailLogEventApi[]+}): JSX.Element | null {+ if (!after.length) {+ return null+ }+ const { comeback, eventCount, sessionCount, outcomes } = summarizeAfter(after, timeline)+ return (+ <div className="flex flex-wrap items-center gap-2 text-sm">+ {comeback && <LemonTag type="success">{comeback}</LemonTag>}+ <LemonTag type="muted">+ {pluralize(eventCount, 'event')} after the email+ {sessionCount > 0 ? ` across ${pluralize(sessionCount, 'session')}` : ''}+ </LemonTag>+ {outcomes.length > 0 && <span className="text-xs text-secondary">Then did</span>}+ {outcomes.slice(0, MAX_OUTCOMES).map((outcome) => (+ <LemonTag key={outcome} type="warning" icon={<IconBolt />}>+ {outcome}+ </LemonTag>+ ))}+ </div>+ )+}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityTimeline.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityTimeline.tsxnew file mode 100644index 000000000000..fb7e5d7021e3--- /dev/null+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityTimeline.tsx@@ -0,0 +1,106 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { pluralize } from 'lib/utils/strings'++import type { TransactionalEmailLogDetailApi } from 'products/messaging/frontend/generated/api.schemas'++import { ACTIVITY_WINDOW_DAYS, PersonActivity, buildActivityTimeline, emailSentAt } from './emailActivity'+import { TransactionalEmailActivityRow } from './TransactionalEmailActivityRow'+import { TransactionalEmailActivitySummary } from './TransactionalEmailActivitySummary'+import { transactionalEmailLogEntryLogic } from './transactionalEmailLogEntryLogic'++/** How many events before the send show until the reader asks for more. */+const BEFORE_PREVIEW = 5++/** The person's loaded activity, split into what they did before and after the email. */+export function TransactionalEmailActivityTimeline({+ email,+ activity,+}: {+ email: TransactionalEmailLogDetailApi+ activity: PersonActivity+}): JSX.Element {+ const { beforeExpanded, otherEmails, otherEmailsFailed, otherEmailsLoading } = useValues(+ transactionalEmailLogEntryLogic+ )+ const { showAllBefore, loadOtherEmails } = useActions(transactionalEmailLogEntryLogic)++ const before = beforeExpanded ? activity.before : activity.before.slice(-BEFORE_PREVIEW)+ const hiddenBefore = activity.before.length - before.length+ const emailEvents = email.timeline.filter((event) => event.kind !== 'queued')+ // Other emails before the send only show alongside the events the reader chose to show.+ const earliestShown = before[0]?.timestamp ?? email.created_at+ const shownOtherEmails = otherEmails.filter((entry) => !dayjs(entry.created_at).isBefore(earliestShown))+ // Times read relative to when the email went out, which is what a reader compares against.+ const sentAt = emailSentAt(email)+ const timeline = buildActivityTimeline([...before, ...activity.after], emailEvents, shownOtherEmails, sentAt)+ const nothingAround = !activity.before.length && !activity.after.length+ return (+ <div className="flex flex-col gap-4">+ <TransactionalEmailActivitySummary after={activity.after} timeline={email.timeline} />+ {otherEmailsFailed && !otherEmailsLoading && (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: () => loadOtherEmails(email),+ 'data-attr': 'transactional-email-other-emails-retry',+ }}+ >+ This person's other emails couldn't load. Check your connection and try again.+ </LemonBanner>+ )}+ {timeline.before.length > 0 && (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <h4 className="text-sm font-semibold m-0">Before the email</h4>+ {hiddenBefore > 0 && (+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={showAllBefore}+ data-attr="transactional-email-activity-show-earlier"+ >+ Show {pluralize(hiddenBefore, 'earlier event')}+ </LemonButton>+ )}+ </div>+ <ol className="flex flex-col gap-1 m-0 p-0 list-none">+ {timeline.before.map((row) => (+ <TransactionalEmailActivityRow key={row.key} row={row} sentAt={sentAt} />+ ))}+ </ol>+ </div>+ )}+ <div className="flex flex-col gap-2">+ <h4 className="text-sm font-semibold m-0">After the email</h4>+ <ol className="flex flex-col gap-1 m-0 p-0 list-none" data-attr="transactional-email-activity">+ {timeline.after.map((row) => (+ <TransactionalEmailActivityRow key={row.key} row={row} sentAt={sentAt} />+ ))}+ </ol>+ {!activity.after.length && (+ <p+ className="text-sm text-secondary m-0 rounded border border-dashed px-3 py-2"+ data-attr="transactional-email-activity-nothing-after"+ >+ {nothingAround+ ? `No events from this person in the ${pluralize(ACTIVITY_WINDOW_DAYS, 'day')} before or after this email.`+ : dayjs().isAfter(dayjs(sentAt).add(ACTIVITY_WINDOW_DAYS, 'day'))+ ? `No activity in your product in the ${pluralize(ACTIVITY_WINDOW_DAYS, 'day')} after this email.`+ : 'No activity in your product since this email.'}+ </p>+ )}+ {activity.hasMoreAfter && (+ <p className="text-xs text-secondary m-0">+ Showing the first {activity.after.length} events after the email. See the rest on the person's+ page.+ </p>+ )}+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailLogEntryScene.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailLogEntryScene.tsxindex 7f8e98fe99e5..1347e0a04126 100644--- a/products/workflows/frontend/Transactional/log/TransactionalEmailLogEntryScene.tsx+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailLogEntryScene.tsx@@ -11,6 +11,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { TransactionalEmailActivity } from './TransactionalEmailActivity'import { TransactionalEmailDeliveryProgress } from './TransactionalEmailDeliveryProgress'import { TransactionalEmailDetails } from './TransactionalEmailDetails'import {@@ -93,6 +94,8 @@ export function TransactionalEmailLogEntryScene(): JSX.Element {<TransactionalEmailDeliveryProgress email={email} /><div className="flex flex-col @3xl:flex-row gap-4 items-start"><div className="w-full @3xl:flex-1 min-w-0 flex flex-col gap-4 order-last @3xl:order-none">+ {/* A send that never went out kept no copy, so nothing links it to a person. */}+ {email.action_id && <TransactionalEmailActivity email={email} />}<TransactionalEmailRendered email={email} /></div><div className="w-full @3xl:w-80 shrink-0 flex flex-col gap-4">diff --git a/products/workflows/frontend/Transactional/log/emailActivity.test.ts b/products/workflows/frontend/Transactional/log/emailActivity.test.tsnew file mode 100644index 000000000000..9b12fafb0e8a--- /dev/null+++ b/products/workflows/frontend/Transactional/log/emailActivity.test.ts@@ -0,0 +1,79 @@+import { ActivityEvent, ActivityRow, buildActivityTimeline, emailSentAt, summarizeAfter } from './emailActivity'++function event(uuid: string, timestamp: string, sessionId: string | null): ActivityEvent {+ return {+ uuid,+ event: '$pageview',+ timestamp,+ url: null,+ pathname: '/files',+ sessionId,+ eventType: null,+ elementsChain: '',+ }+}++describe('emailActivity', () => {+ it('splits at the send, starts the after part with the email block, folds repeats, and keeps other emails in order', () => {+ const timeline = buildActivityTimeline(+ [+ event('before', '2026-06-15T08:59:00Z', 's1'),+ event('after-1', '2026-06-15T09:03:00Z', 's2'),+ { ...event('after-2', '2026-06-15T09:04:00Z', 's2'), pathname: '/pricing' },+ { ...event('after-3', '2026-06-15T09:04:10Z', 's2'), pathname: '/pricing' },+ ],+ [+ { kind: 'sent', at: '2026-06-15T09:00:00Z', reason: null },+ { kind: 'delivered', at: '2026-06-15T09:00:02Z', reason: null },+ { kind: 'clicked', at: '2026-06-15T09:02:00Z', reason: null },+ ],+ [+ {+ message_id: 'receipt',+ created_at: '2026-06-15T09:05:00Z',+ status: 'delivered',+ status_at: '2026-06-15T09:05:01Z',+ reason: null,+ recipient: '[email protected]',+ workflow_id: 'workflow',+ template_id: 'template',+ template_name: 'Payment receipt',+ sending_domain: 'example.com',+ opened: false,+ clicked: false,+ },+ ],+ '2026-06-15T09:00:00Z'+ )++ const shape = (rows: ActivityRow[]): string[] =>+ rows.map((row) =>+ row.kind === 'emailGroup'+ ? `emailGroup(${row.rows.length})`+ : row.kind === 'event'+ ? `event(${row.count})`+ : row.kind+ )+ expect(shape(timeline.before)).toEqual(['session', 'event(1)'])+ expect(shape(timeline.after)).toEqual(['emailGroup(3)', 'session', 'event(1)', 'event(2)', 'otherEmail'])+ })++ it('keeps a return to the app that came before a later open of the email', () => {+ const summary = summarizeAfter(+ [event('return', '2026-06-15T09:03:00Z', 's1')],+ [+ { kind: 'clicked', at: '2026-06-15T09:02:00Z', reason: null },+ { kind: 'opened', at: '2026-06-15T10:00:00Z', reason: null },+ ]+ )++ expect(summary.comeback).toBe('Back in your app 1m after clicking the email')+ })++ it('splits the activity at the send, or at the queue time when nothing went out', () => {+ const sent = { kind: 'sent' as const, at: '2026-06-15T09:05:00Z', reason: null }++ expect(emailSentAt({ created_at: '2026-06-15T09:00:00Z', timeline: [sent] })).toBe(sent.at)+ expect(emailSentAt({ created_at: '2026-06-15T09:00:00Z', timeline: [] })).toBe('2026-06-15T09:00:00Z')+ })+})diff --git a/products/workflows/frontend/Transactional/log/emailActivity.ts b/products/workflows/frontend/Transactional/log/emailActivity.tsindex 527167d24e85..73a4d1a62477 100644--- a/products/workflows/frontend/Transactional/log/emailActivity.ts+++ b/products/workflows/frontend/Transactional/log/emailActivity.ts@@ -1,5 +1,236 @@+import { dayjs } from 'lib/dayjs'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { chainToElements } from 'lib/utils/elements-chain'+import { autoCaptureEventToDescription } from 'lib/utils/events'+import { capitalizeFirstLetter } from 'lib/utils/strings'++import type {+ TransactionalEmailLogDetailApi,+ TransactionalEmailLogEntryApi,+ TransactionalEmailLogEventApi,+} from 'products/messaging/frontend/generated/api.schemas'++/** How far before and after the send the page looks for what the person did. */+export const ACTIVITY_WINDOW_DAYS = 7+export const ACTIVITY_BEFORE_LIMIT = 50+export const ACTIVITY_AFTER_LIMIT = 100++export interface ActivityEvent {+ uuid: string+ event: string+ timestamp: string+ url: string | null+ pathname: string | null+ sessionId: string | null+ eventType: string | null+ elementsChain: string+}+export interface ActivityPerson {id: stringproperties: Record<string, any>createdAt: string}++export interface PersonActivity {+ before: ActivityEvent[]+ after: ActivityEvent[]+ /** True when the window held more events before the send than the page loaded. */+ hasMoreBefore: boolean+ hasMoreAfter: boolean+}++/** A short sentence for what the person did, such as "Viewed /pricing". */+export function describeActivityEvent(event: ActivityEvent): string {+ if (event.event === '$pageview' || event.event === '$screen') {+ const path = event.pathname || (event.url ? safePathname(event.url) : null)+ return path ? `Viewed ${path}` : 'Viewed a page'+ }+ if (event.event === '$autocapture') {+ return capitalizeFirstLetter(+ autoCaptureEventToDescription({+ event: event.event,+ properties: { $event_type: event.eventType },+ elements: chainToElements(event.elementsChain),+ })+ )+ }+ if (event.event === '$rageclick') {+ return 'Rage clicked'+ }+ return event.event+}++/** Custom events are what the product chose to track, so they read as outcomes. */+export function isCustomEvent(event: ActivityEvent): boolean {+ return !event.event.startsWith('$')+}++function safePathname(url: string): string | null {+ try {+ return new URL(url).pathname+ } catch {+ return null+ }+}++export type ActivityEventRow = {+ kind: 'event'+ key: string+ at: string+ event: ActivityEvent+ /** How many identical events in a row this one stands for. */+ count: number+}+export type ActivityOtherEmailRow = {+ kind: 'otherEmail'+ key: string+ at: string+ entry: TransactionalEmailLogEntryApi+}+export type ActivityEmailRow = { kind: 'email'; key: string; at: string; event: TransactionalEmailLogEventApi }+export type ActivityRow =+ | { kind: 'session'; key: string; sessionId: string; at: string }+ | ActivityEventRow+ | ActivityOtherEmailRow+ | { kind: 'emailGroup'; key: string; at: string; rows: ActivityEmailRow[] }++export interface ActivityTimeline {+ /** What the person did before the email went out. */+ before: ActivityRow[]+ /** The email's own steps, then what the person did after it went out. */+ after: ActivityRow[]+}++/**+ * The person's events, this email's steps and their other emails, in time order and split at the send. A row starts+ * each session, the email's consecutive steps fold into one block, and repeats of one interaction fold into one row.+ */+export function buildActivityTimeline(+ events: ActivityEvent[],+ emailEvents: TransactionalEmailLogEventApi[],+ otherEmails: TransactionalEmailLogEntryApi[],+ sentAt: string+): ActivityTimeline {+ const merged: (ActivityEventRow | ActivityEmailRow | ActivityOtherEmailRow)[] = [+ ...events.map(+ (event): ActivityEventRow => ({ kind: 'event', key: event.uuid, at: event.timestamp, event, count: 1 })+ ),+ ...otherEmails.map(+ (entry): ActivityOtherEmailRow => ({+ kind: 'otherEmail',+ key: entry.message_id,+ at: entry.created_at,+ entry,+ })+ ),+ ...emailEvents.map(+ (event, index): ActivityEmailRow => ({+ kind: 'email',+ key: `email-${event.kind}-${index}`,+ at: event.at,+ event,+ })+ ),+ ].sort((a, b) => dayjs(a.at).valueOf() - dayjs(b.at).valueOf())++ const sent = dayjs(sentAt)+ const isBefore = (row: ActivityEventRow | ActivityEmailRow | ActivityOtherEmailRow): boolean =>+ row.kind !== 'email' && dayjs(row.at).isBefore(sent)+ return {+ before: foldRows(merged.filter(isBefore)),+ after: foldRows(merged.filter((row) => !isBefore(row))),+ }+}++function foldRows(merged: (ActivityEventRow | ActivityEmailRow | ActivityOtherEmailRow)[]): ActivityRow[] {+ const rows: ActivityRow[] = []+ let currentSession: string | null = null+ for (const row of merged) {+ const last = rows[rows.length - 1]+ if (row.kind === 'email') {+ if (last?.kind === 'emailGroup') {+ last.rows.push(row)+ } else {+ rows.push({ kind: 'emailGroup', key: `group-${row.key}`, at: row.at, rows: [row] })+ }+ continue+ }+ if (row.kind === 'otherEmail') {+ rows.push(row)+ continue+ }+ if (+ last?.kind === 'event' &&+ last.event.event === row.event.event &&+ last.event.sessionId === row.event.sessionId &&+ describeActivityEvent(last.event) === describeActivityEvent(row.event)+ ) {+ last.count += 1+ continue+ }+ if (row.event.sessionId && row.event.sessionId !== currentSession) {+ currentSession = row.event.sessionId+ rows.push({ kind: 'session', key: `session-${row.key}`, sessionId: row.event.sessionId, at: row.at })+ }+ rows.push(row)+ }+ return rows+}++/** "2m before", "at send" or "3h after", measured from when the email went out. */+export function relativeToSend(at: string, sentAt: string): string {+ const seconds = dayjs(at).diff(dayjs(sentAt), 'second')+ if (Math.abs(seconds) < 1) {+ return 'at send'+ }+ const duration = humanFriendlyDuration(Math.abs(seconds), { maxUnits: 1 })+ return seconds < 0 ? `${duration} before` : `${duration} after`+}++export interface ActivityAfterSummary {+ /** For example "Back in your app 3m after clicking", when the person returned after engaging with the email. */+ comeback: string | null+ eventCount: number+ sessionCount: number+ /** The custom events they did after the email, in the order they first did them. */+ outcomes: string[]+}++/** When the email went out, which is the line between what the person did before and after it. */+export function emailSentAt(email: Pick<TransactionalEmailLogDetailApi, 'timeline' | 'created_at'>): string {+ return email.timeline.find((event) => event.kind === 'sent')?.at ?? email.created_at+}++function firstReturnToApp(+ after: ActivityEvent[],+ timeline: readonly TransactionalEmailLogEventApi[]+): { event: ActivityEvent; engagement: TransactionalEmailLogEventApi } | null {+ const engagements = timeline.filter((event) => event.kind === 'clicked' || event.kind === 'opened').reverse()+ for (const event of after) {+ const engagement = engagements.find((candidate) => dayjs(event.timestamp).isAfter(candidate.at))+ if (engagement) {+ return { event, engagement }+ }+ }+ return null+}++export function summarizeAfter(+ after: ActivityEvent[],+ timeline: readonly TransactionalEmailLogEventApi[]+): ActivityAfterSummary {+ const firstReturn = firstReturnToApp(after, timeline)+ const comeback = firstReturn+ ? `Back in your app ${humanFriendlyDuration(+ Math.max(1, dayjs(firstReturn.event.timestamp).diff(dayjs(firstReturn.engagement.at), 'second')),+ { maxUnits: 1 }+ )} after ${firstReturn.engagement.kind === 'clicked' ? 'clicking the email' : 'opening the email'}`+ : null+ return {+ comeback,+ eventCount: after.length,+ sessionCount: new Set(after.map((event) => event.sessionId).filter(Boolean)).size,+ outcomes: Array.from(new Set(after.filter(isCustomEvent).map((event) => event.event))),+ }+}diff --git a/products/workflows/frontend/Transactional/log/emailActivityQueries.ts b/products/workflows/frontend/Transactional/log/emailActivityQueries.tsindex 377dbaa352bc..bde3a4b722e1 100644--- a/products/workflows/frontend/Transactional/log/emailActivityQueries.ts+++ b/products/workflows/frontend/Transactional/log/emailActivityQueries.ts@@ -1,10 +1,56 @@import api from 'lib/api'+import { dayjs } from 'lib/dayjs'import { hogql } from 'lib/utils/hogql'-import { ActivityPerson } from './emailActivity'+import { transactionalEmailLogList } from 'products/messaging/frontend/generated/api'+import type { TransactionalEmailLogEntryApi } from 'products/messaging/frontend/generated/api.schemas'++import {+ ACTIVITY_AFTER_LIMIT,+ ACTIVITY_BEFORE_LIMIT,+ ACTIVITY_WINDOW_DAYS,+ ActivityEvent,+ ActivityPerson,+ PersonActivity,+} from './emailActivity'+import { LOG_RETENTION_DAYS } from './transactionalEmailLogLogic'++const OTHER_EMAILS_LIMIT = 20++// Events that describe the SDK rather than something the person did.+const HIDDEN_EVENTS = [+ '$feature_flag_called',+ '$identify',+ '$set',+ '$groupidentify',+ '$create_alias',+ '$pageleave',+ '$web_vitals',+ '$opt_in',+ '$autocapture_disabled',+ '$dead_click',+ '$exception',+ '$feature_view',+ '$feature_interaction',+ '$snapshot',+]const QUERY_TAGS = { productKey: 'workflows', scene: 'TransactionalEmailLogEntry' }+function toEvent(row: any[]): ActivityEvent {+ const [uuid, event, timestamp, url, pathname, sessionId, eventType, elementsChain] = row+ return {+ uuid,+ event,+ timestamp,+ url: url || null,+ pathname: pathname || null,+ sessionId: sessionId || null,+ eventType: eventType || null,+ elementsChain: elementsChain || '',+ }+}+export async function fetchActivityPerson(distinctId: string): Promise<ActivityPerson | null> {const response = await api.queryHogQL(hogql`SELECT id, properties, created_at@@ -24,3 +70,60 @@ LIMIT 1`,createdAt,}}++export async function fetchPersonActivity(personId: string, sentAt: string): Promise<PersonActivity> {+ const sent = dayjs(sentAt)+ const from = sent.subtract(ACTIVITY_WINDOW_DAYS, 'day')+ const to = sent.add(ACTIVITY_WINDOW_DAYS, 'day')+ const columns = hogql`uuid, event, timestamp, properties.$current_url, properties.$pathname, properties.$session_id, properties.$event_type, elements_chain`+ const [before, after] = await Promise.all([+ api.queryHogQL(+ hogql`SELECT ${hogql.raw(columns)} FROM events+WHERE person_id = ${personId} AND timestamp >= ${from} AND timestamp < ${sent}+AND event NOT IN ${HIDDEN_EVENTS}+ORDER BY timestamp DESC+LIMIT ${ACTIVITY_BEFORE_LIMIT + 1}`,+ QUERY_TAGS+ ),+ api.queryHogQL(+ hogql`SELECT ${hogql.raw(columns)} FROM events+WHERE person_id = ${personId} AND timestamp >= ${sent} AND timestamp <= ${to}+AND event NOT IN ${HIDDEN_EVENTS}+ORDER BY timestamp ASC+LIMIT ${ACTIVITY_AFTER_LIMIT + 1}`,+ QUERY_TAGS+ ),+ ])+ const beforeRows = (before.results ?? []).map(toEvent)+ const afterRows = (after.results ?? []).map(toEvent)+ return {+ before: beforeRows.slice(0, ACTIVITY_BEFORE_LIMIT).reverse(),+ after: afterRows.slice(0, ACTIVITY_AFTER_LIMIT),+ hasMoreBefore: beforeRows.length > ACTIVITY_BEFORE_LIMIT,+ hasMoreAfter: afterRows.length > ACTIVITY_AFTER_LIMIT,+ }+}++/** Other emails the same recipient got in the activity window, newest last. */+export async function fetchOtherEmails(+ projectId: number,+ recipient: string,+ messageId: string,+ sentAt: string+): Promise<TransactionalEmailLogEntryApi[]> {+ const sent = dayjs(sentAt)+ const now = dayjs()+ const oldest = now.subtract(LOG_RETENTION_DAYS, 'day')+ const from = sent.subtract(ACTIVITY_WINDOW_DAYS, 'day')+ const to = sent.add(ACTIVITY_WINDOW_DAYS, 'day')+ const response = await transactionalEmailLogList(String(projectId), {+ search: recipient,+ date_from: (from.isBefore(oldest) ? oldest : from).toISOString(),+ date_to: (to.isAfter(now) ? now : to).toISOString(),+ limit: OTHER_EMAILS_LIMIT,+ })+ // Search matches part of an address, so keep only this recipient's own sends.+ return response.results+ .filter((entry) => entry.message_id !== messageId && entry.recipient.toLowerCase() === recipient.toLowerCase())+ .sort((a, b) => dayjs(a.created_at).valueOf() - dayjs(b.created_at).valueOf())+}diff --git a/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.ts b/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.tsindex 1c324a1b8298..945697073f3e 100644--- a/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.ts+++ b/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'@@ -9,10 +9,13 @@ import { urls } from 'scenes/urls'import { Breadcrumb } from '~/types'import { transactionalEmailLogRetrieve } from 'products/messaging/frontend/generated/api'-import type { TransactionalEmailLogDetailApi } from 'products/messaging/frontend/generated/api.schemas'+import type {+ TransactionalEmailLogDetailApi,+ TransactionalEmailLogEntryApi,+} from 'products/messaging/frontend/generated/api.schemas'-import { ActivityPerson } from './emailActivity'-import { fetchActivityPerson } from './emailActivityQueries'+import { ActivityPerson, PersonActivity, emailSentAt } from './emailActivity'+import { fetchActivityPerson, fetchOtherEmails, fetchPersonActivity } from './emailActivityQueries'export interface TransactionalEmailLogEntryLogicProps {messageId: string@@ -21,10 +24,17 @@ export interface TransactionalEmailLogEntryLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface transactionalEmailLogEntryLogicValues {currentProjectId: number | null // projectLogic+ activity: PersonActivity | null+ activityFailed: boolean+ activityLoading: boolean+ beforeExpanded: booleanbreadcrumbs: Breadcrumb[]email: TransactionalEmailLogDetailApi | null | undefinedemailFailed: booleanemailLoading: boolean+ otherEmails: TransactionalEmailLogEntryApi[]+ otherEmailsFailed: boolean+ otherEmailsLoading: booleanperson: ActivityPerson | null | undefinedpersonFailed: booleanpersonLoading: boolean@@ -32,6 +42,30 @@ export interface transactionalEmailLogEntryLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface transactionalEmailLogEntryLogicActions {+ loadActivity: ({ personId, sentAt }: { personId: string; sentAt: string }) => {+ personId: string+ sentAt: string+ }+ loadActivityFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadActivitySuccess: (+ activity: PersonActivity,+ payload?: {+ personId: string+ sentAt: string+ }+ ) => {+ activity: PersonActivity+ payload?: {+ personId: string+ sentAt: string+ }+ }loadEmail: () => anyloadEmailFailure: (error: string,@@ -47,6 +81,21 @@ export interface transactionalEmailLogEntryLogicActions {email: TransactionalEmailLogDetailApi | nullpayload?: any}+ loadOtherEmails: (email: TransactionalEmailLogDetailApi) => TransactionalEmailLogDetailApi+ loadOtherEmailsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOtherEmailsSuccess: (+ otherEmails: TransactionalEmailLogEntryApi[],+ payload?: TransactionalEmailLogDetailApi+ ) => {+ otherEmails: TransactionalEmailLogEntryApi[]+ payload?: TransactionalEmailLogDetailApi+ }loadPerson: (distinctId: string) => stringloadPersonFailure: (error: string,@@ -62,6 +111,9 @@ export interface transactionalEmailLogEntryLogicActions {person: ActivityPerson | nullpayload?: string}+ showAllBefore: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -92,7 +144,11 @@ export const transactionalEmailLogEntryLogic = kea<transactionalEmailLogEntryLogkey,]),connect(() => ({ values: [projectLogic, ['currentProjectId']] })),+ actions({+ showAllBefore: true,+ }),reducers({+ beforeExpanded: [false, { showAllBefore: () => true }],personFailed: [false,{@@ -101,6 +157,22 @@ export const transactionalEmailLogEntryLogic = kea<transactionalEmailLogEntryLogloadPersonFailure: () => true,},],+ activityFailed: [+ false,+ {+ loadActivity: () => false,+ loadActivitySuccess: () => false,+ loadActivityFailure: () => true,+ },+ ],+ otherEmailsFailed: [+ false,+ {+ loadOtherEmails: () => false,+ loadOtherEmailsSuccess: () => false,+ loadOtherEmailsFailure: () => true,+ },+ ],emailFailed: [false,{@@ -137,6 +209,27 @@ export const transactionalEmailLogEntryLogic = kea<transactionalEmailLogEntryLogloadPerson: async (distinctId: string) => await fetchActivityPerson(distinctId),},],+ otherEmails: [+ [] as TransactionalEmailLogEntryApi[],+ {+ loadOtherEmails: async (email: TransactionalEmailLogDetailApi) =>+ values.currentProjectId === null+ ? []+ : await fetchOtherEmails(+ values.currentProjectId,+ email.recipient,+ email.message_id,+ email.created_at+ ),+ },+ ],+ activity: [+ null as PersonActivity | null,+ {+ loadActivity: async ({ personId, sentAt }: { personId: string; sentAt: string }) =>+ await fetchPersonActivity(personId, sentAt),+ },+ ],})),selectors({breadcrumbs: [@@ -158,11 +251,19 @@ export const transactionalEmailLogEntryLogic = kea<transactionalEmailLogEntryLog],],}),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({+ loadPersonSuccess: ({ person }) => {+ if (person && values.email) {+ actions.loadActivity({ personId: person.id, sentAt: emailSentAt(values.email) })+ }+ },loadEmailSuccess: ({ email }) => {if (email?.distinct_id) {actions.loadPerson(email.distinct_id)}+ if (email?.recipient) {+ actions.loadOtherEmails(email)+ }// pinned: analytics event name - renaming breaks dashboardsposthog.capture('transactional email log entry viewed', {found: !!email,