Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): add people to a broadcast from an uploaded list (#108521)

Daniel Marchuk0193bebc4d26
diff --git a/frontend/src/scenes/cohorts/CohortCsvDropzone.tsx b/frontend/src/scenes/cohorts/CohortCsvDropzone.tsx
new file mode 100644
index 000000000000..bdbc04b99dff
--- /dev/null
+++ b/frontend/src/scenes/cohorts/CohortCsvDropzone.tsx
@@ -0,0 +1,53 @@
+import { IconUpload } from '@posthog/icons'
+
+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'
+import { cn } from 'lib/utils/css-classes'
+
+export const COHORT_CSV_HELP =
+ "Upload a CSV file to add users to your cohort. For single-column files, include one distinct ID per row (all rows will be processed as data). For multi-column files, include a header row with a 'person_id', 'distinct_id', or 'email' column containing the user identifiers."
+
+export function CohortCsvDropzone({
+ value,
+ onChange,
+}: {
+ value: File | null
+ onChange: (file: File | null) => void
+}): JSX.Element {
+ return (
+ <LemonFileInput
+ accept=".csv"
+ multiple={false}
+ value={value ? [value] : []}
+ onChange={(files) => onChange(files[0] ?? null)}
+ showUploadedFiles={false}
+ callToAction={
+ <div
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ e.currentTarget.click()
+ }
+ }}
+ className={cn(
+ 'flex flex-col items-center justify-center flex-1 cohort-csv-dragger text-text-3000 deprecated-space-y-1',
+ 'text-primary mt-0 bg-transparent border border-dashed border-primary hover:border-secondary p-8',
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent',
+ value?.name && 'border-success'
+ )}
+ >
+ <IconUpload className="text-5xl text-primary" />
+ {value ? (
+ <div>{value.name ?? 'File chosen'}</div>
+ ) : (
+ <>
+ <div>Drag a file here or click to browse for a file</div>
+ <div className="text-secondary text-xs">Accepts .csv files only</div>
+ </>
+ )}
+ </div>
+ }
+ />
+ )
+}
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index 2f7567030def..136892f263b6 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -12,19 +12,9 @@ import {
IconRefresh,
IconSend,
IconTrash,
- IconUpload,
IconWarning,
} from '@posthog/icons'
-import {
- LemonBanner,
- LemonDialog,
- LemonDivider,
- LemonFileInput,
- LemonSnack,
- LemonTabs,
- Link,
- Tooltip,
-} from '@posthog/lemon-ui'
+import { LemonBanner, LemonDialog, LemonDivider, LemonSnack, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { cohortReadsFlagCalls } from 'lib/components/FlagCalledRebuildBanner/flagCalledDependencies'
@@ -72,6 +62,7 @@ import { captureMessageAudienceClicked } from 'products/workflows/frontend/Messa
import { AddPersonToCohortModal } from './AddPersonToCohortModal'
import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'
import { cohortCountWarningLogic } from './cohortCountWarningLogic'
+import { COHORT_CSV_HELP, CohortCsvDropzone } from './CohortCsvDropzone'
import { CohortSceneMenuBar } from './CohortSceneMenuBar'
import {
cohortBroadcastDisabledReason,
@@ -703,26 +694,13 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
<SceneDivider />
<SceneSection
title={isNewCohort ? 'Upload users' : 'Add users'}
- description={
- isNewCohort
- ? `Upload a CSV file to add users to your cohort. For single-column files, include
- one distinct ID per row (all rows will be processed as data). For multi-column
- files, include a header row with a 'person_id', 'distinct_id', or 'email' column
- containing the user identifiers.`
- : undefined
- }
+ description={isNewCohort ? COHORT_CSV_HELP : undefined}
className={cn('ph-ignore-input')}
>
{!isNewCohort && (
<div className="flex flex-col gap-y-0 flex-1 justify-center">
<h3 className="text-sm">Upload a CSV</h3>
- <span className="max-w-prose">
- Upload a CSV file to add users to your cohort. For single-column
- files, include one distinct ID per row (all rows will be processed
- as data). For multi-column files, include a header row with a
- 'person_id', 'distinct_id', or 'email' column containing the user
- identifiers.
- </span>
+ <span className="max-w-prose">{COHORT_CSV_HELP}</span>
</div>
)}
{/* TODO: @adamleithp Allow users to download a template CSV file */}
@@ -730,48 +708,9 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
{/* TODO: @adamleithp Render the csv file and validate it */}
<LemonField name="csv" data-attr="cohort-csv">
{({ onChange }) => (
- <LemonFileInput
- accept=".csv"
- multiple={false}
- value={cohort.csv ? [cohort.csv] : []}
- onChange={(files) => onChange(files[0])}
- showUploadedFiles={false}
- callToAction={
- <div
- className={cn(
- 'flex flex-col items-center justify-center flex-1 cohort-csv-dragger text-text-3000 deprecated-space-y-1',
- 'text-primary mt-0 bg-transparent border border-dashed border-primary hover:border-secondary p-8',
- cohort.csv?.name && 'border-success'
- )}
- >
- {cohort.csv ? (
- <>
- <IconUpload
- style={{
- fontSize: '3rem',
- color: 'var(--color-text-primary)',
- }}
- />
- <div>{cohort.csv?.name ?? 'File chosen'}</div>
- </>
- ) : (
- <>
- <IconUpload
- style={{
- fontSize: '3rem',
- color: 'var(--color-text-primary)',
- }}
- />
- <div>
- Drag a file here or click to browse for a file
- </div>
- <div className="text-secondary text-xs">
- Accepts .csv files only
- </div>
- </>
- )}
- </div>
- }
+ <CohortCsvDropzone
+ value={cohort.csv ?? null}
+ onChange={(file) => onChange(file ?? undefined)}
/>
)}
</LemonField>
diff --git a/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceListModal.tsx b/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceListModal.tsx
new file mode 100644
index 000000000000..661a57776e31
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceListModal.tsx
@@ -0,0 +1,68 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
+
+import { COHORT_CSV_HELP, CohortCsvDropzone } from 'scenes/cohorts/CohortCsvDropzone'
+
+import { broadcastWizardLogic } from '../broadcastWizardLogic'
+import { broadcastAudienceListLogic } from './broadcastAudienceListLogic'
+
+/** Turns an uploaded CSV of people into a static cohort and adds it to the broadcast's audience. */
+export function BroadcastAudienceListModal(): JSX.Element {
+ const { props } = useMountedLogic(broadcastWizardLogic)
+ const logic = broadcastAudienceListLogic(props)
+ const { isListModalOpen, file, cohortName, creating, createError, submitDisabledReason } = useValues(logic)
+ const { audienceProperties } = useValues(broadcastWizardLogic)
+ const { closeListModal, setFile, setCohortName, createListCohort } = useActions(logic)
+
+ return (
+ <LemonModal
+ isOpen={isListModalOpen}
+ onClose={creating ? undefined : closeListModal}
+ title="Upload a list"
+ description="The list is saved as a static cohort, so you can reuse it in other broadcasts."
+ width={560}
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={closeListModal}
+ disabledReason={creating ? 'Saving the list' : null}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={createListCohort}
+ loading={creating}
+ disabledReason={submitDisabledReason}
+ data-attr="broadcast-audience-list-submit"
+ >
+ Add to audience
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-4" data-attr="broadcast-audience-list-modal">
+ <span className="text-sm text-secondary">{COHORT_CSV_HELP}</span>
+ <CohortCsvDropzone value={file} onChange={setFile} />
+ <LemonInput
+ value={cohortName}
+ onChange={setCohortName}
+ placeholder="Cohort name"
+ fullWidth
+ data-attr="broadcast-audience-list-name"
+ prefix={<span className="text-secondary">Cohort name</span>}
+ />
+ <div className="text-xs text-secondary">
+ Only people who are already in PostHog are included. Anyone else on the list won't receive the
+ email.
+ {audienceProperties.length > 0
+ ? ' People must be on every list and match your other conditions to get the email.'
+ : null}
+ </div>
+ {createError ? <LemonBanner type="error">{createError}</LemonBanner> : null}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts b/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts
new file mode 100644
index 000000000000..4daba168a59f
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts
@@ -0,0 +1,45 @@
+import { audienceCohortLaunchError, csvListError } from './audienceList'
+
+describe('audienceList', () => {
+ it.each([
+ { case: 'an empty file', text: '\n', expected: 'The file is empty.' },
+ {
+ case: 'columns without an id',
+ text: 'name,company\nAda,Acme\n',
+ expected: 'The file needs a column named email, distinct_id or person_id.',
+ },
+ { case: 'a header with no rows', text: 'email\n', expected: 'The file has a header row but no people in it.' },
+ { case: 'an email column among others', text: 'Name,Email\nAda,[email protected]\n', expected: null },
+ { case: 'a person-id column among others', text: 'person-id,name\nabc,Ada\n', expected: null },
+ {
+ case: 'an id name only inside a quoted header',
+ text: '"name,email",company\nAda,Acme\n',
+ expected: 'The file needs a column named email, distinct_id or person_id.',
+ },
+ { case: 'one column of ids without a header', text: 'user-1\nuser-2\n', expected: null },
+ ])('checks $case before uploading', ({ text, expected }) => {
+ expect(csvListError(text)).toEqual(expected)
+ })
+
+ it.each([
+ {
+ cohort: 'an uploaded list still matching',
+ state: { isStatic: true, isCalculating: true, failed: false },
+ expected: '"List" is still matching people. You can launch when it finishes.',
+ },
+ {
+ cohort: 'an uploaded list that failed to match',
+ state: { isStatic: true, isCalculating: false, failed: true },
+ expected: '"List" couldn\'t match its people. Remove it from the recipients, or upload the list again.',
+ },
+ { cohort: 'a matched list', state: { isStatic: true, isCalculating: false, failed: false }, expected: null },
+ {
+ cohort: 'a dynamic cohort recalculating',
+ state: { isStatic: false, isCalculating: true, failed: false },
+ expected: null,
+ },
+ ])('decides whether $cohort blocks launch', ({ state, expected }) => {
+ const cohort = { id: 42, name: 'List', count: null, importTotal: null, importUnmatched: null, ...state }
+ expect(audienceCohortLaunchError(cohort)).toEqual(expected)
+ })
+})
diff --git a/products/workflows/frontend/Broadcasts/audience/audienceList.ts b/products/workflows/frontend/Broadcasts/audience/audienceList.ts
new file mode 100644
index 000000000000..a49ad49d4d86
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/audience/audienceList.ts
@@ -0,0 +1,116 @@
+import { AnyPropertyFilter, PropertyFilterType } from '~/types'
+
+import type { CohortApi } from 'products/cohorts/frontend/generated/api.schemas'
+
+import type { AudienceCohort } from './broadcastAudienceCohortsLogic'
+
+const SUPPORTED_ID_HEADERS = ['email', 'e-mail', 'distinct_id', 'distinct-id', 'person_id', 'person-id', 'person .id']
+
+/**
+ * Why the cohort import would reject this CSV, checked before anything is created, because a rejected
+ * import still leaves an empty cohort behind. A single column without a known header is read as distinct IDs.
+ */
+export function csvListError(text: string): string | null {
+ const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '')
+ if (lines.length === 0) {
+ return 'The file is empty.'
+ }
+ const headers = splitCsvRow(lines[0]).map((header) => header.trim().toLowerCase())
+ if (headers.length > 1 && !headers.some((header) => SUPPORTED_ID_HEADERS.includes(header))) {
+ return 'The file needs a column named email, distinct_id or person_id.'
+ }
+ if (headers.some((header) => SUPPORTED_ID_HEADERS.includes(header)) && lines.length === 1) {
+ return 'The file has a header row but no people in it.'
+ }
+ return null
+}
+
+function splitCsvRow(row: string): string[] {
+ const fields: string[] = []
+ let field = ''
+ let quoted = false
+ for (let i = 0; i < row.length; i++) {
+ const char = row[i]
+ if (quoted) {
+ if (char === '"' && row[i + 1] === '"') {
+ field += '"'
+ i++
+ } else if (char === '"') {
+ quoted = false
+ } else {
+ field += char
+ }
+ } else if (char === '"') {
+ quoted = true
+ } else if (char === ',') {
+ fields.push(field)
+ field = ''
+ } else {
+ field += char
+ }
+ }
+ fields.push(field)
+ return fields
+}
+
+/**
+ * Reads an uploaded list as UTF-8. The cohort import decodes the file strictly after it saves the cohort,
+ * so a file in another encoding must fail here, before the cohort exists.
+ */
+export async function readCsvText(file: File): Promise<string> {
+ const bytes = await file.arrayBuffer()
+ try {
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes)
+ } catch {
+ throw new Error('This file isn\'t saved as UTF-8. Save it as "CSV UTF-8" and upload it again.')
+ }
+}
+
+/** Dated, so lists uploaded for the same broadcast stay apart in the cohorts list. */
+export function defaultListCohortName(broadcastName: string, date: string): string {
+ const name = broadcastName.trim()
+ return `${name && name !== 'New broadcast' ? `${name} recipients` : 'Broadcast recipients'}, ${date}`
+}
+
+/** The cohorts an audience filters on, once each. */
+export function audienceCohortIds(audienceProperties: AnyPropertyFilter[]): number[] {
+ return [
+ ...new Set(
+ audienceProperties
+ .filter((filter) => filter.type === PropertyFilterType.Cohort)
+ .map((filter) => Number(filter.value))
+ .filter((id) => Number.isFinite(id))
+ ),
+ ]
+}
+
+export function toAudienceCohort(id: number, cohort: CohortApi): AudienceCohort {
+ return {
+ id,
+ name: cohort.name ?? `Cohort ${id}`,
+ isStatic: !!cohort.is_static,
+ isCalculating: !!cohort.is_calculating,
+ failed: (cohort.errors_calculating ?? 0) > 0 && !cohort.is_calculating,
+ count: cohort.count ?? null,
+ importTotal: cohort.last_import_total_count ?? null,
+ importUnmatched: cohort.last_import_unmatched_count ?? null,
+ }
+}
+
+/**
+ * Why a cohort in the audience stops a launch. A batch sends to the members a cohort has when it runs, so an
+ * uploaded list that is still matching would reach only part of the list. A dynamic cohort keeps its members
+ * while it recalculates, so it never blocks.
+ */
+export function audienceCohortLaunchError(cohort: AudienceCohort): string | null {
+ if (!cohort.isStatic) {
+ return null
+ }
+ if (cohort.isCalculating) {
+ return `"${cohort.name}" is still matching people. You can launch when it finishes.`
+ }
+ if (cohort.failed) {
+ return `"${cohort.name}" couldn't match its people. Remove it from the recipients, or upload the list again.`
+ }
+ return null
+}
diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts
index b91b9afb4c9b..d8028ccfec17 100644
--- a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts
+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts
@@ -8,6 +8,7 @@ import { AnyPropertyFilter, PropertyFilterType } from '~/types'
import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'
import { BroadcastWizardLogicProps, broadcastWizardLogic } from '../broadcastWizardLogic'
+import { audienceCohortIds, audienceCohortLaunchError, toAudienceCohort } from './audienceList'
export interface AudienceCohort {
id: number
@@ -35,6 +36,9 @@ export interface broadcastAudienceCohortsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastAudienceCohortsLogicActions {
loadBlastRadius: () => any // broadcastWizardLogic
+ setAudienceCohortLaunchErrors: (errors: string[]) => {
+ errors: string[]
+ } // broadcastWizardLogic
loadAudienceCohorts: () => {
value: true
}
@@ -65,7 +69,7 @@ export const broadcastAudienceCohortsLogic = kea<broadcastAudienceCohortsLogicTy
key((props) => props.id),
connect((props: BroadcastWizardLogicProps) => ({
values: [broadcastWizardLogic(props), ['audienceProperties'], projectLogic, ['currentProjectId']],
- actions: [broadcastWizardLogic(props), ['loadBlastRadius']],
+ actions: [broadcastWizardLogic(props), ['loadBlastRadius', 'setAudienceCohortLaunchErrors']],
})),
actions({
loadAudienceCohorts: true,
@@ -88,14 +92,7 @@ export const broadcastAudienceCohortsLogic = kea<broadcastAudienceCohortsLogicTy
],
cohortIds: [
(s) => [s.audienceProperties],
- (audienceProperties: AnyPropertyFilter[]): number[] => [
- ...new Set(
- audienceProperties
- .filter((filter) => filter.type === PropertyFilterType.Cohort)
- .map((filter) => Number(filter.value))
- .filter((id) => Number.isFinite(id))
- ),
- ],
+ (audienceProperties: AnyPropertyFilter[]): number[] => audienceCohortIds(audienceProperties),
],
}),
listeners(({ actions, values }) => ({
@@ -104,26 +101,14 @@ export const broadcastAudienceCohortsLogic = kea<broadcastAudienceCohortsLogicTy
const ids = values.cohortIds
if (!values.currentProjectId || ids.length === 0) {
actions.setAudienceCohorts({})
+ actions.setAudienceCohortLaunchErrors([])
return
}
const projectId = String(values.currentProjectId)
const loaded = await Promise.all(
ids.map(async (id): Promise<[number, AudienceCohort | null]> => {
try {
- const cohort = await cohortsRetrieve(projectId, id)
- return [
- id,
- {
- id,
- name: cohort.name ?? `Cohort ${id}`,
- isStatic: !!cohort.is_static,
- isCalculating: !!cohort.is_calculating,
- failed: (cohort.errors_calculating ?? 0) > 0 && !cohort.is_calculating,
- count: cohort.count ?? null,
- importTotal: cohort.last_import_total_count ?? null,
- importUnmatched: cohort.last_import_unmatched_count ?? null,
- },
- ]
+ return [id, toAudienceCohort(id, await cohortsRetrieve(projectId, id))]
} catch (error: any) {
// A failed poll keeps the last card, so a cohort that is still matching keeps polling.
// A deleted cohort has nothing left to show.
@@ -135,6 +120,9 @@ export const broadcastAudienceCohortsLogic = kea<broadcastAudienceCohortsLogicTy
const previous = values.audienceCohorts
const cohorts = Object.fromEntries(loaded)
actions.setAudienceCohorts(cohorts)
+ actions.setAudienceCohortLaunchErrors(
+ Object.values(cohorts).flatMap((cohort) => (cohort ? (audienceCohortLaunchError(cohort) ?? []) : []))
+ )
// The audience size counts a cohort's members, so it is stale until matching finishes.
if (ids.some((id) => previous[id]?.isCalculating && cohorts[id] && !cohorts[id]!.isCalculating)) {
actions.loadBlastRadius()
diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.test.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.test.ts
new file mode 100644
index 000000000000..bad570623826
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.test.ts
@@ -0,0 +1,93 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import { broadcastWizardLogic } from '../broadcastWizardLogic'
+import { broadcastAudienceListLogic } from './broadcastAudienceListLogic'
+
+describe('broadcastAudienceListLogic', () => {
+ let createdCohorts: number
+
+ beforeEach(() => {
+ createdCohorts = 0
+ useMocks({
+ get: {
+ '/api/projects/:team/cohorts/:id/': {
+ id: 42,
+ name: 'Spring sale recipients',
+ is_static: true,
+ is_calculating: true,
+ },
+ },
+ post: {
+ '/api/projects/:team/cohorts/': () => {
+ createdCohorts += 1
+ return [201, { id: 42, name: 'Spring sale recipients', is_static: true, is_calculating: true }]
+ },
+ '/api/projects/:team_id/hog_flows/user_blast_radius/': () => [200, { affected: 0, total: 0 }],
+ },
+ })
+ initKeaTests()
+ broadcastWizardLogic({ id: 'new' }).mount()
+ })
+
+ it('saves an uploaded list as a cohort and adds it to the audience', async () => {
+ const logic = broadcastAudienceListLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.openListModal()
+ logic.actions.setFile(
+ new File(['email\[email protected]\[email protected]\n'], 'people.csv', { type: 'text/csv' })
+ )
+
+ await expectLogic(logic, () => {
+ logic.actions.createListCohort()
+ })
+ .toDispatchActions(['createListCohortFinished', 'closeListModal'])
+ .toMatchValues({ isListModalOpen: false, createError: null })
+
+ expect(createdCohorts).toEqual(1)
+ expect(broadcastWizardLogic({ id: 'new' }).values.audienceProperties).toEqual([
+ {
+ type: PropertyFilterType.Cohort,
+ key: 'id',
+ value: 42,
+ operator: PropertyOperator.In,
+ cohort_name: 'Spring sale recipients',
+ },
+ ])
+ })
+
+ it.each([
+ {
+ file: 'a CSV the import would reject',
+ content: 'name,company\nAda,Acme\n',
+ error: 'The file needs a column named email, distinct_id or person_id.',
+ },
+ {
+ // "Zoë" in Windows-1252, which the cohort import can't decode after it saves the cohort.
+ file: 'a CSV that is not UTF-8',
+ content: new Uint8Array([
+ ...new TextEncoder().encode('email\nzo'),
+ 0xeb,
+ ...new TextEncoder().encode('@example.com\n'),
+ ]),
+ error: 'This file isn\'t saved as UTF-8. Save it as "CSV UTF-8" and upload it again.',
+ },
+ ])('creates no cohort for $file', async ({ content, error }) => {
+ const logic = broadcastAudienceListLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.openListModal()
+ logic.actions.setFile(new File([content], 'people.csv', { type: 'text/csv' }))
+
+ await expectLogic(logic, () => {
+ logic.actions.createListCohort()
+ })
+ .toDispatchActions(['createListCohortFinished'])
+ .toMatchValues({ isListModalOpen: true, createError: error })
+
+ expect(createdCohorts).toEqual(0)
+ expect(broadcastWizardLogic({ id: 'new' }).values.audienceProperties).toEqual([])
+ })
+})
diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.ts
new file mode 100644
index 000000000000..8b6b76d81373
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.ts
@@ -0,0 +1,189 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+import { dayjs } from 'lib/dayjs'
+import { createCohortFormData } from 'scenes/cohorts/cohortUtils'
+
+import { cohortsModel } from '~/models/cohortsModel'
+import { AnyPropertyFilter, CohortType, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { BroadcastWizardLogicProps, broadcastWizardLogic } from '../broadcastWizardLogic'
+import { csvListError, defaultListCohortName, readCsvText } from './audienceList'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface broadcastAudienceListLogicValues {
+ audienceProperties: AnyPropertyFilter[] // broadcastWizardLogic
+ name: string // broadcastWizardLogic
+ cohortName: string
+ createError: string | null
+ creating: boolean
+ file: File | null
+ isListModalOpen: boolean
+ submitDisabledReason: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface broadcastAudienceListLogicActions {
+ setAudienceProperties: (properties: AnyPropertyFilter[]) => {
+ properties: AnyPropertyFilter[]
+ } // broadcastWizardLogic
+ cohortCreated: (cohort: CohortType) => {
+ cohort: CohortType
+ } // cohortsModel
+ closeListModal: () => {
+ value: true
+ }
+ createListCohort: () => {
+ value: true
+ }
+ createListCohortFinished: (error: string | null) => {
+ error: string | null
+ }
+ openListModal: () => {
+ value: true
+ }
+ setCohortName: (cohortName: string) => {
+ cohortName: string
+ }
+ setFile: (file: File | null) => {
+ file: File | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface broadcastAudienceListLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ submitDisabledReason: (file: File | null, cohortName: string) => string | null
+ }
+}
+
+export type broadcastAudienceListLogicType = MakeLogicType<
+ broadcastAudienceListLogicValues,
+ broadcastAudienceListLogicActions,
+ BroadcastWizardLogicProps,
+ broadcastAudienceListLogicMeta
+>
+
+export const broadcastAudienceListLogic = kea<broadcastAudienceListLogicType>([
+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'audience', 'broadcastAudienceListLogic']),
+ props({} as BroadcastWizardLogicProps),
+ key((props) => props.id),
+ connect((props: BroadcastWizardLogicProps) => ({
+ values: [broadcastWizardLogic(props), ['name', 'audienceProperties']],
+ actions: [broadcastWizardLogic(props), ['setAudienceProperties'], cohortsModel, ['cohortCreated']],
+ })),
+ actions({
+ openListModal: true,
+ closeListModal: true,
+ setFile: (file: File | null) => ({ file }),
+ setCohortName: (cohortName: string) => ({ cohortName }),
+ createListCohort: true,
+ createListCohortFinished: (error: string | null) => ({ error }),
+ }),
+ reducers({
+ isListModalOpen: [
+ false,
+ {
+ openListModal: () => true,
+ closeListModal: () => false,
+ },
+ ],
+ file: [
+ null as File | null,
+ {
+ setFile: (_, { file }) => file,
+ openListModal: () => null,
+ },
+ ],
+ cohortName: [
+ '',
+ {
+ setCohortName: (_, { cohortName }) => cohortName,
+ },
+ ],
+ creating: [
+ false,
+ {
+ createListCohort: () => true,
+ createListCohortFinished: () => false,
+ },
+ ],
+ createError: [
+ null as string | null,
+ {
+ createListCohortFinished: (_, { error }) => error,
+ openListModal: () => null,
+ setFile: () => null,
+ },
+ ],
+ }),
+ selectors({
+ submitDisabledReason: [
+ (s) => [s.file, s.cohortName],
+ (file: File | null, cohortName: string): string | null => {
+ if (!file) {
+ return 'Choose a CSV file'
+ }
+ if (!cohortName.trim()) {
+ return 'Give the cohort a name'
+ }
+ return null
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ openListModal: () => {
+ actions.setCohortName(defaultListCohortName(values.name, dayjs().format('MMM D')))
+ },
+ createListCohort: async () => {
+ if (values.submitDisabledReason) {
+ actions.createListCohortFinished(values.submitDisabledReason)
+ return
+ }
+ const csv = values.file!
+ let fileError: string | null
+ try {
+ fileError = csvListError(await readCsvText(csv))
+ } catch (error: any) {
+ actions.createListCohortFinished(error?.message ?? "Couldn't read the file. Try uploading it again.")
+ return
+ }
+ if (fileError) {
+ actions.createListCohortFinished(fileError)
+ return
+ }
+ let cohort: CohortType
+ try {
+ const formData = createCohortFormData({
+ name: values.cohortName.trim(),
+ description: 'Created from a list in a broadcast audience.',
+ is_static: true,
+ csv,
+ } as CohortType)
+ // nosemgrep: prefer-codegen-api -- the CSV goes up as multipart form data, which the generated JSON client can't send.
+ cohort = await api.cohorts.create(formData as Partial<CohortType>)
+ } catch (error: any) {
+ const message = error?.data?.csv?.[0] ?? error?.detail ?? error?.message ?? 'unknown error'
+ actions.createListCohortFinished(`Couldn't create the cohort: ${message}`)
+ return
+ }
+ actions.cohortCreated(cohort)
+ actions.setAudienceProperties([
+ ...values.audienceProperties,
+ {
+ type: PropertyFilterType.Cohort,
+ key: 'id',
+ value: cohort.id as number,
+ operator: PropertyOperator.In,
+ cohort_name: cohort.name,
+ },
+ ])
+ actions.createListCohortFinished(null)
+ actions.closeListModal()
+ lemonToast.success(`Added "${cohort.name}" to the audience. Matching the people on it can take a minute.`)
+ },
+ })),
+])
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index c2cc0c364cf7..a83445f5785f 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -376,6 +376,39 @@ describe('broadcastWizardLogic', () => {
}
)
+ it('stops a launch while an uploaded list in the audience is still matching', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/cohorts/:id/': {
+ id: 42,
+ name: 'Spring list',
+ is_static: true,
+ is_calculating: true,
+ },
+ },
+ })
+ logic.actions.setEmail({
+ ...DEFAULT_BROADCAST_EMAIL,
+ from: { ...DEFAULT_BROADCAST_EMAIL.from, integrationId: 1 },
+ subject: 'Spring sale',
+ html: '<p>Hi</p>',
+ })
+ logic.actions.setAudienceProperties([
+ { type: PropertyFilterType.Cohort, key: 'id', value: 42, operator: PropertyOperator.In },
+ ])
+ logic.actions.setStep('review')
+
+ await expectLogic(logic, () => {
+ logic.actions.launchBroadcast()
+ })
+ .toDispatchActions(['setAudienceCohortLaunchErrors', 'launchBroadcastFinished'])
+ .toNotHaveDispatchedActions(['saveBroadcastFinished'])
+
+ expect(logic.values.stepValidationErrors.review).toEqual([
+ '"Spring list" is still matching people. You can launch when it finishes.',
+ ])
+ })
+
it.each([
{ sender: 'a sender that still exists', integrationId: 1, integrationIds: undefined, expected: [] },
{ sender: 'a deleted sender', integrationId: 7, integrationIds: undefined, expected: [DELETED_SENDER_ERROR] },
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 518865c80046..5d2cd75295f2 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -17,6 +17,7 @@ import { urls } from 'scenes/urls'
import { AnyPropertyFilter, Breadcrumb, IntegrationType, ResourceEditedEvent, TeamPublicType, TeamType } from '~/types'
+import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'
import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'
import {
hogFlowsBatchJobsCancelCreate,
@@ -49,6 +50,7 @@ import {
} from '../Workflows/hogflows/steps/components/rrule-helpers'
import type { UtmTagValues } from '../Workflows/hogflows/steps/components/UtmTagFields'
import { ResourceSaveQueue } from '../Workflows/resourceSaveQueue'
+import { audienceCohortIds, audienceCohortLaunchError, toAudienceCohort } from './audience/audienceList'
import {
AUDIENCE_PREFILL_PARAM,
type BroadcastPrefill,
@@ -208,6 +210,7 @@ export interface broadcastWizardLogicValues {
integrationsLoading: boolean // integrationsLogic
currentProjectId: number | null // projectLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
+ audienceCohortLaunchErrors: string[]
audienceProperties: AnyPropertyFilter[]
batchJobs: HogFlowBatchJobApi[]
batchJobsLoading: boolean
@@ -387,6 +390,9 @@ export interface broadcastWizardLogicActions {
sendToEveryoneAfterRejectedLink: () => {
value: true
}
+ setAudienceCohortLaunchErrors: (errors: string[]) => {
+ errors: string[]
+ }
setAudienceProperties: (properties: AnyPropertyFilter[]) => {
properties: AnyPropertyFilter[]
}
@@ -494,7 +500,8 @@ export interface broadcastWizardLogicMeta {
integrations: IntegrationType[] | null,
integrationsLoading: boolean,
linkAudienceRejected: boolean,
- audienceProperties: AnyPropertyFilter[]
+ audienceProperties: AnyPropertyFilter[],
+ audienceCohortLaunchErrors: string[]
) => Record<BroadcastWizardStep, string[]>
currentStepHasErrors: (
stepValidationErrors: Record<BroadcastWizardStep, string[]>,
@@ -551,6 +558,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
prefillFromLink: (prefill: BroadcastPrefill) => ({ prefill }),
saveName: true,
setAudienceProperties: (properties: AnyPropertyFilter[]) => ({ properties }),
+ setAudienceCohortLaunchErrors: (errors: string[]) => ({ errors }),
rejectLinkAudience: true,
sendToEveryoneAfterRejectedLink: true,
setGoalEnabled: (enabled: boolean) => ({ enabled }),
@@ -690,6 +698,12 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
prefillFromLink: (_, { prefill }) => prefill.source ?? null,
},
],
+ audienceCohortLaunchErrors: [
+ [] as string[],
+ {
+ setAudienceCohortLaunchErrors: (_, { errors }) => errors,
+ },
+ ],
audienceProperties: [
[] as AnyPropertyFilter[],
{
@@ -982,6 +996,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
s.integrationsLoading,
s.linkAudienceRejected,
s.audienceProperties,
+ s.audienceCohortLaunchErrors,
],
(
goalEnabled: boolean,
@@ -993,7 +1008,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
integrations: IntegrationType[] | null,
integrationsLoading: boolean,
linkAudienceRejected: boolean,
- audienceProperties: AnyPropertyFilter[]
+ audienceProperties: AnyPropertyFilter[],
+ audienceCohortLaunchErrors: string[]
): Record<BroadcastWizardStep, string[]> => {
const errors: Record<BroadcastWizardStep, string[]> = {
recipients: [],
@@ -1044,6 +1060,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
if (senderError && !errors.review.includes(senderError)) {
errors.review.push(senderError)
}
+ // Only launch waits for a list to match. Editing the other steps can go on meanwhile.
+ errors.review.push(...audienceCohortLaunchErrors)
return errors
},
@@ -1467,6 +1485,15 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
return
}
const projectId = String(values.currentProjectId)
+ // The cohort cards poll, so a list can finish or fail between the last poll and this click.
+ const cohortErrors = await loadAudienceCohortLaunchErrors(projectId, values.audienceProperties)
+ breakpoint()
+ actions.setAudienceCohortLaunchErrors(cohortErrors)
+ if (cohortErrors.length > 0) {
+ lemonToast.error(cohortErrors[0])
+ actions.launchBroadcastFinished()
+ return
+ }
// Same ordering as Continue: a save that trails the content step must land first.
cache.autosaveConflict = false
const saves = getSaveQueue(cache, values)
@@ -1773,6 +1800,20 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}),
])
+async function loadAudienceCohortLaunchErrors(
+ projectId: string,
+ audienceProperties: AnyPropertyFilter[]
+): Promise<string[]> {
+ const ids = audienceCohortIds(audienceProperties)
+ const results = await Promise.allSettled(ids.map((id) => cohortsRetrieve(projectId, id)))
+ // A cohort that fails to load doesn't block launch, so a lookup error can't stop every send.
+ return results.flatMap((result, index) =>
+ result.status === 'fulfilled'
+ ? (audienceCohortLaunchError(toAudienceCohort(ids[index], result.value)) ?? [])
+ : []
+ )
+}
+
function captureLaunchFailed(
broadcastId: string | null | undefined,
reason: 'audience_over_limit' | 'edited_elsewhere' | 'error'
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
index b6e7b8a15c5c..2f196504072f 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
@@ -1,7 +1,7 @@
-import { useActions, useValues } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import { useState } from 'react'
-import { IconWarning } from '@posthog/icons'
+import { IconUpload, IconWarning } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonModal, LemonSelect, Link, Spinner } from '@posthog/lemon-ui'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
@@ -18,6 +18,8 @@ import { AnyPersonScopeFilter, PropertyFilterType } from '~/types'
import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'
import { WORKFLOW_OPERATOR_ALLOWLIST } from '../../Workflows/hogflows/filters/HogFlowFilters'
import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'
+import { broadcastAudienceListLogic } from '../audience/broadcastAudienceListLogic'
+import { BroadcastAudienceListModal } from '../audience/BroadcastAudienceListModal'
import { broadcastWizardLogic } from '../broadcastWizardLogic'
function AudienceSizePreview(): JSX.Element | null {
@@ -143,6 +145,8 @@ function AudienceListModal({ isOpen, onClose }: { isOpen: boolean; onClose: () =
export function BroadcastRecipientsStep(): JSX.Element {
const { audienceProperties, linkAudienceRejected } = useValues(broadcastWizardLogic)
const { setAudienceProperties, sendToEveryoneAfterRejectedLink } = useActions(broadcastWizardLogic)
+ const { props } = useMountedLogic(broadcastWizardLogic)
+ const { openListModal } = useActions(broadcastAudienceListLogic(props))
const [audienceListOpen, setAudienceListOpen] = useState(false)
return (
@@ -150,7 +154,8 @@ export function BroadcastRecipientsStep(): JSX.Element {
<div>
<h2 className="m-0 text-xl font-semibold">Who should receive this email?</h2>
<p className="m-0 text-secondary">
- Filter by person properties or cohorts. Without filters, the broadcast goes to everyone.
+ Filter by person properties or cohorts, or upload a list. Without filters, the broadcast goes to
+ everyone.
</p>
</div>
{linkAudienceRejected && audienceProperties.length === 0 && (
@@ -204,7 +209,19 @@ export function BroadcastRecipientsStep(): JSX.Element {
hasRowOperator={false}
operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}
/>
+ <div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconUpload />}
+ onClick={openListModal}
+ data-attr="broadcast-audience-add-list"
+ >
+ Upload a list
+ </LemonButton>
+ </div>
<BroadcastAudienceCohorts />
+ <BroadcastAudienceListModal />
<MessageCategoryPicker />
</div>
)