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): create people from a broadcast list upload (#113288)

Harley Alexander8e5a41dc3eeb
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 8abb82421f25..491b03b6b122 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -638,6 +638,7 @@ export const FEATURE_FLAGS = {
WORKFLOW_CLASSIFY_ACTION: 'workflow-classify-action', // owner: #team-workflows
WORKFLOW_RUN_SCOUT_ACTION: 'workflow-run-scout-action', // owner: #team-workflows
WORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflows
+ WORKFLOWS_BROADCAST_RECIPIENT_LISTS: 'workflows-broadcast-recipient-lists', // owner: @mayteio #team-workflows
WORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflows
WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflows
WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflows
diff --git a/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceListModal.tsx b/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceListModal.tsx
index 661a57776e31..8d8c9ef72afb 100644
--- a/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceListModal.tsx
+++ b/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceListModal.tsx
@@ -11,7 +11,8 @@ import { broadcastAudienceListLogic } from './broadcastAudienceListLogic'
export function BroadcastAudienceListModal(): JSX.Element {
const { props } = useMountedLogic(broadcastWizardLogic)
const logic = broadcastAudienceListLogic(props)
- const { isListModalOpen, file, cohortName, creating, createError, submitDisabledReason } = useValues(logic)
+ const { isListModalOpen, file, cohortName, creating, createError, submitDisabledReason, importsPeople } =
+ useValues(logic)
const { audienceProperties } = useValues(broadcastWizardLogic)
const { closeListModal, setFile, setCohortName, createListCohort } = useActions(logic)
@@ -44,7 +45,18 @@ export function BroadcastAudienceListModal(): JSX.Element {
}
>
<div className="flex flex-col gap-4" data-attr="broadcast-audience-list-modal">
- <span className="text-sm text-secondary">{COHORT_CSV_HELP}</span>
+ {importsPeople ? (
+ <span className="text-sm text-secondary">
+ Each row creates or updates a person. The file needs an <code>email</code> column. Every other
+ column is saved on the person, so you can use it in the email, for example{' '}
+ <code>{'{{ person.properties.plan }}'}</code> for a <code>plan</code> column. Property names
+ match the column names exactly, including capital letters. To update people by their ID in your
+ app, add a <code>distinct_id</code> column, or an <code>id</code> column like a Customer.io
+ export has.
+ </span>
+ ) : (
+ <span className="text-sm text-secondary">{COHORT_CSV_HELP}</span>
+ )}
<CohortCsvDropzone value={file} onChange={setFile} />
<LemonInput
value={cohortName}
@@ -55,8 +67,9 @@ export function BroadcastAudienceListModal(): JSX.Element {
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.
+ {importsPeople
+ ? "People who aren't in PostHog yet are created. A column with the same name as an existing property replaces its value, and a blank cell leaves it as it is. Each row is sent as one event, so it counts toward your event usage and triggers any destinations that run on all events."
+ : "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}
diff --git a/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts b/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts
index 4daba168a59f..05ce15a2dc42 100644
--- a/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts
+++ b/products/workflows/frontend/Broadcasts/audience/audienceList.test.ts
@@ -1,4 +1,4 @@
-import { audienceCohortLaunchError, csvListError } from './audienceList'
+import { audienceCohortLaunchError, csvListError, peopleImportMessage } from './audienceList'
describe('audienceList', () => {
it.each([
@@ -42,4 +42,30 @@ describe('audienceList', () => {
const cohort = { id: 42, name: 'List', count: null, importTotal: null, importUnmatched: null, ...state }
expect(audienceCohortLaunchError(cohort)).toEqual(expected)
})
+
+ it.each([
+ {
+ case: 'nothing skipped',
+ dropped: [0, 0, 0],
+ expected:
+ 'Added "List" to the audience. 2 new people were created. Their properties can take a minute to update.',
+ },
+ {
+ case: 'skipped rows',
+ dropped: [1, 2, 0],
+ expected:
+ 'Added "List" to the audience. 2 new people were created. Skipped 3 rows: 1 had no valid email, 2 repeated an email or distinct ID. Their properties can take a minute to update.',
+ },
+ ])('reports an import with $case', ({ dropped: [invalid, duplicate, tooLarge], expected }) => {
+ const summary = {
+ cohort_id: 42,
+ row_count: 2,
+ new_people: 2,
+ columns: ['email'],
+ dropped_invalid_email: invalid,
+ dropped_duplicate_email: duplicate,
+ dropped_too_large: tooLarge,
+ }
+ expect(peopleImportMessage('List', summary)).toEqual(expected)
+ })
})
diff --git a/products/workflows/frontend/Broadcasts/audience/audienceList.ts b/products/workflows/frontend/Broadcasts/audience/audienceList.ts
index a49ad49d4d86..e82278399e3d 100644
--- a/products/workflows/frontend/Broadcasts/audience/audienceList.ts
+++ b/products/workflows/frontend/Broadcasts/audience/audienceList.ts
@@ -2,6 +2,7 @@ import { AnyPropertyFilter, PropertyFilterType } from '~/types'
import type { CohortApi } from 'products/cohorts/frontend/generated/api.schemas'
+import type { PeopleImportApi } from '../../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']
@@ -114,3 +115,23 @@ export function audienceCohortLaunchError(cohort: AudienceCohort): string | null
}
return null
}
+
+/** What an upload added, and which rows it skipped and why, so a short list is never a surprise. */
+export function peopleImportMessage(cohortName: string, summary: PeopleImportApi): string {
+ const parts = [`Added "${cohortName}" to the audience.`]
+ if (summary.new_people) {
+ parts.push(`${summary.new_people} new ${summary.new_people === 1 ? 'person was' : 'people were'} created.`)
+ }
+ const skipped: [number, string][] = [
+ [summary.dropped_invalid_email, 'had no valid email'],
+ [summary.dropped_duplicate_email, 'repeated an email or distinct ID'],
+ [summary.dropped_too_large, 'held more than 4KB of data'],
+ ]
+ const reasons = skipped.filter(([count]) => count > 0).map(([count, reason]) => `${count} ${reason}`)
+ const skippedRows = skipped.reduce((total, [count]) => total + count, 0)
+ if (skippedRows) {
+ parts.push(`Skipped ${skippedRows} ${skippedRows === 1 ? 'row' : 'rows'}: ${reasons.join(', ')}.`)
+ }
+ parts.push('Their properties can take a minute to update.')
+ return parts.join(' ')
+}
diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.test.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.test.ts
index bad570623826..745460a032fe 100644
--- a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.test.ts
@@ -1,5 +1,8 @@
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { PropertyFilterType, PropertyOperator } from '~/types'
@@ -44,7 +47,7 @@ describe('broadcastAudienceListLogic', () => {
await expectLogic(logic, () => {
logic.actions.createListCohort()
})
- .toDispatchActions(['createListCohortFinished', 'closeListModal'])
+ .toDispatchActions(['closeListModal', 'createListCohortFinished'])
.toMatchValues({ isListModalOpen: false, createError: null })
expect(createdCohorts).toEqual(1)
@@ -90,4 +93,143 @@ describe('broadcastAudienceListLogic', () => {
expect(createdCohorts).toEqual(0)
expect(broadcastWizardLogic({ id: 'new' }).values.audienceProperties).toEqual([])
})
+
+ const SPRING_SALE_COHORT = {
+ type: PropertyFilterType.Cohort,
+ key: 'id',
+ value: 42,
+ operator: PropertyOperator.In,
+ cohort_name: 'Spring sale recipients',
+ }
+
+ const IMPORTED = [
+ 201,
+ {
+ cohort_id: 42,
+ row_count: 1,
+ new_people: 1,
+ columns: ['email'],
+ dropped_invalid_email: 0,
+ dropped_duplicate_email: 0,
+ dropped_too_large: 0,
+ },
+ ]
+ const ADDED = { isListModalOpen: false, createError: null }
+
+ it.each([
+ {
+ outcome: 'imports the people and adds their cohort to the audience',
+ csv: 'email,plan\[email protected],Pro\n',
+ response: IMPORTED,
+ expected: ADDED,
+ audience: [SPRING_SALE_COHORT],
+ importedRows: [{ email: '[email protected]', plan: 'Pro' }],
+ },
+ {
+ outcome: 'keeps quoted column names that contain commas',
+ csv: 'email,"Address, line 1","Address, line 2"\[email protected],1 Main St,Flat 2\n',
+ response: IMPORTED,
+ expected: ADDED,
+ audience: [SPRING_SALE_COHORT],
+ importedRows: [{ email: '[email protected]', 'Address, line 1': '1 Main St', 'Address, line 2': 'Flat 2' }],
+ },
+ {
+ outcome: 'drops an empty column with no name',
+ csv: 'email,\[email protected],\n',
+ response: IMPORTED,
+ expected: ADDED,
+ audience: [SPRING_SALE_COHORT],
+ importedRows: [{ email: '[email protected]' }],
+ },
+ {
+ outcome: 'adds the cohort even when reading it back fails, so a retry cannot import twice',
+ csv: 'email\[email protected]\n',
+ response: IMPORTED,
+ cohortReadFails: true,
+ expected: ADDED,
+ audience: [SPRING_SALE_COHORT],
+ importedRows: [{ email: '[email protected]' }],
+ },
+ {
+ outcome: 'rejects a file that is not UTF-8',
+ csv: new Uint8Array([
+ ...new TextEncoder().encode('email\nzo'),
+ 0xeb,
+ ...new TextEncoder().encode('@example.com\n'),
+ ]),
+ response: [500, {}],
+ expected: {
+ isListModalOpen: true,
+ createError: 'This file isn\'t saved as UTF-8. Save it as "CSV UTF-8" and upload it again.',
+ },
+ audience: [],
+ importedRows: undefined,
+ },
+ {
+ outcome: 'rejects a column with data but no name',
+ csv: 'email,\[email protected],Acme\n',
+ response: [500, {}],
+ expected: {
+ isListModalOpen: true,
+ createError: 'A column with data in it has no name. Name it and try again.',
+ },
+ audience: [],
+ importedRows: undefined,
+ },
+ {
+ outcome: 'shows why the API rejected the file and keeps the audience',
+ csv: 'name\nAda\n',
+ response: [400, { detail: 'Add a column named "email" with each person\'s address.' }],
+ expected: {
+ isListModalOpen: true,
+ createError: 'Couldn\'t import the people: Add a column named "email" with each person\'s address.',
+ },
+ audience: [],
+ importedRows: [{ name: 'Ada' }],
+ },
+ {
+ // The two columns would collapse into one key, so the API could not see the repeat.
+ outcome: 'rejects two email columns before sending anything',
+ csv: '\nemail,email\[email protected],[email protected]\n',
+ response: [500, {}],
+ expected: {
+ isListModalOpen: true,
+ createError: 'Two columns are both named "email". Rename one and try again.',
+ },
+ audience: [],
+ importedRows: undefined,
+ },
+ ])(
+ 'with the people import flag on, an upload $outcome',
+ async ({ csv, response, cohortReadFails, expected, audience, importedRows }) => {
+ let sentRows: unknown
+ useMocks({
+ ...(cohortReadFails ? { get: { '/api/projects/:team/cohorts/:id/': () => [500, {}] } } : {}),
+ post: {
+ '/api/projects/:team_id/workflow_people_imports/': async ({ request }) => {
+ sentRows = ((await request.json()) as { rows: unknown }).rows
+ return response as [number, object]
+ },
+ },
+ })
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WORKFLOWS_BROADCAST_RECIPIENT_LISTS], {
+ [FEATURE_FLAGS.WORKFLOWS_BROADCAST_RECIPIENT_LISTS]: true,
+ })
+ const logic = broadcastAudienceListLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.openListModal()
+ logic.actions.setCohortName('Spring sale recipients')
+ logic.actions.setFile(new File([csv], 'people.csv', { type: 'text/csv' }))
+
+ await expectLogic(logic, () => {
+ logic.actions.createListCohort()
+ })
+ .toDispatchActions(['createListCohortFinished'])
+ .toMatchValues(expected)
+
+ expect(sentRows).toEqual(importedRows)
+ expect(createdCohorts).toEqual(0)
+ expect(broadcastWizardLogic({ id: 'new' }).values.audienceProperties).toEqual(audience)
+ }
+ )
})
diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.ts
index 8b6b76d81373..47fcb2cd0af1 100644
--- a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.ts
+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceListLogic.ts
@@ -3,23 +3,33 @@ import { MakeLogicType, actions, connect, kea, key, listeners, path, props, redu
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { createCohortFormData } from 'scenes/cohorts/cohortUtils'
import { cohortsModel } from '~/models/cohortsModel'
import { AnyPropertyFilter, CohortType, PropertyFilterType, PropertyOperator } from '~/types'
+import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'
+
+import { workflowPeopleImportsCreate } from '../../generated/api'
+import type { PeopleImportApi } from '../../generated/api.schemas'
import { BroadcastWizardLogicProps, broadcastWizardLogic } from '../broadcastWizardLogic'
-import { csvListError, defaultListCohortName, readCsvText } from './audienceList'
+import { csvListError, defaultListCohortName, peopleImportMessage, readCsvText } from './audienceList'
+import { parsePeopleCsv } from './peopleCsv'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastAudienceListLogicValues {
audienceProperties: AnyPropertyFilter[] // broadcastWizardLogic
+ currentProjectId: number | null // broadcastWizardLogic
name: string // broadcastWizardLogic
+ featureFlags: FeatureFlagsSet // featureFlagLogic
cohortName: string
createError: string | null
creating: boolean
file: File | null
+ importsPeople: boolean
isListModalOpen: boolean
submitDisabledReason: string | null
}
@@ -56,6 +66,7 @@ export interface broadcastAudienceListLogicActions {
export interface broadcastAudienceListLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ importsPeople: (featureFlags: FeatureFlagsSet) => boolean
submitDisabledReason: (file: File | null, cohortName: string) => string | null
}
}
@@ -72,7 +83,12 @@ export const broadcastAudienceListLogic = kea<broadcastAudienceListLogicType>([
props({} as BroadcastWizardLogicProps),
key((props) => props.id),
connect((props: BroadcastWizardLogicProps) => ({
- values: [broadcastWizardLogic(props), ['name', 'audienceProperties']],
+ values: [
+ broadcastWizardLogic(props),
+ ['name', 'audienceProperties', 'currentProjectId'],
+ featureFlagLogic,
+ ['featureFlags'],
+ ],
actions: [broadcastWizardLogic(props), ['setAudienceProperties'], cohortsModel, ['cohortCreated']],
})),
actions({
@@ -121,6 +137,12 @@ export const broadcastAudienceListLogic = kea<broadcastAudienceListLogicType>([
],
}),
selectors({
+ // With the flag on, each row creates or updates a person and the columns become person properties.
+ importsPeople: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.WORKFLOWS_BROADCAST_RECIPIENT_LISTS],
+ ],
submitDisabledReason: [
(s) => [s.file, s.cohortName],
(file: File | null, cohortName: string): string | null => {
@@ -134,56 +156,111 @@ export const broadcastAudienceListLogic = kea<broadcastAudienceListLogicType>([
},
],
}),
- listeners(({ actions, values }) => ({
- openListModal: () => {
- actions.setCohortName(defaultListCohortName(values.name, dayjs().format('MMM D')))
- },
- createListCohort: async () => {
- if (values.submitDisabledReason) {
- actions.createListCohortFinished(values.submitDisabledReason)
+ listeners(({ actions, values }) => {
+ const addCohortToAudience = (cohort: CohortType): void => {
+ 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.closeListModal()
+ actions.createListCohortFinished(null)
+ }
+
+ const importPeople = async (csv: File): Promise<void> => {
+ if (values.currentProjectId === null) {
+ actions.createListCohortFinished("Couldn't find the project. Reload the page and try again.")
return
}
- const csv = values.file!
- let fileError: string | null
+ const projectId = String(values.currentProjectId)
+ let rows: Record<string, string>[]
try {
- fileError = csvListError(await readCsvText(csv))
+ rows = parsePeopleCsv(await readCsvText(csv))
} catch (error: any) {
- actions.createListCohortFinished(error?.message ?? "Couldn't read the file. Try uploading it again.")
+ actions.createListCohortFinished(error?.message ?? "Couldn't read the file.")
return
}
- if (fileError) {
- actions.createListCohortFinished(fileError)
+ let summary: PeopleImportApi
+ try {
+ summary = await workflowPeopleImportsCreate(projectId, { name: values.cohortName.trim(), rows })
+ } catch (error: any) {
+ actions.createListCohortFinished(
+ `Couldn't import the people: ${error?.detail ?? error?.message ?? 'unknown error'}`
+ )
return
}
+ // The import has started, so a failed read must not let a retry start a second one.
let cohort: CohortType
try {
- const formData = createCohortFormData({
+ cohort = (await cohortsRetrieve(projectId, summary.cohort_id)) as unknown as CohortType
+ } catch {
+ cohort = {
+ id: summary.cohort_id,
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
+ is_calculating: true,
+ } as CohortType
}
- 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.`)
- },
- })),
+ addCohortToAudience(cohort)
+ const skippedRows =
+ summary.dropped_invalid_email + summary.dropped_duplicate_email + summary.dropped_too_large
+ const toast = skippedRows ? lemonToast.warning : lemonToast.success
+ toast(peopleImportMessage(cohort.name ?? values.cohortName.trim(), summary))
+ }
+
+ return {
+ openListModal: () => {
+ actions.setCohortName(defaultListCohortName(values.name, dayjs().format('MMM D')))
+ },
+ createListCohort: async () => {
+ if (values.submitDisabledReason) {
+ actions.createListCohortFinished(values.submitDisabledReason)
+ return
+ }
+ const csv = values.file!
+ if (values.importsPeople) {
+ await importPeople(csv)
+ return
+ }
+ 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
+ }
+ addCohortToAudience(cohort)
+ lemonToast.success(
+ `Added "${cohort.name}" to the audience. Matching the people on it can take a minute.`
+ )
+ },
+ }
+ }),
])
diff --git a/products/workflows/frontend/Broadcasts/audience/peopleCsv.ts b/products/workflows/frontend/Broadcasts/audience/peopleCsv.ts
new file mode 100644
index 000000000000..cdb05ffd9469
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/audience/peopleCsv.ts
@@ -0,0 +1,43 @@
+import Papa from 'papaparse'
+
+// The API accepts request bodies up to 20MB. The rows go up as JSON, which is larger than the CSV.
+const MAX_REQUEST_BYTES = 19 * 1024 * 1024
+
+/** Reads a CSV of people into rows. Throws a message for the uploader when the file cannot be used. */
+export function parsePeopleCsv(text: string): Record<string, string>[] {
+ // Papa's header mode rewrites repeated headers from a naive split of the first line, which breaks quoted
+ // headers that contain the delimiter. One parse into arrays keeps the headers exactly as the file has them.
+ const { data, errors } = Papa.parse<string[]>(text, { skipEmptyLines: true })
+ // A row with an unclosed quote puts values under the wrong columns.
+ // Papa also reports that it could not detect a delimiter in a one-column file, which is not an error.
+ const problem = errors.find((error) => error.type === 'Quotes')
+ if (problem) {
+ throw new Error(`Row ${(problem.row ?? 0) + 1} of the file can't be read: ${problem.message}.`)
+ }
+ const [headers = [], ...rows] = data
+ // Two columns with one name would collapse into one key, so the API could not see the repeat.
+ const repeated = headers.find((header, index) => header.trim() !== '' && headers.indexOf(header) !== index)
+ if (repeated !== undefined) {
+ throw new Error(`Two columns are both named "${repeated}". Rename one and try again.`)
+ }
+ const people = rows.map((cells, index) => {
+ if (cells.length !== headers.length) {
+ throw new Error(
+ `Row ${index + 2} of the file has ${cells.length} values, but the first row has ${headers.length} column names. Fix the row and try again.`
+ )
+ }
+ const person: Record<string, string> = {}
+ headers.forEach((header, column) => {
+ if (header.trim() !== '') {
+ person[header] = cells[column]
+ } else if (cells[column].trim() !== '') {
+ throw new Error('A column with data in it has no name. Name it and try again.')
+ }
+ })
+ return person
+ })
+ if (new Blob([JSON.stringify(people)]).size > MAX_REQUEST_BYTES) {
+ throw new Error('This file is too large to upload. Remove some rows or columns and try again.')
+ }
+ return people
+}