: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): add search, status and creator filters to the broadcasts list (#106464)
Daniel Marchuk9293faea469a
diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsxindex 30936cb70451..26c495786e64 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx@@ -1,7 +1,8 @@import { useActions, useValues } from 'kea'-import { LemonTag, LemonTagType } from '@posthog/lemon-ui'+import { LemonInput, LemonSelect, LemonTag, LemonTagType } from '@posthog/lemon-ui'+import { MemberSelect } from 'lib/components/MemberSelect'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'@@ -14,12 +15,13 @@ import type { HogFlowMinimalApi } from 'products/workflows/frontend/generated/apimport {BROADCASTS_PAGE_SIZE,BroadcastStatus,+ BroadcastsStatusFilter,broadcastsLogic,getBroadcastStatus,isEligibleWorkflow,} from './broadcastsLogic'-const STATUS_CONFIG: Record<BroadcastStatus, { label: string; type: LemonTagType }> = {+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' },@@ -37,8 +39,13 @@ const METRIC_COLUMNS: { title: string; metricName: string }[] = []export function BroadcastsTable(): JSX.Element {- const { broadcasts, broadcastsLoading, hasLoadedBroadcasts, rowDetailsById, page } = useValues(broadcastsLogic)- const { setPage } = useActions(broadcastsLogic)+ const { broadcasts, broadcastsLoading, hasLoadedBroadcasts, rowDetailsById, filters, filtersPending, loadFailed } =+ useValues(broadcastsLogic)+ // Rows from other filters stay behind the loading state, and are dropped once the load for these fails.+ const hideRows = loadFailed && filtersPending+ const { setFilters } = useActions(broadcastsLogic)+ const { page } = filters+ const isFiltered = !!filters.search || filters.status !== 'all' || !!filters.createdByconst columns: LemonTableColumns<HogFlowMinimalApi> = [{@@ -67,7 +74,11 @@ export function BroadcastsTable(): JSX.Element {title: 'Status',width: 0,render: (_, item) => {- const config = STATUS_CONFIG[getBroadcastStatus(item, rowDetailsById[item.id])]+ 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>},},@@ -80,7 +91,7 @@ export function BroadcastsTable(): JSX.Element {if (item.status === 'draft') {return <span className="text-muted">-</span>}- if (!details) {+ if (!details?.totals) {return <span className="text-muted">…</span>}return <span>{humanFriendlyNumber(details.totals[metricName] ?? 0)}</span>@@ -90,7 +101,13 @@ export function BroadcastsTable(): JSX.Element {createdAtColumn() as LemonTableColumns<HogFlowMinimalApi>[number],]- const isEmpty = hasLoadedBroadcasts && !broadcastsLoading && broadcasts.results.length === 0+ const isEmpty =+ hasLoadedBroadcasts &&+ !broadcastsLoading &&+ !filtersPending &&+ !loadFailed &&+ !isFiltered &&+ broadcasts.count === 0if (isEmpty) {return (@@ -108,22 +125,62 @@ export function BroadcastsTable(): JSX.Element {}return (- <LemonTable- dataSource={broadcasts.results}- pagination={{- controlled: true,- pageSize: BROADCASTS_PAGE_SIZE,- currentPage: page,- entryCount: broadcasts.count,- onForward: broadcasts.next ? () => setPage(page + 1) : undefined,- onBackward: page > 1 ? () => setPage(page - 1) : undefined,- }}- loading={broadcastsLoading}- rowKey="id"- columns={columns}- nouns={['broadcast', 'broadcasts']}- emptyState="No broadcasts"- data-attr="broadcasts-table"- />+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <LemonInput+ type="search"+ placeholder="Search broadcasts"+ onChange={(search) => setFilters({ search })}+ value={filters.search}+ // The API rejects longer search terms.+ maxLength={200}+ data-attr="broadcasts-search"+ />+ <div className="flex flex-wrap items-center gap-2">+ <b>Status</b>+ <LemonSelect+ dropdownMatchSelectWidth={false}+ size="small"+ onChange={(status) => setFilters({ status: status as BroadcastsStatusFilter })}+ options={[+ { label: 'All', value: 'all' },+ { label: 'Active', value: 'active' },+ { label: 'Draft', value: 'draft' },+ { label: 'Archived', value: 'archived' },+ ]}+ value={filters.status}+ data-attr="broadcasts-status-filter"+ />+ <b className="ml-1">Created by</b>+ <MemberSelect+ value={filters.createdBy}+ onChange={(user) => setFilters({ createdBy: user?.uuid || null })}+ />+ </div>+ </div>+ <LemonTable+ dataSource={hideRows ? [] : broadcasts.results}+ pagination={{+ controlled: true,+ pageSize: BROADCASTS_PAGE_SIZE,+ currentPage: page,+ entryCount: broadcasts.count,+ onForward: broadcasts.next ? () => setFilters({ page: page + 1 }) : undefined,+ onBackward: page > 1 ? () => setFilters({ page: page - 1 }) : undefined,+ }}+ loading={broadcastsLoading || (filtersPending && !loadFailed)}+ rowKey="id"+ columns={columns}+ nouns={['broadcast', 'broadcasts']}+ emptyState={+ loadFailed+ ? "Couldn't load broadcasts. Refresh the page to try again."+ : isFiltered+ ? 'No broadcasts match these filters'+ : 'No broadcasts'+ }+ data-attr="broadcasts-table"+ />+ </div>)}diff --git a/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts b/products/workflows/frontend/Broadcasts/broadcastStatus.test.tsindex 250fce272020..993140713164 100644--- a/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts+++ b/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts@@ -18,7 +18,9 @@ describe('getBroadcastStatus', () => {// 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'), undefined, 'scheduled'],+ ['no run yet', flow('active'), { latestBatchJob: null, totals: {} }, 'scheduled'],+ // 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) => {expect(getBroadcastStatus(broadcast, details)).toBe(expected)})diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.tsindex 88eff4467ff7..999a8fcf386f 100644--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts@@ -1,12 +1,15 @@-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import { loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'import { dayjs } from 'lib/dayjs'+import { objectsEqual } from 'lib/utils/objects'import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { TeamPublicType, TeamType } from '~/types'@@ -17,16 +20,28 @@ import type {PaginatedHogFlowMinimalListApi,} from 'products/workflows/frontend/generated/api.schemas'-export type BroadcastStatus = 'draft' | 'scheduled' | 'sending' | 'sent' | 'failed' | 'archived'+export type BroadcastStatus = 'draft' | 'scheduled' | 'sending' | 'sent' | 'failed' | 'archived' | 'unknown'export interface BroadcastRowDetails {latestBatchJob: HogFlowBatchJobApi | null- totals: Record<string, number>+ /** Null until the run's metrics load, or when they fail to. */+ totals: Record<string, number> | null}-/** An ordinary workflow shaped like a broadcast. It opens in the workflow editor, since the wizard would rewrite its graph. *//** Rows per page. Each row loads its latest run and metrics, so a page stays small enough to enrich. */-export const BROADCASTS_PAGE_SIZE = 100+export const BROADCASTS_PAGE_SIZE = 30++export type BroadcastsStatusFilter = 'all' | 'draft' | 'active' | 'archived'+const BROADCASTS_STATUS_FILTERS: BroadcastsStatusFilter[] = ['all', 'draft', 'active', 'archived']++export interface BroadcastsFilters {+ search: string+ status: BroadcastsStatusFilter+ createdBy: string | null+ page: number+}++const DEFAULT_FILTERS: BroadcastsFilters = { search: '', status: 'all', createdBy: null, page: 1 }/** Mirrors the list API's broadcast_eligible filter: a batch trigger, one email step, nothing else. */export function isBroadcastShaped(@@ -86,7 +101,10 @@ export function getBroadcastStatus(if (broadcast.status === 'archived') {return 'archived'}- const latestJob = details?.latestBatchJob+ if (!details) {+ return 'unknown'+ }+ const latestJob = details.latestBatchJobif (latestJob) {if (['waiting', 'queued', 'active'].includes(latestJob.status ?? '')) {return 'sending'@@ -125,13 +143,20 @@ export interface broadcastsLogicValues {currentTeam: TeamPublicType | TeamType | null // teamLogicbroadcasts: PaginatedHogFlowMinimalListApibroadcastsLoading: boolean+ filters: BroadcastsFilters+ filtersPending: booleanhasLoadedBroadcasts: boolean- page: number+ listGeneration: number+ loadFailed: boolean+ loadedFilters: BroadcastsFilters | nullrowDetailsById: Record<string, BroadcastRowDetails>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface broadcastsLogicActions {+ clearRowDetails: (id: string) => {+ id: string+ }loadBroadcasts: () => {value: true}@@ -153,8 +178,14 @@ export interface broadcastsLogicActions {value: true}}- setPage: (page: number) => {- page: number+ setFilters: (filters: Partial<BroadcastsFilters>) => {+ filters: Partial<BroadcastsFilters>+ }+ setFiltersFromUrl: (filters: BroadcastsFilters) => {+ filters: BroadcastsFilters+ }+ setLoadedFilters: (filters: BroadcastsFilters) => {+ filters: BroadcastsFilters}setRowDetails: (id: string,@@ -165,7 +196,19 @@ export interface broadcastsLogicActions {}}-export type broadcastsLogicType = MakeLogicType<broadcastsLogicValues, broadcastsLogicActions>+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ filtersPending: (filters: BroadcastsFilters, loadedFilters: BroadcastsFilters | null) => boolean+ }+}++export type broadcastsLogicType = MakeLogicType<+ broadcastsLogicValues,+ broadcastsLogicActions,+ Record<string, any>,+ broadcastsLogicMeta+>export const broadcastsLogic = kea<broadcastsLogicType>([path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastsLogic']),@@ -174,24 +217,34 @@ export const broadcastsLogic = kea<broadcastsLogicType>([})),actions({loadBroadcasts: true,- setPage: (page: number) => ({ page }),+ setFilters: (filters: Partial<BroadcastsFilters>) => ({ filters }),+ setFiltersFromUrl: (filters: BroadcastsFilters) => ({ filters }),setRowDetails: (id: string, details: BroadcastRowDetails) => ({ id, details }),+ clearRowDetails: (id: string) => ({ id }),+ setLoadedFilters: (filters: BroadcastsFilters) => ({ filters }),}),- loaders(({ values }) => ({+ loaders(({ actions, values }) => ({broadcasts: [{ results: [], count: 0 } as PaginatedHogFlowMinimalListApi,{- loadBroadcasts: async () => {+ loadBroadcasts: async (_, breakpoint) => {if (!values.currentProjectId) {return values.broadcasts}- return await hogFlowsList(String(values.currentProjectId), {+ const requested = values.filters+ const response = await hogFlowsList(String(values.currentProjectId), {// Broadcasts plus the ordinary workflows already shaped like one (a batch// trigger and a single email), so existing sends show up here too.broadcast_eligible: true,+ search: values.filters.search || undefined,+ status: values.filters.status !== 'all' ? values.filters.status : undefined,+ created_by: values.filters.createdBy || undefined,limit: BROADCASTS_PAGE_SIZE,- offset: (values.page - 1) * BROADCASTS_PAGE_SIZE,+ offset: (values.filters.page - 1) * BROADCASTS_PAGE_SIZE,})+ breakpoint()+ actions.setLoadedFilters(requested)+ return response},},],@@ -201,6 +254,31 @@ export const broadcastsLogic = kea<broadcastsLogicType>([{} as Record<string, BroadcastRowDetails>,{setRowDetails: (state, { id, details }) => ({ ...state, [id]: details }),+ clearRowDetails: (state, { id }) => {+ const { [id]: _, ...rest } = state+ return rest+ },+ },+ ],+ // The filters the shown rows were loaded for, so rows from other filters never read as results.+ loadedFilters: [+ null as BroadcastsFilters | null,+ {+ setLoadedFilters: (_, { filters }) => filters,+ },+ ],+ loadFailed: [+ false,+ {+ loadBroadcasts: () => false,+ loadBroadcastsFailure: () => true,+ },+ ],+ // Bumped per list load, so a slow row lookup from an earlier load can't change a newer one's rows.+ listGeneration: [+ 0,+ {+ loadBroadcastsSuccess: (state) => state + 1,},],hasLoadedBroadcasts: [@@ -209,48 +287,113 @@ export const broadcastsLogic = kea<broadcastsLogicType>([loadBroadcastsSuccess: () => true,},],- page: [- 1,+ filters: [+ DEFAULT_FILTERS,{- setPage: (_, { page }) => page,+ // Any change other than the page itself starts the list over from the first page.+ setFilters: (state, { filters }) => ({ ...state, page: 1, ...filters }),+ setFiltersFromUrl: (_, { filters }) => filters,},],}),+ selectors({+ filtersPending: [+ (s) => [s.filters, s.loadedFilters],+ (filters: BroadcastsFilters, loadedFilters: BroadcastsFilters | null): boolean =>+ !objectsEqual(filters, loadedFilters),+ ],+ }),listeners(({ actions, values }) => ({loadBroadcastsSuccess: ({ broadcasts }) => {const projectId = values.currentProjectIdif (!projectId) {return}+ // A page past the end (a stale link, or rows removed since) would show an empty table with+ // no way back, so land on the last real page.+ const lastPage = Math.max(1, Math.ceil(broadcasts.count / BROADCASTS_PAGE_SIZE))+ if (values.filters.page > lastPage) {+ actions.setFilters({ page: lastPage })+ return+ }// Best-effort per-row enrichment: batch jobs decide the status chip, metric totals fill- // the engagement counts. Rows without details just show their fallbacks.+ // the engagement counts. The run is stored before its metrics load, so a slow or failed+ // metrics query can't leave the status unknown.+ const generation = values.listGeneration+ const isCurrent = (): boolean => values.listGeneration === generationfor (const broadcast of broadcasts.results ?? []) {void (async () => {+ let latestBatchJob: HogFlowBatchJobApi | nulltry {const batchJobs =broadcast.status === 'draft'? ([] as HogFlowBatchJobApi[]): await hogFlowsBatchJobsList(String(projectId), broadcast.id)- const latestBatchJob = batchJobs[0] ?? null- actions.setRowDetails(broadcast.id, {- latestBatchJob,- totals: latestBatchJob- ? await loadRunMetricTotals(latestBatchJob, values.currentTeam?.timezone ?? 'UTC')- : {},- })+ latestBatchJob = batchJobs[0] ?? null} catch {- // Leave the row on its fallbacks; the list itself already loaded.+ if (isCurrent()) {+ actions.clearRowDetails(broadcast.id)+ }+ return+ }+ if (!isCurrent()) {+ return+ }+ actions.setRowDetails(broadcast.id, { latestBatchJob, totals: latestBatchJob ? null : {} })+ if (!latestBatchJob) {+ return+ }+ try {+ const totals = await loadRunMetricTotals(latestBatchJob, values.currentTeam?.timezone ?? 'UTC')+ if (isCurrent()) {+ actions.setRowDetails(broadcast.id, { latestBatchJob, totals })+ }+ } catch {+ // The counts stay unknown; the status already rendered from the run.}})()}},- setPage: () => {+ setFilters: async (_, breakpoint) => {+ // Debounce so typing in the search box doesn't fire a request per keystroke.+ await breakpoint(300)+ actions.loadBroadcasts()+ },+ setFiltersFromUrl: () => {actions.loadBroadcasts()},loadBroadcastsFailure: () => {lemonToast.error("Couldn't load broadcasts. Refresh the page to try again.")},})),+ actionToUrl(({ values }) => ({+ setFilters: () => {+ const { search, status, createdBy, page } = values.filters+ const searchParams = {+ ...router.values.searchParams,+ search: search || undefined,+ status: status !== 'all' ? status : undefined,+ created_by: createdBy || undefined,+ page: page > 1 ? page : undefined,+ }+ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]+ },+ })),+ urlToAction(({ actions, values }) => ({+ [urls.broadcasts()]: (_, searchParams) => {+ const status = searchParams['status']+ const parsed: BroadcastsFilters = {+ // The API rejects longer search terms.+ search: searchParams['search'] ? String(searchParams['search']).slice(0, 200) : '',+ status: BROADCASTS_STATUS_FILTERS.includes(status) ? status : 'all',+ createdBy: searchParams['created_by'] ? String(searchParams['created_by']) : null,+ page: Math.max(1, parseInt(String(searchParams['page'])) || 1),+ }+ if (!objectsEqual(parsed, values.filters)) {+ actions.setFiltersFromUrl(parsed)+ }+ },+ })),afterMount(({ actions }) => {actions.loadBroadcasts()}),