: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): accounts list UI (#59627)
Arthur Moreira de Deus18a626a623de
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5bb9f1e96d44..fa1a8cf6c212 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3914,6 +3914,18 @@ snapshots:hash: v1.k794b7964.7cc999f3110d9405931cc753d05915fda71cb29c8a90a2193b3ae31a3926f499.9G89dEXlEiukTuz2fdGpLNvl1b3_0ay3YbJYoHXbeWUscenes-app-batchexports--runs-with-data--light:hash: v1.k794b7964.16d41760315438545fd73de3be17f86a448d610c5de8c83080846df46160adad.pN4E8_VwUHnjkEPT3vBTdgvE5VYwsxKnDC3b6SpOqU8+ scenes-app-customer-analytics-accounts--default--dark:+ hash: v1.k794b7964.13930dddceb89d7e58360ee17b6a91689ae230d8a9e577fbc73885cdbf8ed288.E9XTd8lmS5bzaKx68L300cwx7jgPF_6FZchcZBiDKbg+ scenes-app-customer-analytics-accounts--default--light:+ hash: v1.k794b7964.aa275d1c9d782e7e983a188b54b714d1b8fb0a78860f34489afba54c87688bb4.UaRjVun1d_9vgIQcyHAyPou_TG4RB5UkzSnl4f8aICY+ scenes-app-customer-analytics-accounts--empty--dark:+ hash: v1.k794b7964.0e77ed387ddfc5a021fd92663c321af1c35ca7809d8b10f9e21cbc5aadbdb9f5.Rq9FZCQ18F5gG7yUjMbsn_A1MP3TcX50xKuHoPIzDbc+ scenes-app-customer-analytics-accounts--empty--light:+ hash: v1.k794b7964.54ff7564100ba487dcec1e83b2e38d447bfad4bd6f4bdd51511a00524d97b4fd.D4_qg1kISkcJR3-ePoQSBOc66Xy9Y1Pf-qj4EW2GZAg+ scenes-app-customer-analytics-accounts--feature-gate-off--dark:+ hash: v1.k794b7964.ee8ffba2752bee9a1d3168353fece49f3346aa3b003aa1264eba29927f810dca.uTwzaJktdzjCWjjfJX7f_CQJsFSS5OswqcCi6X4uMpA+ scenes-app-customer-analytics-accounts--feature-gate-off--light:+ hash: v1.k794b7964.b7b6a05e00f979a0f05cda466ce264aaba64bf27dfa98a667d356b4f092e5ff3.Jzxc53MjPbkqmhCl0Yi8GH1-ztkZPZL7-9G5JsefCgIscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--dark:hash: v1.k794b7964.b1e7b3b4db44122983952ce49cdcb2721216d6e09cdda2e03d88250a66f9531d.XEmKGVDBb7ph1xN1zMKNGWDQAkJPR509WPM2orhsrZoscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--light:@@ -4581,7 +4593,7 @@ snapshots:scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--dark:hash: v1.k794b7964.e37d1addf9a1b24963872de93f7ffdd30084f8a3a4c2d8dde83008de73ae7bdd.OfE7OfHSRIRo7NJfsJdlxt9UOoYoB1WHd-JKL97AWNsscenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--light:- hash: v1.k794b7964.b064f0872c3d2f28a37fc2e35d6df7b343068dbb76e001be1262ec621a716f0b.a87F7-yuvANU_xqociPIyIrGhNxULwoky2YkPc0UI-c+ hash: v1.k794b7964.1a564a7e326dd6ce74422aeec8cc336763529a54aac381e2c3039c950f73e0b9.pQOeGG7_eD40sEsh7BApyC7wiUAQx9-TXPHrzC_seWIscenes-app-insights-funnels--funnel-time-to-convert--dark:hash: v1.k794b7964.d64808d2bfc36017f89b57feeaa373e20188738a622801207fa1beb59d02fdd9.cFuKF_Ow887Z3X3BoNhtTvkUWY2vips9HDBe-B02eQEscenes-app-insights-funnels--funnel-time-to-convert--light:@@ -4609,7 +4621,7 @@ snapshots:scenes-app-insights-funnels--funnel-with-inline-events-edit--dark:hash: v1.k794b7964.3b7b5f9590d162bbe6f2e9c980281218985542e069bdaa62881134a0bcd9fe98.Z2CxEngtWWGcwOMrnGVOSX7a8FL1Qh9znhaktn5CAmUscenes-app-insights-funnels--funnel-with-inline-events-edit--light:- hash: v1.k794b7964.1c7d2d59e5b8bbf66576d32edc0143491917e8727df5208392cfb7afe9d0b5cc.VuGrwvXftddRxmYzQ6Y1rmCIbA0fJQZltACO8j10KkA+ hash: v1.k794b7964.ef2a683a9034e167ca35da73c09cfc46aca4b4cc7474a65fdbf62ba30c117f0f.cMd53yhvyE1YHaNA9k0Ky4KtCVG09l0YwHylbqYbhgEscenes-app-insights-insight-quick-start--default--dark:hash: v1.k794b7964.e91e85b0ee937a14ef9bc524a1b98568c55a38eafdff6415d46c0e27f04a0771.LUZPkOS3UjH82ME39wve3LwP9FipEC-HrNVr6Ag8t84scenes-app-insights-insight-quick-start--default--light:diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex d423127cb05c..a65e8b6b9dc6 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -158,6 +158,7 @@ export const productRoutes: Record<string, [string, string]> = {'/support/tickets/:ticketId': ['SupportTicketDetail', 'supportTicketDetail'],'/support/settings': ['SupportSettings', 'supportSettings'],'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],+ '/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],'/customer_analytics/journeys/templates': ['CustomerJourneyTemplates', 'customerJourneyTemplates'],'/customer_analytics/journeys/:id/edit': ['CustomerJourneyBuilder', 'customerJourneyEdit'],@@ -776,6 +777,7 @@ export const productUrls = {supportSettings: (): string => '/support/settings',customerAnalytics: (): string => '/customer_analytics',customerAnalyticsDashboard: (): string => '/customer_analytics/dashboard',+ customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',customerAnalyticsConfiguration: (): string => '/customer_analytics/configuration',customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',diff --git a/products/customer_analytics/backend/api/test_views.py b/products/customer_analytics/backend/api/test_views.pyindex ebc1f1c4516c..7345f3aa9d49 100644--- a/products/customer_analytics/backend/api/test_views.py+++ b/products/customer_analytics/backend/api/test_views.py@@ -4,6 +4,7 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterizedfrom rest_framework import status+from posthog.api.tagged_item import set_tags_on_objectfrom posthog.constants import AvailableFeaturefrom posthog.models import Insight, Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -792,6 +793,136 @@ class TestAccountViewSet(APIBaseTest):new_logs = ActivityLog.objects.filter(team_id=self.team.id, scope="Account", activity="updated").count()self.assertGreater(new_logs, initial_logs)+ def test_list_accounts_filter_by_csm_user_id(self):+ self._create_account(name="A", _properties={"csm": {"id": 7, "email": "[email protected]"}})+ self._create_account(name="B", _properties={"csm": {"id": 9, "email": "[email protected]"}})+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?csm=7")+ names = [r["name"] for r in response.json()["results"]]+ assert names == ["A"]++ @parameterized.expand(+ [+ # `_properties` defaults to {} — every role key is absent.+ ("absent_keys", {"_properties": {}}),+ # The manager fills every role key with an explicit JSON null.+ ("null_valued_keys", {"properties": {}}),+ ]+ )+ def test_list_accounts_filter_by_csm_unassigned(self, _name, unassigned_kwargs):+ self._create_account(name="Assigned", properties={"csm": {"id": 7, "email": "[email protected]"}})+ self._create_account(name="Unassigned", **unassigned_kwargs)+ response = self.client.get(f"{self.endpoint_base}?csm=unassigned")+ assert [r["name"] for r in response.json()["results"]] == ["Unassigned"]++ def test_list_accounts_filter_by_account_executive_user_id(self):+ self._create_account(name="A", _properties={"account_executive": {"id": 7, "email": "[email protected]"}})+ self._create_account(name="B")+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?account_executive=7")+ assert [r["name"] for r in response.json()["results"]] == ["A"]++ def test_list_accounts_filter_by_account_owner_user_id(self):+ self._create_account(name="A", _properties={"account_owner": {"id": 7, "email": "[email protected]"}})+ self._create_account(name="B")+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?account_owner=7")+ assert [r["name"] for r in response.json()["results"]] == ["A"]++ @parameterized.expand(+ [+ # `_properties` defaults to {} — every role key is absent.+ ("absent_keys", {"_properties": {}}),+ # The manager fills every role key with an explicit JSON null.+ ("null_valued_keys", {"properties": {}}),+ ]+ )+ def test_list_accounts_filter_all_roles_unassigned(self, _name, unassigned_kwargs):+ # Created through the manager, so every role key is present and csm has a real id.+ self._create_account(name="Has CSM", properties={"csm": {"id": 7, "email": "[email protected]"}})+ self._create_account(name="Unassigned", **unassigned_kwargs)+ response = self.client.get(f"{self.endpoint_base}?all_roles_unassigned=true")+ assert [r["name"] for r in response.json()["results"]] == ["Unassigned"]++ def test_list_accounts_filter_combined_role_and_tags(self):+ account_a = self._create_account(name="A", _properties={"csm": {"id": 7, "email": "[email protected]"}})+ account_b = self._create_account(name="B", _properties={"csm": {"id": 7, "email": "[email protected]"}})+ account_c = self._create_account(name="C", _properties={"csm": {"id": 8, "email": "[email protected]"}})+ set_tags_on_object(["enterprise"], account_a)+ set_tags_on_object(["startup"], account_b)+ set_tags_on_object(["enterprise"], account_c)+ response = self.client.get(f'/api/environments/{self.team.id}/accounts/?csm=7&tags=["enterprise"]')+ assert [r["name"] for r in response.json()["results"]] == ["A"]++ def test_list_accounts_invalid_csm_value_is_ignored(self):+ # Malformed user id should be a no-op (return both accounts), not "match nothing".+ self._create_account(name="A")+ self._create_account(name="B", _properties={"csm": {"id": 7, "email": "[email protected]"}})+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?csm=not-a-user")+ assert response.status_code == status.HTTP_200_OK+ names = sorted(r["name"] for r in response.json()["results"])+ assert names == ["A", "B"]++ def test_list_accounts_ordering_by_name_asc(self):+ # Create in alphabetical order so default `-created_at` order is [Banana, Apple];+ # ordering=name only matches if the filter actually flips the order.+ self._create_account(name="Apple")+ self._create_account(name="Banana")+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?ordering=name")+ assert [r["name"] for r in response.json()["results"]] == ["Apple", "Banana"]++ def test_list_accounts_ordering_by_name_desc(self):+ # Default `-created_at` order would be [Apple, Banana]; ordering=-name flips to [Banana, Apple].+ self._create_account(name="Banana")+ self._create_account(name="Apple")+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?ordering=-name")+ assert [r["name"] for r in response.json()["results"]] == ["Banana", "Apple"]++ def test_list_accounts_invalid_ordering_is_ignored(self):+ # Malformed ordering should fall back to default `-created_at` order.+ self._create_account(name="Apple")+ self._create_account(name="Banana")+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?ordering=robert');drop")+ assert response.status_code == status.HTTP_200_OK+ assert [r["name"] for r in response.json()["results"]] == ["Banana", "Apple"]++ @parameterized.expand(+ [+ ("name_exact", "Acme Corp", ["Acme Corp"]),+ ("name_partial_case_insensitive", "acme", ["Acme Corp"]),+ ("external_id_partial", "glx-9", ["Globex"]),+ ("matches_name_or_external_id", "1", ["Acme Corp"]),+ ("no_match", "zzzz", []),+ ]+ )+ def test_list_accounts_search(self, _name, search, expected):+ self._create_account(name="Acme Corp", external_id="acme-1")+ self._create_account(name="Globex", external_id="glx-99")+ response = self.client.get(f"{self.endpoint_base}?search={search}")+ assert response.status_code == status.HTTP_200_OK+ assert sorted(r["name"] for r in response.json()["results"]) == sorted(expected)++ def test_list_accounts_blank_search_returns_all(self):+ self._create_account(name="Acme Corp")+ self._create_account(name="Globex")+ response = self.client.get(f"{self.endpoint_base}?search=")+ assert sorted(r["name"] for r in response.json()["results"]) == ["Acme Corp", "Globex"]++ def test_list_accounts_search_respects_team_isolation(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ self._create_account(team=other_team, name="Acme Corp")+ self._create_account(name="Acme Corp")+ response = self.client.get(f"{self.endpoint_base}?search=acme")+ assert len(response.json()["results"]) == 1++ def test_list_accounts_role_filter_respects_team_isolation(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ self._create_account(+ team=other_team,+ name="OtherTeamAccount",+ _properties={"csm": {"id": 7, "email": "[email protected]"}},+ )+ self._create_account(name="MyAccount", _properties={"csm": {"id": 7, "email": "[email protected]"}})+ response = self.client.get(f"/api/environments/{self.team.id}/accounts/?csm=7")+ assert [r["name"] for r in response.json()["results"]] == ["MyAccount"]+@pytest.mark.eeclass TestCustomerAnalyticsAccessControl(APIBaseTest):diff --git a/products/customer_analytics/backend/api/views.py b/products/customer_analytics/backend/api/views.pyindex b0fb52035a99..bbfa21ccae8b 100644--- a/products/customer_analytics/backend/api/views.py+++ b/products/customer_analytics/backend/api/views.py@@ -1,5 +1,7 @@import json+from django.db.models import Q+from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schemafrom rest_framework import viewsets@@ -69,8 +71,17 @@ class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContrserializer_class = AccountSerializerbulk_update_tags = None # Mixin action assumes integer PKs; Account uses UUIDs.+ ALLOWED_ORDERING = frozenset({"name", "-name", "created_at", "-created_at", "updated_at", "-updated_at"})+@extend_schema(parameters=[+ OpenApiParameter(+ name="search",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Case-insensitive substring search across account name and external ID.",+ ),OpenApiParameter(name="tags",type=OpenApiTypes.STR,@@ -81,6 +92,44 @@ class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContr"Returns accounts that have any of the listed tags."),),+ OpenApiParameter(+ name="csm",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description=("Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id."),+ ),+ OpenApiParameter(+ name="account_executive",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by account executive. Use 'unassigned' or an integer user id.",+ ),+ OpenApiParameter(+ name="account_owner",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by account owner. Use 'unassigned' or an integer user id.",+ ),+ OpenApiParameter(+ name="all_roles_unassigned",+ type=OpenApiTypes.BOOL,+ location=OpenApiParameter.QUERY,+ required=False,+ description=(+ "When true, returns only accounts where CSM, account executive, and account owner are all unset."+ ),+ ),+ OpenApiParameter(+ name="ordering",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ enum=["name", "-name", "created_at", "-created_at", "updated_at", "-updated_at"],+ description="Sort order. Defaults to '-created_at'.",+ ),],)def list(self, request, *args, **kwargs):@@ -89,14 +138,59 @@ class AccountViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContrdef safely_get_queryset(self, queryset):queryset = queryset.filter(team_id=self.team.id)+ search = self.request.query_params.get("search", "").strip()+ if search:+ queryset = queryset.filter(Q(name__icontains=search) | Q(external_id__icontains=search))+tags_param = self.request.query_params.get("tags")if tags_param:try:tags_list = json.loads(tags_param)+ if isinstance(tags_list, list) and tags_list:+ queryset = queryset.filter(tagged_items__tag__name__in=tags_list).distinct()except json.JSONDecodeError:- return queryset- if isinstance(tags_list, list) and tags_list:- queryset = queryset.filter(tagged_items__tag__name__in=tags_list).distinct()+ pass++ # An unset role is serialized as JSON null, which `_properties__role__isnull`+ # does not match; probing the nested `id` matches every unassigned+ # representation (missing key, null value, or empty object).+ if self.request.query_params.get("all_roles_unassigned", "").lower() == "true":+ queryset = queryset.filter(+ _properties__csm__id__isnull=True,+ _properties__account_executive__id__isnull=True,+ _properties__account_owner__id__isnull=True,+ )++ csm_value = self.request.query_params.get("csm")+ if csm_value == "unassigned":+ queryset = queryset.filter(_properties__csm__id__isnull=True)+ elif csm_value:+ try:+ queryset = queryset.filter(_properties__csm__id=int(csm_value))+ except ValueError:+ pass++ ae_value = self.request.query_params.get("account_executive")+ if ae_value == "unassigned":+ queryset = queryset.filter(_properties__account_executive__id__isnull=True)+ elif ae_value:+ try:+ queryset = queryset.filter(_properties__account_executive__id=int(ae_value))+ except ValueError:+ pass++ owner_value = self.request.query_params.get("account_owner")+ if owner_value == "unassigned":+ queryset = queryset.filter(_properties__account_owner__id__isnull=True)+ elif owner_value:+ try:+ queryset = queryset.filter(_properties__account_owner__id=int(owner_value))+ except ValueError:+ pass++ ordering = self.request.query_params.get("ordering")+ if ordering in self.ALLOWED_ORDERING:+ queryset = queryset.order_by(ordering)return querysetdiff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.pyindex 7f8e9d7c8ad0..8f40acddc858 100644--- a/products/customer_analytics/backend/models/account.py+++ b/products/customer_analytics/backend/models/account.py@@ -90,7 +90,7 @@ def _enforce_account_group_type_index_drift_policy(sender, instance, **kwargs) -returnprevious = sender.objects.filter(pk=instance.pk).values_list("account_group_type_index", flat=True).first()- if previous == instance.account_group_type_index:+ if previous is None or previous == instance.account_group_type_index:returnAccountModel = apps.get_model("customer_analytics", "Account")diff --git a/products/customer_analytics/backend/models/account_test.py b/products/customer_analytics/backend/models/account_test.pyindex 6a1a4615904c..2d7f6f326bca 100644--- a/products/customer_analytics/backend/models/account_test.py+++ b/products/customer_analytics/backend/models/account_test.py@@ -6,6 +6,7 @@ from posthog.test.base import BaseTestfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import IntegrityError, transaction+from parameterized import parameterizedfrom pydantic import ValidationError as PydanticValidationErrorfrom posthog.models import Team, User@@ -96,19 +97,30 @@ class TeamCustomerAnalyticsConfigDriftPolicyTest(_AccountTeamScopedTestMixin, Badef setUp(self):super().setUp()self.config = TeamCustomerAnalyticsConfig.objects.get(team=self.team)- self.config.account_group_type_index = 0- self.config.save()- def test_drift_blocked_when_accounts_exist(self):- Account.objects.create(team=self.team, name="Existing")+ @parameterized.expand(+ [+ # Changing an already-set index while accounts exist is drift, and is blocked.+ ("drift_blocked_when_accounts_exist", 0, True, 1, True),+ # Changing the index is harmless, and allowed, while no accounts exist.+ ("drift_allowed_when_no_accounts_exist", 0, False, 1, False),+ # Setting the index for the first time (it was never set) is not drift,+ # so it is allowed even when accounts already exist.+ ("first_time_set_allowed_when_accounts_exist", None, True, 2, False),+ ]+ )+ def test_account_group_type_index_drift_policy(self, _name, initial_index, create_account, new_index, should_block):+ # `update()` skips the pre_save signal, so the policy does not fire on the fixture itself.+ TeamCustomerAnalyticsConfig.objects.filter(pk=self.config.pk).update(account_group_type_index=initial_index)+ if create_account:+ Account.objects.create(team=self.team, name="Existing")+ self.config.refresh_from_db()- self.config.account_group_type_index = 1- with pytest.raises(DjangoValidationError):+ self.config.account_group_type_index = new_index+ if should_block:+ with pytest.raises(DjangoValidationError):+ self.config.save()+ else:self.config.save()-- def test_drift_allowed_when_no_accounts_exist(self):- self.config.account_group_type_index = 1- self.config.save()-- self.config.refresh_from_db()- assert self.config.account_group_type_index == 1+ self.config.refresh_from_db()+ assert self.config.account_group_type_index == new_indexdiff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsxindex 6cd34c3ce66c..29d9c95ac5f8 100644--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx@@ -6,6 +6,7 @@ import { LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'+import { NotFound } from 'lib/components/NotFound'import { FEATURE_FLAGS } from 'lib/constants'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'@@ -27,6 +28,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { SessionInsights } from 'products/customer_analytics/frontend/components/Insights/SessionInsights'+import { AccountsTabContent } from './components/Accounts/AccountsTabContent'import { CustomerJourneys } from './components/CustomerJourneys/CustomerJourneys'import { CustomerJourneySelect } from './components/CustomerJourneys/CustomerJourneySelect'import { customerJourneysLogic } from './components/CustomerJourneys/customerJourneysLogic'@@ -79,6 +81,12 @@ function CustomerAnalyticsSceneContent({ tabId }: { tabId?: string }): JSX.ElemereportCustomerAnalyticsViewed()})+ // Accounts is gated by CUSTOMER_ANALYTICS_CSP; without it the tab does not+ // exist, so a guessed `/customer_analytics/accounts` URL is a 404.+ if (activeTab === 'accounts' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {+ return <NotFound object="page" />+ }+const dashboardContent =businessType === 'b2b' && shouldShowGroupsIntroduction ? (<>@@ -96,14 +104,23 @@ function CustomerAnalyticsSceneContent({ tabId }: { tabId?: string }): JSX.Eleme</>)- const tabs: LemonTab<string>[] = [- {- key: 'dashboard',- label: 'Dashboard',- content: dashboardContent,- link: combineUrl(urls.customerAnalyticsDashboard(), searchParams).url,- },- ]+ const tabs: LemonTab<string>[] = []++ if (featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {+ tabs.push({+ key: 'accounts',+ label: 'Accounts',+ content: <AccountsTabContent />,+ link: combineUrl(urls.customerAnalyticsAccounts(), searchParams).url,+ })+ }++ tabs.push({+ key: 'dashboard',+ label: 'Dashboard',+ content: dashboardContent,+ link: combineUrl(urls.customerAnalyticsDashboard(), searchParams).url,+ })if (featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_JOURNEYS]) {tabs.push({@@ -114,6 +131,13 @@ function CustomerAnalyticsSceneContent({ tabId }: { tabId?: string }): JSX.Eleme})}+ const tabsContent =+ tabs.length > 1 ? (+ <LemonTabs activeKey={activeTab} data-attr="customer-analytics-tabs" tabs={tabs} sceneInset />+ ) : (+ dashboardContent+ )+return (<BindLogic logic={dataNodeCollectionLogic} props={{ key: CUSTOMER_ANALYTICS_DATA_COLLECTION_NODE_ID }}><SceneContent>@@ -183,7 +207,11 @@ function CustomerAnalyticsSceneContent({ tabId }: { tabId?: string }): JSX.Elemeicon={<IconGear />}size="small"type="secondary"- to={urls.customerAnalyticsConfiguration()}+ to={+ activeTab === 'accounts'+ ? `${urls.customerAnalyticsConfiguration()}?tab=customer-analytics-accounts`+ : urls.customerAnalyticsConfiguration()+ }onClick={() => {addProductIntent({product_type: ProductKey.CUSTOMER_ANALYTICS,@@ -201,11 +229,7 @@ function CustomerAnalyticsSceneContent({ tabId }: { tabId?: string }): JSX.Eleme</>}/>- {tabs.length > 1 ? (- <LemonTabs activeKey={activeTab} data-attr="customer-analytics-tabs" tabs={tabs} sceneInset />- ) : (- dashboardContent- )}+ {tabsContent}</SceneContent></BindLogic>)diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxnew file mode 100644index 000000000000..7873af13ca60--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -0,0 +1,105 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++const ACCOUNTS_ENDPOINT = 'api/environments/:team_id/accounts/'++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Customer Analytics/Accounts',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-05-21',+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS, FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP],+ pageUrl: urls.customerAnalyticsAccounts(),+ testOptions: {+ waitForSelector: '[data-attr="accounts-refresh"]',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ [ACCOUNTS_ENDPOINT]: {+ count: 3,+ next: null,+ previous: null,+ results: [+ {+ id: 'acc-1',+ name: 'Acme Inc',+ external_id: 'cust_acme_001',+ properties: {+ csm: { id: 1, email: '[email protected]' },+ account_executive: { id: 2, email: '[email protected]' },+ account_owner: null,+ },+ tags: ['enterprise', 'priority'],+ created_at: '2026-05-01T00:00:00Z',+ created_by: 1,+ updated_at: '2026-05-20T00:00:00Z',+ },+ {+ id: 'acc-2',+ name: 'Globex',+ external_id: 'cust_globex_002',+ properties: {},+ tags: [],+ created_at: '2026-05-02T00:00:00Z',+ created_by: 1,+ updated_at: '2026-05-19T00:00:00Z',+ },+ {+ id: 'acc-3',+ name: 'Hooli',+ external_id: null,+ properties: {+ csm: { id: 1, email: '[email protected]' },+ account_executive: null,+ account_owner: { id: 3, email: '[email protected]' },+ },+ tags: ['scaleup'],+ created_at: '2026-05-03T00:00:00Z',+ created_by: 1,+ updated_at: '2026-05-18T00:00:00Z',+ },+ ],+ },+ },+ }),+ ],+}+export default meta++type Story = StoryObj<{}>++export const Default: Story = {+ render: () => <App />,+}++export const Empty: Story = {+ render: () => <App />,+ decorators: [+ mswDecorator({+ get: {+ [ACCOUNTS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ },+ }),+ ],+}++// CUSTOMER_ANALYTICS must stay enabled (the outer scene gate) so we get past it;+// without CUSTOMER_ANALYTICS_CSP the accounts URL is treated as a 404.+export const FeatureGateOff: Story = {+ render: () => <App />,+ parameters: {+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS],+ testOptions: {+ waitForSelector: '[data-attr="not-found-page"]',+ },+ },+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsxnew file mode 100644index 000000000000..ed53f9f2eb2f--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx@@ -0,0 +1,11 @@+import { AccountsTabFilters } from './AccountsTabFilters'+import { AccountsTable } from './AccountsTable'++export function AccountsTabContent(): JSX.Element {+ return (+ <div className="flex flex-col gap-3">+ <AccountsTabFilters />+ <AccountsTable />+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsxnew file mode 100644index 000000000000..f1a8336a355f--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx@@ -0,0 +1,137 @@+import { useActions, useValues } from 'kea'++import { IconChevronDown, IconRefresh, IconX } from '@posthog/icons'+import { LemonButton, LemonCheckbox, LemonDropdown, LemonInput, LemonInputSelect } from '@posthog/lemon-ui'++import { MemberSelect } from 'lib/components/MemberSelect'++import { tagsModel } from '~/models/tagsModel'++import { accountsLogic, RoleFilterValue } from './accountsLogic'++export function AccountsTabFilters(): JSX.Element {+ const {+ searchQuery,+ tagsFilter,+ allRolesUnassigned,+ csmFilter,+ accountExecutiveFilter,+ accountOwnerFilter,+ accountsLoading,+ } = useValues(accountsLogic)+ const {+ setSearchQuery,+ setTagsFilter,+ setAllRolesUnassigned,+ setCsmFilter,+ setAccountExecutiveFilter,+ setAccountOwnerFilter,+ refresh,+ } = useActions(accountsLogic)+ const { tags: tagsAvailable } = useValues(tagsModel)++ const tagsButtonLabel =+ tagsFilter.length === 0 ? 'All tags' : tagsFilter.length === 1 ? tagsFilter[0] : `${tagsFilter.length} tags`++ return (+ <div className="flex flex-wrap gap-3 items-center">+ <LemonInput+ type="search"+ placeholder="Search by name or ID..."+ value={searchQuery}+ onChange={setSearchQuery}+ size="small"+ className="min-w-64"+ data-attr="accounts-search"+ />+ <LemonDropdown+ closeOnClickInside={false}+ overlay={+ <div className="p-2 min-w-64">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={tagsFilter}+ options={(tagsAvailable || []).map((t: string) => ({ key: t, label: t }))}+ onChange={setTagsFilter}+ placeholder="Select or type tags..."+ data-attr="accounts-tags-filter"+ />+ </div>+ }+ >+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>+ {tagsButtonLabel}+ </LemonButton>+ </LemonDropdown>+ {tagsFilter.length > 0 && (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconX />}+ onClick={() => setTagsFilter([])}+ tooltip="Clear tag filter"+ />+ )}++ <RolePicker label="CSM" value={csmFilter} onChange={setCsmFilter} dataAttr="accounts-csm-filter" />+ <RolePicker+ label="AE"+ value={accountExecutiveFilter}+ onChange={setAccountExecutiveFilter}+ dataAttr="accounts-ae-filter"+ />+ <RolePicker+ label="Owner"+ value={accountOwnerFilter}+ onChange={setAccountOwnerFilter}+ dataAttr="accounts-owner-filter"+ />+ <LemonCheckbox+ checked={allRolesUnassigned}+ onChange={setAllRolesUnassigned}+ label="Unassigned only"+ disabledReason={accountsLoading ? 'Loading…' : undefined}+ data-attr="accounts-unassigned-filter"+ />++ <div className="ml-auto">+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ loading={accountsLoading}+ disabledReason={accountsLoading ? 'Loading…' : undefined}+ onClick={refresh}+ size="small"+ data-attr="accounts-refresh"+ >+ Refresh+ </LemonButton>+ </div>+ </div>+ )+}++function RolePicker({+ label,+ value,+ onChange,+ dataAttr,+}: {+ label: string+ value: RoleFilterValue+ onChange: (value: RoleFilterValue) => void+ dataAttr: string+}): JSX.Element {+ return (+ <div data-attr={dataAttr}>+ <MemberSelect+ size="small"+ type="secondary"+ defaultLabel={`Any ${label}`}+ value={value}+ onChange={(user) => onChange(user ? user.id : null)}+ />+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsxnew file mode 100644index 000000000000..a21499a3ef38--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx@@ -0,0 +1,94 @@+import { useActions, useValues } from 'kea'++import { LemonTable, LemonTableColumns, ProfilePicture } from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+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'++type AccountAssignment = { id: number; email: string } | null++export function AccountsTable(): JSX.Element {+ const { results, totalCount, accountsLoading, currentPage } = useValues(accountsLogic)+ const { setCurrentPage } = useActions(accountsLogic)++ const columns: LemonTableColumns<AccountApi> = [+ {+ title: 'Account',+ key: 'name',+ dataIndex: 'name',+ render: (_, account) => (+ <div className="flex flex-col min-w-40">+ <span className="font-medium">{account.name}</span>+ {account.external_id ? (+ <CopyToClipboardInline+ explicitValue={account.external_id}+ iconStyle={{ color: 'var(--color-accent)' }}+ description="account ID"+ >+ {account.external_id}+ </CopyToClipboardInline>+ ) : null}+ </div>+ ),+ },+ {+ title: 'Tags',+ key: 'tags',+ dataIndex: 'tags',+ render: (_, account) =>+ account.tags && account.tags.length > 0 ? (+ <ObjectTags tags={account.tags} staticOnly />+ ) : (+ <span className="text-muted">—</span>+ ),+ },+ {+ title: 'CSM',+ key: 'csm',+ render: (_, account) => <AssigneeCell assignment={account.properties?.csm ?? null} />,+ },+ {+ title: 'Account executive',+ key: 'account_executive',+ render: (_, account) => <AssigneeCell assignment={account.properties?.account_executive ?? null} />,+ },+ {+ title: 'Account owner',+ key: 'account_owner',+ render: (_, account) => <AssigneeCell assignment={account.properties?.account_owner ?? null} />,+ },+ ]++ return (+ <LemonTable<AccountApi>+ dataSource={results}+ rowKey="id"+ loading={accountsLoading}+ columns={columns}+ pagination={{+ controlled: true,+ currentPage,+ pageSize: ACCOUNTS_PAGE_SIZE,+ entryCount: totalCount,+ onBackward: () => setCurrentPage(Math.max(1, currentPage - 1)),+ onForward: () => setCurrentPage(currentPage + 1),+ }}+ />+ )+}++function AssigneeCell({ assignment }: { assignment: AccountAssignment }): JSX.Element {+ if (!assignment) {+ return <span className="text-muted">Unassigned</span>+ }+ return (+ <div className="flex items-center gap-2">+ <ProfilePicture user={{ email: assignment.email }} size="sm" />+ <span className="text-sm">{assignment.email}</span>+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsnew file mode 100644index 000000000000..0248fbea2d45--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -0,0 +1,172 @@+import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { accountsList } from 'products/customer_analytics/frontend/generated/api'++import { ACCOUNTS_PAGE_SIZE, accountsLogic } from './accountsLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ accountsList: jest.fn(),+}))++const mockAccountsList = accountsList as jest.MockedFunction<typeof accountsList>++describe('accountsLogic', () => {+ let logic: ReturnType<typeof accountsLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.resetAllMocks()+ mockAccountsList.mockResolvedValue({+ count: 0,+ next: null,+ previous: null,+ results: [],+ })+ logic = accountsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('starts with empty filters', () => {+ expect(logic.values.searchQuery).toBe('')+ expect(logic.values.tagsFilter).toEqual([])+ expect(logic.values.allRolesUnassigned).toBe(false)+ expect(logic.values.csmFilter).toBeNull()+ expect(logic.values.accountExecutiveFilter).toBeNull()+ expect(logic.values.accountOwnerFilter).toBeNull()+ expect(logic.values.currentPage).toBe(1)+ })++ it('loads accounts on mount with default pagination', async () => {+ await expectLogic(logic).toFinishAllListeners()++ expect(mockAccountsList).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {+ limit: ACCOUNTS_PAGE_SIZE,+ offset: 0,+ })+ })++ it('setTagsFilter updates the reducer and resets to page 1', async () => {+ logic.actions.setCurrentPage(3)+ logic.actions.setTagsFilter(['enterprise'])+ await expectLogic(logic).toMatchValues({+ tagsFilter: ['enterprise'],+ currentPage: 1,+ })+ })++ it('setSearchQuery updates the reducer and resets to page 1', async () => {+ logic.actions.setCurrentPage(3)+ logic.actions.setSearchQuery('acme')+ await expectLogic(logic).toMatchValues({+ searchQuery: 'acme',+ currentPage: 1,+ })+ })++ it('loadAccounts sends a trimmed search param', async () => {+ logic.actions.setSearchQuery(' acme ')+ await expectLogic(logic).toFinishAllListeners()+ expect(mockAccountsList).toHaveBeenLastCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ search: 'acme' })+ )+ })++ it('loadAccounts omits the search param when the query is blank', async () => {+ logic.actions.setSearchQuery(' ')+ await expectLogic(logic).toFinishAllListeners()+ expect(mockAccountsList).toHaveBeenLastCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.not.objectContaining({ search: expect.anything() })+ )+ })++ it('setAllRolesUnassigned toggles the flag', () => {+ logic.actions.setAllRolesUnassigned(true)+ expect(logic.values.allRolesUnassigned).toBe(true)+ })++ it('setCsmFilter accepts a user id and null', () => {+ logic.actions.setCsmFilter(42)+ expect(logic.values.csmFilter).toBe(42)+ logic.actions.setCsmFilter(null)+ expect(logic.values.csmFilter).toBeNull()+ })++ it('loadAccounts sends tags as a JSON-encoded array string', async () => {+ logic.actions.setTagsFilter(['a', 'b'])+ await expectLogic(logic).toFinishAllListeners()++ expect(mockAccountsList).toHaveBeenLastCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ tags: '["a","b"]' })+ )+ })++ it('setting a role filter clears the all_roles_unassigned flag', async () => {+ logic.actions.setAllRolesUnassigned(true)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setCsmFilter(7)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.allRolesUnassigned).toBe(false)+ expect(logic.values.csmFilter).toBe(7)+ expect(mockAccountsList).toHaveBeenLastCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ csm: '7', limit: ACCOUNTS_PAGE_SIZE, offset: 0 })+ )+ expect(mockAccountsList.mock.calls.at(-1)?.[1]).not.toHaveProperty('all_roles_unassigned')+ })++ it('enabling all_roles_unassigned clears any active role filters', async () => {+ logic.actions.setCsmFilter(7)+ logic.actions.setAccountExecutiveFilter(9)+ logic.actions.setAccountOwnerFilter(11)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setAllRolesUnassigned(true)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.allRolesUnassigned).toBe(true)+ expect(logic.values.csmFilter).toBeNull()+ expect(logic.values.accountExecutiveFilter).toBeNull()+ expect(logic.values.accountOwnerFilter).toBeNull()++ const lastParams = mockAccountsList.mock.calls.at(-1)?.[1]+ expect(lastParams).toEqual(+ expect.objectContaining({ all_roles_unassigned: true, limit: ACCOUNTS_PAGE_SIZE, offset: 0 })+ )+ expect(lastParams).not.toHaveProperty('csm')+ expect(lastParams).not.toHaveProperty('account_executive')+ expect(lastParams).not.toHaveProperty('account_owner')+ })++ it('setCurrentPage updates the offset in the next request', async () => {+ logic.actions.setCurrentPage(3)+ await expectLogic(logic).toFinishAllListeners()+ expect(mockAccountsList).toHaveBeenLastCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ limit: ACCOUNTS_PAGE_SIZE, offset: 2 * ACCOUNTS_PAGE_SIZE })+ )+ })++ it('refresh triggers a fresh request with current filters', async () => {+ logic.actions.setTagsFilter(['priority'])+ await expectLogic(logic).toFinishAllListeners()+ mockAccountsList.mockClear()+ logic.actions.refresh()+ await expectLogic(logic).toFinishAllListeners()+ expect(mockAccountsList).toHaveBeenCalledTimes(1)+ expect(mockAccountsList).toHaveBeenLastCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ tags: '["priority"]' })+ )+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsnew file mode 100644index 000000000000..5ad93ccddafe--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -0,0 +1,180 @@+import { actions, afterMount, connect, isBreakpoint, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+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 { accountsLogicType } from './accountsLogicType'++export const ACCOUNTS_PAGE_SIZE = 20++export type RoleFilterValue = number | null++export interface AccountsLoadResult {+ count: number+ results: AccountApi[]+}++const EMPTY_RESULT: AccountsLoadResult = { count: 0, results: [] }++export const accountsLogic = kea<accountsLogicType>([+ path(['scenes', 'customerAnalytics', 'accounts', 'accountsLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),+ actions({+ setSearchQuery: (query: string) => ({ query }),+ setTagsFilter: (tags: string[]) => ({ tags }),+ setAllRolesUnassigned: (value: boolean) => ({ value }),+ setCsmFilter: (value: RoleFilterValue) => ({ value }),+ setAccountExecutiveFilter: (value: RoleFilterValue) => ({ value }),+ setAccountOwnerFilter: (value: RoleFilterValue) => ({ value }),+ setCurrentPage: (page: number) => ({ page }),+ refresh: true,+ }),+ reducers({+ searchQuery: [+ '',+ {+ setSearchQuery: (_, { query }) => query,+ },+ ],+ tagsFilter: [+ [] as string[],+ {+ setTagsFilter: (_, { tags }) => tags,+ },+ ],+ allRolesUnassigned: [+ false,+ {+ setAllRolesUnassigned: (_, { value }) => value,+ },+ ],+ csmFilter: [+ null as RoleFilterValue,+ {+ setCsmFilter: (_, { value }) => value,+ },+ ],+ accountExecutiveFilter: [+ null as RoleFilterValue,+ {+ setAccountExecutiveFilter: (_, { value }) => value,+ },+ ],+ accountOwnerFilter: [+ null as RoleFilterValue,+ {+ setAccountOwnerFilter: (_, { value }) => value,+ },+ ],+ currentPage: [+ 1,+ {+ setCurrentPage: (_, { page }) => page,+ },+ ],+ }),+ loaders(({ values }) => ({+ accounts: [+ EMPTY_RESULT,+ {+ loadAccounts: async (_ = null, breakpoint) => {+ await breakpoint(300)+ const projectId = String(values.currentTeamId)+ const params: Record<string, string | number | boolean> = {+ limit: ACCOUNTS_PAGE_SIZE,+ offset: (values.currentPage - 1) * ACCOUNTS_PAGE_SIZE,+ }+ if (values.searchQuery.trim()) {+ params.search = values.searchQuery.trim()+ }+ if (values.tagsFilter.length > 0) {+ params.tags = JSON.stringify(values.tagsFilter)+ }+ if (values.allRolesUnassigned) {+ params.all_roles_unassigned = true+ }+ if (values.csmFilter !== null) {+ params.csm = String(values.csmFilter)+ }+ if (values.accountExecutiveFilter !== null) {+ params.account_executive = String(values.accountExecutiveFilter)+ }+ if (values.accountOwnerFilter !== null) {+ params.account_owner = String(values.accountOwnerFilter)+ }+ try {+ const response = await accountsList(projectId, params)+ breakpoint()+ return { count: response.count, results: response.results }+ } catch (error) {+ if (!isBreakpoint(error as Error)) {+ posthog.captureException(error as Error, { scope: 'accountsLogic.loadAccounts' })+ lemonToast.error('Failed to load accounts')+ }+ throw error+ }+ },+ },+ ],+ })),+ selectors({+ totalCount: [(s) => [s.accounts], (a: AccountsLoadResult): number => a.count],+ results: [(s) => [s.accounts], (a: AccountsLoadResult): AccountApi[] => a.results],+ }),+ listeners(({ actions, values }) => ({+ setSearchQuery: () => {+ actions.setCurrentPage(1)+ },+ setTagsFilter: () => {+ actions.setCurrentPage(1)+ },+ setAllRolesUnassigned: ({ value }) => {+ if (value) {+ if (values.csmFilter !== null) {+ actions.setCsmFilter(null)+ }+ if (values.accountExecutiveFilter !== null) {+ actions.setAccountExecutiveFilter(null)+ }+ if (values.accountOwnerFilter !== null) {+ actions.setAccountOwnerFilter(null)+ }+ }+ actions.setCurrentPage(1)+ },+ setCsmFilter: ({ value }) => {+ if (value !== null && values.allRolesUnassigned) {+ actions.setAllRolesUnassigned(false)+ }+ actions.setCurrentPage(1)+ },+ setAccountExecutiveFilter: ({ value }) => {+ if (value !== null && values.allRolesUnassigned) {+ actions.setAllRolesUnassigned(false)+ }+ actions.setCurrentPage(1)+ },+ setAccountOwnerFilter: ({ value }) => {+ if (value !== null && values.allRolesUnassigned) {+ actions.setAllRolesUnassigned(false)+ }+ actions.setCurrentPage(1)+ },+ setCurrentPage: () => {+ actions.loadAccounts()+ },+ refresh: () => {+ actions.loadAccounts()+ },+ })),+ afterMount(({ actions }) => {+ actions.loadAccounts()+ }),+])diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.tsindex 06170417dea4..761057a8af68 100644--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts@@ -149,8 +149,14 @@ export const customerAnalyticsSceneLogic = kea<customerAnalyticsSceneLogicType>(],activeTab: [(s) => [s.sceneKey],- (sceneKey): 'dashboard' | 'journeys' => {- return sceneKey === 'customerAnalyticsJourneys' ? 'journeys' : 'dashboard'+ (sceneKey): 'dashboard' | 'journeys' | 'accounts' => {+ if (sceneKey === 'customerAnalyticsJourneys') {+ return 'journeys'+ }+ if (sceneKey === 'customerAnalyticsAccounts') {+ return 'accounts'+ }+ return 'dashboard'},],breadcrumbs: [diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex ff77cd81842f..0fc16c6ff365 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -341,6 +341,22 @@ export interface PatchedGroupUsageMetricApi {}export type AccountsListParams = {+ /**+ * Filter by account executive. Use 'unassigned' or an integer user id.+ */+ account_executive?: string+ /**+ * Filter by account owner. Use 'unassigned' or an integer user id.+ */+ account_owner?: string+ /**+ * When true, returns only accounts where CSM, account executive, and account owner are all unset.+ */+ all_roles_unassigned?: boolean+ /**+ * Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id.+ */+ csm?: string/*** Number of results to return per page.*/@@ -349,6 +365,14 @@ export type AccountsListParams = {* The initial index from which to return the results.*/offset?: number+ /**+ * Sort order. Defaults to '-created_at'.+ */+ ordering?: string+ /**+ * Case-insensitive substring search across account name and external ID.+ */+ search?: string/*** JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts that have any of the listed tags.*/diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.tsindex c1dbe8c6222d..ceed61db5de5 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts@@ -1,5 +1,5 @@import { actions, connect, kea, path, props, reducers, selectors } from 'kea'-import { actionToUrl, router } from 'kea-router'+import { actionToUrl, router, urlToAction } from 'kea-router'import { Scene } from 'scenes/sceneTypes'import { settingsLogic } from 'scenes/settings/settingsLogic'@@ -50,11 +50,14 @@ export const customerAnalyticsConfigurationSceneLogic = kea<customerAnalyticsConselectors({breadcrumbs: [- () => [],- (): Breadcrumb[] => [+ (s) => [s.tab],+ (tab): Breadcrumb[] => [{key: Scene.CustomerAnalytics,- path: urls.customerAnalytics(),+ path:+ tab === 'customer-analytics-accounts'+ ? urls.customerAnalyticsAccounts()+ : urls.customerAnalytics(),name: 'Customer analytics',iconType: 'cohort',},@@ -79,4 +82,13 @@ export const customerAnalyticsConfigurationSceneLogic = kea<customerAnalyticsCon]},}),++ urlToAction(({ actions, values }) => ({+ [urls.customerAnalyticsConfiguration()]: (_, searchParams) => {+ const tab = searchParams.tab as ConfigurationSceneTabType | undefined+ if (tab && tab !== values.tab) {+ actions.setTab(tab)+ }+ },+ })),])diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsxindex 17d64bf0851c..425c22362f49 100644--- a/products/customer_analytics/manifest.tsx+++ b/products/customer_analytics/manifest.tsx@@ -35,6 +35,7 @@ export const manifest: ProductManifest = {},routes: {'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],+ '/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],'/customer_analytics/journeys/templates': ['CustomerJourneyTemplates', 'customerJourneyTemplates'],'/customer_analytics/journeys/:id/edit': ['CustomerJourneyBuilder', 'customerJourneyEdit'],@@ -48,6 +49,7 @@ export const manifest: ProductManifest = {urls: {customerAnalytics: (): string => '/customer_analytics',customerAnalyticsDashboard: (): string => '/customer_analytics/dashboard',+ customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',customerAnalyticsConfiguration: (): string => '/customer_analytics/configuration',customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e689e1830658..a5d3eb8da1b6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -40344,6 +40344,22 @@ export namespace Schemas {};export type AccountsListParams = {+ /**+ * Filter by account executive. Use 'unassigned' or an integer user id.+ */+ account_executive?: string;+ /**+ * Filter by account owner. Use 'unassigned' or an integer user id.+ */+ account_owner?: string;+ /**+ * When true, returns only accounts where CSM, account executive, and account owner are all unset.+ */+ all_roles_unassigned?: boolean;+ /**+ * Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id.+ */+ csm?: string;/*** Number of results to return per page.*/@@ -40352,6 +40368,14 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Sort order. Defaults to '-created_at'.+ */+ ordering?: string;+ /**+ * Case-insensitive substring search across account name and external ID.+ */+ search?: string;/*** JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts that have any of the listed tags.*/diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex 6d2b1850b15d..6bfa4c94a66c 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -17,8 +17,23 @@ export const AccountsListParams = /* @__PURE__ */ zod.object({})export const AccountsListQueryParams = /* @__PURE__ */ zod.object({+ account_executive: zod+ .string()+ .optional()+ .describe("Filter by account executive. Use 'unassigned' or an integer user id."),+ account_owner: zod.string().optional().describe("Filter by account owner. Use 'unassigned' or an integer user id."),+ all_roles_unassigned: zod+ .boolean()+ .optional()+ .describe('When true, returns only accounts where CSM, account executive, and account owner are all unset.'),+ csm: zod+ .string()+ .optional()+ .describe("Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id."),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),+ ordering: zod.string().optional().describe("Sort order. Defaults to '-created_at'."),+ search: zod.string().optional().describe('Case-insensitive substring search across account name and external ID.'),tags: zod.string().optional()diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex 7f1ce0e21c15..913eee81f113 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -88,8 +88,14 @@ const accountsList = (): ToolBase<typeof AccountsListSchema, WithPostHogUrl<Schemethod: 'GET',path: `/api/environments/${encodeURIComponent(String(projectId))}/accounts/`,query: {+ account_executive: params.account_executive,+ account_owner: params.account_owner,+ all_roles_unassigned: params.all_roles_unassigned,+ csm: params.csm,limit: params.limit,offset: params.offset,+ ordering: params.ordering,+ search: params.search,tags: params.tags,},})