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(cohorts): move add-users controls into a menu once a cohort has people (#116867)

ruby childs379e5911c0ff
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 978d9ba7c49a..1342fef0c0a8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -14475,45 +14475,45 @@ snapshots:
scenes-app-oauth-authorize--with-required-scopes--light:
hash: v1.k794b7964.8405b959e06c12f3570148cc6fc886506649388af3f863325b19318154b43a5f.NfwfuBsYksnILN1RfeaDmcaY-IUB9UYRJfS4C9tbIVA
scenes-app-people-cohorts--cohort-edit-dynamic--dark:
- hash: v1.k794b7964.64bc82476828e61d420a9fc2ef3c550d45acf9c24f8d0bec694f803ecd147df7.eqlptg68mBa-l30eKEMGIEqcHeTSh2GAlhd0ybVid-k
+ hash: v1.k794b7964.2c1b733fd9d842f8a01a79c0dd5070d772946be3b5d971305532819dfe101fcb.Tdmt5xyxou7KEnyx_dboWsfL64wrqeWhwuAGcIbaGLU
scenes-app-people-cohorts--cohort-edit-dynamic--light:
- hash: v1.k794b7964.16bae00697363fb140788023823ca272a1f57bf2b9cc4984f62f6b39e098b87a.sga7qTbJWVb7MG-E8DSdsDVlcJm9nBZzZAY6TxrBIUw
+ hash: v1.k794b7964.2349bc936147b2fc67560400dcbe00d59c619123863e64bac242253f0feadd55.B-_1XH-fj07LM7kDWJ6gjDxiE1Do7juRsQqbnkYEb50
scenes-app-people-cohorts--cohort-edit-person-properties--dark:
- hash: v1.k794b7964.c861bd63cb563dc388df44cfacc390a132486e925becb5551d3ac0ae4cffbcf8.IMaQW8Yon_VqNVEE9-tnOtK1lNSyMuwxN9a-4SWgZzU
+ hash: v1.k794b7964.5e194ee97b0244ed9ee703d6ff128b3c60edfbd35ca2634ca7be9814d0242e77.zpU6IoJWLSvpuDck9B35acOL16jaSt33b0_kmRb00gQ
scenes-app-people-cohorts--cohort-edit-person-properties--light:
- hash: v1.k794b7964.807a4d957649a09c0bf100246a9775fb014f907223253589e37093881012d7ad.Bl-7G3Js_fWVnQosKpAu3X_rHwpzRHzNE1vRW2kT8nk
+ hash: v1.k794b7964.7b208eb63baa7674265d95c1771f475be41a39ae8c5067ed6c64fb8b42c1e8e7.cbaJowSd3JMx7jHK8oLHsTyGzswQKdOg89-fTv_5H2E
scenes-app-people-cohorts--cohort-edit-realtime-daily--dark:
- hash: v1.k794b7964.a58ca2763bf4d0ad21bb045e3df40fd66dae0019c4a89b4cb737e65b15fe750e.7RdVV0PgCXVw93t_xhrf1HWZAWgaq3zvBJT4pngMQIk
+ hash: v1.k794b7964.466ace009d091933d49b94a9f0f99cb0200f51f64bf2abf070210601ee4cbaa8.-rGWHDT3KkeeFOjBoDR1OKPAB_TvTGeTvzipwURq_mc
scenes-app-people-cohorts--cohort-edit-realtime-daily--light:
- hash: v1.k794b7964.4d701ca553c0d342a85d2fdd08ca0bbcb6629649c53f78727d78092398dd1896.o1JWPnOlcTpxJcPTjW9uJn8jqDzGDKS1LQct4B0C9Sw
+ hash: v1.k794b7964.19cc12d6d9012fdd1b91476da2d033f6f66de1a38955e5cbcd08c8f19f6e9144.fcRRiMvbK1ylZyMfAHE-C_d0ZOtZ8Xq8ojQqs3Xsp9g
scenes-app-people-cohorts--cohort-edit-realtime-not-available--dark:
- hash: v1.k794b7964.4847c1eb77cf7e1f6110d265f1bfdb56bc4f0189a70dd2e583b5a5f185d3faae.CsN_IL0uPTuj08TbFDHDm_paheQ8HqyW642RyqgwZdY
+ hash: v1.k794b7964.27868f1b196762c4a290113b8968861364f68d1ccb3f4a4f841823b478b387de.P5f6cfgB2V88npA1FEIPynbdOHeuQIYfQCWe4fT3Rys
scenes-app-people-cohorts--cohort-edit-realtime-not-available--light:
- hash: v1.k794b7964.866758eefcc8d322577356d38b0eae109bc70d4eabf5db82ae3da8cd68789ce4.RXO-YDcFl2jvjmLQqL--j0mzpxS4aP4QYiogAj2W3go
+ hash: v1.k794b7964.bb0f2a7318624aa9eee73a506613355e0d22bea3678905ee7d0628a7067c8fce.59NEErSvZUs5M-Cr5bfwet6k6jjD_PUOt5tlVKyqO8I
scenes-app-people-cohorts--cohort-edit-realtime-preparing--dark:
- hash: v1.k794b7964.9defa779b81d25f039dbaca787951ff704b9164b8ed30b0a3c22f8fd4971d0bf.zc5GaVgiUk6vXu2IwEypg-IMGY_hMrWaNRLjim6sUco
+ hash: v1.k794b7964.37ca56bfe927a5c4f70ffc323e32c926f7ad6e6ae3e105e9592c58fee55e7c8f.vhHkW-2ao4ThzkNhitoXdtmexE2T0WCB3GPsYReaBNg
scenes-app-people-cohorts--cohort-edit-realtime-preparing--light:
- hash: v1.k794b7964.0cc1a93242b81e89b8883bc0cd035a996d1fb350cee8b286eeb95441fa0f5f08.fAaV7TDHUxCTTF69ZkxCFnYPFdUsu9qFsZnJENDajt8
+ hash: v1.k794b7964.9199b4e2c063905be6ec3767da17e89561c86dffdf309e8414df84cb20e7b762.JyIwiEUOQIYo2eZNCJZfvhn8vuFpWyDXcoxtH6VH430
scenes-app-people-cohorts--cohort-edit-realtime-ready--dark:
- hash: v1.k794b7964.ea59791b66afcac2fb6b17109103110cfa6894d73d28feaadd34d043ae996db6.Tfdgur8DZ7q3kmgInIhMJhStne4aR53yux7IErBb_8w
+ hash: v1.k794b7964.7e1939184514f3b684566607bde8464e10b6313fac3e3bff11b012fc4cadb175.JZg2q3VbloJ8aEt1XlHG3j9fAchc2d-GVi3VOgAJWns
scenes-app-people-cohorts--cohort-edit-realtime-ready--light:
- hash: v1.k794b7964.db7cc98ca551776dad599e2f3eeb42b3f11f7b8f83e895e6911c929d8064f5b2.kh0GmHQxkSVgSu4FH-AW0vDquF3E394dIizr4Catrpc
+ hash: v1.k794b7964.e171b8b4f85bcc8b17c883079a75eb43dff4ad619478ad419b12fa2e736c9863.6vzQvAExhSAPpzdCX_35TEdpSbuB0nD-W4xcZ1PXdjU
scenes-app-people-cohorts--cohort-edit-realtime-ready-flag-off--dark:
- hash: v1.k794b7964.37bc61b07982efe2362b9f1b53be9ff92fdef34ee81ea3c27fb85bd06e59c72b.78dmguEbam8nczYdzBuy3sKYNdyuL0EfjchkrGMxwkE
+ hash: v1.k794b7964.57dfce45c5c5617a4ee57a2afe53bd342cdf741bedecbc898cda4f9f5046393d.4FE_8ptB3NoicvsqPmyzvlqmafQxlA0bhBdyOao86Gk
scenes-app-people-cohorts--cohort-edit-realtime-ready-flag-off--light:
- hash: v1.k794b7964.8b9ff865378d2be1c33ea33ba2af40701bd14ed017efb4fe22fc08fdcacabeaf.tQPkU-8mNsMRhArTuUfVseT73s9Jmq5bowgKFwwvOV8
+ hash: v1.k794b7964.e1594dd8081c08aaf16f34d980b6aca91d293128245b7028f6362644590ce0de.sS6lmEtXAveUhh_3tpF6Qac4x9Lx6EBYwUjfmbgpYYQ
scenes-app-people-cohorts--cohort-edit-realtime-rebuilding--dark:
- hash: v1.k794b7964.a0f634f2653893f153a800999372cfce15cbb4ec8ebd86e942acd28a1462cf3f.BALCFCmvgyITBYveLRY4gx2q2j7TJiZ4ftzPJttYJJY
+ hash: v1.k794b7964.ed373fbd3237d0a478e2f8b7795c2b767957941956ed0d544de21836a8179d88.0HTrjK6zpi8DsbH-_6UxeTPoyxCFuMkks4ASUgeCpJw
scenes-app-people-cohorts--cohort-edit-realtime-rebuilding--light:
- hash: v1.k794b7964.bd689fe21ea1df944d85fe88ddc72504ccb364c64c73765033d31cc5ef575d93.ldN8Fbay-ZcPzeyEHo8nIIilevKutTa03vXv2zo4aWE
+ hash: v1.k794b7964.3c29aca76bf99f6633deb5c7e169bf27141902c0ecc654fae474841526d39c69.2l6TiRlerGaUvfN0rscVx9uoqJL5Ry_r4jIHd5JLu60
scenes-app-people-cohorts--cohort-edit-static--dark:
- hash: v1.k794b7964.267b40e33b380519b46d4b7b8068b869a6250b5fd446c6335a9e95f683ee2302.jnRu9rG_ZQxTsYzmKQqEbN-aIU3psCpbQN8hV8OsX6Y
+ hash: v1.k794b7964.5da1cf3f5f3ee759a855340a6ba403e8d8ce661e100f006bff61b04497a9436c.M4cIrZEwRfa_oGQJnObhCdPCZNFglVAMgXD8lQnifBg
scenes-app-people-cohorts--cohort-edit-static--light:
- hash: v1.k794b7964.ccca565eab13d0a15b96b664f72fe2a86cd7f94f71144041020507f80e4f0123.7Aj84hi9A22Kzcp0q7Whjal9N_XI9QOHNqHjB2DFRgs
+ hash: v1.k794b7964.7c5ed7bc8c0017dc6d4e3b2a43d3f2ab835b939d2c162b1f3518b13713d0b462.m55J4liwt9b7yiePSSZ-UX2SoUqJvGgfl9OPnGOXPqc
scenes-app-people-cohorts--cohort-edit-static-population-failed--dark:
- hash: v1.k794b7964.56f875299f9005db364cc362050e4d425528d2205c202def0d2a6e98c9745b25.tXvxMJzkKQb5UhOTQMrfwndgLUz8aBUxAaSvpdQtl2I
+ hash: v1.k794b7964.3377058215713b55e0c992bfcd0b2a0aa10bf6bd4afb058ec40ced11690f06a1.3vBNXvNFpPec-rN7qpunj_AeOHoCmJ_acPajbauNn-E
scenes-app-people-cohorts--cohort-edit-static-population-failed--light:
- hash: v1.k794b7964.3c2fb12b8b97a3126412bd6667a2873d37f97288b86d90afed2ff6ff12f320f3.RLtxz6gSL0p-CpgRQE5RdOzgVgAkyPBRz4yMz8IgbDM
+ hash: v1.k794b7964.088be3f23f47c0cd8c2cf08d9fcb2034a448a514e19c38490a4228fabf9b2d2b.3Wdw5GoWdFtwC0l9u07B8wKIlgAy86dM0Y7aqzsOkeI
scenes-app-people-cohorts--cohort-new--dark:
hash: v1.k794b7964.0c0b9da85f85dac4c299d0527725f192c0c07d204e28462a64736552aaba735b.aX2s9DQu-pQIZHJDYBeZXL9lyni7w6PSMh3u3b_cvhA
scenes-app-people-cohorts--cohort-new--light:
diff --git a/frontend/src/scenes/cohorts/CohortCsvUploadModal.tsx b/frontend/src/scenes/cohorts/CohortCsvUploadModal.tsx
new file mode 100644
index 000000000000..8815734bb3ef
--- /dev/null
+++ b/frontend/src/scenes/cohorts/CohortCsvUploadModal.tsx
@@ -0,0 +1,67 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { COHORT_CSV_HELP, CohortCsvDropzone } from './CohortCsvDropzone'
+import { CohortLogicProps, cohortEditLogic } from './cohortEditLogic'
+import { cohortCsvTooLargeMessage } from './cohortUtils'
+
+export function CohortCsvUploadModal({ id }: CohortLogicProps): JSX.Element {
+ const logic = cohortEditLogic({ id })
+ const { cohort, cohortLoading, csvUploadModalOpen, csvMaxBytes } = useValues(logic)
+ const { setCohortValue, setCsvUploadModalOpen, uploadCohortCsv } = useActions(logic)
+
+ const csvTooLarge = !!cohort.csv && cohort.csv.size > csvMaxBytes
+
+ // The modal only opens for saved cohorts, where the upload sends the CSV alone,
+ // so an abandoned file can always be dropped on close.
+ const onClose = (): void => {
+ setCohortValue('csv', undefined)
+ setCsvUploadModalOpen(false)
+ }
+
+ return (
+ <LemonModal
+ title="Upload a CSV"
+ description={<span className="max-w-prose">{COHORT_CSV_HELP}</span>}
+ isOpen={csvUploadModalOpen}
+ onClose={onClose}
+ closable={!cohortLoading}
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={onClose}
+ disabledReason={cohortLoading ? 'Uploading the CSV' : undefined}
+ data-attr="cohort-upload-csv-modal-cancel"
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={() => uploadCohortCsv()}
+ loading={cohortLoading}
+ disabledReason={
+ !cohort.csv
+ ? 'Choose a CSV file first'
+ : csvTooLarge
+ ? cohortCsvTooLargeMessage(csvMaxBytes)
+ : undefined
+ }
+ data-attr="cohort-upload-csv-modal-save"
+ >
+ Upload
+ </LemonButton>
+ </>
+ }
+ >
+ {csvTooLarge && <LemonBanner type="error">{cohortCsvTooLargeMessage(csvMaxBytes)}</LemonBanner>}
+ <div className="ph-ignore-input">
+ <CohortCsvDropzone
+ value={cohort.csv ?? null}
+ onChange={(file) => setCohortValue('csv', file ?? undefined)}
+ />
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
index e38d305765f2..7dace83669d5 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
@@ -29,6 +29,7 @@ import {
PropertyType,
} from '~/types'
+import { CohortCsvUploadModal } from './CohortCsvUploadModal'
import { CohortEdit } from './CohortEdit'
jest.mock('lib/components/AutoSizer', () => ({
@@ -119,6 +120,73 @@ describe('cohortEditLogic', () => {
})
})
+ describe('CSV upload modal', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('clears the chosen CSV on close and on cancel', async () => {
+ logic = cohortEditLogic({ id: 10 })
+ render(<CohortCsvUploadModal id={10} />)
+
+ // Let the mount-time fetch land first, or its response would replace the state set below.
+ await waitFor(() => expect(logic.values.cohort.id).toEqual(mockCohort.id))
+
+ act(() => {
+ logic.actions.setCohort({
+ ...NEW_COHORT,
+ id: 10,
+ name: 'Saved cohort',
+ is_static: true,
+ csv: new File(['[email protected]'], 'people.csv', { type: 'text/csv' }),
+ })
+ logic.actions.setCsvUploadModalOpen(true)
+ })
+
+ const closeButton = document.querySelector('.LemonModal__close button') as HTMLElement
+ await userEvent.click(closeButton)
+ expect(logic.values.cohort.csv).toBeUndefined()
+ expect(logic.values.csvUploadModalOpen).toBe(false)
+
+ act(() => {
+ logic.actions.setCohortValue('csv', new File(['[email protected]'], 'people.csv', { type: 'text/csv' }))
+ logic.actions.setCsvUploadModalOpen(true)
+ })
+ const cancelButton = document.querySelector('[data-attr="cohort-upload-csv-modal-cancel"]') as HTMLElement
+ await userEvent.click(cancelButton)
+ expect(logic.values.cohort.csv).toBeUndefined()
+ expect(logic.values.csvUploadModalOpen).toBe(false)
+ })
+
+ it('shows the size limit and disables Upload for an oversized CSV', async () => {
+ logic = cohortEditLogic({ id: 10 })
+ render(<CohortCsvUploadModal id={10} />)
+
+ // Let the mount-time fetch land first, or its response would replace the state set below.
+ await waitFor(() => expect(logic.values.cohort.id).toEqual(mockCohort.id))
+
+ const csv = new File(['[email protected]'], 'people.csv', { type: 'text/csv' })
+ Object.defineProperty(csv, 'size', { value: logic.values.csvMaxBytes + 1 })
+
+ act(() => {
+ logic.actions.setCohort({
+ ...NEW_COHORT,
+ id: 10,
+ name: 'Saved cohort',
+ is_static: true,
+ csv,
+ })
+ logic.actions.setCsvUploadModalOpen(true)
+ })
+
+ expect(await screen.findByText(/larger than the limit/i)).toBeVisible()
+ const uploadButton = document.querySelector(
+ '[data-attr="cohort-upload-csv-modal-save"]'
+ ) as HTMLButtonElement
+ expect(uploadButton).toHaveAttribute('aria-disabled', 'true')
+ })
+ })
+
describe('scroll to error functionality', () => {
let scrollIntoViewSpy: jest.SpyInstance
let querySelectorSpy: jest.SpyInstance
@@ -151,7 +219,7 @@ describe('cohortEditLogic', () => {
logic.actions.submitCohort()
}).toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
- await new Promise((resolve) => setTimeout(resolve, 10))
+ await new Promise((resolve) => requestAnimationFrame(resolve))
expect(querySelectorSpy).toHaveBeenCalledWith('.Field--error')
expect(scrollIntoViewSpy).toHaveBeenCalledWith({
@@ -693,6 +761,45 @@ describe('cohortEditLogic', () => {
})
})
+ describe('add users controls on an existing people cohort', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ { count: 0, showsInlineUpload: true },
+ { count: 3, showsInlineUpload: false },
+ ])('with $count people shows inline upload: $showsInlineUpload', async ({ count, showsInlineUpload }) => {
+ const cohortId = 20 + count
+ const cohortName = `People cohort ${count}`
+ useMocks({
+ get: {
+ [`/api/projects/:team_id/cohorts/${cohortId}/`]: {
+ ...mockCohort,
+ id: cohortId,
+ name: cohortName,
+ is_static: true,
+ filters: { properties: { type: 'OR', values: [] } },
+ count,
+ },
+ },
+ })
+
+ render(<CohortEdit id={cohortId} />)
+
+ await screen.findAllByText(cohortName)
+ const dropzone = screen.queryByText('Drag a file here or click to browse for a file')
+ const addUsersMenu = document.querySelector('[data-attr="cohort-add-users-menu"]')
+ if (showsInlineUpload) {
+ expect(dropzone).toBeInTheDocument()
+ expect(addUsersMenu).not.toBeInTheDocument()
+ } else {
+ expect(dropzone).not.toBeInTheDocument()
+ expect(addUsersMenu).toBeInTheDocument()
+ }
+ })
+ })
+
describe('used-in summary', () => {
afterEach(() => {
cleanup()
@@ -1085,12 +1192,12 @@ describe('cohortEditLogic', () => {
)
})
- describe('locked type and populate-from controls on existing cohorts', () => {
+ describe('type tag on existing cohorts', () => {
afterEach(() => {
cleanup()
})
- it('renders locked controls as a read-only value with an info tooltip, not a dead-click dropdown', async () => {
+ it('shows the type as a tag next to the title instead of body rows', async () => {
const cohortId = 10
useMocks({
@@ -1112,19 +1219,13 @@ describe('cohortEditLogic', () => {
render(<CohortEdit id={cohortId} />)
- // The current value is always visible in plain text; the "why can't I change this"
- // explanation lives in an info tooltip instead of being repeated inline.
- const typeContainer = (await screen.findByText('Static')).closest('[data-attr="cohort-type"]')
- const populateFromContainer = screen
- .getByText('Criteria · One-time snapshot')
- .closest('[data-attr="static-cohort-mode"]')
- expect(typeContainer).toBeInTheDocument()
- expect(populateFromContainer).toBeInTheDocument()
-
- // The locked controls are read-only text, not interactive select buttons (the dead click):
- // a LemonSelect would render the data-attr onto a <button>
- expect(typeContainer?.tagName).not.toBe('BUTTON')
- expect(populateFromContainer?.tagName).not.toBe('BUTTON')
+ // The type is a tag in the title row; the populate-from detail lives in its tooltip.
+ const typeTag = (await screen.findByText('Static')).closest('[data-attr="cohort-type-tag"]')
+ expect(typeTag).toBeInTheDocument()
+
+ // The old read-only body rows are gone, so the persons table is not pushed down.
+ expect(document.querySelector('[data-attr="cohort-type"]')).not.toBeInTheDocument()
+ expect(document.querySelector('[data-attr="static-cohort-mode"]')).not.toBeInTheDocument()
})
})
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index 2833efd6360f..6f6830bf74db 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -9,12 +9,13 @@ import {
IconExpand,
IconInfo,
IconLetter,
+ IconPlus,
IconRefresh,
IconSend,
IconTrash,
IconWarning,
} from '@posthog/icons'
-import { LemonBanner, LemonDivider, LemonSnack, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonDivider, LemonMenu, LemonSnack, LemonTabs, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { Button } from '@posthog/quill'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
@@ -72,6 +73,7 @@ import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'
import { CohortBlockingWorkflowsModal } from './CohortBlockingWorkflowsModal'
import { cohortCountWarningLogic } from './cohortCountWarningLogic'
import { COHORT_CSV_HELP, CohortCsvDropzone } from './CohortCsvDropzone'
+import { CohortCsvUploadModal } from './CohortCsvUploadModal'
import { CohortSceneMenuBar } from './CohortSceneMenuBar'
import { cohortUsedInSections } from './cohortUsedIn'
import { CohortUsedInList } from './CohortUsedInList'
@@ -185,6 +187,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
setUsedInExpanded,
openBlockingWorkflowsModal,
submitCohort,
+ setCsvUploadModalOpen,
} = useActions(logic)
const modalLogic = addPersonToCohortModalLogic(logicProps)
const { showAddPersonToCohortModal } = useActions(modalLogic)
@@ -202,6 +205,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
usedInExpanded,
staticCohortMode,
activeTab,
+ hasAddUsersMenu,
} = useValues(logic)
const { featureFlags } = useValues(featureFlagLogic)
const { canCopyToProject } = useValues(interProjectCopyLogic)
@@ -220,6 +224,14 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
const cohortId = typeof cohort.id === 'number' ? cohort.id : null
+ // The details section and the divider above the persons table render only when they have
+ // content, so a plain static cohort shows its people right under the tabs.
+ const hasOverviewDetails =
+ isNewCohort ||
+ !cohort.is_static ||
+ (usedIn ? cohortUsedInSections(usedIn).length > 0 || usedIn.workflows.total > 0 : false)
+ const hasSectionAbovePersons = hasOverviewDetails || staticCohortMode === 'criteria' || !hasAddUsersMenu
+
useFileSystemLogView({
type: 'cohort',
ref: cohortId,
@@ -254,6 +266,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
<BindLogic logic={cohortEditLogic} props={logicProps}>
<div className="cohort">
<AddPersonToCohortModal id={id} />
+ <CohortCsvUploadModal id={id} />
<CohortBlockingWorkflowsModal />
<CohortSceneMenuBar id={id} />
@@ -374,6 +387,23 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
<LemonField name="name" className="contents">
<SceneTitleSection
name={cohort.name}
+ nameSuffix={
+ !isNewCohort ? (
+ <Tooltip
+ title={
+ cohort.is_static
+ ? staticCohortMode === 'criteria'
+ ? 'This cohort is a fixed list, snapshotted from criteria when it was created. It will not update as people change. Create a new cohort to use a different type.'
+ : 'This cohort is a fixed list, populated by uploading a CSV or adding people individually. Create a new cohort to use a different type.'
+ : 'This cohort updates automatically as people and their data change. Create a new cohort to use a different type.'
+ }
+ >
+ <LemonTag size="small" data-attr="cohort-type-tag">
+ {cohort.is_static ? 'Static' : 'Dynamic'}
+ </LemonTag>
+ </Tooltip>
+ ) : undefined
+ }
description={cohort.description || ''}
// When the SceneMenuBar renders above the title, the title's default
// negative top margin pulls it up under the bar — drop it in that case.
@@ -416,6 +446,28 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
>
Save
</Button>
+ {hasAddUsersMenu && (
+ <LemonMenu
+ items={[
+ {
+ label: 'Upload a CSV',
+ onClick: () => setCsvUploadModalOpen(true),
+ 'data-attr': 'cohort-upload-csv-modal-open',
+ },
+ {
+ label: 'Add users manually',
+ onClick: showAddPersonToCohortModal,
+ 'data-attr': 'cohort-add-users-modal-open',
+ },
+ ]}
+ placement="bottom-end"
+ >
+ <Button variant="outline" data-attr="cohort-add-users-menu">
+ <IconPlus />
+ Add users
+ </Button>
+ </LemonMenu>
+ )}
</>
) : (
<>
@@ -443,6 +495,32 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
>
Save
</LemonButton>
+ {hasAddUsersMenu && (
+ <LemonMenu
+ items={[
+ {
+ label: 'Upload a CSV',
+ onClick: () => setCsvUploadModalOpen(true),
+ 'data-attr': 'cohort-upload-csv-modal-open',
+ },
+ {
+ label: 'Add users manually',
+ onClick: showAddPersonToCohortModal,
+ 'data-attr': 'cohort-add-users-modal-open',
+ },
+ ]}
+ placement="bottom-end"
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ data-attr="cohort-add-users-menu"
+ >
+ Add users
+ </LemonButton>
+ </LemonMenu>
+ )}
</>
)
}
@@ -457,6 +535,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
{ key: 'overview', label: 'Overview' },
{ key: 'history', label: 'History' },
]}
+ sceneInset
/>
)}
@@ -471,46 +550,82 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
) : null}
<div className={cn(activeTab === 'overview' ? 'contents' : 'hidden')}>
- <SceneSection
- title={isNewCohort ? 'Type' : undefined}
- description={
- isNewCohort
- ? 'Static cohorts are created once and never updated, while dynamic cohorts are recalculated based on the latest data.'
- : undefined
- }
- className="max-w-200 flex flex-col gap-y-2"
- hideTitleAndDescription
- >
- <div className="flex gap-4 flex-wrap">
- <div className={cn('flex-1 flex flex-col gap-y-4')}>
- {isNewCohort ? (
- <LemonField name="is_static" label={null}>
- {({ value, onChange }) => (
- <LemonSelect
- options={COHORT_TYPE_OPTIONS}
- value={value ? CohortTypeEnum.Static : CohortTypeEnum.Dynamic}
- onChange={(cohortType) => {
- onChange(cohortType === CohortTypeEnum.Static)
- }}
- fullWidth
- data-attr="cohort-type"
- />
- )}
- </LemonField>
- ) : (
- <div className="flex items-center gap-x-2" data-attr="cohort-type">
- <span className="text-sm text-secondary">
- Type:{' '}
- <strong className="font-medium text-default">
- {cohort.is_static ? 'Static' : 'Dynamic'}
- </strong>
- </span>
- <Tooltip title="Create a new cohort to use a different type of cohort.">
- <IconInfo className="text-secondary text-base" />
- </Tooltip>
- {usedIn && usedIn.workflows.total > 0 && (
- <>
- <span className="text-secondary">·</span>
+ {!isNewCohort &&
+ (isCalculatingOrPending ? (
+ <LemonBanner type="warning">
+ {isPendingCalculation && !cohort.is_calculating
+ ? cohort.last_calculation
+ ? "We're queuing a recalculation. The table below shows results from the previous calculation."
+ : "We're queuing the calculation. It should be ready in a few minutes."
+ : cohort.last_calculation
+ ? "We're recalculating the cohort. The table below shows results from the previous calculation."
+ : "We're calculating the cohort. It should be ready in a few minutes."}
+ </LemonBanner>
+ ) : cohort.errors_calculating ? (
+ <LemonBanner
+ type="error"
+ // A static cohort is populated once from the source it was created
+ // with, and the edit form does not resend that source, so saving the
+ // cohort again would not run the population.
+ action={
+ cohort.is_static
+ ? undefined
+ : {
+ onClick: () => submitCohort(),
+ children: 'Retry',
+ }
+ }
+ >
+ <strong>Calculation failed:</strong>{' '}
+ {cohort.last_error_message ||
+ (cohort.is_static
+ ? 'Unable to populate this cohort from its source.'
+ : 'Unable to calculate this cohort. Please check your matching criteria and try again.')}{' '}
+ {cohort.is_static ? 'If it keeps happening, ' : 'If it fails again, '}
+ <Link onClick={() => openSidePanel(SidePanelTab.Support, 'bug:cohorts::true')}>
+ contact support
+ </Link>
+ .
+ </LemonBanner>
+ ) : null)}
+ {!isNewCohort && (
+ <div aria-live="polite">
+ <UnmatchedImportBanner cohort={cohort} />
+ </div>
+ )}
+ {hasOverviewDetails && (
+ <SceneSection
+ title={isNewCohort ? 'Type' : undefined}
+ description={
+ isNewCohort
+ ? 'Static cohorts are created once and never updated, while dynamic cohorts are recalculated based on the latest data.'
+ : undefined
+ }
+ className="max-w-200 flex flex-col gap-y-2"
+ hideTitleAndDescription
+ >
+ <div className="flex gap-4 flex-wrap">
+ <div className={cn('flex-1 flex flex-col gap-y-4')}>
+ {isNewCohort ? (
+ <LemonField name="is_static" label={null}>
+ {({ value, onChange }) => (
+ <LemonSelect
+ options={COHORT_TYPE_OPTIONS}
+ value={
+ value ? CohortTypeEnum.Static : CohortTypeEnum.Dynamic
+ }
+ onChange={(cohortType) => {
+ onChange(cohortType === CohortTypeEnum.Static)
+ }}
+ fullWidth
+ data-attr="cohort-type"
+ />
+ )}
+ </LemonField>
+ ) : (
+ usedIn &&
+ usedIn.workflows.total > 0 && (
+ <div className="flex items-center gap-x-2">
<Link
className="text-sm"
onClick={() =>
@@ -524,145 +639,63 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
Used in {usedIn.workflows.total}{' '}
{usedIn.workflows.total === 1 ? 'workflow' : 'workflows'}
</Link>
- </>
- )}
- </div>
- )}
+ </div>
+ )
+ )}
- {cohort.is_static && (
- <div className="flex flex-col gap-y-2">
- {isNewCohort ? (
- <>
- <h2 className="text-base mb-0">Populate from</h2>
- <p className="text-sm text-secondary my-0 max-w-prose">
- {staticCohortMode === 'criteria'
- ? 'People matching the criteria below will be snapshotted into a fixed list when the cohort is created. Unlike a dynamic cohort, the list will not update as people change.'
- : 'Manually add people via CSV upload or by selecting them individually.'}
- </p>
- <LemonSelect
- options={POPULATE_FROM_OPTIONS}
- value={staticCohortMode}
- onChange={(value) => setStaticCohortMode(value)}
- fullWidth
- data-attr="static-cohort-mode"
- />
- </>
- ) : (
- <div
- className="flex items-center gap-x-2"
+ {cohort.is_static && isNewCohort && (
+ <div className="flex flex-col gap-y-2">
+ <h2 className="text-base mb-0">Populate from</h2>
+ <p className="text-sm text-secondary my-0 max-w-prose">
+ {staticCohortMode === 'criteria'
+ ? 'People matching the criteria below will be snapshotted into a fixed list when the cohort is created. Unlike a dynamic cohort, the list will not update as people change.'
+ : 'Manually add people via CSV upload or by selecting them individually.'}
+ </p>
+ <LemonSelect
+ options={POPULATE_FROM_OPTIONS}
+ value={staticCohortMode}
+ onChange={(value) => setStaticCohortMode(value)}
+ fullWidth
data-attr="static-cohort-mode"
- >
- <span className="text-sm text-secondary">
- Populate from:{' '}
- <strong className="font-medium text-default">
- {
- POPULATE_FROM_OPTIONS.find(
- (option) => option.value === staticCohortMode
- )?.label
- }
- </strong>
- </span>
- <Tooltip
- title={
- staticCohortMode === 'criteria'
- ? 'This cohort was snapshotted from criteria at creation time and will not update as people change. Create a new cohort to change how a static cohort is populated.'
- : 'This cohort was populated by uploading a CSV or selecting people individually. Create a new cohort to change how a static cohort is populated.'
- }
- >
+ />
+ </div>
+ )}
+
+ {!isNewCohort && !cohort.is_static && (
+ <div className="flex items-center gap-x-2 my-0">
+ <strong>Last calculated:</strong>
+ {featureFlags[FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING] && (
+ <Tooltip title="When PostHog last worked out who belongs to this cohort. That count is what insights, breakdowns and the people list below use, and it is recalculated once a day and whenever you edit the cohort.">
<IconInfo className="text-secondary text-base" />
</Tooltip>
- </div>
- )}
- </div>
- )}
-
- {!isNewCohort && (
- <div className="flex flex-col gap-y-2">
- {!cohort.is_static && (
- <div className="flex items-center gap-x-2 my-0">
- <strong>Last calculated:</strong>
- {featureFlags[FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING] && (
- <Tooltip title="When PostHog last worked out who belongs to this cohort. That count is what insights, breakdowns and the people list below use, and it is recalculated once a day and whenever you edit the cohort.">
- <IconInfo className="text-secondary text-base" />
- </Tooltip>
- )}
- {isCalculatingOrPending ? (
- <div className="flex items-center gap-x-2">
- <Spinner size="small" />
- <span className="text-muted">In progress...</span>
- </div>
- ) : cohort.last_calculation ? (
- <TZLabel time={cohort.last_calculation} />
- ) : (
- <span className="text-muted">Not yet calculated</span>
- )}
- </div>
- )}
-
- {isCalculatingOrPending ? (
- <LemonBanner type="warning">
- {isPendingCalculation && !cohort.is_calculating
- ? cohort.last_calculation
- ? "We're queuing a recalculation. The table below shows results from the previous calculation."
- : "We're queuing the calculation. It should be ready in a few minutes."
- : cohort.last_calculation
- ? "We're recalculating the cohort. The table below shows results from the previous calculation."
- : "We're calculating the cohort. It should be ready in a few minutes."}
- </LemonBanner>
- ) : cohort.errors_calculating ? (
- <LemonBanner
- type="error"
- // A static cohort is populated once from the source it was created
- // with, and the edit form does not resend that source, so saving the
- // cohort again would not run the population.
- action={
- cohort.is_static
- ? undefined
- : {
- onClick: () => submitCohort(),
- children: 'Retry',
- }
- }
- >
- <strong>Calculation failed:</strong>{' '}
- {cohort.last_error_message ||
- (cohort.is_static
- ? 'Unable to populate this cohort from its source.'
- : 'Unable to calculate this cohort. Please check your matching criteria and try again.')}{' '}
- {cohort.is_static
- ? 'If it keeps happening, '
- : 'If it fails again, '}
- <Link
- onClick={() =>
- openSidePanel(SidePanelTab.Support, 'bug:cohorts::true')
- }
- >
- contact support
- </Link>
- .
- </LemonBanner>
- ) : null}
- </div>
- )}
+ )}
+ {isCalculatingOrPending ? (
+ <div className="flex items-center gap-x-2">
+ <Spinner size="small" />
+ <span className="text-muted">In progress...</span>
+ </div>
+ ) : cohort.last_calculation ? (
+ <TZLabel time={cohort.last_calculation} />
+ ) : (
+ <span className="text-muted">Not yet calculated</span>
+ )}
+ </div>
+ )}
- {!isNewCohort && !cohort.is_static && (
- <CohortRealtimeStatus realtime={cohort.realtime} />
- )}
+ {!isNewCohort && !cohort.is_static && (
+ <CohortRealtimeStatus realtime={cohort.realtime} />
+ )}
- {!isNewCohort && usedIn && (
- <UsedInSummary
- usedIn={usedIn}
- isExpanded={usedInExpanded}
- setIsExpanded={setUsedInExpanded}
- />
- )}
+ {!isNewCohort && usedIn && (
+ <UsedInSummary
+ usedIn={usedIn}
+ isExpanded={usedInExpanded}
+ setIsExpanded={setUsedInExpanded}
+ />
+ )}
+ </div>
</div>
- </div>
- </SceneSection>
- {!isNewCohort && (
- <div aria-live="polite">
- <UnmatchedImportBanner cohort={cohort} />
- </div>
+ </SceneSection>
)}
{cohort.is_static && staticCohortMode === 'criteria' ? (
<>
@@ -699,7 +732,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
</div>
</SceneSection>
</>
- ) : cohort.is_static ? (
+ ) : cohort.is_static && !hasAddUsersMenu ? (
<>
<SceneDivider />
<SceneSection
@@ -794,7 +827,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
</>
)}
</>
- ) : (
+ ) : cohort.is_static ? null : (
<>
<SceneDivider />
{!isNewCohort && (
@@ -853,7 +886,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
{/* The typeof here is needed to pass the cohort id to the query below. Using `isNewCohort` won't work */}
{typeof cohort.id === 'number' && (
<>
- <SceneDivider />
+ {hasSectionAbovePersons && <SceneDivider />}
<SceneSection
title={
<>
diff --git a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx
index 6758c7c44549..2ec11c30e4fe 100644
--- a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx
+++ b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { IconClock, IconCopy, IconLetter, IconRefresh, IconSend, IconTrash } from '@posthog/icons'
+import { IconClock, IconCopy, IconLetter, IconPlus, IconRefresh, IconSend, IconTrash } from '@posthog/icons'
import { SceneMenuBarAddToNotebook } from 'lib/components/Scenes/SceneMenuBarAddToNotebook'
import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
@@ -34,6 +34,8 @@ import {
} from 'products/workflows/frontend/MessageAudience/messageAudience'
import { openMessageAudience } from 'products/workflows/frontend/MessageAudience/messageAudienceWarnings'
+import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'
+
const RESOURCE_TYPE = 'cohort'
export function CohortSceneMenuBar({ id }: { id?: CohortType['id'] }): JSX.Element | null {
@@ -46,8 +48,10 @@ export function CohortSceneMenuBar({ id }: { id?: CohortType['id'] }): JSX.Eleme
function CohortSceneMenuBarInner({ id }: { id?: CohortType['id'] }): JSX.Element | null {
const logic = cohortEditLogic({ id })
- const { cohort, cohortLoading } = useValues(logic)
- const { duplicateCohort, deleteCohort, restoreCohort } = useActions(logic)
+ const { cohort, cohortLoading, hasAddUsersMenu } = useValues(logic)
+ const { duplicateCohort, deleteCohort, restoreCohort, setCsvUploadModalOpen } = useActions(logic)
+ const modalLogic = addPersonToCohortModalLogic({ id })
+ const { showAddPersonToCohortModal } = useActions(modalLogic)
const { canCopyToProject } = useValues(interProjectCopyLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
@@ -157,6 +161,29 @@ function CohortSceneMenuBarInner({ id }: { id?: CohortType['id'] }): JSX.Element
</SceneMenuBarMenu>
{!isDeleted && (
<SceneMenuBarMenu label="Edit" dataAttr={`${RESOURCE_TYPE}-menubar-edit`}>
+ {hasAddUsersMenu && (
+ <>
+ <SceneMenuBarSubMenu label="Add users">
+ <SceneMenuBarItem
+ onClick={() => setCsvUploadModalOpen(true)}
+ opensFloatingUi
+ data-attr={`${RESOURCE_TYPE}-menubar-upload-csv`}
+ >
+ <IconPlus />
+ Upload a CSV
+ </SceneMenuBarItem>
+ <SceneMenuBarItem
+ onClick={showAddPersonToCohortModal}
+ opensFloatingUi
+ data-attr={`${RESOURCE_TYPE}-menubar-add-users-manually`}
+ >
+ <IconPlus />
+ Add users manually
+ </SceneMenuBarItem>
+ </SceneMenuBarSubMenu>
+ <SceneMenuBarSeparator />
+ </>
+ )}
<SceneMenuBarItem
onClick={() => duplicateCohort(false)}
disabled={isNewCohort || cohort.is_static === true || (cohort.is_calculating ?? false)}
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index 371debdb94fa..d9c243d578fc 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -1245,6 +1245,79 @@ describe('cohortEditLogic', () => {
})
})
+ describe('CSV upload', () => {
+ const savedCohort = {
+ ...mockCohort,
+ id: 1,
+ name: 'Saved name',
+ description: 'Saved description',
+ is_static: true,
+ }
+
+ it('uploads only the CSV, preserves unsaved cohort details and closes the modal', async () => {
+ await initCohortLogic({ id: 1 })
+ const updateSpy = jest.spyOn(api.cohorts, 'update').mockResolvedValue(savedCohort)
+ const csv = new File(['[email protected]'], 'people.csv', { type: 'text/csv' })
+
+ await expectLogic(logic, () => {
+ logic.actions.setCohort({
+ ...savedCohort,
+ name: 'Unsaved name',
+ description: 'Unsaved description',
+ csv,
+ })
+ logic.actions.setCsvUploadModalOpen(true)
+ logic.actions.uploadCohortCsv()
+ }).toDispatchActions(['setCohort', 'uploadCohortCsv', 'saveCohort', 'saveCohortSuccess'])
+
+ expect(updateSpy).toHaveBeenCalledTimes(1)
+ const formData = updateSpy.mock.calls[0][1] as FormData
+ expect([...formData.keys()]).toEqual(['csv'])
+ expect(formData.get('csv')).toBe(csv)
+ expect(logic.values.cohort.name).toBe('Unsaved name')
+ expect(logic.values.cohort.description).toBe('Unsaved description')
+ expect(logic.values.csvUploadModalOpen).toBe(false)
+
+ updateSpy.mockRestore()
+ })
+
+ it('keeps the modal open when the upload fails', async () => {
+ await initCohortLogic({ id: 1 })
+ const updateSpy = jest.spyOn(api.cohorts, 'update').mockRejectedValue({ detail: 'Upload failed' })
+ const csv = new File(['[email protected]'], 'people.csv', { type: 'text/csv' })
+
+ await expectLogic(logic, () => {
+ logic.actions.setCohort({ ...savedCohort, csv })
+ logic.actions.setCsvUploadModalOpen(true)
+ logic.actions.uploadCohortCsv()
+ }).toDispatchActions(['uploadCohortCsv', 'saveCohort', 'saveCohortSuccess'])
+
+ // The loader catch path keeps the csv on the cohort, which keeps the modal open for a retry.
+ expect(logic.values.csvUploadModalOpen).toBe(true)
+ expect(logic.values.cohort.csv).toBe(csv)
+
+ updateSpy.mockRestore()
+ })
+
+ it('does not start the upload when the CSV exceeds the size limit', async () => {
+ await initCohortLogic({ id: 1 })
+ const updateSpy = jest.spyOn(api.cohorts, 'update').mockResolvedValue(savedCohort)
+ const csv = new File(['[email protected]'], 'people.csv', { type: 'text/csv' })
+ Object.defineProperty(csv, 'size', { value: logic.values.csvMaxBytes + 1 })
+
+ await expectLogic(logic, () => {
+ logic.actions.setCohort({ ...savedCohort, csv })
+ logic.actions.setCsvUploadModalOpen(true)
+ logic.actions.uploadCohortCsv()
+ }).toDispatchActions(['uploadCohortCsv'])
+
+ expect(updateSpy).not.toHaveBeenCalled()
+ expect(logic.values.csvUploadModalOpen).toBe(true)
+
+ updateSpy.mockRestore()
+ })
+ })
+
describe('manual person selection for static cohort creation', () => {
it('keeps the display name so it can be shown in the selected list, and forgets it on remove', async () => {
await initCohortLogic({ id: 'new' })
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index 6428bfab1f5e..bfd51ca7d8dd 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -149,9 +149,11 @@ export interface cohortEditLogicValues {
cohortValidationErrors: DeepPartialMap<CohortType, ValidationErrorType>
creationPersonQuery: ActorsQuery
csvMaxBytes: number
+ csvUploadModalOpen: boolean
duplicatedCohort: CohortType | null
duplicatedCohortLoading: boolean
effectiveQuery: DataTableNode
+ hasAddUsersMenu: boolean
isCalculatingOrPending: boolean
isCohortSubmitting: boolean
isCohortValid: boolean
@@ -337,8 +339,12 @@ export interface cohortEditLogicActions {
value: true
}
}
- saveCohort: (cohortParams?: any) => {
+ saveCohort: (
+ cohortParams?: any,
+ csvOnlyFormData?: FormData
+ ) => {
cohortParams: any
+ csvOnlyFormData: FormData | undefined
}
saveCohortFailure: (
error: string,
@@ -351,11 +357,13 @@ export interface cohortEditLogicActions {
cohort: CohortType,
payload?: {
cohortParams: any
+ csvOnlyFormData: FormData | undefined
}
) => {
cohort: CohortType
payload?: {
cohortParams: any
+ csvOnlyFormData: FormData | undefined
}
}
setActiveTab: (tab: CohortEditTab) => {
@@ -410,6 +418,9 @@ export interface cohortEditLogicActions {
groupIndex: number
newCriteria: AnyCohortCriteriaType
}
+ setCsvUploadModalOpen: (open: boolean) => {
+ open: boolean
+ }
setFilterTestAccounts: (filterTestAccounts: boolean) => {
filterTestAccounts: boolean
}
@@ -532,6 +543,9 @@ export interface cohortEditLogicActions {
value: true
}
}
+ uploadCohortCsv: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -542,6 +556,7 @@ export interface cohortEditLogicMeta {
canRemovePersonFromCohort: (cohort: CohortType) => boolean | undefined
isPendingCalculation: (cohort: CohortType) => boolean
csvMaxBytes: (preflight: PreflightStatus | null) => number
+ hasAddUsersMenu: (cohort: CohortType, staticCohortMode: StaticCohortMode) => boolean
isCalculatingOrPending: (cohort: CohortType, isPendingCalculation: boolean) => boolean
}
}
@@ -577,7 +592,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
})),
actions({
- saveCohort: (cohortParams = {}) => ({ cohortParams }),
+ saveCohort: (cohortParams = {}, csvOnlyFormData?: FormData) => ({ cohortParams, csvOnlyFormData }),
setCohort: (cohort: CohortType) => ({ cohort }),
deleteCohort: true,
restoreCohort: true,
@@ -604,6 +619,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
setQuery: (query: Node) => ({ query }),
duplicateCohort: (asStatic: boolean) => ({ asStatic }),
updateCohortCount: true,
+ uploadCohortCsv: true,
setCreationPersonQuery: (query: ActorsQuery) => ({ query }),
addPersonToCreateStaticCohort: (personId: string, displayName: string | null) => ({ personId, displayName }),
removePersonFromCreateStaticCohort: (personId: string) => ({ personId }),
@@ -613,6 +629,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
setStaticCohortMode: (mode: StaticCohortMode) => ({ mode }),
setActiveTab: (tab: CohortEditTab) => ({ tab }),
setUsedInExpanded: (expanded: boolean) => ({ expanded }),
+ setCsvUploadModalOpen: (open: boolean) => ({ open }),
}),
reducers(({ props }) => ({
@@ -825,6 +842,14 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
setUsedInExpanded: (_, { expanded }) => expanded,
},
],
+ csvUploadModalOpen: [
+ false,
+ {
+ setCsvUploadModalOpen: (_, { open }) => open,
+ // A failed save returns the cohort with the CSV still attached, so the modal stays open for a retry.
+ saveCohortSuccess: (state, { cohort }) => (cohort.csv ? state : false),
+ },
+ ],
})),
selectors({
@@ -851,6 +876,16 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
],
isPendingCalculation: [(s) => [s.cohort], (cohort: CohortType) => checkIsPendingCalculation(cohort)],
csvMaxBytes: [(s) => [s.preflight], (preflight: PreflightStatus | null) => cohortCsvMaxBytes(preflight)],
+ // Single source for when the add-users controls collapse into a menu, read by both the
+ // title actions in CohortEdit and the Edit menu in CohortSceneMenuBar.
+ hasAddUsersMenu: [
+ (s) => [s.cohort, s.staticCohortMode],
+ (cohort: CohortType, staticCohortMode: StaticCohortMode) =>
+ typeof cohort.id === 'number' &&
+ !!cohort.is_static &&
+ staticCohortMode === 'people' &&
+ (cohort.count ?? 0) > 0,
+ ],
isCalculatingOrPending: [
(s) => [s.cohort, s.isPendingCalculation],
(cohort: CohortType, isPendingCalculation: boolean) => {
@@ -953,22 +988,44 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
return values.cohort
}
},
- saveCohort: async ({ cohortParams }, breakpoint) => {
+ saveCohort: async ({ cohortParams, csvOnlyFormData }, breakpoint) => {
const existingCohort = values.cohort
let cohort = { ...existingCohort, ...cohortParams }
- const cohortFormData = createCohortFormData(cohort, {
- preserveStaticFilters: cohort.is_static && values.staticCohortMode === 'criteria',
- })
+ const cohortFormData =
+ csvOnlyFormData ??
+ createCohortFormData(cohort, {
+ preserveStaticFilters: cohort.is_static && values.staticCohortMode === 'criteria',
+ })
try {
if (cohort.id !== 'new') {
- cohort = await api.cohorts.update(cohort.id, cohortFormData as Partial<CohortType>)
- cohortsModel.actions.updateCohort(cohort)
+ // The generated client only sends JSON, and this call uploads the CSV as
+ // multipart FormData, so there is no generated equivalent.
+ // nosemgrep: prefer-codegen-api-namespaced-cohorts
+ const savedCohort = await api.cohorts.update(
+ cohort.id,
+ cohortFormData as Partial<CohortType>
+ )
+ cohortsModel.actions.updateCohort(savedCohort)
- if (cohort.experiment_set && cohort.experiment_set.length > 0) {
+ if (
+ !csvOnlyFormData &&
+ savedCohort.experiment_set &&
+ savedCohort.experiment_set.length > 0
+ ) {
// someone edited an exposure cohort. Track what kind of updates were made
- actions.reportExperimentExposureCohortEdited(existingCohort, cohort)
+ actions.reportExperimentExposureCohortEdited(existingCohort, savedCohort)
}
+
+ // A CSV-only PATCH doesn't send the name or description, so the server
+ // response carries the saved values; keep the editor's unsaved drafts.
+ cohort = csvOnlyFormData
+ ? {
+ ...savedCohort,
+ name: existingCohort.name,
+ description: existingCohort.description,
+ }
+ : savedCohort
} else {
cohort = await api.cohorts.create(cohortFormData as Partial<CohortType>)
cohortsModel.actions.cohortCreated(cohort)
@@ -1172,6 +1229,30 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
],
})),
listeners(({ actions, values, cache }) => ({
+ uploadCohortCsv: () => {
+ if (values.cohortLoading) {
+ return
+ }
+
+ if (values.cohort.id === 'new') {
+ actions.submitCohort()
+ return
+ }
+
+ if (!values.cohort.csv) {
+ return
+ }
+
+ // The CSV-only path skips form validation, so the size limit from `forms.cohort.errors`
+ // must be enforced here; the modal shows the limit and disables Upload.
+ if (values.cohort.csv.size > values.csvMaxBytes) {
+ return
+ }
+
+ const csvOnlyFormData = new FormData()
+ csvOnlyFormData.append('csv', values.cohort.csv)
+ actions.saveCohort({}, csvOnlyFormData)
+ },
setCriteria: ({ newCriteria, groupIndex, criteriaIndex }) => {
// When the person property key changes, auto-reset the operator to match the
// property type (DateTime → "on the date", non-DateTime → "equals").