:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add bulk task controls (#123589)
Arthur Moreira de Deusaa78b57a3d64
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex fb4421c2e00a..a38c92f7f341 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10173,13 +10173,13 @@ snapshots:scenes-app-customer-analytics-dashboard--b-2-c-mode--light:hash: v1.k794b7964.ff25e11868464e00df352180254dbe0a1017cd1d8c7c4f4c7d6995068e80e2dc.m0XFOZVPCdSaCLaPQ6XTePvkZJ1I11QI2KARZi9QpWsscenes-app-customer-analytics-dashboard--customer-tasks--dark:- hash: v1.k794b7964.08e8cd42e255347bc8144b25b3592a4103483ebd5587cb14e9013786f000023b.duE7w5P1SNIj600LVcMaVEe9UWEqi-oGOprjEEeJaIE+ hash: v1.k794b7964.9380089dadd38c212ac554255d1a11cc2deaa7197d49f6c532dc605039bb7b64.yhr5sRJvxJh0pmIjb3cIUsK_W9EVVJYMB5IX0qwDMnEscenes-app-customer-analytics-dashboard--customer-tasks--light:- hash: v1.k794b7964.d936025c0bd0ec7e3886085746a8160e92c0f5e36b64ca46eea3dbf44839ea4a.9Lx5kC0EJ_EHO-lvAOH6xGgv_BkbefqSM-HpKmuzusM+ hash: v1.k794b7964.f9dca8dbf88d7c960301dd95db91966e02be4d9df5f7378dda0b331f77e52fdb.isOceWjpgKBgXFpeFbcazFF98eptte9x2QQmDKmtBP8scenes-app-customer-analytics-dashboard--customer-tasks-assignee-roles--dark:- hash: v1.k794b7964.ff1e2d80d015ed8d85aa11b81e21fbe6651f3f10f08184c5dacdbf297db0ffd2.EfU11y8W9FRIQhKcqwM67uop3eSNdNwPsp5Uv6Z09yU+ hash: v1.k794b7964.b9d7329bb49b4dde0e252e7079613b0e13f7a72bf586dbb53d4de94da9a0fbe3.YQB66a27LE6uxn9to0dLOAhOgXYSIl_nYM_6sPj78Cwscenes-app-customer-analytics-dashboard--customer-tasks-assignee-roles--light:- hash: v1.k794b7964.1eed6cafb7b3199131a277eba2e0afa88d1ef9359d122bc7c509d97300399c22.IHVs3nKi8DZlyCOFHz1f1kw9BXUnYdpBWK3Q4pgY4LA+ hash: v1.k794b7964.5c4d2683941e468b8d48c40f269b67faabc6b41d064c0b58afbd576cf2f10a01.pUDiVcY-h4rlRsYHuymT4qKf3EC77gdMRk35kQLxCOwscenes-app-customer-analytics-dashboard--feature-request-details--dark:hash: v1.k794b7964.d87f1abf2d12f5814dd652ba1c760a15d00f6fa2f6927f9aaa662dacbd91a83c.8qn3xLm6N1ZugTMoofH8kEhupFhydr4UcG0Wlko4SLYscenes-app-customer-analytics-dashboard--feature-request-details--light:diff --git a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsxindex 2e161af86d43..e58d984eb90d 100644--- a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx@@ -19,6 +19,16 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSeconst isOpen = context.selectedCount > 0const [singular, plural] = nounconst word = context.selectedCount === 1 ? singular : plural+ const summary = (+ <span className="text-secondary text-sm">+ {context.selectedCount} {word} selected+ </span>+ )+ const clearButton = (+ <LemonButton type="secondary" size="small" onClick={context.clearSelection}>+ Clear+ </LemonButton>+ )const bar = (<div@@ -27,13 +37,11 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSeconfig.barClassName)}>- <span className="text-secondary text-sm">- {context.selectedCount} {word} selected- </span>- <LemonButton type="secondary" size="small" onClick={context.clearSelection}>- Clear- </LemonButton>+ {config.actionsPlacement !== 'start' && summary}+ {config.actionsPlacement !== 'start' && clearButton}{config.renderActions(context)}+ {config.actionsPlacement === 'start' && clearButton}+ {config.actionsPlacement === 'start' && summary}</div>)diff --git a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.tsindex cd3aa3db91ff..aa15a8f7676b 100644--- a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts+++ b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts@@ -20,6 +20,7 @@ export interface BulkSelectionContext<T, K extends BulkSelectionKey = BulkSelectexport interface BulkSelectionConfig<T extends Record<string, any>, K extends BulkSelectionKey = BulkSelectionKey> {/** Render bulk action UI shown above the table whenever `selectedCount > 0`. */renderActions: (ctx: BulkSelectionContext<T, K>) => ReactNode+ actionsPlacement?: 'start' | 'end'/** Per-row gate. Return `false` or `{ disabledReason }` to disable that row's checkbox. */isRowSelectable?: (record: T, rowIndex: number) => BulkSelectionRowGate/** Override how a record is mapped to a selection key. Defaults to LemonTable's `rowKey`.diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scssindex 8fe315e822e6..28c74b2bd15f 100644--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss@@ -31,25 +31,26 @@}// LemonTable renders one <col> per column, so these must follow the column order in CustomerTasksTable.tsx.- // Account: Assignee (3) and Updated (5). Inbox adds Account at 3: Assignee (4) and Updated (6).- .CustomerTasksTable--account .LemonTable colgroup col:nth-child(3),- .CustomerTasksTable--account .LemonTable colgroup col:nth-child(5),- .CustomerTasksTable--inbox .LemonTable colgroup col:nth-child(4),- .CustomerTasksTable--inbox .LemonTable colgroup col:nth-child(6) {+ // Account: The selection column shifts Assignee to 4 and Updated to 6. Inbox adds Account at 4.+ .CustomerTasksTable--account .LemonTable colgroup col:nth-child(4),+ .CustomerTasksTable--account .LemonTable colgroup col:nth-child(6),+ .CustomerTasksTable--inbox .LemonTable colgroup col:nth-child(5),+ .CustomerTasksTable--inbox .LemonTable colgroup col:nth-child(7) {width: 0 !important;}}@container (max-width: 560px) {- .CustomerTasksTable--account {- // Also collapses the Status (2) and Due (4) <col> elements.+ .CustomerTasksTable {.CustomerTasksTable__status,.CustomerTasksTable__due {@include collapsed-cell;}- .LemonTable colgroup col:nth-child(2),- .LemonTable colgroup col:nth-child(4) {+ &--account .LemonTable colgroup col:nth-child(3),+ &--account .LemonTable colgroup col:nth-child(5),+ &--inbox .LemonTable colgroup col:nth-child(3),+ &--inbox .LemonTable colgroup col:nth-child(6) {width: 0 !important;}@@ -62,7 +63,7 @@}}- .LemonTable colgroup col:first-child {+ &--account .LemonTable colgroup col:nth-child(2) {width: auto !important;}}diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsxindex d4462be56214..6f53cb90a701 100644--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx@@ -74,6 +74,53 @@ describe('CustomerTasksTable', () => {logic.unmount()})+ test.each([false, true])('offers bulk actions for archived=%s tasks in display order', async (archived) => {+ mockList.mockResolvedValue({+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ ...accountlessTask,+ can_edit: !archived,+ can_restore: archived,+ archived_at: archived ? '2026-09-03T12:00:00Z' : null,+ },+ ],+ })+ logic.actions.loadTaskPage()+ await expectLogic(logic).toFinishAllListeners()+ const { container } = render(+ <Provider>+ <CustomerTasksTable logic={logic} context="inbox" />+ </Provider>+ )+ fireEvent.click(screen.getByLabelText('Select task Follow up'))++ const bar = container.querySelector('.LemonTable__bulk-selection-bar') as HTMLElement+ const controls = Array.from(bar.querySelectorAll('[data-attr^="customer-tasks-bulk-"]'))+ expect(controls.map((control) => control.getAttribute('data-attr'))).toEqual([+ 'customer-tasks-bulk-status',+ 'customer-tasks-bulk-assignee',+ 'customer-tasks-bulk-due',+ 'customer-tasks-bulk-account',+ 'customer-tasks-bulk-archive',+ ])+ const statusButton = controls[0]+ if (archived) {+ expect(statusButton).toHaveAttribute('aria-disabled', 'true')+ } else {+ expect(statusButton).not.toHaveAttribute('aria-disabled', 'true')+ }+ expect(controls[4]).not.toHaveAttribute('aria-disabled', 'true')+ const clear = within(bar).getByText('Clear')+ const summary = within(bar).getByText('1 task selected')+ expect(controls[4].compareDocumentPosition(clear) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(clear.compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ fireEvent.click(clear)+ expect(screen.getByLabelText('Select task Follow up')).not.toBeChecked()+ })+test('renders task details and opens the read-only modal', async () => {await expectLogic(logic).toFinishAllListeners()@@ -84,7 +131,7 @@ describe('CustomerTasksTable', () => {)const table = screen.getByRole('table')- expect(tableHeaders(table)[0]).toHaveTextContent('Task')+ expect(tableHeaders(table)[1]).toHaveTextContent('Task')const taskName = within(table).getByText('Follow up')const taskRow = taskName.closest('tr')expect(taskRow).not.toBeNull()diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsxindex 233c08255d8c..8bba1aaa8a68 100644--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx@@ -2,9 +2,13 @@ import './CustomerTasksTable.scss'import { useActions, useValues } from 'kea'-import { LemonBanner, LemonButton, LemonSkeleton } from '@posthog/lemon-ui'+import { IconX } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDropdown, LemonInputSelect, LemonMenu, LemonSkeleton } from '@posthog/lemon-ui'+import { MemberSelect } from 'lib/components/MemberSelect'import { TZLabel } from 'lib/components/TZLabel'+import { dayjsLocalToTimezone } from 'lib/dayjs'+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'import { LemonTable, type LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'@@ -14,7 +18,11 @@ import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generimport { CustomerTaskActionsMenu } from './CustomerTaskActionsMenu'import { CustomerTaskAssigneeSelect } from './CustomerTaskAssigneeSelect'import { CustomerTaskDueAtInput } from './CustomerTaskDueAtInput'-import type { CustomerTasksContext } from './customerTaskFilters'+import {+ CUSTOMER_TASK_STATUS_TRANSITIONS,+ customerTaskEditDisabledReason,+ type CustomerTasksContext,+} from './customerTaskFilters'import { CustomerTaskModal } from './CustomerTaskModal'import { CustomerTasksFilters } from './CustomerTasksFilters'import type { customerTasksLogicType } from './customerTasksLogic'@@ -34,9 +42,34 @@ export function CustomerTasksTable({canViewAll = false,embedded = true,}: CustomerTasksTableProps): JSX.Element {- const { taskPage, taskPageError, taskPageLoading, tasks, pagination, hasActiveFilters, taskSorting, timezone } =- useValues(logic)- const { loadTaskPage, openCreateModal, openEditModal, setTaskSorting } = useActions(logic)+ const {+ taskPage,+ taskPageError,+ taskPageLoading,+ tasks,+ pagination,+ hasActiveFilters,+ taskSorting,+ timezone,+ filters,+ page,+ ordering,+ mutationKeys,+ accountOptions,+ accountOptionsResponseLoading,+ bulkAccountOpen,+ } = useValues(logic)+ const {+ loadTaskPage,+ openCreateModal,+ openEditModal,+ setTaskSorting,+ bulkUpdateTasks,+ loadAccountOptions,+ setBulkAccountOpen,+ } = useActions(logic)+ const bulkSaving = Boolean(mutationKeys.bulk)+ const bulkDisabledReason = bulkSaving ? 'Saving' : taskPageLoading ? 'Loading tasks' : undefinedif (taskPage === null && taskPageLoading) {return <LemonSkeleton className="h-64 w-full" />}@@ -69,12 +102,10 @@ export function CustomerTasksTable({<div className="CustomerTasksTable__narrow-assignee"><CustomerTaskAssigneeSelect task={task} logic={logic} /></div>- {context === 'account' && (- <div className="CustomerTasksTable__narrow-controls flex-wrap items-center gap-1">- <CustomerTaskStatusSelect task={task} logic={logic} />- <CustomerTaskDueAtInput task={task} logic={logic} timezone={timezone} />- </div>- )}+ <div className="CustomerTasksTable__narrow-controls flex-wrap items-center gap-1">+ <CustomerTaskStatusSelect task={task} logic={logic} />+ <CustomerTaskDueAtInput task={task} logic={logic} timezone={timezone} />+ </div></div>),},@@ -150,7 +181,7 @@ export function CustomerTasksTable({)return (<div className={`CustomerTasksTable CustomerTasksTable--${context}`} data-attr="customer-tasks-table">- <div className="mb-4 flex items-start justify-between gap-2">+ <div className="mb-2 flex flex-wrap items-start justify-between gap-2"><CustomerTasksFilters logic={logic} context={context} canViewAll={canViewAll} />{canCreate && (<LemonButton type="primary" size="small" onClick={openCreateModal}>@@ -163,7 +194,7 @@ export function CustomerTasksTable({Couldn't load tasks. Try again.</LemonBanner>)}- <LemonTable<CustomerTaskApi>+ <LemonTable<CustomerTaskApi, string>embedded={embedded}dataSource={tasks}columns={columns}@@ -177,6 +208,215 @@ export function CustomerTasksTable({emptyState={empty}nouns={['task', 'tasks']}tableLayout="fixed"+ bulkSelection={{+ actionsPlacement: 'start',+ barClassName: 'mb-2 flex-wrap justify-start! pl-0!',+ noun: ['task', 'tasks'],+ rowAriaLabel: (task) => `Select task ${task.name}`,+ headerAriaLabel: 'Select all tasks on this page',+ clearSelectionKey: JSON.stringify({ filters, page, ordering }),+ isRowSelectable: (task) => {+ const disabledReason =+ (task.archived_at+ ? task.can_restore+ ? undefined+ : 'You cannot restore this task'+ : customerTaskEditDisabledReason(task)) ??+ (mutationKeys[task.id] ? 'Saving' : bulkDisabledReason)+ return disabledReason ? { disabledReason } : true+ },+ renderActions: ({ selectedKeys, selectedRecords, setSelectedKeys }) => {+ const editDisabledReason =+ bulkDisabledReason ??+ (selectedRecords.some((task) => task.archived_at)+ ? 'Unarchive the selected tasks to edit them'+ : undefined)+ return (+ <>+ <LemonMenu+ items={[+ {+ items: (['open', 'in_progress', 'completed', 'canceled'] as const).map(+ (status) => ({+ label:+ status === 'in_progress'+ ? 'In progress'+ : status.charAt(0).toUpperCase() + status.slice(1),+ disabledReason: selectedRecords.every(+ (task) =>+ task.status === status ||+ CUSTOMER_TASK_STATUS_TRANSITIONS[task.status].includes(+ status+ )+ )+ ? editDisabledReason+ : 'Some selected tasks cannot change to this status',+ onClick: () =>+ bulkUpdateTasks([...selectedKeys], { status }, setSelectedKeys),+ })+ ),+ },+ ]}+ >+ <LemonButton+ type="secondary"+ size="small"+ loading={bulkSaving}+ disabledReason={editDisabledReason}+ data-attr="customer-tasks-bulk-status"+ >+ Change status+ </LemonButton>+ </LemonMenu>+ <MemberSelect+ value={null}+ defaultLabel="Unassigned"+ allowNone+ onChange={(user) =>+ bulkUpdateTasks(+ [...selectedKeys],+ { assigned_to_id: user?.id ?? null },+ setSelectedKeys+ )+ }+ >+ {() => (+ <LemonButton+ type="secondary"+ size="small"+ loading={bulkSaving}+ disabledReason={editDisabledReason}+ data-attr="customer-tasks-bulk-assignee"+ >+ Assign to+ </LemonButton>+ )}+ </MemberSelect>+ <LemonCalendarSelectInput+ value={null}+ onChange={(value) =>+ bulkUpdateTasks(+ [...selectedKeys],+ {+ due_at: value+ ? dayjsLocalToTimezone(+ value.format('YYYY-MM-DDTHH:mm'),+ timezone+ ).toISOString()+ : null,+ },+ setSelectedKeys+ )+ }+ granularity="minute"+ use24HourFormat+ placeholder="Due at"+ buttonProps={{+ type: 'secondary',+ size: 'small',+ fullWidth: false,+ loading: bulkSaving,+ disabledReason: editDisabledReason,+ 'data-attr': 'customer-tasks-bulk-due',+ sideAction: {+ icon: <IconX />,+ onClick: () =>+ bulkUpdateTasks([...selectedKeys], { due_at: null }, setSelectedKeys),+ disabledReason: editDisabledReason,+ 'aria-label': 'Clear due dates',+ },+ }}+ />+ <LemonDropdown+ visible={bulkAccountOpen}+ closeOnClickInside={false}+ onVisibilityChange={(open) => {+ setBulkAccountOpen(open)+ if (open) {+ loadAccountOptions({ query: '' })+ }+ }}+ overlay={+ <div className="w-64 p-2">+ <LemonInputSelect+ mode="single"+ value={[]}+ options={[+ { key: 'none', label: 'No account' },+ ...accountOptions.map((account) => ({+ key: account.id,+ label: account.name,+ })),+ ]}+ loading={accountOptionsResponseLoading}+ onInputChange={(query) => loadAccountOptions({ query })}+ onChange={(values) => {+ if (values[0]) {+ bulkUpdateTasks(+ [...selectedKeys],+ { account_id: values[0] === 'none' ? null : values[0] },+ setSelectedKeys+ )+ }+ }}+ placeholder="Search accounts"+ disabledReason={editDisabledReason}+ />+ </div>+ }+ >+ <LemonButton+ type="secondary"+ size="small"+ loading={bulkSaving}+ disabledReason={editDisabledReason}+ data-attr="customer-tasks-bulk-account"+ >+ Account+ </LemonButton>+ </LemonDropdown>+ <LemonMenu+ items={[+ {+ label: 'Archive tasks',+ disabledReason:+ bulkDisabledReason ??+ (selectedRecords.every((task) => task.archived_at)+ ? 'The selected tasks are already archived'+ : undefined),+ onClick: () =>+ bulkUpdateTasks([...selectedKeys], { archived: true }, setSelectedKeys),+ },+ {+ label: 'Unarchive tasks',+ disabledReason:+ bulkDisabledReason ??+ (selectedRecords.every((task) => !task.archived_at)+ ? 'The selected tasks are already active'+ : undefined),+ onClick: () =>+ bulkUpdateTasks(+ [...selectedKeys],+ { archived: false },+ setSelectedKeys+ ),+ },+ ]}+ >+ <LemonButton+ type="secondary"+ size="small"+ loading={bulkSaving}+ disabledReason={bulkDisabledReason}+ data-attr="customer-tasks-bulk-archive"+ >+ Archive/unarchive+ </LemonButton>+ </LemonMenu>+ </>+ )+ },+ }}/><CustomerTaskModal logic={logic} context={context} /></div>diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.tsindex 97321e3be1e1..949968e835e0 100644--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts@@ -16,12 +16,18 @@ import { initKeaTests } from '~/test/init'import {accountsList,accountsRetrieve,+ customerTasksArchiveCreate,+ customerTasksBulkUpdateCreate,customerTasksCreate,customerTasksList,customerTasksRetrieve,customerTasksPartialUpdate,+ customerTasksRestoreCreate,} from 'products/customer_analytics/frontend/generated/api'-import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import type {+ CustomerTaskApi,+ CustomerTaskBulkPatchApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'import { customerTasksPersistencePrefix, parseCustomerTaskSearchParams } from './customerTaskFilters'import { customerTasksLogic } from './customerTasksLogic'@@ -30,6 +36,7 @@ jest.mock('products/customer_analytics/frontend/generated/api', () => ({accountsList: jest.fn(),accountsRetrieve: jest.fn(),customerTasksArchiveCreate: jest.fn(),+ customerTasksBulkUpdateCreate: jest.fn(),customerTasksCreate: jest.fn(),customerTasksList: jest.fn(),customerTasksRetrieve: jest.fn(),@@ -37,10 +44,13 @@ jest.mock('products/customer_analytics/frontend/generated/api', () => ({customerTasksRestoreCreate: jest.fn(),}))+const mockBulkUpdate = customerTasksBulkUpdateCreate as jest.MockedFunction<typeof customerTasksBulkUpdateCreate>const mockCreate = customerTasksCreate as jest.MockedFunction<typeof customerTasksCreate>const mockList = customerTasksList as jest.MockedFunction<typeof customerTasksList>const mockAccounts = accountsList as jest.MockedFunction<typeof accountsList>const mockUpdate = customerTasksPartialUpdate as jest.MockedFunction<typeof customerTasksPartialUpdate>+const mockArchive = customerTasksArchiveCreate as jest.MockedFunction<typeof customerTasksArchiveCreate>+const mockRestore = customerTasksRestoreCreate as jest.MockedFunction<typeof customerTasksRestoreCreate>const mockAccount = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>const URL_ACCOUNT_ID = '0199ed4a-5c03-0000-3220-df21df612e95'@@ -74,6 +84,7 @@ describe('customerTasksLogic', () => {beforeEach(() => {initKeaTests()localStorage.clear()+ mockBulkUpdate.mockResolvedValue({ updated_count: 2 })mockCreate.mockResolvedValue(task())mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })mockAccounts.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })@@ -87,6 +98,117 @@ describe('customerTasksLogic', () => {localStorage.clear()})+ test.each<CustomerTaskBulkPatchApi>([+ { status: 'completed' },+ { assigned_to_id: 7 },+ { assigned_to_id: null },+ { due_at: '2026-10-30T12:00:00Z' },+ { due_at: null },+ { account_id: URL_ACCOUNT_ID },+ { account_id: null },+ { archived: true },+ { archived: false },+ ])('updates selected tasks with %j and reloads once', async (patch) => {+ const tasks = [+ {+ ...task(),+ assigned_to: { id: 9, email: '[email protected]', first_name: 'Sam', last_name: '' },+ account: { id: SECOND_URL_ACCOUNT_ID, name: 'Example account' },+ due_at: '2026-10-29T12:00:00Z',+ },+ {+ ...task(),+ id: 'task-2',+ assigned_to: { id: 9, email: '[email protected]', first_name: 'Sam', last_name: '' },+ account: { id: SECOND_URL_ACCOUNT_ID, name: 'Example account' },+ due_at: '2026-10-29T12:00:00Z',+ },+ { ...task(), id: 'task-3' },+ ]+ mockList.mockResolvedValue({ count: tasks.length, next: null, previous: null, results: tasks })+ logic = customerTasksLogic({ context: 'inbox' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ mockList.mockClear()+ const onComplete = jest.fn()++ logic.actions.bulkUpdateTasks(['task-1', 'task-2'], patch, onComplete)+ await expectLogic(logic).toFinishAllListeners()++ expect(mockBulkUpdate).toHaveBeenCalledTimes(1)+ expect(mockBulkUpdate).toHaveBeenCalledWith(expect.any(String), {+ task_ids: ['task-1', 'task-2'],+ updates: patch,+ })+ expect(mockUpdate).not.toHaveBeenCalled()+ expect(mockArchive).not.toHaveBeenCalled()+ expect(mockRestore).not.toHaveBeenCalled()+ expect(mockList).toHaveBeenCalledTimes(1)+ expect(onComplete).toHaveBeenCalledWith([])+ expect(logic.values.mutationKeys).toEqual({})+ })++ test.each([false, true])('retains the failed batch only in the same filter scope: %s', async (changeFilters) => {+ const tasks = [task(), { ...task(), id: 'task-2' }]+ mockList.mockResolvedValue({ count: 2, next: null, previous: null, results: tasks })+ let rejectUpdate!: (error: ApiError) => void+ mockBulkUpdate.mockImplementationOnce(+ () =>+ new Promise((_, reject) => {+ rejectUpdate = reject+ })+ )+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '' as never)+ logic = customerTasksLogic({ context: 'inbox' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const onComplete = jest.fn()++ logic.actions.bulkUpdateTasks(['task-1', 'task-2'], { status: 'completed' }, onComplete)+ expect(logic.values.mutationKeys).toEqual({ bulk: true, 'task-1': true, 'task-2': true })+ logic.actions.bulkUpdateTasks(['task-1', 'task-2'], { status: 'completed' }, onComplete)+ logic.actions.updateTask('task-2', { assigned_to_id: 7 })+ expect(mockBulkUpdate).toHaveBeenCalledTimes(1)+ expect(mockUpdate).not.toHaveBeenCalled()+ if (changeFilters) {+ logic.actions.setFilters({ status: 'all' })+ }+ rejectUpdate(new ApiError(undefined, 409, undefined, { detail: 'Restore this task before editing it.' }))+ await expectLogic(logic).toFinishAllListeners()++ expect(onComplete).toHaveBeenCalledWith(changeFilters ? [] : ['task-1', 'task-2'])+ expect(toast).toHaveBeenCalledWith('Restore this task before editing it.')+ expect(logic.values.mutationKeys).toEqual({})+ toast.mockRestore()+ })++ test('shows the assignee validation error and retains every selected task', async () => {+ const tasks = [task(), { ...task(), id: 'task-2' }]+ mockList.mockResolvedValue({ count: 2, next: null, previous: null, results: tasks })+ mockBulkUpdate.mockRejectedValueOnce(+ new ApiError(undefined, 400, undefined, { assigned_to_id: 'Select a member of this project.' })+ )+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '' as never)+ logic = customerTasksLogic({ context: 'inbox' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ mockList.mockClear()+ const onComplete = jest.fn()++ logic.actions.bulkUpdateTasks(['task-1', 'task-2', 'not-on-page'], { assigned_to_id: 7 }, onComplete)+ await expectLogic(logic).toFinishAllListeners()++ expect(mockBulkUpdate).toHaveBeenCalledWith(expect.any(String), {+ task_ids: ['task-1', 'task-2'],+ updates: { assigned_to_id: 7 },+ })+ expect(onComplete).toHaveBeenCalledWith(['task-1', 'task-2'])+ expect(toast).toHaveBeenCalledWith('Select a member of this project.')+ expect(mockList).not.toHaveBeenCalled()+ expect(logic.values.mutationKeys).toEqual({})+ toast.mockRestore()+ })+test.each([['account', 'account-1', 20, { account_id: 'account-1' }],['inbox', undefined, 50, { assigned_to: 'me' }],diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.tsindex 487848ccb8c5..5df07136d664 100644--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts@@ -31,6 +31,7 @@ import {accountsList,accountsRetrieve,customerTasksArchiveCreate,+ customerTasksBulkUpdateCreate,customerTasksCreate,customerTasksList,customerTasksRetrieve,@@ -41,6 +42,7 @@ import type {AccountApi,CustomerTaskApi,CustomerTaskCreateApi,+ CustomerTaskBulkPatchApi,CustomerTaskPageApi,CustomerTaskUserApi,PaginatedAccountListApi,@@ -86,6 +88,7 @@ export interface customerTasksLogicValues {accountOptionsResponse: PaginatedAccountListApi | nullaccountOptionsResponseLoading: booleanaccountFilterOpen: boolean+ bulkAccountOpen: booleancurrentTeamId: number | nullfilters: CustomerTaskFiltershasActiveFilters: boolean@@ -110,6 +113,11 @@ export interface customerTasksLogicValues {user: UserType | null}export interface customerTasksLogicActions {+ bulkUpdateTasks: (+ taskIds: string[],+ patch: CustomerTaskBulkPatchApi,+ onComplete: (failedIds: string[]) => void+ ) => { taskIds: string[]; patch: CustomerTaskBulkPatchApi; onComplete: (failedIds: string[]) => void }openTaskFromUrl: (taskId: string) => { taskId: string }closeModal: () => voidcreateTask: (task: CustomerTaskCreateApi) => { task: CustomerTaskCreateApi }@@ -125,6 +133,7 @@ export interface customerTasksLogicActions {archiveTask: (taskId: string) => { taskId: string }setAccountFilter: (account: CustomerTaskAccountFilter | null) => { account: CustomerTaskAccountFilter | null }setAccountFilterOpen: (open: boolean) => { open: boolean }+ setBulkAccountOpen: (open: boolean) => { open: boolean }setAssignee: (assignee: CustomerTaskAssigneeFilter) => { assignee: CustomerTaskAssigneeFilter }setFilters: (filters: Partial<CustomerTaskFilters>) => { filters: Partial<CustomerTaskFilters> }setFiltersFromUrl: (state: CustomerTaskUrlState) => { state: CustomerTaskUrlState }@@ -209,6 +218,7 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<custsetSearch: (search: string) => ({ search }),setAccountFilter: (account: CustomerTaskAccountFilter | null) => ({ account }),setAccountFilterOpen: (open: boolean) => ({ open }),+ setBulkAccountOpen: (open: boolean) => ({ open }),setPage: (page: number) => ({ page }),resetFilters: () => ({}),openCreateModal: () => ({}),@@ -222,6 +232,11 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<custsubmitModal: () => ({}),createTask: (task: CustomerTaskCreateApi) => ({ task }),updateTask: (taskId: string, patch: PatchedCustomerTaskUpdateApi) => ({ taskId, patch }),+ bulkUpdateTasks: (+ taskIds: string[],+ patch: CustomerTaskBulkPatchApi,+ onComplete: (failedIds: string[]) => void+ ) => ({ taskIds, patch, onComplete }),archiveTask: (taskId: string) => ({ taskId }),restoreTask: (taskId: string) => ({ taskId }),mutationStarted: (key: string) => ({ key }),@@ -322,6 +337,7 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust},],accountFilterOpen: [false, { setAccountFilterOpen: (_, { open }) => open }],+ bulkAccountOpen: [false, { setBulkAccountOpen: (_, { open }) => open, bulkUpdateTasks: () => false }],mutationKeys: [{} as Record<string, boolean>,{@@ -431,6 +447,33 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust],})),listeners(({ actions, props, values }) => ({+ bulkUpdateTasks: async ({ taskIds, patch, onComplete }) => {+ if (values.currentTeamId === null || values.mutationKeys.bulk || values.taskPageLoading) {+ return+ }+ const projectId = String(values.currentTeamId)+ const selectionScope = JSON.stringify(taskUrlState(values))+ const tasks = values.tasks.filter((task) => taskIds.includes(task.id))+ if (tasks.length === 0 || tasks.some((task) => values.mutationKeys[task.id])) {+ return+ }+ actions.mutationStarted('bulk')+ tasks.forEach((task) => actions.mutationStarted(task.id))+ try {+ await customerTasksBulkUpdateCreate(projectId, {+ task_ids: tasks.map((task) => task.id),+ updates: patch,+ })+ onComplete([])+ actions.loadTaskPage()+ } catch (error) {+ onComplete(JSON.stringify(taskUrlState(values)) === selectionScope ? tasks.map((task) => task.id) : [])+ lemonToast.error(taskWriteFailureMessage(error, 'Could not update the tasks. Try again.'))+ } finally {+ tasks.forEach((task) => actions.mutationFinished(task.id))+ actions.mutationFinished('bulk')+ }+ },openTaskFromUrl: async ({ taskId }, breakpoint) => {if (values.currentTeamId === null) {return