: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): search account users (#89483)
Arthur Moreira de Deus78cc80a0fef2
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 9286fa09279a..3361e0c87b3b 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -3638,7 +3638,7 @@ const api = {async listForOrg(organizationId: OrganizationType['id'],- params: { limit?: number; offset?: number } = {}+ params: { limit?: number; offset?: number; search?: string } = {}): Promise<CountedPaginatedResponse<Pick<OrganizationMemberType, 'id' | 'user' | 'level'>>> {return await new ApiRequest().organizationMembersForAccount()diff --git a/products/customer_analytics/backend/presentation/views/organization_members.py b/products/customer_analytics/backend/presentation/views/organization_members.pyindex b7b8633eaf7a..2f9899bb91da 100644--- a/products/customer_analytics/backend/presentation/views/organization_members.py+++ b/products/customer_analytics/backend/presentation/views/organization_members.py@@ -1,12 +1,14 @@from uuid import UUID-from django.db.models import QuerySet+from django.db.models import Q, QuerySet, Value+from django.db.models.functions import Concatfrom drf_spectacular.utils import extend_schema-from rest_framework import mixins, viewsets+from rest_framework import mixins, serializers, viewsetsfrom posthog.api.organization_member import organization_members_base_querysetfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH, normalize_search_termfrom posthog.models import OrganizationMembershipfrom posthog.permissions import IsStaffUserOrImpersonating, PostHogFeatureFlagPermission@@ -41,4 +43,19 @@ class OrganizationMembersForAccountViewSet(return OrganizationMembership.objects.none()# Ordering kept (not removed): pagination needs a stable, index-backed order; `-joined_at`# is served by the (organization, -joined_at) composite index when filtering by organization_id.- return organization_members_base_queryset().filter(organization_id=organization_id).order_by("-joined_at")+ queryset = organization_members_base_queryset().filter(organization_id=organization_id).order_by("-joined_at")+ search = self.request.query_params.get("search", "")+ if len(search) > MAX_SEARCH_LENGTH:+ raise serializers.ValidationError(+ {"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}+ )+ if normalized_search := normalize_search_term(search):+ return queryset.annotate(+ account_member_full_name=Concat("user__first_name", Value(" "), "user__last_name")+ ).filter(+ Q(user__first_name__icontains=normalized_search)+ | Q(user__last_name__icontains=normalized_search)+ | Q(user__email__icontains=normalized_search)+ | Q(account_member_full_name__icontains=normalized_search)+ )+ return querysetdiff --git a/products/customer_analytics/backend/test/test_organization_members.py b/products/customer_analytics/backend/test/test_organization_members.pyindex 2ad49ac5f269..d4f9d4e2dba1 100644--- a/products/customer_analytics/backend/test/test_organization_members.py+++ b/products/customer_analytics/backend/test/test_organization_members.py@@ -1,3 +1,5 @@+from urllib.parse import urlencode+from posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -50,6 +52,28 @@ class TestOrganizationMembersForAccountAPI(APIBaseTest):{r["user"]["email"]: r["level"] for r in results}, {"[email protected]": 8, "[email protected]": 1})+ @parameterized.expand(+ [+ ("name", "ada", "[email protected]"),+ ("email", "hopper@", "[email protected]"),+ ("full name", "Grace Hopper", "[email protected]"),+ ]+ )+ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_searches_members_by_name_or_email(self, _name, search, expected_email, _mock_flag):+ self._join("[email protected]", first_name="Ada", distinct_id="distinct-ada")+ self._join(+ "[email protected]",+ first_name="Grace",+ last_name="Hopper",+ distinct_id="distinct-grace",+ )++ response = self.client.get(f"{self._url(self.target_org.id)}&{urlencode({'search': search})}")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([member["user"]["email"] for member in response.json()["results"]], [expected_email])+@patch("posthoganalytics.feature_enabled", return_value=False)def test_forbidden_when_flag_disabled(self, _mock_flag):response = self.client.get(self._url(self.target_org.id))diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 932ee2e8398e..9fa80e580a32 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -48,7 +48,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. || `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. || `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |-| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated in pages of 20 client-side. Both sources include the member's organization access level. The EU view also includes the source Django user ID. Each member carries its source region so staff admin links open the correct user's detail page in the correct cloud. A missing view (local dev) degrades to the normal empty state. |+| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). It debounces name and email searches. US-region orgs use the org-members endpoint. When it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion then searched and paginated in pages of 20 client-side. Both sources include the member's organization access level. The EU view also includes the source Django user ID. Each member carries its source region so staff admin links open the correct user's detail page in the correct cloud. A missing view (local dev) degrades to the normal empty state. || `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. || `accountFeatureRequestsLogic` | Feature requests for one account (keyed by `accountId`): loads linked requests in server pages of five with debounced search, then searches a bounded server page of accessible, editable active requests for the link picker. Request links carry the account's Feature requests deep link as their origin, so the detail breadcrumb returns to the same account tab. The picker exposes load failures with retry guidance and refreshes stale options after optimistic-concurrency conflicts. || `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, preloads each insight result when the account expands, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsxindex 155c4fe3308a..7fe6d07da933 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx@@ -52,6 +52,7 @@ describe('AccountRelatedUsersExpansion', () => {)expect(await screen.findByText('Owner')).toBeInTheDocument()+ expect(screen.getByPlaceholderText('Search users by name or email...')).toHaveAttribute('maxLength', '200')const impersonateButton = await screen.findByText('Impersonate')expect(impersonateButton.closest('a')).toHaveAttribute('href', 'http://localhost/admin/posthog/user/42/change/')})diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsxindex 3bc53fd98133..c402637fecf7 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import posthog from 'posthog-js'-import { LemonButton, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'import { membershipLevelToName } from 'lib/utils/permissioning'import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'@@ -14,9 +14,9 @@ import { AccountsEvents } from './constants'export function AccountRelatedUsersExpansion({ externalId }: { externalId: string }): JSX.Element {const logic = accountRelatedUsersLogic({ externalId })- const { membersResponse, membersResponseLoading, page } = useValues(logic)+ const { membersResponse, membersResponseLoading, page, searchTerm } = useValues(logic)const { user } = useValues(userLogic)- const { setPage } = useActions(logic)+ const { setPage, setSearchTerm } = useActions(logic)const columns: LemonTableColumns<AccountOrganizationMember> = [{@@ -77,29 +77,43 @@ export function AccountRelatedUsersExpansion({ externalId }: { externalId: strin}return (- <LemonTable<AccountOrganizationMember>- size="small"- embedded- dataSource={membersResponse?.results ?? []}- rowKey="id"- loading={membersResponseLoading}- columns={columns}- pagination={{- controlled: true,- pageSize: PAGE_SIZE,- currentPage: page,- useUrl: false,- entryCount: membersResponse?.count ?? 0,- onForward: () => setPage(page + 1),- onBackward: () => setPage(page - 1),- }}- emptyState={- !externalId- ? 'This account has no linked organization.'- : membersResponse === null- ? 'Failed to load related users.'- : 'No users related to this account yet.'- }- />+ <div className="flex flex-col gap-2">+ <LemonInput+ type="search"+ value={searchTerm}+ onChange={setSearchTerm}+ placeholder="Search users by name or email..."+ maxLength={200}+ size="small"+ className="min-w-64"+ data-attr="customer-analytics-account-users-search"+ />+ <LemonTable<AccountOrganizationMember>+ size="small"+ embedded+ dataSource={membersResponse?.results ?? []}+ rowKey="id"+ loading={membersResponseLoading}+ columns={columns}+ pagination={{+ controlled: true,+ pageSize: PAGE_SIZE,+ currentPage: page,+ useUrl: false,+ entryCount: membersResponse?.count ?? 0,+ onForward: () => setPage(page + 1),+ onBackward: () => setPage(page - 1),+ }}+ emptyState={+ !externalId+ ? 'This account has no linked organization.'+ : membersResponse === null+ ? 'Failed to load related users.'+ : searchTerm+ ? 'No users match your search.'+ : 'No users related to this account yet.'+ }+ />+ </div>)}diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.tsindex fdd93ef1e498..7577116de125 100644--- a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts@@ -85,6 +85,44 @@ describe('accountRelatedUsersLogic', () => {expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: 20, offset: 20 })})+ it('resets to the first page and sends the user search to the API', async () => {+ const listForOrg = jest+ .spyOn(api.organizationMembers, 'listForOrg')+ .mockResolvedValue(buildResponse([buildMember()], PAGE_SIZE + 1))++ logic = accountRelatedUsersLogic({ externalId: 'org-uuid' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setPage(2)+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSearchTerm('Ada')++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ page: 1, searchTerm: 'Ada' })+ expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: PAGE_SIZE, offset: 0, search: 'Ada' })+ })++ it('does not load EU members when a US user search has no matches', async () => {+ const listForOrg = jest+ .spyOn(api.organizationMembers, 'listForOrg')+ .mockResolvedValueOnce(buildResponse([buildMember()]))+ .mockResolvedValueOnce(buildResponse([]))+ const query = jest.spyOn(api, 'query')++ logic = accountRelatedUsersLogic({ externalId: 'org-uuid' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSearchTerm('Nobody')++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ membersResponse: buildResponse([]) })+ expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: PAGE_SIZE, offset: 0, search: 'Nobody' })+ expect(query).not.toHaveBeenCalled()+ })+const buildEuRow = (n: number,level: OrganizationMembershipLevel = OrganizationMembershipLevel.Member@@ -141,6 +179,22 @@ describe('accountRelatedUsersLogic', () => {})})+ it('filters cached EU members by name without loading them again', async () => {+ const listForOrg = jest.spyOn(api.organizationMembers, 'listForOrg').mockResolvedValue(buildResponse([], 0))+ const query = jest.spyOn(api, 'query').mockResolvedValue({ results: [buildEuRow(1), buildEuRow(2)] } as any)++ logic = accountRelatedUsersLogic({ externalId: 'org-uuid' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSearchTerm('First2')++ await expectLogic(logic).toFinishAllListeners()+ expect(listForOrg).toHaveBeenCalledTimes(1)+ expect(query).toHaveBeenCalledTimes(1)+ expect(logic.values.membersResponse).toMatchObject({ count: 1, results: [{ id: 'eu-m-2' }] })+ })+it('degrades to the empty response when the EU view does not exist', async () => {const emptyResponse = buildResponse([], 0)jest.spyOn(api.organizationMembers, 'listForOrg').mockResolvedValue(emptyResponse)diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.tsindex 291bc22abbbc..abf0b99c9dc1 100644--- a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts@@ -10,6 +10,7 @@ import { hogql } from '~/queries/utils'import { OrganizationMemberType, Region } from '~/types'import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'+import { AccountsEvents } from './constants'export type AccountOrganizationMember = Pick<OrganizationMemberType, 'id' | 'user' | 'level'> & {region: Region.US | Region.EU@@ -30,13 +31,26 @@ const isExpectedMissingViewError = (error: unknown): boolean => {)}+const memberMatchesSearch = (member: AccountOrganizationMember, searchTerm: string): boolean => {+ const normalizedSearch = searchTerm.trim().toLowerCase()+ if (!normalizedSearch) {+ return true+ }+ const { first_name, last_name, email } = member.user+ return `${first_name} ${last_name} ${email}`.toLowerCase().includes(normalizedSearch)+}+const paginateMembers = (members: AccountOrganizationMember[],- page: number-): CountedPaginatedResponse<AccountOrganizationMember> => ({- results: members.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE),- count: members.length,-})+ page: number,+ searchTerm: string = ''+): CountedPaginatedResponse<AccountOrganizationMember> => {+ const matchingMembers = members.filter((member) => memberMatchesSearch(member, searchTerm))+ return {+ results: matchingMembers.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE),+ count: matchingMembers.length,+ }+}const fetchEuMembers = async (externalId: string): Promise<AccountOrganizationMember[] | null> => {try {@@ -83,6 +97,7 @@ export interface accountRelatedUsersLogicValues {membersResponse: CountedPaginatedResponse<AccountOrganizationMember> | nullmembersResponseLoading: booleanpage: number+ searchTerm: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -105,6 +120,9 @@ export interface accountRelatedUsersLogicActions {setPage: (page: number) => {page: number}+ setSearchTerm: (searchTerm: string) => {+ searchTerm: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -126,14 +144,17 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([key((props) => props.externalId),actions({setPage: (page: number) => ({ page }),+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),}),reducers({page: [1,{setPage: (_, { page }) => page,+ setSearchTerm: () => 1,},],+ searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],}),loaders(({ cache, props, values }) => ({membersResponse: [@@ -141,12 +162,14 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([{loadMembers: async (_ = null, breakpoint) => {if (cache.euMembers) {- return paginateMembers(cache.euMembers, values.page)+ return paginateMembers(cache.euMembers, values.page, values.searchTerm)}try {+ const search = values.searchTerm.trim()const response = await api.organizationMembers.listForOrg(props.externalId, {limit: PAGE_SIZE,offset: (values.page - 1) * PAGE_SIZE,+ ...(search ? { search } : {}),})breakpoint()if (response.count > 0) {@@ -155,11 +178,13 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([results: response.results.map((member) => ({ ...member, region: Region.US })),}}- const euMembers = await fetchEuMembers(props.externalId)- breakpoint()- if (euMembers?.length) {- cache.euMembers = euMembers- return paginateMembers(euMembers, values.page)+ if (!search) {+ const euMembers = await fetchEuMembers(props.externalId)+ breakpoint()+ if (euMembers?.length) {+ cache.euMembers = euMembers+ return paginateMembers(euMembers, values.page, values.searchTerm)+ }}return { ...response, results: [] }} catch (error) {@@ -177,6 +202,14 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([})),listeners(({ actions }) => ({setPage: () => actions.loadMembers(),+ setSearchTerm: async ({ searchTerm }, breakpoint) => {+ await breakpoint(300)+ actions.loadMembers()+ posthog.capture(AccountsEvents.RelatedUsersSearched, {+ has_query: searchTerm.trim().length > 0,+ query_length: searchTerm.trim().length,+ })+ },})),afterMount(({ actions, props }) => {if (props.externalId) {diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex 9073b0bd963c..323078244011 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -51,6 +51,7 @@ export const AccountsEvents = {UsageSeriesToggled: 'customer analytics account usage series toggled',UsageSeriesBulkToggled: 'customer analytics account usage series bulk toggled',RelatedUserClicked: 'customer analytics account related user clicked',+ RelatedUsersSearched: 'customer analytics account related users searched',RelatedUserAdminOpened: 'customer analytics account related user admin opened',OpportunityClicked: 'customer analytics account opportunity clicked',SummaryCadenceChanged: 'customer analytics account summary cadence changed',