: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): sort and filter the account Users tab by access level and last login (#97224)
leonhardprinzf1b76a8f2baa
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 4070ad8c7d05..58ab33b49088 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -3617,7 +3617,7 @@ const api = {async listForOrg(organizationId: OrganizationType['id'],- params: { limit?: number; offset?: number; search?: string } = {}+ params: { limit?: number; offset?: number; search?: string; levels?: string; ordering?: string } = {}): Promise<CountedPaginatedResponse<Pick<OrganizationMemberType, 'id' | 'user' | 'level' | 'last_login'>>> {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 128a90efb06a..a7e8ab5603ba 100644--- a/products/customer_analytics/backend/presentation/views/organization_members.py+++ b/products/customer_analytics/backend/presentation/views/organization_members.py@@ -15,6 +15,9 @@ from posthog.permissions import IsStaffUserOrImpersonating, PostHogFeatureFlagPefrom products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_CSP_FLAGfrom products.customer_analytics.backend.presentation.views.serializers import AccountOrganizationMemberSerializer+DEFAULT_ORDERING = "-joined_at"+ALLOWED_ORDERINGS = frozenset({"joined_at", "-joined_at", "level", "-level", "last_login", "-last_login"})+# Excluded from the generated OpenAPI clients: this is an INTERNAL, staff-only endpoint# consumed only by the customer-analytics Accounts UI via a handwritten api call (consistent@@ -41,14 +44,15 @@ class OrganizationMembersForAccountViewSet(UUID(str(organization_id))except (ValueError, TypeError):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.+ # Pagination needs a stable order. The default `-joined_at` is served by the+ # (organization, -joined_at) composite index when filtering by organization_id.queryset = (organization_members_base_queryset().filter(organization_id=organization_id).annotate(last_login=F("user__last_login"))- .order_by("-joined_at")+ .order_by(*self._ordering()))+ queryset = self._apply_levels_filter(queryset)search = self.request.query_params.get("search", "")if len(search) > MAX_SEARCH_LENGTH:raise serializers.ValidationError(@@ -64,3 +68,25 @@ class OrganizationMembersForAccountViewSet(| Q(account_member_full_name__icontains=normalized_search))return queryset++ def _ordering(self) -> list:+ """Whitelisted `ordering` param, nulls-last for last_login, `-joined_at` as the tiebreaker."""+ ordering = self.request.query_params.get("ordering") or DEFAULT_ORDERING+ if ordering not in ALLOWED_ORDERINGS:+ raise serializers.ValidationError({"ordering": f"Must be one of: {', '.join(sorted(ALLOWED_ORDERINGS))}."})+ if ordering in ("joined_at", "-joined_at"):+ return [ordering]+ descending = ordering.startswith("-")+ field = F(ordering.lstrip("-"))+ primary = field.desc(nulls_last=True) if descending else field.asc(nulls_first=True)+ return [primary, DEFAULT_ORDERING]++ def _apply_levels_filter(self, queryset: QuerySet) -> QuerySet:+ levels_param = self.request.query_params.get("levels")+ if not levels_param:+ return queryset+ try:+ levels = [int(level) for level in levels_param.split(",") if level]+ except ValueError:+ raise serializers.ValidationError({"levels": "Must be a comma-separated list of integers."})+ return queryset.filter(level__in=levels)diff --git a/products/customer_analytics/backend/test/test_organization_members.py b/products/customer_analytics/backend/test/test_organization_members.pyindex 158f9bfff98d..4cd82a25521e 100644--- a/products/customer_analytics/backend/test/test_organization_members.py+++ b/products/customer_analytics/backend/test/test_organization_members.py@@ -81,6 +81,50 @@ class TestOrganizationMembersForAccountAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual([member["user"]["email"] for member in response.json()["results"]], [expected_email])+ @parameterized.expand(+ [+ ("recent login first", "-last_login", ["[email protected]", "[email protected]", "[email protected]"]),+ ("never logged in first", "last_login", ["[email protected]", "[email protected]", "[email protected]"]),+ ]+ )+ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_orders_members_by_level_or_last_login(self, _name, ordering, expected_emails, _mock_flag):+ owner = self._join("[email protected]", distinct_id="distinct-owner", level=OrganizationMembership.Level.OWNER)+ admin = self._join("[email protected]", distinct_id="distinct-admin", level=OrganizationMembership.Level.ADMIN)+ self._join("[email protected]", distinct_id="distinct-never")+ owner.last_login = datetime(2026, 1, 1, tzinfo=UTC)+ owner.save(update_fields=["last_login"])+ admin.last_login = datetime(2026, 2, 1, tzinfo=UTC)+ admin.save(update_fields=["last_login"])++ response = self.client.get(f"{self._url(self.target_org.id)}&{urlencode({'ordering': ordering})}")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([member["user"]["email"] for member in response.json()["results"]], expected_emails)++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_rejects_unknown_ordering(self, _mock_flag):+ response = self.client.get(f"{self._url(self.target_org.id)}&ordering=user__email")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @patch("posthoganalytics.feature_enabled", return_value=True)+ def test_filters_members_by_levels(self, _mock_flag):+ self._join("[email protected]", distinct_id="distinct-owner", level=OrganizationMembership.Level.OWNER)+ self._join("[email protected]", distinct_id="distinct-admin", level=OrganizationMembership.Level.ADMIN)+ self._join("[email protected]", distinct_id="distinct-member")++ response = self.client.get(f"{self._url(self.target_org.id)}&levels=15,8")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.json()+ self.assertEqual(body["count"], 2)+ self.assertEqual({r["user"]["email"] for r in body["results"]}, {"[email protected]", "[email protected]"})++ response = self.client.get(f"{self._url(self.target_org.id)}&levels=owner")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+@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 2318da776561..d0bb02bdc5e2 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -41,25 +41,25 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc### Logics and what each owns-| Logic | Owns |-| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `accountsLogic` | The hub. Search (debounced), tag / assignment-status (the canonical `assignmentStatus`: `all` \| `assigned` \| `unassigned`, default `all`) + assigned-to / native-field / relationship / custom-property filters, sort, inline role and custom-property assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). Canonical and warehouse-backed property values are read-only. Workflow-backed properties stay editable, but a future workflow run overwrites a manual value. `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |-| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select) and browser-persisted column widths. Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |-| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |-| `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`). 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), fetched once per expansion then searched and paginated in pages of 20 client-side. Both reads supply the member's organization access level and last-login data. EU values refresh daily. 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), `endRelationship` (per active row, POSTs the end endpoint), and `deleteRelationship` (admin-only, confirmation-gated hard delete). All mutations share the `relationshipSaving` guard, 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. |-| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |-| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. |-| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |-| `accountEmailThreadsLogic` | Matched email communication used by the Conversations tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. |-| `accountConversationsLogic` | The unified Conversations timeline (keyed by `accountId`): loads email, Support, and Slack independently so one denied or failed source does not blank successful sources; merges them newest-first; owns search, source filters, expansion state, Support message loading, and collapsed Slack message links. It preserves email and Slack response counts and loads older source pages on demand instead of silently limiting search to the first 50 rows. |-| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `list_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). The endpoint discovers synced Gong `calls` tables and matches `calendar_event_id` to the meeting's iCal UID plus recurrence instance. Matching rows include a validated `gong_url`; the table shows an "Open in Gong" button and records `GongCallOpened`. Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching`; merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |-| `accountLinksLogic` | The "Useful links" sidebar and editor for one account (keyed by `accountId`). The editor updates `website_domain` and external links through `accountsPartialUpdate` without replacing unrelated account properties. |+| Logic | Owns |+| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `accountsLogic` | The hub. Search (debounced), tag / assignment-status (the canonical `assignmentStatus`: `all` \| `assigned` \| `unassigned`, default `all`) + assigned-to / native-field / relationship / custom-property filters, sort, inline role and custom-property assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). Canonical and warehouse-backed property values are read-only. Workflow-backed properties stay editable, but a future workflow run overwrites a manual value. `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select) and browser-persisted column widths. Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |+| `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`). It debounces name and email searches, and owns the table's sort (`sorting`, on `level` or `last_login`) and access-level filter (`levels`); both reset to page 1 and reload. US-region orgs use the org-members endpoint, which takes `search`, `levels` and a whitelisted `ordering`. 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), fetched once per expansion then searched, filtered, sorted and paginated in pages of 20 client-side (mirroring the backend's ordering, "never logged in" at the far end). Once a US request has returned members the org is remembered as US-hosted and an empty filtered page is treated as "no match"; until then an empty US page falls back to the EU view, so a filter set before the first load finishes still applies. Both reads supply the member's organization access level and last-login data. EU values refresh daily. 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), `endRelationship` (per active row, POSTs the end endpoint), and `deleteRelationship` (admin-only, confirmation-gated hard delete). All mutations share the `relationshipSaving` guard, 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. |+| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |+| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. |+| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |+| `accountEmailThreadsLogic` | Matched email communication used by the Conversations tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. |+| `accountConversationsLogic` | The unified Conversations timeline (keyed by `accountId`): loads email, Support, and Slack independently so one denied or failed source does not blank successful sources; merges them newest-first; owns search, source filters, expansion state, Support message loading, and collapsed Slack message links. It preserves email and Slack response counts and loads older source pages on demand instead of silently limiting search to the first 50 rows. |+| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `list_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). The endpoint discovers synced Gong `calls` tables and matches `calendar_event_id` to the meeting's iCal UID plus recurrence instance. Matching rows include a validated `gong_url`; the table shows an "Open in Gong" button and records `GongCallOpened`. Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching`; merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |+| `accountLinksLogic` | The "Useful links" sidebar and editor for one account (keyed by `accountId`). The editor updates `website_domain` and external links through `accountsPartialUpdate` without replacing unrelated account properties. |## Data & query model@@ -189,7 +189,7 @@ With the flag disabled, the body is `AccountNotebooksExpansion`: the Useful link**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `AccountDetailTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountNotebooksLogic({ accountId })`, `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountConversationsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components so both resolve to the same keyed instance. `accountLinksLogic` mounts through the always-rendered sidebar. `CustomerTasksMount` keeps the account task logic mounted only when `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` is enabled. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. Flag-gated tabs load only when their flag is enabled.-The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Staff also see an "Impersonate" action that opens the user's Django admin detail page in the member's US or EU cloud. Outside PostHog Cloud, the action stays on the current origin so local and self-hosted users can test their own admin. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. This prevents duplicate loads and keeps results across tab switches. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)+The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Its "Access level" and "Last logged in" headers sort (server-side for US orgs via `ordering`, client-side for cached EU rows; sorting is not written to the URL since it's per expanded row), and the "Access level" header carries a filter menu (owner / admin / member checkboxes, count badge) built with the shared `columnValueFilter` helper in `components/columnValueFilter.tsx`, which turns any enumerated column into a header filter and leaves the actual filtering to the caller. Staff also see an "Impersonate" action that opens the user's Django admin detail page in the member's US or EU cloud. Outside PostHog Cloud, the action stays on the current origin so local and self-hosted users can test their own admin. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. This prevents duplicate loads and keeps results across tab switches. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)The Usage and Spend tabs render existing saved billing insights — **point users to them, don't rebuild billing as new insights.**@@ -379,6 +379,8 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics account usage series toggled` | `accountBillingLogic` `toggleHiddenSeriesKey` listener (dispatched by the `AccountBillingSeriesToggle` chips) | `kind` (`usage` \| `spend`), `is_hidden` (the post-click state), `series_count` (no series label / no PII) || `customer analytics account usage series bulk toggled` | `accountBillingLogic` `setAllSeriesHidden` listener (dispatched by the Select all / Clear all buttons in `AccountBillingSeriesToggle`) | `kind` (`usage` \| `spend`), `is_hidden` (`true` when hiding all, `false` when showing all), `series_count` (no series label / no PII) || `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |+| `customer analytics account related users filtered` | `accountRelatedUsersLogic` `setLevels` listener | `levels` (selected `OrganizationMembershipLevel[]`) |+| `customer analytics account related users sorted` | `accountRelatedUsersLogic` `setSorting` listener | `column` (`level` \| `last_login` \| `null`), `direction` (`asc` \| `desc` \| `cleared`) || `customer analytics account related user admin opened` | `AccountRelatedUsersExpansion.tsx` staff-only "Impersonate" button | `region` (`US` \| `EU`; user ID kept out) || `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ || `customer analytics account summary cadence changed` | `accountSummariesLogic` `setCadence` listener (after the PATCH succeeds) | `cadence` (`daily` \| `weekly` \| `monthly` \| `off`) |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsxindex 2c46d2b8a52b..6e7af07bad68 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx@@ -70,6 +70,12 @@ describe('AccountRelatedUsersExpansion', () => {expect(screen.getByText('2026-01-02T03:04:05Z')).toBeInTheDocument()expect(screen.getByText('Never')).toBeInTheDocument()expect(screen.getByPlaceholderText('Search users by name or email...')).toHaveAttribute('maxLength', '200')+ for (const header of ['Access level', 'Last logged in']) {+ expect(screen.getByText(header).closest('th')).toHaveClass('LemonTable__header--actionable')+ }+ expect(+ screen.getByText('Access level').closest('th')!.querySelector('[data-attr="table-header-more"]')+ ).not.toBeNull()const [impersonateButton] = await screen.findAllByText('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 61500ea1a7a0..f555793bdf2a 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx@@ -4,15 +4,26 @@ import posthog from 'posthog-js'import { LemonButton, LemonInput, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'+import { OrganizationMembershipLevel } from 'lib/constants'import { membershipLevelToName } from 'lib/utils/permissioning'import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'+import { columnValueFilter } from '../columnValueFilter'import { getAccountRelatedUserAdminUrl } from './accountRelatedUserAdminUrl'import { accountRelatedUsersLogic, AccountOrganizationMember, PAGE_SIZE } from './accountRelatedUsersLogic'import { AccountsEvents } from './constants'+const LEVEL_FILTER_OPTIONS = [+ OrganizationMembershipLevel.Owner,+ OrganizationMembershipLevel.Admin,+ OrganizationMembershipLevel.Member,+].map((level) => ({+ value: level,+ label: capitalizeFirstLetter(membershipLevelToName.get(level) ?? 'Unknown'),+}))+export function AccountRelatedUsersExpansion({externalId,embedded = true,@@ -21,9 +32,9 @@ export function AccountRelatedUsersExpansion({embedded?: boolean}): JSX.Element {const logic = accountRelatedUsersLogic({ externalId })- const { membersResponse, membersResponseLoading, page, searchTerm } = useValues(logic)+ const { membersResponse, membersResponseLoading, page, searchTerm, levels, sorting } = useValues(logic)const { user } = useValues(userLogic)- const { setPage, setSearchTerm } = useActions(logic)+ const { setPage, setSearchTerm, setLevels, setSorting } = useActions(logic)const columns: LemonTableColumns<AccountOrganizationMember> = [{@@ -52,11 +63,21 @@ export function AccountRelatedUsersExpansion({{title: 'Access level',key: 'level',+ sorter: true,+ defaultSortOrder: -1,+ ...columnValueFilter<AccountOrganizationMember, OrganizationMembershipLevel>({+ options: LEVEL_FILTER_OPTIONS,+ selected: levels,+ onChange: setLevels,+ 'data-attr': 'customer-analytics-account-users-level-option',+ }),render: (_, member) => capitalizeFirstLetter(membershipLevelToName.get(member.level) ?? 'Unknown'),},{title: 'Last logged in',key: 'last_login',+ sorter: true,+ defaultSortOrder: -1,render: (_, member) => (member.last_login ? <TZLabel time={member.last_login} /> : 'Never'),},]@@ -107,6 +128,9 @@ export function AccountRelatedUsersExpansion({rowKey="id"loading={membersResponseLoading}columns={columns}+ sorting={sorting}+ onSort={setSorting}+ useURLForSorting={false}pagination={{controlled: true,pageSize: PAGE_SIZE,@@ -121,8 +145,8 @@ export function AccountRelatedUsersExpansion({? 'This account has no linked organization.': membersResponse === null? 'Failed to load related users.'- : searchTerm- ? 'No users match your search.'+ : searchTerm || levels.length+ ? 'No users match your filters.': 'No users related to this account yet.'}/>diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.tsindex 370e5166f7f9..02f779007249 100644--- a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts@@ -104,6 +104,52 @@ describe('accountRelatedUsersLogic', () => {expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: PAGE_SIZE, offset: 0, search: 'Ada' })})+ it('sends the sort as the backend ordering param and resets to the first page', 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.setSorting({ columnKey: 'last_login', order: -1 })++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ page: 1 })+ expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', {+ limit: PAGE_SIZE,+ offset: 0,+ ordering: '-last_login',+ })++ logic.actions.setSorting(null)++ await expectLogic(logic).toFinishAllListeners()+ expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: PAGE_SIZE, offset: 0 })+ })++ it('sends selected access levels as a comma-separated levels param', 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.setLevels([OrganizationMembershipLevel.Owner, OrganizationMembershipLevel.Admin])++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ page: 1 })+ expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: PAGE_SIZE, offset: 0, levels: '15,8' })+ // The org has US members, so an empty filtered page is "no match", not a reason to look in the EU view.+ expect(query).not.toHaveBeenCalled()+ })+it('does not load EU members when a US user search has no matches', async () => {const listForOrg = jest.spyOn(api.organizationMembers, 'listForOrg')@@ -199,6 +245,69 @@ describe('accountRelatedUsersLogic', () => {expect(logic.values.membersResponse).toMatchObject({ count: 1, results: [{ id: 'eu-m-2' }] })})+ it('applies a filter set before the first load finishes to EU members', async () => {+ jest.spyOn(api.organizationMembers, 'listForOrg').mockResolvedValue(buildResponse([], 0))+ const query = jest.spyOn(api, 'query').mockResolvedValue({+ results: [+ buildEuRow(1, OrganizationMembershipLevel.Member),+ buildEuRow(2, OrganizationMembershipLevel.Admin),+ ],+ } as any)++ logic = accountRelatedUsersLogic({ externalId: 'org-uuid' })+ logic.mount()+ logic.actions.setLevels([OrganizationMembershipLevel.Admin])++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.membersResponse).toMatchObject({ count: 1, results: [{ id: 'eu-m-2' }] })++ logic.actions.setLevels([])++ await expectLogic(logic).toFinishAllListeners()+ expect(query).toHaveBeenCalledTimes(1)+ expect(logic.values.membersResponse).toMatchObject({ count: 2 })+ })++ it('sorts and filters cached EU members client-side without refetching', async () => {+ const listForOrg = jest.spyOn(api.organizationMembers, 'listForOrg').mockResolvedValue(buildResponse([], 0))+ const query = jest.spyOn(api, 'query').mockResolvedValue({+ results: [+ buildEuRow(1, OrganizationMembershipLevel.Member, '2026-03-01T00:00:00Z'),+ buildEuRow(2, OrganizationMembershipLevel.Owner, null),+ buildEuRow(3, OrganizationMembershipLevel.Admin, '2026-01-01T00:00:00Z'),+ ],+ } as any)++ logic = accountRelatedUsersLogic({ externalId: 'org-uuid' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSorting({ columnKey: 'level', order: -1 })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.membersResponse).toMatchObject({+ results: [{ id: 'eu-m-2' }, { id: 'eu-m-3' }, { id: 'eu-m-1' }],+ })++ logic.actions.setSorting({ columnKey: 'last_login', order: -1 })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.membersResponse).toMatchObject({+ results: [{ id: 'eu-m-1' }, { id: 'eu-m-3' }, { id: 'eu-m-2' }],+ })++ logic.actions.setSorting({ columnKey: 'last_login', order: 1 })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.membersResponse).toMatchObject({+ results: [{ id: 'eu-m-2' }, { id: 'eu-m-3' }, { id: 'eu-m-1' }],+ })++ logic.actions.setLevels([OrganizationMembershipLevel.Admin])+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.membersResponse).toMatchObject({ count: 1, results: [{ id: 'eu-m-3' }] })++ expect(listForOrg).toHaveBeenCalledTimes(1)+ expect(query).toHaveBeenCalledTimes(1)+ })+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 14af2dd092f5..93c0a5f84c21 100644--- a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts@@ -1,8 +1,23 @@-import { MakeLogicType, actions, afterMount, isBreakpoint, kea, key, listeners, path, props, reducers } from 'kea'+import {+ MakeLogicType,+ actions,+ afterMount,+ isBreakpoint,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'+import { Sorting } from '@posthog/lemon-ui'+import api, { CountedPaginatedResponse } from 'lib/api'+import { OrganizationMembershipLevel } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'@@ -31,6 +46,23 @@ const isExpectedMissingViewError = (error: unknown): boolean => {)}+/** Column keys the table can sort by. They double as the backend's whitelisted `ordering` values. */+export type RelatedUsersSortKey = 'level' | 'last_login'++export interface RelatedUsersQuery {+ searchTerm: string+ levels: OrganizationMembershipLevel[]+ sorting: Sorting | null+}++// Maps the table's sorting state onto the backend's whitelisted `ordering` param.+const sortingToOrdering = (sorting: Sorting | null): string | undefined => {+ if (!sorting) {+ return undefined+ }+ return sorting.order === -1 ? `-${sorting.columnKey}` : sorting.columnKey+}+const memberMatchesSearch = (member: AccountOrganizationMember, searchTerm: string): boolean => {const normalizedSearch = searchTerm.trim().toLowerCase()if (!normalizedSearch) {@@ -40,15 +72,31 @@ const memberMatchesSearch = (member: AccountOrganizationMember, searchTerm: strireturn `${first_name} ${last_name} ${email}`.toLowerCase().includes(normalizedSearch)}+const compareMembers = (a: AccountOrganizationMember, b: AccountOrganizationMember, sorting: Sorting): number => {+ if (sorting.columnKey === 'level') {+ return (a.level - b.level) * sorting.order+ }+ if (sorting.columnKey === 'last_login') {+ if (!a.last_login || !b.last_login) {+ return a.last_login === b.last_login ? 0 : (a.last_login ? 1 : -1) * sorting.order+ }+ return a.last_login.localeCompare(b.last_login) * sorting.order+ }+ return 0+}+const paginateMembers = (members: AccountOrganizationMember[],page: number,- searchTerm: string = ''+ { searchTerm, levels, sorting }: RelatedUsersQuery): CountedPaginatedResponse<AccountOrganizationMember> => {- const matchingMembers = members.filter((member) => memberMatchesSearch(member, searchTerm))+ const matchingMembers = members.filter(+ (member) => memberMatchesSearch(member, searchTerm) && (!levels.length || levels.includes(member.level))+ )+ const sortedMembers = sorting ? [...matchingMembers].sort((a, b) => compareMembers(a, b, sorting)) : matchingMembersreturn {- results: matchingMembers.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE),- count: matchingMembers.length,+ results: sortedMembers.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE),+ count: sortedMembers.length,}}@@ -95,10 +143,13 @@ export interface AccountRelatedUsersLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountRelatedUsersLogicValues {+ levels: OrganizationMembershipLevel[]membersResponse: CountedPaginatedResponse<AccountOrganizationMember> | nullmembersResponseLoading: booleanpage: number+ query: RelatedUsersQuerysearchTerm: string+ sorting: Sorting | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -118,17 +169,26 @@ export interface accountRelatedUsersLogicActions {membersResponse: CountedPaginatedResponse<AccountOrganizationMember>payload?: any}+ setLevels: (levels: OrganizationMembershipLevel[]) => {+ levels: OrganizationMembershipLevel[]+ }setPage: (page: number) => {page: number}setSearchTerm: (searchTerm: string) => {searchTerm: string}+ setSorting: (sorting: Sorting | null) => {+ sorting: Sorting | null+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountRelatedUsersLogicMeta {key: string+ __keaTypeGenInternalSelectorTypes: {+ query: (searchTerm: string, levels: OrganizationMembershipLevel[], sorting: Sorting | null) => RelatedUsersQuery+ }}export type accountRelatedUsersLogicType = MakeLogicType<@@ -146,6 +206,8 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([actions({setPage: (page: number) => ({ page }),setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setLevels: (levels: OrganizationMembershipLevel[]) => ({ levels }),+ setSorting: (sorting: Sorting | null) => ({ sorting }),}),reducers({page: [@@ -153,9 +215,23 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([{setPage: (_, { page }) => page,setSearchTerm: () => 1,+ setLevels: () => 1,+ setSorting: () => 1,},],searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],+ levels: [[] as OrganizationMembershipLevel[], { setLevels: (_, { levels }) => levels }],+ sorting: [null as Sorting | null, { setSorting: (_, { sorting }) => sorting }],+ }),+ selectors({+ query: [+ (s) => [s.searchTerm, s.levels, s.sorting],+ (+ searchTerm: string,+ levels: OrganizationMembershipLevel[],+ sorting: Sorting | null+ ): RelatedUsersQuery => ({ searchTerm, levels, sorting }),+ ],}),loaders(({ cache, props, values }) => ({membersResponse: [@@ -163,28 +239,32 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([{loadMembers: async (_ = null, breakpoint) => {if (cache.euMembers) {- return paginateMembers(cache.euMembers, values.page, values.searchTerm)+ return paginateMembers(cache.euMembers, values.page, values.query)}try {const search = values.searchTerm.trim()+ const levels = values.levels.join(',')const response = await api.organizationMembers.listForOrg(props.externalId, {limit: PAGE_SIZE,offset: (values.page - 1) * PAGE_SIZE,...(search ? { search } : {}),+ ...(levels ? { levels } : {}),+ ...(values.sorting ? { ordering: sortingToOrdering(values.sorting) } : {}),})breakpoint()if (response.count > 0) {+ cache.isUsOrg = truereturn {...response,results: response.results.map((member) => ({ ...member, region: Region.US })),}}- if (!search) {+ if (!cache.isUsOrg) {const euMembers = await fetchEuMembers(props.externalId)breakpoint()if (euMembers?.length) {cache.euMembers = euMembers- return paginateMembers(euMembers, values.page, values.searchTerm)+ return paginateMembers(euMembers, values.page, values.query)}}return { ...response, results: [] }@@ -211,6 +291,17 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([query_length: searchTerm.trim().length,})},+ setLevels: ({ levels }) => {+ actions.loadMembers()+ posthog.capture(AccountsEvents.RelatedUsersFiltered, { levels })+ },+ setSorting: ({ sorting }) => {+ actions.loadMembers()+ posthog.capture(AccountsEvents.RelatedUsersSorted, {+ column: (sorting?.columnKey as RelatedUsersSortKey | undefined) ?? null,+ direction: sorting ? (sorting.order === -1 ? 'desc' : 'asc') : 'cleared',+ })+ },})),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 8faf31f14344..10f03b62f778 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -56,6 +56,8 @@ export const AccountsEvents = {UsageSeriesBulkToggled: 'customer analytics account usage series bulk toggled',RelatedUserClicked: 'customer analytics account related user clicked',RelatedUsersSearched: 'customer analytics account related users searched',+ RelatedUsersFiltered: 'customer analytics account related users filtered',+ RelatedUsersSorted: 'customer analytics account related users sorted',RelatedUserAdminOpened: 'customer analytics account related user admin opened',OpportunityClicked: 'customer analytics account opportunity clicked',SummaryCadenceChanged: 'customer analytics account summary cadence changed',diff --git a/products/customer_analytics/frontend/components/columnValueFilter.test.tsx b/products/customer_analytics/frontend/components/columnValueFilter.test.tsxnew file mode 100644index 000000000000..a6c108d82e15--- /dev/null+++ b/products/customer_analytics/frontend/components/columnValueFilter.test.tsx@@ -0,0 +1,31 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { columnValueFilter } from './columnValueFilter'++describe('columnValueFilter', () => {+ afterEach(() => cleanup())++ const options = [+ { value: 'owner', label: 'Owner' },+ { value: 'admin', label: 'Admin' },+ { value: 'member', label: 'Member' },+ ]++ it('reports the selection count and toggles values in option order', async () => {+ const onChange = jest.fn()+ const column = columnValueFilter<Record<string, any>, string>({ options, selected: ['member'], onChange })++ expect(column.moreFilterCount).toBe(1)+ render(<>{column.more}</>)++ await userEvent.click(screen.getByText('Owner'))+ // Owner is listed before Member, so it lands first regardless of click order.+ expect(onChange).toHaveBeenLastCalledWith(['owner', 'member'])++ await userEvent.click(screen.getByText('Member'))+ expect(onChange).toHaveBeenLastCalledWith([])+ })+})diff --git a/products/customer_analytics/frontend/components/columnValueFilter.tsx b/products/customer_analytics/frontend/components/columnValueFilter.tsxnew file mode 100644index 000000000000..55bf9120cee0--- /dev/null+++ b/products/customer_analytics/frontend/components/columnValueFilter.tsx@@ -0,0 +1,63 @@+import { IconFilter } from '@posthog/icons'+import { LemonCheckbox, LemonMenuItems, LemonMenuOverlay, LemonTableColumn } from '@posthog/lemon-ui'++export interface ColumnValueFilterOption<V> {+ value: V+ label: string+}++export interface ColumnValueFilterProps<V> {+ /** Section heading inside the menu, e.g. "Show only". */+ title?: string+ /** The full set of values the column can take, in the order to list them. */+ options: ColumnValueFilterOption<V>[]+ /** Currently selected values. Empty means "no filter". */+ selected: V[]+ onChange: (selected: V[]) => void+ 'data-attr'?: string+}++function ColumnValueFilterOverlay<V>({+ title = 'Show only',+ options,+ selected,+ onChange,+ 'data-attr': dataAttr,+}: ColumnValueFilterProps<V>): JSX.Element {+ const items: LemonMenuItems = [+ {+ title,+ items: options.map((option) => ({+ icon: <LemonCheckbox checked={selected.includes(option.value)} className="pointer-events-none" />,+ label: option.label,+ 'data-attr': dataAttr,+ onClick: () =>+ onChange(+ selected.includes(option.value)+ ? selected.filter((value) => value !== option.value)+ : options+ .map(({ value }) => value)+ .filter((value) => selected.includes(value) || value === option.value)+ ),+ })),+ },+ ]+ return <LemonMenuOverlay items={items} />+}++/**+ * Header-menu filter for a categorical LemonTable column: a filter icon in the column title that opens+ * a checkbox list of the column's possible values, with a badge showing how many are selected.+ *+ * Spread the result into the column definition. Filtering itself stays with the caller (server-side+ * or client-side), this only owns the header UI, so any table with an enumerated column can reuse it.+ */+export function columnValueFilter<T extends Record<string, any>, V>(+ props: ColumnValueFilterProps<V>+): Pick<LemonTableColumn<T, keyof T | undefined>, 'more' | 'moreIcon' | 'moreFilterCount'> {+ return {+ more: <ColumnValueFilterOverlay {...props} />,+ moreIcon: <IconFilter />,+ moreFilterCount: props.selected.length,+ }+}