: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): rebuild the broadcast detail page around the numbers that matter (#106786)
Daniel Marchukbbd86e0a1160
diff --git a/products/workflows/frontend/Broadcasts/BroadcastEmailPreview.tsx b/products/workflows/frontend/Broadcasts/BroadcastEmailPreview.tsxindex 6cff420d614a..05d56f597137 100644--- a/products/workflows/frontend/Broadcasts/BroadcastEmailPreview.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastEmailPreview.tsx@@ -22,7 +22,11 @@ function PreviewRow({ label, children }: { label: string; children: React.ReactN* filled in. Anything the person has no value for stays on screen as `{{ ... }}` rather than* rendering blank, so a missing variable is visible before the send rather than after.*/-export function BroadcastEmailPreview(): JSX.Element {+export function BroadcastEmailPreview({+ intro = 'Preview and test before this reaches the audience.',+}: {+ intro?: string+}): JSX.Element {const { email } = useValues(broadcastWizardLogic)const {persons,@@ -42,7 +46,7 @@ export function BroadcastEmailPreview(): JSX.Element {return (<div className="flex flex-col gap-3"><div className="flex flex-wrap items-center justify-between gap-2">- <span className="text-muted text-xs">Preview and test before this reaches the audience.</span>+ <span className="text-muted text-xs">{intro}</span><LemonButtontype="secondary"size="small"diff --git a/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx b/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsxnew file mode 100644index 000000000000..41af1fd3ec02--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx@@ -0,0 +1,81 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'++import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'++import { EmailLinksTable } from '../Workflows/EmailLinksTable'+import { BroadcastPerformanceLogicProps, broadcastPerformanceLogic } from './broadcastPerformanceLogic'++function share(part: number, whole: number): string {+ return whole > 0 ? percentage(part / whole, 1) : '-'+}++export function BroadcastPerformance(props: BroadcastPerformanceLogicProps): JSX.Element {+ const logic = broadcastPerformanceLogic(props)+ const { stats, totalsLoading, totalsFailed, links, linksLoading } = useValues(logic)+ const { loadTotals } = useActions(logic)++ if (totalsFailed && !totalsLoading) {+ return (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: loadTotals, 'data-attr': 'broadcast-performance-retry' }}+ >+ Couldn't load this send's numbers.+ </LemonBanner>+ )+ }+ if (!stats) {+ return <LemonSkeleton className="h-40" active={totalsLoading} />+ }++ const headline = [+ { label: 'Sent', value: humanFriendlyNumber(stats.sent), detail: null },+ { label: 'Delivered', value: share(stats.delivered, stats.sent), detail: stats.delivered },+ { label: 'Bounced', value: share(stats.bounced, stats.sent), detail: stats.bounced },+ { label: 'Marked as spam', value: share(stats.markedAsSpam, stats.sent), detail: stats.markedAsSpam },+ { label: 'Failed', value: share(stats.failed, stats.sent), detail: stats.failed },+ ]+ const engagement = [+ { label: 'Opened', part: stats.opened, whole: stats.trackedSends },+ { label: 'Clicked', part: stats.clicked, whole: stats.trackedSends },+ { label: 'Clicked to opened', part: stats.clicked, whole: stats.opened },+ ]++ return (+ <div className="flex flex-col gap-4 rounded-lg border border-border bg-surface-primary p-4">+ <div className="grid grid-cols-2 gap-4 @xl:grid-cols-5">+ {headline.map(({ label, value, detail }) => (+ <div key={label} className="flex flex-col">+ <span className="text-xl font-semibold">{value}</span>+ <span className="text-xs uppercase tracking-wide text-muted">+ {detail === null ? label : `${humanFriendlyNumber(detail)} ${label.toLowerCase()}`}+ </span>+ </div>+ ))}+ </div>++ <div className="flex flex-col gap-3">+ {engagement.map(({ label, part, whole }) => (+ <div key={label} className="grid grid-cols-[9rem_minmax(0,1fr)] items-center gap-3">+ <div className="flex flex-col text-right">+ <span className="font-semibold">{share(part, whole)}</span>+ <span className="text-xs text-muted">+ {humanFriendlyNumber(part)} {label.toLowerCase()}+ </span>+ </div>+ <LemonProgress percent={whole > 0 ? (part / whole) * 100 : 0} size="large" />+ </div>+ ))}+ <span className="text-xs text-muted">Opens and clicks are counted against sends with tracking on.</span>+ </div>++ <div className="flex flex-col gap-2">+ <h3 className="m-0 text-sm font-semibold">Top clicked links</h3>+ <EmailLinksTable links={links} loading={linksLoading} emptyState="No link clicks yet" />+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastStatusTag.tsx b/products/workflows/frontend/Broadcasts/BroadcastStatusTag.tsxnew file mode 100644index 000000000000..03ea3022469d--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastStatusTag.tsx@@ -0,0 +1,20 @@+import { LemonTag, LemonTagType } from '@posthog/lemon-ui'++import { BroadcastStatus } from './broadcastsLogic'++const STATUS_CONFIG: Record<Exclude<BroadcastStatus, 'unknown'>, { label: string; type: LemonTagType }> = {+ draft: { label: 'Draft', type: 'default' },+ scheduled: { label: 'Scheduled', type: 'warning' },+ sending: { label: 'Sending', type: 'completion' },+ sent: { label: 'Sent', type: 'success' },+ failed: { label: 'Failed', type: 'danger' },+ archived: { label: 'Archived', type: 'muted' },+}++export function BroadcastStatusTag({ status }: { status: BroadcastStatus }): JSX.Element {+ if (status === 'unknown') {+ return <span className="text-muted">…</span>+ }+ const config = STATUS_CONFIG[status]+ return <LemonTag type={config.type}>{config.label}</LemonTag>+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsxindex ce771a3a2db8..1cf11ed490de 100644--- a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx@@ -1,24 +1,26 @@import { BindLogic, useActions, useValues } from 'kea'import { useEffect } from 'react'-import { IconArrowLeft, IconLetter } from '@posthog/icons'+import { IconArrowLeft, IconChevronDown, IconLetter } from '@posthog/icons'import { LemonButton, LemonDialog, LemonDivider, LemonInput, LemonTag, LemonTagType } from '@posthog/lemon-ui'-import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'import { TZLabel } from 'lib/components/TZLabel'-import { dayjs } from 'lib/dayjs'+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { humanFriendlyNumber } from 'lib/utils/numbers'import { capitalizeFirstLetter } from 'lib/utils/strings'import { urls } from 'scenes/urls'import type { HogFlowBatchJobApi } from 'products/workflows/frontend/generated/api.schemas'-import { EmailMetricsSummary } from '../Workflows/EmailMetricsSummary'import { EmailViewerModal } from '../Workflows/EmailViewerModal'import type { MessageAsset } from '../Workflows/messageAssetsApi'+import { BroadcastEmailPreview } from './BroadcastEmailPreview'+import { BroadcastPerformance } from './BroadcastPerformance'import { broadcastSentLogic } from './broadcastSentLogic'+import { BroadcastStatusTag } from './BroadcastStatusTag'import { broadcastWizardLogic } from './broadcastWizardLogic'const BATCH_JOB_STATUS_TAG: Record<string, LemonTagType> = {@@ -231,6 +233,15 @@ function RunsTable({)}+const LATEST_RUN_LABEL: Record<string, string> = {+ completed: 'Sent',+ waiting: 'Sending, started',+ queued: 'Sending, started',+ active: 'Sending, started',+ failed: 'Last send failed, started',+ cancelled: 'Last send was cancelled, started',+}+export function BroadcastSummary(): JSX.Element {const {broadcast,@@ -243,8 +254,13 @@ export function BroadcastSummary(): JSX.Element {batchJobsLoading,canMoveToDraft,movingToDraft,+ canEditContent,+ duplicating,+ summaryStatus,+ summaryTab,} = useValues(broadcastWizardLogic)- const { moveToDraft } = useActions(broadcastWizardLogic)+ const { moveToDraft, duplicateBroadcast, setSummaryTab } = useActions(broadcastWizardLogic)+ const pendingSchedule = broadcast?.schedules?.find((schedule) => schedule.status === 'active')const confirmMoveToDraft = (): void => {LemonDialog.open({@@ -260,31 +276,8 @@ export function BroadcastSummary(): JSX.Element {})}- // Email metrics from a batch send are attributed to the batch job, not the flow (see- // `parentRunId ?? functionId` in the plugin server's email service), so a flow-scoped query- // returns zeros for every broadcast. Key the logic by the run so it remounts once runs load.const latestBatchJob = batchJobs[0]const latestBatchJobId = latestBatchJob?.id- const metricsSourceId = latestBatchJobId ?? broadcastId- const logicKey = `broadcast-${metricsSourceId}`- // Mounting with force params here pins the metrics query to this run; EmailMetricsSummary- // reads the same keyed logic below. The date window follows the run rather than a fixed- // lookback, so a send older than 30 days still shows its counts.- useValues(- appMetricsLogic({- logicKey,- loadOnMount: true,- loadOnChanges: true,- forceParams: {- appSource: 'hog_flow',- appSourceId: metricsSourceId ?? undefined,- breakdownBy: 'metric_name',- dateFrom: latestBatchJob ? dayjs(latestBatchJob.created_at).subtract(1, 'hour').toISOString() : '-30d',- dateTo: latestBatchJob ? dayjs().add(1, 'hour').toISOString() : undefined,- interval: 'day',- },- })- )const batchJobColumns: LemonTableColumns<HogFlowBatchJobApi> = [{@@ -309,68 +302,141 @@ export function BroadcastSummary(): JSX.Element {]return (- <div className="min-h-full w-full shrink-0 bg-bg-light">- <div className="mx-auto max-w-4xl space-y-5 px-6 py-6">- <div className="flex items-center justify-between gap-2">- <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.broadcasts()}>- Broadcasts- </LemonButton>- {canMoveToDraft ? (- <LemonButton- type="secondary"- size="small"- onClick={confirmMoveToDraft}- loading={movingToDraft}- data-attr="broadcast-move-to-draft"- >- Stop and edit- </LemonButton>- ) : null}- </div>+ <div className="@container min-h-full w-full shrink-0 bg-bg-light">+ <div className="mx-auto max-w-6xl space-y-4 px-6 py-6">+ <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.broadcasts()}>+ Broadcasts+ </LemonButton>- <div className="flex items-center gap-2">- <h1 className="m-0 text-2xl font-semibold">{name}</h1>- <LemonTag type={broadcast?.status === 'active' ? 'success' : 'default'}>- {capitalizeFirstLetter(broadcast?.status ?? 'draft')}- </LemonTag>- </div>-- <div className="flex flex-col gap-3 rounded-lg border border-border bg-surface-primary p-4">- <div className="flex flex-col gap-1">- <span className="text-xs font-semibold uppercase tracking-wide text-muted">Audience</span>- {audienceProperties.length > 0 ? (- <PropertyFiltersDisplay filters={audienceProperties} />- ) : (- <span className="text-muted">Everyone</span>- )}- </div>- <div className="flex flex-col gap-1">- <span className="text-xs font-semibold uppercase tracking-wide text-muted">Schedule</span>- <span>{scheduleSummary}</span>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex min-w-0 items-center gap-2">+ <BroadcastStatusTag status={summaryStatus} />+ <h1 className="m-0 truncate text-2xl font-semibold">{name}</h1></div>- <div className="flex flex-col gap-1">- <span className="text-xs font-semibold uppercase tracking-wide text-muted">Email subject</span>- <span>{email.subject || 'No subject'}</span>- </div>- </div>-- <div className="flex flex-col gap-2">- <h2 className="m-0 text-lg font-semibold">- {latestBatchJobId ? 'Performance (latest send)' : 'Performance (last 30 days)'}- </h2>- <EmailMetricsSummary logicKey={logicKey} compact />+ {canMoveToDraft || canEditContent ? (+ <LemonMenu+ items={[+ canMoveToDraft+ ? {+ label: 'Stop and edit',+ onClick: confirmMoveToDraft,+ 'data-attr': 'broadcast-move-to-draft',+ }+ : null,+ canEditContent+ ? {+ label: 'Send again as a new broadcast',+ onClick: duplicateBroadcast,+ 'data-attr': 'broadcast-send-again',+ }+ : null,+ ]}+ >+ <LemonButton+ type="secondary"+ size="small"+ sideIcon={<IconChevronDown />}+ loading={movingToDraft || duplicating}+ data-attr="broadcast-actions"+ >+ Actions+ </LemonButton>+ </LemonMenu>+ ) : null}</div>- <div className="flex flex-col gap-2">- <h2 className="m-0 text-lg font-semibold">Runs</h2>- <RunsTable- workflowId={broadcastId ?? ''}- batchJobs={batchJobs}- batchJobsLoading={batchJobsLoading}- columns={batchJobColumns}- />- </div>+ <LemonTabs+ activeKey={summaryTab}+ onChange={setSummaryTab}+ tabs={[+ {+ key: 'overview',+ 'data-attr': 'broadcast-summary-tab-overview',+ label: 'Overview',+ content: (+ <div className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-4 rounded-lg border border-border bg-surface-primary p-4 @2xl:grid-cols-3">+ <SummaryRow label="Audience">+ {audienceProperties.length > 0 ? (+ <PropertyFiltersDisplay filters={audienceProperties} />+ ) : (+ <span className="text-muted">Everyone</span>+ )}+ </SummaryRow>+ <SummaryRow label="Schedule">+ {pendingSchedule ? (+ <div className="flex flex-col gap-0.5">+ <span>{scheduleSummary}</span>+ {pendingSchedule.next_run_at ? (+ <span className="text-xs text-muted">+ Next send <TZLabel time={pendingSchedule.next_run_at} />+ </span>+ ) : null}+ </div>+ ) : latestBatchJob ? (+ <span>+ {LATEST_RUN_LABEL[latestBatchJob.status ?? 'waiting'] ?? 'Last run'}{' '}+ <TZLabel time={latestBatchJob.created_at} />+ </span>+ ) : (+ <span>{scheduleSummary}</span>+ )}+ </SummaryRow>+ <SummaryRow label="Subject">+ {email.subject || <span className="text-muted">No subject</span>}+ </SummaryRow>+ </div>+ <div className="flex flex-col gap-2">+ <h2 className="m-0 text-base font-semibold">+ {latestBatchJobId ? 'Performance (latest send)' : 'Performance'}+ </h2>+ {latestBatchJob ? (+ <BroadcastPerformance+ runId={latestBatchJob.id}+ runStartedAt={latestBatchJob.created_at}+ />+ ) : (+ <span className="text-muted">+ Numbers show up here once the first send goes out.+ </span>+ )}+ </div>+ </div>+ ),+ },+ {+ key: 'content',+ 'data-attr': 'broadcast-summary-tab-content',+ label: 'Content',+ content: (+ <BroadcastEmailPreview intro="Preview the email for anyone in the audience, or send yourself a test." />+ ),+ },+ {+ key: 'runs',+ 'data-attr': 'broadcast-summary-tab-runs',+ label: 'Runs',+ content: (+ <RunsTable+ workflowId={broadcastId ?? ''}+ batchJobs={batchJobs}+ batchJobsLoading={batchJobsLoading}+ columns={batchJobColumns}+ />+ ),+ },+ ]}+ /></div></div>)}++function SummaryRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+ return (+ <div className="flex flex-col gap-1">+ <span className="text-xs font-semibold uppercase tracking-wide text-muted">{label}</span>+ {children}+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsxindex 26c495786e64..e9b32c96de70 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonInput, LemonSelect, LemonTag, LemonTagType } from '@posthog/lemon-ui'+import { LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'import { MemberSelect } from 'lib/components/MemberSelect'import { LemonButton } from 'lib/lemon-ui/LemonButton'@@ -14,21 +14,12 @@ import type { HogFlowMinimalApi } from 'products/workflows/frontend/generated/apimport {BROADCASTS_PAGE_SIZE,- BroadcastStatus,BroadcastsStatusFilter,broadcastsLogic,getBroadcastStatus,isEligibleWorkflow,} from './broadcastsLogic'--const STATUS_CONFIG: Record<Exclude<BroadcastStatus, 'unknown'>, { label: string; type: LemonTagType }> = {- draft: { label: 'Draft', type: 'default' },- scheduled: { label: 'Scheduled', type: 'warning' },- sending: { label: 'Sending', type: 'completion' },- sent: { label: 'Sent', type: 'success' },- failed: { label: 'Failed', type: 'danger' },- archived: { label: 'Archived', type: 'muted' },-}+import { BroadcastStatusTag } from './BroadcastStatusTag'const METRIC_COLUMNS: { title: string; metricName: string }[] = [{ title: 'Sent', metricName: 'email_sent' },@@ -74,12 +65,7 @@ export function BroadcastsTable(): JSX.Element {title: 'Status',width: 0,render: (_, item) => {- const status = getBroadcastStatus(item, rowDetailsById[item.id])- if (status === 'unknown') {- return <span className="text-muted">…</span>- }- const config = STATUS_CONFIG[status]- return <LemonTag type={config.type}>{config.label}</LemonTag>+ return <BroadcastStatusTag status={getBroadcastStatus(item, rowDetailsById[item.id])} />},},...METRIC_COLUMNS.map(({ title, metricName }) => ({diff --git a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.tsnew file mode 100644index 000000000000..c6337f7666d8--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts@@ -0,0 +1,197 @@+import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'+import { dayjs } from 'lib/dayjs'+import { teamLogic } from 'scenes/teamLogic'++import type { TeamPublicType, TeamType } from '../../../../frontend/src/types'+import { type EmailLinkRow, parseEmailLinkTotals } from '../Workflows/workflowMetricsSummaryLogic'++export interface BroadcastPerformanceLogicProps {+ /** The batch run the numbers belong to. A batch send's email metrics are recorded against the run, not the flow. */+ runId: string+ runStartedAt: string+}++export interface BroadcastPerformanceStats {+ sent: number+ delivered: number+ opened: number+ clicked: number+ bounced: number+ markedAsSpam: number+ failed: number+ /** Sends with open and click tracking, the denominator for engagement rates. */+ trackedSends: number+}++const TOTALS_METRICS = [+ 'email_sent',+ 'email_delivered',+ 'email_opened',+ 'email_link_clicked',+ 'email_bounced',+ 'email_blocked',+ 'email_failed',+ 'email_untracked',+]++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastPerformanceLogicValues {+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ links: EmailLinkRow[]+ linksLoading: boolean+ stats: BroadcastPerformanceStats | null+ totals: Record<string, number> | null+ totalsFailed: boolean+ totalsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastPerformanceLogicActions {+ loadLinks: () => any+ loadLinksFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadLinksSuccess: (+ links: EmailLinkRow[],+ payload?: any+ ) => {+ links: EmailLinkRow[]+ payload?: any+ }+ loadTotals: () => any+ loadTotalsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTotalsSuccess: (+ totals: {+ [k: string]: number+ },+ payload?: any+ ) => {+ totals: {+ [k: string]: number+ }+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastPerformanceLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ stats: (totals: Record<string, number> | null) => BroadcastPerformanceStats | null+ }+}++export type broadcastPerformanceLogicType = MakeLogicType<+ broadcastPerformanceLogicValues,+ broadcastPerformanceLogicActions,+ BroadcastPerformanceLogicProps,+ broadcastPerformanceLogicMeta+>++export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([+ path((runId) => ['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastPerformanceLogic', runId]),+ props({} as BroadcastPerformanceLogicProps),+ key((props) => props.runId),+ connect(() => ({+ values: [teamLogic, ['currentTeam']],+ })),+ loaders(({ props, values }) => {+ const window = (): { dateFrom: string; dateTo: string } => ({+ dateFrom: dayjs(props.runStartedAt).subtract(1, 'hour').toISOString(),+ dateTo: dayjs().add(1, 'hour').toISOString(),+ })+ return {+ totals: [+ null as Record<string, number> | null,+ {+ loadTotals: async () => {+ const response = await loadAppMetricsTotals(+ {+ appSource: 'hog_flow',+ appSourceId: props.runId,+ metricName: TOTALS_METRICS,+ breakdownBy: ['metric_name'],+ ...window(),+ },+ values.currentTeam?.timezone ?? 'UTC'+ )+ return Object.fromEntries(+ Object.values(response).map(({ total, breakdowns }) => [breakdowns[0], total])+ )+ },+ },+ ],+ links: [+ [] as EmailLinkRow[],+ {+ loadLinks: async () => {+ const response = await loadAppMetricsTotals(+ {+ appSource: 'hog_flow',+ appSourceId: props.runId,+ metricName: ['email_link_clicked_by_link'],+ breakdownBy: ['instance_id'],+ limit: 100,+ ...window(),+ },+ values.currentTeam?.timezone ?? 'UTC'+ )+ // A broadcast has one email step, so its links are every link in the run.+ return Object.values(parseEmailLinkTotals(response))+ .flat()+ .sort((a, b) => b.clicks - a.clicks)+ },+ },+ ],+ }+ }),+ reducers({+ totalsFailed: [+ false,+ {+ loadTotals: () => false,+ loadTotalsSuccess: () => false,+ loadTotalsFailure: () => true,+ },+ ],+ }),+ selectors({+ stats: [+ (s) => [s.totals],+ (totals: Record<string, number> | null): BroadcastPerformanceStats | null => {+ if (!totals) {+ return null+ }+ const sent = totals.email_sent ?? 0+ return {+ sent,+ delivered: totals.email_delivered ?? 0,+ opened: totals.email_opened ?? 0,+ clicked: totals.email_link_clicked ?? 0,+ bounced: totals.email_bounced ?? 0,+ // Spam complaints are stored under email_blocked.+ markedAsSpam: totals.email_blocked ?? 0,+ failed: totals.email_failed ?? 0,+ trackedSends: Math.max(sent - (totals.email_untracked ?? 0), 0),+ }+ },+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadTotals()+ actions.loadLinks()+ }),+])diff --git a/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts b/products/workflows/frontend/Broadcasts/broadcastStatus.test.tsindex 993140713164..72ca8ea66e06 100644--- a/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts+++ b/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts@@ -13,12 +13,25 @@ describe('getBroadcastStatus', () => {['a draft, whatever its runs say', flow('draft'), withJob('completed'), 'draft'],['an archived broadcast', flow('archived'), withJob('completed'), 'archived'],['a run still going', flow('active'), withJob('active'), 'sending'],- ['a run that finished', flow('active'), withJob('completed'), 'sent'],+ ['a run that finished', flow('active'), { ...withJob('completed'), hasPendingSchedule: false }, 'sent'],+ ['a finished run whose schedules did not load', flow('active'), withJob('completed'), 'unknown'],// A terminal run used to fall through to the no-run fallback and read as "scheduled",// telling the sender another send was pending when nothing was coming.['a run that failed', flow('active'), withJob('failed'), 'failed'],['a run that was cancelled', flow('active'), withJob('cancelled'), 'failed'],['no run yet', flow('active'), { latestBatchJob: null, totals: {} }, 'scheduled'],+ [+ 'a recurring broadcast between runs',+ flow('active'),+ { ...withJob('completed'), hasPendingSchedule: true },+ 'scheduled',+ ],+ [+ 'a recurring broadcast whose last run failed',+ flow('active'),+ { ...withJob('failed'), hasPendingSchedule: true },+ 'failed',+ ],// Runs not loaded yet, or failed to load, used to read as "scheduled" for a broadcast that already sent.['a live broadcast whose runs have not loaded', flow('active'), undefined, 'unknown'],])('reads %s as %s', (_name, broadcast, details, expected) => {diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.tsindex 79fc8a594a1c..7569b9f3070a 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts@@ -43,7 +43,13 @@ import {parseRRuleToState,stateToRRule,} from '../Workflows/hogflows/steps/components/rrule-helpers'-import { StoppableBroadcast, canMoveToDraft } from './broadcastsLogic'+import {+ BroadcastStatus,+ StoppableBroadcast,+ canEditInWizard,+ canMoveToDraft,+ getBroadcastStatus,+} from './broadcastsLogic'export type BroadcastWizardStep = 'recipients' | 'goal' | 'content' | 'schedule' | 'review'@@ -95,6 +101,8 @@ function findAction(broadcast: HogFlowApi, type: string): Record<string, any> |return flowActions.find((action) => action.type === type)}+export type BroadcastSummaryTab = 'overview' | 'content' | 'runs'+export interface BroadcastWizardLogicProps {id: string // 'new' for new broadcasts, or a UUID for editing/viewing}@@ -112,10 +120,12 @@ export interface broadcastWizardLogicValues {broadcast: HogFlowApi | nullbroadcastId: string | nullbroadcastLoading: boolean+ canEditContent: booleancanMoveToDraft: booleanconversion: HogFlowConversionApicurrentStep: BroadcastWizardStepcurrentStepHasErrors: boolean+ duplicating: booleaneffectiveTimezone: stringemail: BroadcastEmailValueemailRateLimit: HogFlowEmailSendingRateLimitApi | null@@ -139,6 +149,8 @@ export interface broadcastWizardLogicValues {scheduleTimezone: string | nullsendAt: string | nullstepValidationErrors: Record<BroadcastWizardStep, string[]>+ summaryStatus: BroadcastStatus+ summaryTab: BroadcastSummaryTab}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -149,6 +161,12 @@ export interface broadcastWizardLogicActions {continueStep: () => {value: true}+ duplicateBroadcast: () => {+ value: true+ }+ duplicateBroadcastFinished: () => {+ value: true+ }expandRun: (runId: string) => {runId: string}@@ -277,6 +295,9 @@ export interface broadcastWizardLogicActions {setStep: (step: BroadcastWizardStep) => {step: BroadcastWizardStep}+ setSummaryTab: (tab: BroadcastSummaryTab) => {+ tab: BroadcastSummaryTab+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -290,6 +311,12 @@ export interface broadcastWizardLogicMeta {batchJobs: HogFlowBatchJobApi[],hasLoadedBatchJobs: boolean) => boolean+ canEditContent: (broadcast: HogFlowApi | null) => boolean+ summaryStatus: (+ broadcast: HogFlowApi | null,+ batchJobs: HogFlowBatchJobApi[],+ hasLoadedBatchJobs: boolean+ ) => BroadcastStatusisReadOnly: (broadcast: HogFlowApi | null) => booleaneffectiveTimezone: (scheduleTimezone: string | null, currentTeam: TeamPublicType | TeamType | null) => stringstepValidationErrors: (@@ -364,10 +391,13 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([expandRun: (runId: string) => ({ runId }),collapseRun: (runId: string) => ({ runId }),setExpandedRunOverride: (runIds: string[]) => ({ runIds }),+ setSummaryTab: (tab: BroadcastSummaryTab) => ({ tab }),launchBroadcast: true,launchBroadcastFinished: true,moveToDraft: true,moveToDraftFinished: true,+ duplicateBroadcast: true,+ duplicateBroadcastFinished: true,}),loaders(({ props, values }) => ({@@ -415,6 +445,12 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([broadcast ?? state,},// Null until the sender expands or collapses a run; until then the latest run shows open.+ summaryTab: [+ 'overview' as BroadcastSummaryTab,+ {+ setSummaryTab: (_, { tab }) => tab,+ },+ ],expandedRunOverride: [null as string[] | null,{@@ -575,6 +611,13 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([moveToDraftFinished: () => false,},],+ duplicating: [+ false,+ {+ duplicateBroadcast: () => true,+ duplicateBroadcastFinished: () => false,+ },+ ],// Set once the initial load of an existing draft has hydrated the reducers, so the wizard can// resume at the first incomplete step exactly once.hasHydrated: [@@ -601,6 +644,33 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([(broadcast: HogFlowApi | null, batchJobs: HogFlowBatchJobApi[], hasLoadedBatchJobs: boolean): boolean =>canMoveToDraft(broadcast as StoppableBroadcast | null, hasLoadedBatchJobs ? batchJobs : null),],+ canEditContent: [+ (s) => [s.broadcast],+ (broadcast: HogFlowApi | null): boolean =>+ !!broadcast && canEditInWizard(broadcast.actions as any, broadcast.edges as any),+ ],+ summaryStatus: [+ (s) => [s.broadcast, s.batchJobs, s.hasLoadedBatchJobs],+ (+ broadcast: HogFlowApi | null,+ batchJobs: HogFlowBatchJobApi[],+ hasLoadedBatchJobs: boolean+ ): BroadcastStatus =>+ broadcast+ ? getBroadcastStatus(+ broadcast,+ hasLoadedBatchJobs+ ? {+ latestBatchJob: batchJobs[0] ?? null,+ totals: null,+ hasPendingSchedule: !!broadcast.schedules?.some(+ (schedule) => schedule.status === 'active'+ ),+ }+ : undefined+ )+ : 'unknown',+ ],isReadOnly: [(s) => [s.broadcast],(broadcast: HogFlowApi | null): boolean => !!broadcast && broadcast.status !== 'draft',@@ -960,6 +1030,25 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([}actions.moveToDraftFinished()},+ duplicateBroadcast: async () => {+ if (!values.currentProjectId) {+ actions.duplicateBroadcastFinished()+ return+ }+ try {+ // A fresh broadcast with this one's audience and email, so sending again goes through+ // the wizard's review and launch like any other send.+ const copy = await hogFlowsCreate(+ String(values.currentProjectId),+ buildBroadcastPayload({ ...values, name: `${values.name} (copy)`, broadcast: null }) as any+ )+ actions.duplicateBroadcastFinished()+ router.actions.push(urls.broadcast(copy.id))+ } catch (error: any) {+ actions.duplicateBroadcastFinished()+ lemonToast.error(`Couldn't copy the broadcast: ${error?.detail || error?.message || 'unknown error'}`)+ }+ },loadBroadcastSuccess: ({ broadcast }) => {if (!broadcast || values.hasHydrated) {returndiff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.tsindex d9dde51b104b..884862c8124e 100644--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts@@ -13,7 +13,7 @@ import { urls } from 'scenes/urls'import { TeamPublicType, TeamType } from '~/types'-import { hogFlowsBatchJobsList, hogFlowsList } from 'products/workflows/frontend/generated/api'+import { hogFlowsBatchJobsList, hogFlowsList, hogFlowsSchedulesList } from 'products/workflows/frontend/generated/api'import type {HogFlowApi,HogFlowBatchJobApi,@@ -28,6 +28,8 @@ export interface BroadcastRowDetails {latestBatchJob: HogFlowBatchJobApi | null/** Null until the run's metrics load, or when they fail to. */totals: Record<string, number> | null+ /** Whether an active schedule has sends still to come. Unset when the schedules couldn't load. */+ hasPendingSchedule?: boolean}/** Rows per page. Each row loads its latest run and metrics, so a page stays small enough to enrich. */@@ -119,7 +121,7 @@ export function isEligibleWorkflow(flow: Pick<HogFlowMinimalApi, 'origin_product}export function getBroadcastStatus(- broadcast: HogFlowMinimalApi,+ broadcast: { status?: string | null },details: BroadcastRowDetails | undefined): BroadcastStatus {if (broadcast.status === 'draft') {@@ -137,7 +139,11 @@ export function getBroadcastStatus(return 'sending'}if (latestJob.status === 'completed') {- return 'sent'+ // A recurring broadcast between runs has more to send. A failed run still reads as failed.+ if (details.hasPendingSchedule === undefined) {+ return 'unknown'+ }+ return details.hasPendingSchedule ? 'scheduled' : 'sent'}// Without this a failed or cancelled run falls through to the no-run fallback below, which// tells the sender another send is still pending when nothing is coming.@@ -351,12 +357,19 @@ export const broadcastsLogic = kea<broadcastsLogicType>([for (const broadcast of broadcasts.results ?? []) {void (async () => {let latestBatchJob: HogFlowBatchJobApi | null+ let hasPendingSchedule: boolean | undefinedtry {- const batchJobs =+ // The list rows carry no schedules, and a recurring broadcast between runs needs them+ // to read as scheduled. A failed schedules request only loses that distinction.+ const [batchJobs, schedules] =broadcast.status === 'draft'- ? ([] as HogFlowBatchJobApi[])- : await hogFlowsBatchJobsList(String(projectId), broadcast.id)+ ? [[] as HogFlowBatchJobApi[], undefined]+ : await Promise.all([+ hogFlowsBatchJobsList(String(projectId), broadcast.id),+ hogFlowsSchedulesList(String(projectId), broadcast.id).catch(() => undefined),+ ])latestBatchJob = batchJobs[0] ?? null+ hasPendingSchedule = schedules?.some((schedule) => schedule.status === 'active')} catch {if (isCurrent()) {actions.clearRowDetails(broadcast.id)@@ -366,14 +379,18 @@ export const broadcastsLogic = kea<broadcastsLogicType>([if (!isCurrent()) {return}- actions.setRowDetails(broadcast.id, { latestBatchJob, totals: latestBatchJob ? null : {} })+ actions.setRowDetails(broadcast.id, {+ latestBatchJob,+ totals: latestBatchJob ? null : {},+ hasPendingSchedule,+ })if (!latestBatchJob) {return}try {const totals = await loadRunMetricTotals(latestBatchJob, values.currentTeam?.timezone ?? 'UTC')if (isCurrent()) {- actions.setRowDetails(broadcast.id, { latestBatchJob, totals })+ actions.setRowDetails(broadcast.id, { latestBatchJob, totals, hasPendingSchedule })}} catch {// The counts stay unknown; the status already rendered from the run.diff --git a/products/workflows/frontend/Workflows/EmailLinksTable.tsx b/products/workflows/frontend/Workflows/EmailLinksTable.tsxnew file mode 100644index 000000000000..41a4e14d4f4a--- /dev/null+++ b/products/workflows/frontend/Workflows/EmailLinksTable.tsx@@ -0,0 +1,62 @@+import { LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import { type EmailLinkRow } from './workflowMetricsSummaryLogic'++const EMAIL_LINK_COLUMNS: LemonTableColumns<EmailLinkRow> = [+ {+ title: 'Link',+ key: 'url',+ render: (_: unknown, row: EmailLinkRow) => (+ <div className="flex items-center gap-2">+ {row.truncated ? (+ // Navigating to a URL that was cut mid-path would land somewhere wrong,+ // so show it as text rather than something clickable.+ <span className="break-all" title="This link was too long to store in full">+ {row.url}…+ </span>+ ) : (+ <Link to={row.url} target="_blank" className="break-all">+ {row.url}+ </Link>+ )}+ {row.duplicateUrl && row.linkIndex ? (+ <LemonTag type="muted" title="Another link in this email points to the same page">+ Position {row.linkIndex}+ </LemonTag>+ ) : null}+ </div>+ ),+ },+ {+ title: 'Clicks',+ key: 'clicks',+ align: 'right',+ render: (_: unknown, row: EmailLinkRow) => humanFriendlyNumber(row.clicks),+ },+]++export function EmailLinksTable({+ links,+ loading,+ embedded,+ emptyState,+}: {+ links: EmailLinkRow[]+ loading?: boolean+ embedded?: boolean+ emptyState?: string+}): JSX.Element {+ return (+ <LemonTable+ columns={EMAIL_LINK_COLUMNS}+ dataSource={links}+ loading={loading}+ rowKey={(link) => `${link.linkIndex}:${link.url}`}+ size="small"+ embedded={embedded}+ emptyState={emptyState}+ />+ )+}diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsxindex 5ace42e54a5c..96cdf368227d 100644--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx@@ -10,9 +10,9 @@ import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'import { type ExpandableConfig } from 'lib/lemon-ui/LemonTable'import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'+import { EmailLinksTable } from './EmailLinksTable'import { WorkflowMetricCard } from './WorkflowMetricCard'import {- type EmailLinkRow,type EmailMetric,type EmailMetricRow,METRIC_COLORS,@@ -185,56 +185,14 @@ export function WorkflowMetricsSummary({]}, [onSelectAction, onMetricClick, viewMetricsColumn])- const emailLinkColumns: LemonTableColumns<EmailLinkRow> = useMemo(- () => [- {- title: 'Link',- key: 'url',- render: (_: unknown, row: EmailLinkRow) => (- <div className="flex items-center gap-2">- {row.truncated ? (- // Navigating to a URL that was cut mid-path would land somewhere wrong,- // so show it as text rather than something clickable.- <span className="break-all" title="This link was too long to store in full">- {row.url}…- </span>- ) : (- <Link to={row.url} target="_blank" className="break-all">- {row.url}- </Link>- )}- {row.duplicateUrl && row.linkIndex ? (- <LemonTag type="muted" title="Another link in this email points to the same page">- Position {row.linkIndex}- </LemonTag>- ) : null}- </div>- ),- },- {- title: 'Clicks',- key: 'clicks',- align: 'right',- render: (_: unknown, row: EmailLinkRow) => humanFriendlyNumber(row.clicks),- },- ],- []- )-const emailExpandable: ExpandableConfig<EmailMetricRow> = useMemo(() => ({rowExpandable: (row: EmailMetricRow) => (emailLinkTotalsByActionId[row.id]?.length ?? 0) > 0,expandedRowRender: (row: EmailMetricRow) => (- <LemonTable- columns={emailLinkColumns}- dataSource={emailLinkTotalsByActionId[row.id] ?? []}- rowKey={(link) => `${link.linkIndex}:${link.url}`}- size="small"- embedded- />+ <EmailLinksTable links={emailLinkTotalsByActionId[row.id] ?? []} embedded />),}),- [emailLinkTotalsByActionId, emailLinkColumns]+ [emailLinkTotalsByActionId])const pushColumns: LemonTableColumns<PushMetricRow> = useMemo(() => {