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(customer-analytics): account role assignment (#60075)

Arthur Moreira de Deusc81b84622412
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d7f8a68683db..838f7913dbc6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3979,9 +3979,9 @@ snapshots:
scenes-app-batchexports--runs-with-data--light:
hash: v1.k794b7964.f4a8d5cc4f5447f093d5ddbbcd8572e13f7297a7db8a89504f9290226e60a2bc._CkUe6i49hMMGaDUNDHeNZDgaVp5DJQCay44V8WqfR4
scenes-app-customer-analytics-accounts--default--dark:
- hash: v1.k794b7964.b64ab80fac4a73cee1ff6a383ad9f40961b061f38c606014b38c683ce6f399fb.BGLWJjIrm8jKJ0cgbg0N8-tr7KL675JJqN_9SkLCgmA
+ hash: v1.k794b7964.3238a24e463f3827b40563d9c5a9189bd8ee2ec78858f0dc20d4c41560b1a858.bFuIqVd9GZf6oGWeDP9T3cCXClf6wK4f6pRQP3ccd0A
scenes-app-customer-analytics-accounts--default--light:
- hash: v1.k794b7964.21d11055ac489c5d965e0d3256ce0986ca896c1fc92ecb21c47a22bca77c929b.bVU8oCCiqYQT14HPANB_-ghcaWBP16m1TJF4N2H5drs
+ hash: v1.k794b7964.c13dc63d3ccaf85d8bed2840d7abba59ddbf49cfe879cba28e75d8dc76f6d9f2.TuTzFLakjBSqBtiKnKyubF3rVo-r3nwj0u8vM28YiMw
scenes-app-customer-analytics-accounts--empty--dark:
hash: v1.k794b7964.1db26d99c1ac9c7ea882bae7d36a3d4fcc234e21d8cd28cc1ededb941a687cdf.OcbjFe5xD5bLFViFj0meBcCEoxa2bhK9VzJRPF0dQHo
scenes-app-customer-analytics-accounts--empty--light:
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index 58d36fe03564..90c559c78418 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -1,16 +1,19 @@
import { useActions, useValues } from 'kea'
-import { LemonTable, LemonTableColumns, ProfilePicture } from '@posthog/lemon-ui'
+import { LemonButton, LemonTable, LemonTableColumns, ProfilePicture } from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+import { MemberSelect } from 'lib/components/MemberSelect'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
-import { ACCOUNTS_PAGE_SIZE, accountsLogic } from './accountsLogic'
+import { ACCOUNTS_PAGE_SIZE, AccountRoleKey, accountsLogic } from './accountsLogic'
type AccountAssignment = { id: number; email: string } | null
+const ROLE_DEFAULT_LABEL = 'Unassigned'
+
export function AccountsTable(): JSX.Element {
const { results, totalCount, accountsLoading, currentPage } = useValues(accountsLogic)
const { setCurrentPage } = useActions(accountsLogic)
@@ -58,17 +61,17 @@ export function AccountsTable(): JSX.Element {
{
title: 'CSM',
key: 'csm',
- render: (_, account) => <AssigneeCell assignment={account.properties?.csm ?? null} />,
+ render: (_, account) => <RoleAssignmentCell account={account} role="csm" />,
},
{
title: 'Account executive',
key: 'account_executive',
- render: (_, account) => <AssigneeCell assignment={account.properties?.account_executive ?? null} />,
+ render: (_, account) => <RoleAssignmentCell account={account} role="account_executive" />,
},
{
title: 'Account owner',
key: 'account_owner',
- render: (_, account) => <AssigneeCell assignment={account.properties?.account_owner ?? null} />,
+ render: (_, account) => <RoleAssignmentCell account={account} role="account_owner" />,
},
]
@@ -90,14 +93,42 @@ export function AccountsTable(): JSX.Element {
)
}
-function AssigneeCell({ assignment }: { assignment: AccountAssignment }): JSX.Element {
- if (!assignment) {
- return <span className="text-muted">Unassigned</span>
- }
+function RoleAssignmentCell({ account, role }: { account: AccountApi; role: AccountRoleKey }): JSX.Element {
+ const { isRoleSaving } = useValues(accountsLogic)
+ const { updateAccountRole } = useActions(accountsLogic)
+
+ const assignment: AccountAssignment = account.properties?.[role] ?? null
+ const saving = isRoleSaving(account.id, role)
+
return (
- <div className="flex items-center gap-2">
- <ProfilePicture user={{ email: assignment.email }} size="sm" />
- <span className="text-sm">{assignment.email}</span>
+ <div data-attr={`accounts-${role}-cell`}>
+ <MemberSelect
+ value={assignment?.id ?? null}
+ defaultLabel={ROLE_DEFAULT_LABEL}
+ onChange={(user) => updateAccountRole(account.id, role, user)}
+ >
+ {(selectedUser) => (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ loading={saving}
+ disabledReason={saving ? 'Saving…' : undefined}
+ icon={
+ selectedUser ? (
+ <ProfilePicture user={selectedUser} size="sm" />
+ ) : assignment ? (
+ <ProfilePicture user={{ email: assignment.email }} size="sm" />
+ ) : undefined
+ }
+ >
+ {assignment ? (
+ <span className="text-sm">{assignment.email}</span>
+ ) : (
+ <span className="text-muted">Unassigned</span>
+ )}
+ </LemonButton>
+ )}
+ </MemberSelect>
</div>
)
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 0248fbea2d45..7ee3b9289e4c 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -3,16 +3,46 @@ import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
+import type { UserBasicType } from '~/types'
-import { accountsList } from 'products/customer_analytics/frontend/generated/api'
+import { accountsList, accountsPartialUpdate } from 'products/customer_analytics/frontend/generated/api'
+import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
-import { ACCOUNTS_PAGE_SIZE, accountsLogic } from './accountsLogic'
+import { ACCOUNTS_PAGE_SIZE, accountsLogic, savingRoleKey } from './accountsLogic'
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
accountsList: jest.fn(),
+ accountsPartialUpdate: jest.fn(),
}))
const mockAccountsList = accountsList as jest.MockedFunction<typeof accountsList>
+const mockAccountsPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>
+
+const buildAccount = (overrides: Partial<AccountApi> = {}): AccountApi => ({
+ id: 'acc-1',
+ name: 'Acme',
+ external_id: 'ext-1',
+ properties: {
+ csm: { id: 1, email: '[email protected]' },
+ stripe_customer_id: 'cus_123',
+ },
+ tags: [],
+ notebooks: [],
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+})
+
+const buildUser = (overrides: Partial<UserBasicType> = {}): UserBasicType =>
+ ({
+ id: 42,
+ uuid: 'user-uuid-42',
+ first_name: 'Alex',
+ last_name: 'Mercer',
+ email: '[email protected]',
+ ...overrides,
+ }) as UserBasicType
describe('accountsLogic', () => {
let logic: ReturnType<typeof accountsLogic.build>
@@ -169,4 +199,107 @@ describe('accountsLogic', () => {
expect.objectContaining({ tags: '["priority"]' })
)
})
+
+ describe('updateAccountRole', () => {
+ const existingAccount = buildAccount()
+
+ beforeEach(async () => {
+ mockAccountsList.mockResolvedValue({
+ count: 1,
+ next: null,
+ previous: null,
+ results: [existingAccount],
+ })
+ logic.actions.refresh()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('PATCHes the merged properties payload with the new assignment', async () => {
+ const user = buildUser()
+ const updated = buildAccount({
+ properties: {
+ csm: { id: user.id, email: user.email },
+ stripe_customer_id: 'cus_123',
+ },
+ })
+ mockAccountsPartialUpdate.mockResolvedValue(updated)
+
+ logic.actions.updateAccountRole('acc-1', 'csm', user)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {
+ properties: {
+ csm: { id: user.id, email: user.email },
+ stripe_customer_id: 'cus_123',
+ },
+ })
+ expect(logic.values.results[0].properties?.csm).toEqual({ id: user.id, email: user.email })
+ })
+
+ it('sends null when clearing an assignment', async () => {
+ mockAccountsPartialUpdate.mockResolvedValue(
+ buildAccount({ properties: { csm: null, stripe_customer_id: 'cus_123' } })
+ )
+
+ logic.actions.updateAccountRole('acc-1', 'csm', null)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {
+ properties: {
+ csm: null,
+ stripe_customer_id: 'cus_123',
+ },
+ })
+ })
+
+ it('flips savingRoles during the in-flight window', async () => {
+ const key = savingRoleKey('acc-1', 'account_executive')
+ let resolveUpdate!: (value: AccountApi) => void
+ mockAccountsPartialUpdate.mockReturnValueOnce(
+ new Promise<AccountApi>((resolve) => {
+ resolveUpdate = resolve
+ })
+ )
+
+ logic.actions.updateAccountRole('acc-1', 'account_executive', buildUser())
+ await new Promise<void>((r) => setTimeout(r, 0))
+ expect(logic.values.savingRoles[key]).toBe(true)
+ expect(logic.values.isRoleSaving('acc-1', 'account_executive')).toBe(true)
+
+ resolveUpdate(buildAccount())
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.savingRoles[key]).toBeUndefined()
+ expect(logic.values.isRoleSaving('acc-1', 'account_executive')).toBe(false)
+ })
+
+ it('leaves the row untouched on failure', async () => {
+ mockAccountsPartialUpdate.mockRejectedValueOnce(new Error('boom'))
+
+ logic.actions.updateAccountRole('acc-1', 'account_owner', buildUser())
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.results[0]).toEqual(existingAccount)
+ expect(logic.values.isRoleSaving('acc-1', 'account_owner')).toBe(false)
+ })
+
+ it('is a no-op while a save for the same role is already in flight', async () => {
+ let resolveFirst!: (value: AccountApi) => void
+ mockAccountsPartialUpdate.mockReturnValueOnce(
+ new Promise<AccountApi>((resolve) => {
+ resolveFirst = resolve
+ })
+ )
+
+ logic.actions.updateAccountRole('acc-1', 'csm', buildUser({ id: 1, email: '[email protected]' }))
+ await new Promise<void>((r) => setTimeout(r, 0))
+ logic.actions.updateAccountRole('acc-1', 'csm', buildUser({ id: 2, email: '[email protected]' }))
+ await new Promise<void>((r) => setTimeout(r, 0))
+
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledTimes(1)
+
+ resolveFirst(buildAccount())
+ await expectLogic(logic).toFinishAllListeners()
+ })
+ })
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 5ad93ccddafe..19b502a253d4 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -5,8 +5,13 @@ import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import { accountsList } from 'products/customer_analytics/frontend/generated/api'
-import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { UserBasicType } from '~/types'
+
+import { accountsList, accountsPartialUpdate } from 'products/customer_analytics/frontend/generated/api'
+import type {
+ AccountApi,
+ PatchedAccountApiProperties,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
import type { accountsLogicType } from './accountsLogicType'
@@ -14,6 +19,16 @@ export const ACCOUNTS_PAGE_SIZE = 20
export type RoleFilterValue = number | null
+export type AccountRoleKey = 'csm' | 'account_executive' | 'account_owner'
+
+const ROLE_LABELS: Record<AccountRoleKey, string> = {
+ csm: 'CSM',
+ account_executive: 'Account executive',
+ account_owner: 'Account owner',
+}
+
+export const savingRoleKey = (accountId: string, role: AccountRoleKey): string => `${accountId}:${role}`
+
export interface AccountsLoadResult {
count: number
results: AccountApi[]
@@ -35,6 +50,14 @@ export const accountsLogic = kea<accountsLogicType>([
setAccountOwnerFilter: (value: RoleFilterValue) => ({ value }),
setCurrentPage: (page: number) => ({ page }),
refresh: true,
+ updateAccountRole: (accountId: string, role: AccountRoleKey, user: UserBasicType | null) => ({
+ accountId,
+ role,
+ user,
+ }),
+ roleUpdateStarted: (accountId: string, role: AccountRoleKey) => ({ accountId, role }),
+ roleUpdateFinished: (accountId: string, role: AccountRoleKey) => ({ accountId, role }),
+ replaceAccount: (account: AccountApi) => ({ account }),
}),
reducers({
searchQuery: [
@@ -79,6 +102,27 @@ export const accountsLogic = kea<accountsLogicType>([
setCurrentPage: (_, { page }) => page,
},
],
+ savingRoles: [
+ {} as Record<string, true>,
+ {
+ roleUpdateStarted: (state, { accountId, role }) => ({
+ ...state,
+ [savingRoleKey(accountId, role)]: true,
+ }),
+ roleUpdateFinished: (state, { accountId, role }) => {
+ const next = { ...state }
+ delete next[savingRoleKey(accountId, role)]
+ return next
+ },
+ },
+ ],
+ accountOverrides: [
+ {} as Record<string, AccountApi>,
+ {
+ replaceAccount: (state, { account }) => ({ ...state, [account.id]: account }),
+ loadAccountsSuccess: () => ({}),
+ },
+ ],
}),
loaders(({ values }) => ({
accounts: [
@@ -126,7 +170,17 @@ export const accountsLogic = kea<accountsLogicType>([
})),
selectors({
totalCount: [(s) => [s.accounts], (a: AccountsLoadResult): number => a.count],
- results: [(s) => [s.accounts], (a: AccountsLoadResult): AccountApi[] => a.results],
+ results: [
+ (s) => [s.accounts, s.accountOverrides],
+ (a: AccountsLoadResult, overrides: Record<string, AccountApi>): AccountApi[] =>
+ a.results.map((account) => overrides[account.id] ?? account),
+ ],
+ isRoleSaving: [
+ (s) => [s.savingRoles],
+ (savingRoles: Record<string, true>) =>
+ (accountId: string, role: AccountRoleKey): boolean =>
+ !!savingRoles[savingRoleKey(accountId, role)],
+ ],
}),
listeners(({ actions, values }) => ({
setSearchQuery: () => {
@@ -173,6 +227,30 @@ export const accountsLogic = kea<accountsLogicType>([
refresh: () => {
actions.loadAccounts()
},
+ updateAccountRole: async ({ accountId, role, user }) => {
+ if (values.isRoleSaving(accountId, role)) {
+ return
+ }
+ const account = values.results.find((a) => a.id === accountId)
+ if (!account) {
+ return
+ }
+ const nextProperties: PatchedAccountApiProperties = {
+ ...account.properties,
+ [role]: user ? { id: user.id, email: user.email } : null,
+ }
+ const projectId = String(values.currentTeamId)
+ actions.roleUpdateStarted(accountId, role)
+ try {
+ const updated = await accountsPartialUpdate(projectId, accountId, { properties: nextProperties })
+ actions.replaceAccount(updated)
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'accountsLogic.updateAccountRole' })
+ lemonToast.error(`Failed to update ${ROLE_LABELS[role]}`)
+ } finally {
+ actions.roleUpdateFinished(accountId, role)
+ }
+ },
})),
afterMount(({ actions }) => {
actions.loadAccounts()