: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): save custom accounts table views (#64050)
Arthur Moreira de Deus6056da3bf38e
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1f4deb5ba7bf..b2ad3f4a68b6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2510,6 +2510,9 @@ importers:kea:specifier: 'catalog:'version: 4.0.0-pre.5([email protected])+ kea-forms:+ specifier: 'catalog:'+ version: 3.2.0([email protected]([email protected]))kea-loaders:specifier: 'catalog:'version: 3.1.1([email protected]([email protected]))diff --git a/posthog/api/column_configuration.py b/posthog/api/column_configuration.pyindex 2b7882b1cc07..3a48171584e7 100644--- a/posthog/api/column_configuration.py+++ b/posthog/api/column_configuration.py@@ -5,7 +5,7 @@ from django.db.models import Q, QuerySetfrom drf_spectacular.utils import extend_schemafrom rest_framework import serializers, viewsets-from rest_framework.exceptions import PermissionDenied+from rest_framework.exceptions import NotFound, PermissionDeniedfrom rest_framework.permissions import SAFE_METHODSfrom rest_framework.response import Response@@ -18,7 +18,11 @@ from posthog.models import ColumnConfigurationclass ColumnConfigurationSerializer(serializers.ModelSerializer):- filters = serializers.JSONField(required=False, default=dict)+ filters = serializers.JSONField(+ required=False,+ default=dict,+ help_text="Column filter state persisted with this view configuration.",+ )order_by = serializers.ListField(child=serializers.CharField(),required=False,@@ -26,6 +30,11 @@ class ColumnConfigurationSerializer(serializers.ModelSerializer):allow_empty=True,help_text="Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.",)+ properties = serializers.JSONField(+ required=False,+ default=dict,+ help_text="Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display).",+ )class Meta:model = ColumnConfiguration@@ -36,6 +45,7 @@ class ColumnConfigurationSerializer(serializers.ModelSerializer):"name","filters","order_by",+ "properties","visibility","created_by","created_at",@@ -48,6 +58,13 @@ class ColumnConfigurationSerializer(serializers.ModelSerializer):return []return filters+ def validate_properties(self, properties):+ # create() validates this inline for a uniform error envelope, but that gate+ # doesn't run on partial updates — guard PATCH here so a non-dict can't be stored.+ if properties is not None and not isinstance(properties, dict):+ raise serializers.ValidationError("properties must be an object")+ return properties+def to_representation(self, instance: ColumnConfiguration):values = super().to_representation(instance)values["filters"] = self.validate_filters(values["filters"])@@ -61,16 +78,21 @@ class ColumnConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer_class = ColumnConfigurationSerializerdef safely_get_queryset(self, queryset):+ # Always visibility-scope (own private + team shared) so a request without a+ # context_key — or an object lookup by id — can't reach another user's private view.+ queryset = queryset.filter(Q(visibility="private", created_by=self.request.user) | Q(visibility="shared"))context_key = self.request.GET.get("context_key")if context_key:- queryset = queryset.filter(- Q(context_key=context_key)- & (Q(visibility="private", created_by=self.request.user) | Q(visibility="shared"))- )+ queryset = queryset.filter(context_key=context_key)return queryset.order_by("visibility", "-created_at")def safely_get_object(self, queryset: QuerySet) -> Any:- object = queryset.get(pk=self.kwargs["pk"])+ try:+ object = queryset.get(pk=self.kwargs["pk"])+ except ColumnConfiguration.DoesNotExist:+ # The queryset is visibility-scoped, so a row outside it (another user's private+ # view, or a wrong id) is a 404 — not an unhandled 500.+ raise NotFound("View not found")if self.request.method not in SAFE_METHODS and object.created_by != self.request.user:raise PermissionDenied("You do not have permission to change this view")@@ -110,6 +132,10 @@ class ColumnConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if len(order_by) > 100:return Response({"error": "cannot order by more than 100 expressions"}, status=400)+ properties = request.data.get("properties")+ if properties is not None and not isinstance(properties, dict):+ return Response({"error": "properties must be an object"}, status=400)+return super().create(request, *args, **kwargs)def perform_create(self, serializer):diff --git a/posthog/api/test/test_column_configuration.py b/posthog/api/test/test_column_configuration.pyindex 7e8fac5b9c7b..3a40bf561256 100644--- a/posthog/api/test/test_column_configuration.py+++ b/posthog/api/test/test_column_configuration.py@@ -128,7 +128,7 @@ class TestColumnConfigurationAPI(APIBaseTest):def test_user_can_only_edit_their_views(self):another_config = ColumnConfiguration.objects.create(team=self.team,- visibility=ColumnConfiguration.Visibility.PRIVATE,+ visibility=ColumnConfiguration.Visibility.SHARED,context_key="context-key",columns=["*", "person", "timestamp"],created_by=self.another_user,@@ -144,7 +144,7 @@ class TestColumnConfigurationAPI(APIBaseTest):def test_user_can_only_delete_their_views(self):another_config = ColumnConfiguration.objects.create(team=self.team,- visibility=ColumnConfiguration.Visibility.PRIVATE,+ visibility=ColumnConfiguration.Visibility.SHARED,context_key="context-key",columns=["*", "person", "timestamp"],created_by=self.another_user,@@ -157,6 +157,41 @@ class TestColumnConfigurationAPI(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDENassert response.json()["detail"] == "You do not have permission to change this view"+ def test_list_without_context_key_excludes_others_private_views(self):+ ColumnConfiguration.objects.create(+ team=self.team,+ visibility=ColumnConfiguration.Visibility.PRIVATE,+ context_key="context-key",+ columns=["*"],+ created_by=self.another_user,+ )+ own = ColumnConfiguration.objects.create(+ team=self.team,+ visibility=ColumnConfiguration.Visibility.PRIVATE,+ context_key="context-key",+ columns=["*"],+ created_by=self.user,+ )++ response = self.client.get(f"/api/environments/{self.team.id}/column_configurations/")++ assert response.status_code == status.HTTP_200_OK+ ids = {row["id"] for row in response.json()["results"]}+ assert ids == {str(own.id)}++ def test_cannot_retrieve_another_users_private_view(self):+ another_config = ColumnConfiguration.objects.create(+ team=self.team,+ visibility=ColumnConfiguration.Visibility.PRIVATE,+ context_key="context-key",+ columns=["*"],+ created_by=self.another_user,+ )++ response = self.client.get(f"/api/environments/{self.team.id}/column_configurations/{str(another_config.id)}/")++ assert response.status_code == status.HTTP_404_NOT_FOUND+def test_update_via_patch(self):create_response = self.client.post(f"/api/environments/{self.team.id}/column_configurations/",@@ -320,6 +355,80 @@ class TestColumnConfigurationAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["order_by"] == ["person.created_at ASC"]+ def test_create_with_properties(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/column_configurations/",+ {+ "context_key": "customer_analytics_accounts_columns",+ "columns": ["name"],+ "properties": {"tiles": [{"id": "t1", "label": "Accounts", "metric": {"type": "count"}}]},+ },+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["properties"] == {+ "tiles": [{"id": "t1", "label": "Accounts", "metric": {"type": "count"}}]+ }++ def test_properties_defaults_to_empty_dict(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/column_configurations/",+ {"context_key": "survey:123", "columns": ["*"]},+ )++ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["properties"] == {}++ def test_update_properties(self):+ config = ColumnConfiguration.objects.create(+ team=self.team,+ created_by=self.user,+ context_key="customer_analytics_accounts_columns",+ columns=["name"],+ )++ response = self.client.patch(+ f"/api/environments/{self.team.id}/column_configurations/{config.id}/",+ {"properties": {"tiles": [{"id": "t2", "label": "MRR", "metric": {"type": "count"}}]}},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["properties"]["tiles"][0]["id"] == "t2"++ def test_properties_must_be_an_object(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/column_configurations/",+ {"context_key": "survey:123", "columns": ["*"], "properties": ["not", "a", "dict"]},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["error"] == "properties must be an object"++ def test_update_properties_must_be_an_object(self):+ config = ColumnConfiguration.objects.create(+ team=self.team,+ created_by=self.user,+ context_key="customer_analytics_accounts_columns",+ columns=["name"],+ )++ response = self.client.patch(+ f"/api/environments/{self.team.id}/column_configurations/{config.id}/",+ {"properties": ["not", "a", "dict"]},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json() == {+ "type": "validation_error",+ "code": "invalid_input",+ "detail": "properties must be an object",+ "attr": "properties",+ }+def test_team_isolation(self):other_team = self.organization.teams.create(name="Other Team")diff --git a/posthog/migrations/1224_columnconfiguration_properties.py b/posthog/migrations/1224_columnconfiguration_properties.pynew file mode 100644index 000000000000..fce98bcb42d2--- /dev/null+++ b/posthog/migrations/1224_columnconfiguration_properties.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-06-15 16:46++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1223_remove_ducklakecatalog_cross_account_fields"),+ ]++ operations = [+ migrations.AddField(+ model_name="columnconfiguration",+ name="properties",+ field=models.JSONField(blank=True, default=dict, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 65584c9596fc..fc48247429b1 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1223_remove_ducklakecatalog_cross_account_fields+1224_columnconfiguration_propertiesdiff --git a/posthog/models/column_configuration.py b/posthog/models/column_configuration.pyindex e2beb0de0e6f..da4131ed80a3 100644--- a/posthog/models/column_configuration.py+++ b/posthog/models/column_configuration.py@@ -16,6 +16,7 @@ class ColumnConfiguration(UUIDModel):columns = ArrayField(models.TextField(), null=False, blank=False, default=list)filters = models.JSONField(default=dict, null=True, blank=True)order_by = ArrayField(models.TextField(), null=True, blank=True, default=None)+ properties = models.JSONField(default=dict, null=True, blank=True)visibility = models.CharField(max_length=10, choices=Visibility, default=Visibility.SHARED)created_by = models.ForeignKey("posthog.User", on_delete=models.CASCADE, null=True)diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 9dc1223875b0..b440fb6ef39a 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -34,9 +34,10 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc| Logic | Owns || ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `accountsLogic` | The hub. Search (debounced), tag and assigned-to/unassigned filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). 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`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API). || `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 (persisted per team); feeds `metrics` into the query. |+| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); feeds `metrics` into the query. 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`). || `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). || `accountBillingLogic` | Billing/usage data behind the Usage tab. |@@ -63,6 +64,32 @@ The Usage tab renders an existing saved billing-usage insight — **point users`accountsLogic` mirrors the full view (search, tags, unassigned, assigned-to, sort, columns, tile filter) into the URL hash `#view=...` via `actionToUrl`/`urlToAction`, so a copied URL reproduces the exact list. Only non-default values are serialized. The "assigned to" filter persists as concrete `assignedTo` ids (not a `mine` flag), so a link shared with a colleague resolves to the **same** accounts for them as for the sharer; the legacy `mine: true` hash is still read and resolved to the current user's id for backward compatibility. A shared link's `columns` win over the per-user saved column config (`accountsColumnConfigLogic` enforces this when its async saved-config load resolves by checking the live URL).+## Saved views++A saved view is a named snapshot of the full Accounts list state (columns, sort, filters, overview tiles).+Views are persisted as `ColumnConfiguration` rows under `context_key = 'customer_analytics_accounts_columns'` (the `ACCOUNTS_COLUMN_CONFIG_KEY` constant).+`accountsViewsLogic` is the single owner of this lifecycle; components only call its actions.++`accountsViewState.ts` is a pure module that maps UI state ↔ the `ColumnConfiguration` payload:++- `columns` ← `selectColumns` (column names in order)+- `order_by` ← sort, stored as `["<column> <ASC|DESC>"]` using the logical column name+ (query-time `deriveAccountsOrderByExpr` wraps role/tuple columns at build time; the stored name stays clean)+- `filters` ← search text, tags, unassigned toggle, assigned-to filter, tile filter (JSON)+- `properties` ← `{ tiles }` — overview tile configuration (a `properties` field added to the `ColumnConfiguration` model)++**Visibility** is `private` or `shared`; only the creator can edit or delete a view (enforced by the backend viewset).++**Auto-restore:** the last-used view `id` is persisted in a team-scoped localStorage key (`currentViewId`).+A shared link's `#view=` URL hash always wins over the saved `currentViewId`.+`isDirty` is true when the live state diverges from the selected view's saved state.++**One-time tiles migration:** on first load, if the signed-in user is the creator of the existing default `ColumnConfiguration` row and its `properties.tiles` is empty while their localStorage tiles differ from `DEFAULT_TILES`, `accountsViewsLogic` patches the localStorage tiles into that row.+The operation is idempotent and skips non-creators.++**Column configurator:** `AccountsColumnConfigurator.tsx` no longer persists columns itself — its footer button is "Done" (closes only).+Column changes are saved as part of a view via `AccountsViewSelector.tsx` (the view dropdown in `AccountsTabFilters`), which offers "Save current view" (creates) and "Update '<name>'" (patches the selected view).+## Max / agent integrationThe Accounts list exposes one contextual tool, `open_account`, so Max can show an account on screen.@@ -103,20 +130,25 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions### Tracked events-| Event | Fires from | Properties |-| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |-| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `unassigned_only` \| `my_accounts` \| `assigned_to`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assigned_to` also `role_count` |-| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |-| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |-| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics accounts columns saved` | `accountsColumnConfigLogic` `saveColumns` (success, only when changed) | `column_count`, `columns`, `added_count`, `removed_count`, `reordered` |-| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |-| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |-| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |-| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage`) |-| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |+| Event | Fires from | Properties |+| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |+| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `unassigned_only` \| `my_accounts` \| `assigned_to`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assigned_to` also `role_count` |+| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |+| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |+| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |+| ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ |+| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |+| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |+| `customer analytics accounts view saved` | `accountsViewsLogic` `submitNewViewForm` listener (success) | `visibility` (`private` \| `shared`) |+| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener | _(none)_ |+| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |+| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |+| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |+| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |+| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage`) |+| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |> **Keep this table up to date.** Whenever you add, rename, or remove a `posthog.capture()` event in the Accounts area — or change its properties — update this table in the same change. An agent reading this file should be able to trust it as the source of truth for what the Accounts list reports.diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsxindex 4abeef592dab..139285111668 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx@@ -46,8 +46,7 @@ export function AccountsColumnConfigurator(): JSX.Element {function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }): JSX.Element {const { selectColumns, accountsColumnGroups, databaseLoading } = useValues(accountsColumnConfigLogic)- const { saveColumns, moveColumn, resetColumns, setSelectColumns, unselectColumn } =- useActions(accountsColumnConfigLogic)+ const { moveColumn, resetColumns, setSelectColumns, unselectColumn } = useActions(accountsColumnConfigLogic)const onEditColumn = (column: string, index: number): void => {const next = window.prompt('Edit column', column)@@ -69,18 +68,8 @@ function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean;Reset to defaults</LemonButton></div>- <LemonButton type="secondary" onClick={onClose}>- Close- </LemonButton>- <LemonButton- type="primary"- onClick={() => {- saveColumns()- onClose()- }}- data-attr="accounts-columns-save"- >- Save+ <LemonButton type="primary" onClick={onClose} data-attr="accounts-columns-done">+ Done</LemonButton></>}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsxindex 5fbe670a8346..7cdc8c57e1d9 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx@@ -18,6 +18,7 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { AccountsColumnConfigurator } from './AccountsColumnConfigurator'import { accountsLogic, RoleFilterValue } from './accountsLogic'import { AccountsOverviewTilesButton } from './AccountsOverviewTilesButton'+import { AccountsViewSelector } from './AccountsViewSelector'export function AccountsTabFilters(): JSX.Element {const { searchInput, tagsFilter, allRolesUnassigned, assignedToCurrentUser, assignedToFilter } =@@ -40,15 +41,18 @@ export function AccountsTabFilters(): JSX.Element {return (<div className="flex flex-col gap-2"><div className="flex flex-wrap gap-2 items-center justify-between">- <LemonInput- type="search"- placeholder="Search by name or ID..."- value={searchInput}- onChange={setSearchInput}- size="small"- className="min-w-64"- data-attr="accounts-search"- />+ <div className="flex flex-wrap gap-2 items-center">+ <LemonInput+ type="search"+ placeholder="Search by name or ID..."+ value={searchInput}+ onChange={setSearchInput}+ size="small"+ className="min-w-64"+ data-attr="accounts-search"+ />+ <AccountsViewSelector />+ </div><LemonButtontype="secondary"icon={<IconRefresh />}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsViewSelector.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsViewSelector.tsxnew file mode 100644index 000000000000..4413a8f270b0--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsViewSelector.tsx@@ -0,0 +1,243 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'++import { IconChevronDown, IconGlobe, IconPencil, IconPlus, IconUser } from '@posthog/icons'+import {+ LemonButton,+ LemonInput,+ LemonMenu,+ LemonMenuItem,+ LemonMenuItems,+ LemonModal,+ LemonSegmentedButton,+ Tooltip,+} from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'++import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'++import { accountsViewsLogic } from './accountsViewsLogic'++export function AccountsViewSelector(): JSX.Element {+ const { views, currentView, isDirty, viewsLoading, canEditCurrentView, user } = useValues(accountsViewsLogic)+ const { selectView, updateView, setViewToDelete, setViewToRename, setIsCreating } = useActions(accountsViewsLogic)++ const menuItems: LemonMenuItems = [+ {+ items: views.map((view) => {+ const canEdit = view.created_by === user?.id+ return {+ label: view.name,+ icon: <ViewVisibilityIcon view={view} />,+ active: currentView?.id === view.id,+ onClick: () => selectView(view.id),+ ...(canEdit && {+ sideAction: {+ icon: <IconPencil />,+ tooltip: 'Manage view',+ dropdown: {+ overlay: (+ <>+ <LemonButton size="small" fullWidth onClick={() => setViewToRename(view.id)}>+ Rename+ </LemonButton>+ <LemonButton+ size="small"+ fullWidth+ status="danger"+ onClick={() => setViewToDelete(view.id)}+ >+ Delete+ </LemonButton>+ </>+ ),+ },+ },+ }),+ } as LemonMenuItem+ }),+ },+ {+ items: [{ label: 'Save as new view...', icon: <IconPlus />, onClick: () => setIsCreating(true) }],+ },+ ]++ return (+ <div className="flex items-center gap-2">+ {currentView ? (+ <LemonMenu items={menuItems} closeOnClickInside>+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>+ <ViewVisibilityIcon view={currentView} />+ <span className="ml-2">{currentView.name}</span>+ </LemonButton>+ </LemonMenu>+ ) : (+ <LemonButton+ icon={<IconPlus />}+ size="small"+ type="secondary"+ onClick={() => setIsCreating(true)}+ data-attr="accounts-save-view"+ >+ Save current view+ </LemonButton>+ )}++ {currentView && isDirty && (+ <LemonButton+ size="small"+ type="secondary"+ tooltip="Update this view with the current configuration"+ disabledReason={!canEditCurrentView ? 'You can only edit views you created' : undefined}+ loading={viewsLoading}+ onClick={() => updateView({ id: currentView.id, updates: {} })}+ data-attr="accounts-update-view"+ >+ Update "{currentView.name}"+ </LemonButton>+ )}++ <CreateViewModal />+ <RenameViewModal />+ <DeleteViewModal />+ </div>+ )+}++function CreateViewModal(): JSX.Element {+ const { isCreating, isNewViewFormSubmitting } = useValues(accountsViewsLogic)+ const { submitNewViewForm, resetNewViewForm, setIsCreating } = useActions(accountsViewsLogic)++ const close = (): void => {+ setIsCreating(false)+ resetNewViewForm()+ }++ return (+ <LemonModal+ isOpen={isCreating}+ onClose={close}+ title="Save as new view"+ description="Save the current filters, columns, ordering, and overview tiles as a reusable view"+ footer={+ <>+ <LemonButton type="secondary" onClick={close}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={submitNewViewForm}+ loading={isNewViewFormSubmitting}+ disabledReason={isNewViewFormSubmitting ? 'Saving…' : undefined}+ >+ Save view+ </LemonButton>+ </>+ }+ >+ <Form logic={accountsViewsLogic} formKey="newViewForm">+ <div className="space-y-4">+ <LemonField name="name" label="View name">+ <LemonInput placeholder="e.g. Enterprise accounts" autoFocus onPressEnter={submitNewViewForm} />+ </LemonField>+ <LemonField name="visibility" label="Visibility">+ <LemonSegmentedButton+ options={[+ { value: 'private', label: 'Private (only visible to me)', icon: <IconUser /> },+ { value: 'shared', label: 'Shared with team', icon: <IconGlobe /> },+ ]}+ fullWidth+ />+ </LemonField>+ </div>+ </Form>+ </LemonModal>+ )+}++function RenameViewModal(): JSX.Element {+ const { views, viewToRename, viewsLoading } = useValues(accountsViewsLogic)+ const { setViewToRename, submitRenameViewForm, resetRenameViewForm } = useActions(accountsViewsLogic)+ const view = views.find((v) => v.id === viewToRename)++ const close = (): void => {+ setViewToRename(null)+ resetRenameViewForm()+ }++ return (+ <LemonModal+ isOpen={!!viewToRename}+ onClose={close}+ title="Rename view"+ footer={+ <>+ <LemonButton type="secondary" onClick={close}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={submitRenameViewForm}+ loading={viewsLoading}+ disabledReason={viewsLoading ? 'Saving…' : undefined}+ >+ Rename+ </LemonButton>+ </>+ }+ >+ <Form logic={accountsViewsLogic} formKey="renameViewForm">+ <LemonField name="name" label="View name">+ <LemonInput placeholder={view?.name} autoFocus onPressEnter={submitRenameViewForm} />+ </LemonField>+ </Form>+ </LemonModal>+ )+}++function DeleteViewModal(): JSX.Element {+ const { views, viewToDelete } = useValues(accountsViewsLogic)+ const { deleteView, setViewToDelete } = useActions(accountsViewsLogic)+ const view = views.find((v) => v.id === viewToDelete)++ return (+ <LemonModal+ isOpen={!!viewToDelete}+ onClose={() => setViewToDelete(null)}+ title="Delete view"+ description={`Are you sure you want to delete the view "${view?.name ?? ''}"?`}+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setViewToDelete(null)}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ status="danger"+ onClick={() => {+ if (viewToDelete) {+ deleteView({ id: viewToDelete })+ setViewToDelete(null)+ }+ }}+ >+ Delete+ </LemonButton>+ </>+ }+ />+ )+}++function ViewVisibilityIcon({ view }: { view: ColumnConfigurationApi }): JSX.Element {+ return view.visibility === 'private' ? (+ <Tooltip title="Only you can see this view.">+ <IconUser />+ </Tooltip>+ ) : (+ <Tooltip title="Everyone on your team can see this view.">+ <IconGlobe />+ </Tooltip>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.tsindex bd489c1281a6..fd59762761a7 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts@@ -1,10 +1,5 @@-import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'-import { router } from 'kea-router'-import posthog from 'posthog-js'+import { actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'-import api from 'lib/api'-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { objectsEqual } from 'lib/utils'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { teamLogic } from 'scenes/teamLogic'@@ -16,7 +11,6 @@ import type { DataWarehouseViewLink } from '~/types'import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'import type { accountsColumnConfigLogicType } from './accountsColumnConfigLogicType'-import { AccountsEvents } from './constants'// Mandatory — the backend emits it as `tuple(name, external_id, id)` so the// row identity (id) and copy-able external_id ride along with the display name.@@ -201,7 +195,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([unselectColumn: (column: string) => ({ column }),moveColumn: (oldIndex: number, newIndex: number) => ({ oldIndex, newIndex }),resetColumns: true,- saveColumns: true,showColumnConfigurator: true,hideColumnConfigurator: true,}),@@ -230,37 +223,9 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([{showColumnConfigurator: () => true,hideColumnConfigurator: () => false,- saveColumns: () => false,},],}),- loaders(({ values }) => ({- savedColumnConfiguration: [- null as { id: string; columns: string[] } | null,- {- loadSavedColumnConfiguration: async (): Promise<{ id: string; columns: string[] } | null> => {- try {- const response = await api.columnConfigurations.list({- teamId: values.currentTeamId || undefined,- context_key: ACCOUNTS_COLUMN_CONFIG_KEY,- })- if (response.results && response.results.length > 0) {- return {- id: response.results[0].id,- columns: response.results[0].columns || [],- }- }- return null- } catch (error) {- posthog.captureException(error as Error, {- scope: 'accountsColumnConfigLogic.loadSavedColumnConfiguration',- })- return null- }- },- },- ],- })),selectors({visibleColumnNames: [(s) => [s.selectColumns],@@ -274,54 +239,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([): AccountColumnGroup[] => buildAccountColumnGroups(allTablesMap, warehouseJoins),],}),- listeners(({ actions, values }) => ({- loadSavedColumnConfigurationSuccess: ({ savedColumnConfiguration }) => {- // A shared link's columns (in the URL hash) win over the per-user- // saved config, which loads asynchronously after mount. Read the- // live URL rather than tracking state, so this stays correct- // regardless of later column edits.- const urlHasColumns = !!router.values.hashParams?.view?.columns- if (savedColumnConfiguration && !urlHasColumns) {- actions.setSelectColumns(savedColumnConfiguration.columns)- }- },- saveColumns: async () => {- const teamId = values.currentTeamId || undefined- const columns = values.selectColumns- const previousColumns = values.savedColumnConfiguration?.columns ?? ACCOUNTS_HOGQL_DEFAULT_SELECT- try {- if (values.savedColumnConfiguration?.id) {- await api.columnConfigurations.update({- teamId,- id: values.savedColumnConfiguration.id,- data: { columns },- })- } else {- const response = await api.columnConfigurations.create({- teamId,- data: { context_key: ACCOUNTS_COLUMN_CONFIG_KEY, columns },- })- actions.loadSavedColumnConfigurationSuccess({ id: response.id, columns: response.columns || [] })- }- lemonToast.success('Columns saved')- const diff = diffColumnConfiguration(previousColumns, columns)- if (diff.changed) {- posthog.capture(AccountsEvents.ColumnsSaved, {- column_count: columns.length,- columns,- added_count: diff.added,- removed_count: diff.removed,- reordered: diff.reordered,- })- }- } catch (error) {- posthog.captureException(error as Error, { scope: 'accountsColumnConfigLogic.saveColumns' })- lemonToast.error('Failed to save columns')- }- },- })),afterMount(({ actions, values }) => {- actions.loadSavedColumnConfiguration()// Lazily fetch the database schema only if it isn't already in flight / loaded.// databaseTableListLogic dedupes concurrent calls internally.if (!values.allTablesMap || Object.keys(values.allTablesMap).length === 0) {diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex 8876c266375e..82980a75f8a8 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -341,7 +341,7 @@ describe('accountsLogic', () => {expect(logic.values.assignedToFilter).toEqual([7])})- it('restores columns and shields them from a late saved column config', async () => {+ it('restores columns from the view hash param', async () => {router.actions.push(urls.customerAnalyticsAccounts(),{},@@ -353,27 +353,6 @@ describe('accountsLogic', () => {const config = accountsColumnConfigLogic.findMounted()expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm'])-- // A saved config arriving after the URL was applied must not clobber the shared view.- config?.actions.loadSavedColumnConfigurationSuccess({- id: 'saved-1',- columns: [ACCOUNTS_NAME_COLUMN, 'account_owner'],- })- await expectLogic(config!).toFinishAllListeners()- expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm'])- })-- it('applies the saved column config when the URL has no columns', async () => {- router.actions.push(urls.customerAnalyticsAccounts(), {}, {})- await expectLogic(logic).toFinishAllListeners()-- const config = accountsColumnConfigLogic.findMounted()- config?.actions.loadSavedColumnConfigurationSuccess({- id: 'saved-1',- columns: [ACCOUNTS_NAME_COLUMN, 'account_owner'],- })- await expectLogic(config!).toFinishAllListeners()- expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'account_owner'])})})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex da6f21de1882..cfa7283c9f9b 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -27,6 +27,7 @@ import {import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'import type { accountsLogicType } from './accountsLogicType'import { accountsOverviewTilesLogic, TileFilter } from './accountsOverviewTilesLogic'+import { normalizeRoleFilter } from './accountsViewState'import { AccountsEvents } from './constants'export const SEARCH_DEBOUNCE_MS = 300@@ -60,17 +61,6 @@ function clearSortIfColumnRemoved(values: SortLikeValues, actions: SortLikeActioexport type RoleFilterValue = number[]-// Shared URLs persisted a single role id (e.g. `csm: 7`) before the filters-// became multi-select. Coerce any scalar (or malformed value) from the view-// hash into a `number[]` so restoring a legacy link can't poison the array-// (a stray number breaks the `.length`/`.map` the filters now rely on).-function normalizeRoleFilter(value: unknown): RoleFilterValue {- if (Array.isArray(value)) {- return value.filter((entry): entry is number => typeof entry === 'number')- }- return typeof value === 'number' ? [value] : []-}-export type AccountRoleKey = 'csm' | 'account_executive' | 'account_owner'export type AccountFilterType = 'tag' | 'unassigned_only' | 'my_accounts' | 'assigned_to'diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.tsindex 228b1152f7e9..2b71485b2643 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts@@ -1,3 +1,6 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'@@ -13,7 +16,12 @@ import {tileMetricExpression,tileToRowFilter,} from './accountsOverviewTilesLogic'-import { MAX_ACCOUNTS_OVERVIEW_TILES } from './constants'+import {+ ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX,+ AccountsEvents,+ DEFAULT_TILES,+ MAX_ACCOUNTS_OVERVIEW_TILES,+} from './constants'describe('stripHogqlAlias', () => {it('strips a trailing AS alias', () => {@@ -207,3 +215,58 @@ describe('addTile limit', () => {expect(logic.values.tiles).toHaveLength(MAX_ACCOUNTS_OVERVIEW_TILES)})})++describe('accountsOverviewTilesLogic setTiles', () => {+ beforeEach(() => {+ initKeaTests()+ })++ it('replaces the entire tile set', async () => {+ const logic = accountsOverviewTilesLogic()+ logic.mount()+ const tiles = [+ { id: 'a', label: 'A', metric: { type: 'count' as const } },+ { id: 'b', label: 'B', metric: { type: 'count' as const } },+ ]+ await expectLogic(logic, () => logic.actions.setTiles(tiles)).toMatchValues({ tiles })+ })+})++describe('accountsOverviewTilesLogic legacy localStorage tiles (read-only + tombstone)', () => {+ const LEGACY_KEY = `${ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX}.scenes.customerAnalytics.accounts.accountsOverviewTilesLogic.tiles`+ const customTiles: AccountsOverviewTile[] = [{ id: 'legacy', label: 'Legacy', metric: { type: 'count' as const } }]++ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ })++ afterEach(() => {+ localStorage.clear()+ jest.restoreAllMocks()+ })++ it('reads a pre-existing custom value on mount, emits a tombstone, and never writes it back', async () => {+ localStorage.setItem(LEGACY_KEY, JSON.stringify(customTiles))+ const logic = accountsOverviewTilesLogic()+ logic.mount()+ await expectLogic(logic).toMatchValues({ tiles: customTiles })+ expect(posthog.capture).toHaveBeenCalledWith(AccountsEvents.OverviewTilesLocalStorageRead, { tile_count: 1 })++ // never writes: changing tiles must not update or recreate the legacy key+ logic.actions.setTiles([{ id: 'x', label: 'X', metric: { type: 'count' as const } }])+ expect(JSON.parse(localStorage.getItem(LEGACY_KEY) as string)).toEqual(customTiles)+ })++ it('ignores a default-valued legacy key — no seed, no tombstone', async () => {+ localStorage.setItem(LEGACY_KEY, JSON.stringify(DEFAULT_TILES))+ const logic = accountsOverviewTilesLogic()+ logic.mount()+ await expectLogic(logic).toMatchValues({ tiles: DEFAULT_TILES })+ expect(posthog.capture).not.toHaveBeenCalledWith(+ AccountsEvents.OverviewTilesLocalStorageRead,+ expect.anything()+ )+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.tsindex 5dae26baae06..1aa319d37774 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts@@ -1,4 +1,4 @@-import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import posthog from 'posthog-js'import { v4 as uuidv4 } from 'uuid'@@ -11,7 +11,7 @@ import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'import { AccountColumnGroup, AccountColumnOption, accountsColumnConfigLogic } from './accountsColumnConfigLogic'import type { accountsOverviewTilesLogicType } from './accountsOverviewTilesLogicType'import {- ACCOUNTS_OVERVIEW_PERSIST_CONFIG,+ ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX,AccountsEvents,AccountsOverviewThresholdOperator,DEFAULT_TILES,@@ -155,6 +155,27 @@ export function diffOverviewTiles(return { changed: added > 0 || removed > 0 || updated > 0 || reordered, added, removed, updated, reordered }}+// Read-only access to the legacy per-team localStorage tiles (see ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX+// in constants.ts). We never write this key; we read any pre-existing CUSTOM value once on mount to+// seed the working state and emit a tombstone, so the localStorage read path can eventually be removed.+function readLegacyOverviewTiles(): AccountsOverviewTile[] | null {+ try {+ const key = Object.keys(window.localStorage).find(+ (k) => k.startsWith(ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX) && k.endsWith('.tiles')+ )+ if (!key) {+ return null+ }+ const parsed = JSON.parse(window.localStorage.getItem(key) ?? 'null')+ if (Array.isArray(parsed) && parsed.length > 0 && !objectsEqual(parsed, DEFAULT_TILES)) {+ return parsed as AccountsOverviewTile[]+ }+ } catch {+ // Inaccessible or malformed localStorage — fall back to defaults.+ }+ return null+}+export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([path(['scenes', 'customerAnalytics', 'accounts', 'accountsOverviewTilesLogic']),connect(() => ({@@ -170,6 +191,7 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([updateTile: (id: string, tile: Omit<AccountsOverviewTile, 'id'>) => ({ id, tile }),removeTile: (id: string) => ({ id }),moveTile: (oldIndex: number, newIndex: number) => ({ oldIndex, newIndex }),+ setTiles: (tiles: AccountsOverviewTile[]) => ({ tiles }),toggleTileSelection: (tile: AccountsOverviewTile) => ({ tile }),setTileFilter: (filter: TileFilter | null) => ({ filter }),resetTiles: true,@@ -179,7 +201,6 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([reducers(() => ({tiles: [DEFAULT_TILES,- ACCOUNTS_OVERVIEW_PERSIST_CONFIG,{addTile: (state: AccountsOverviewTile[],@@ -205,6 +226,7 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([next.splice(newIndex, 0, removed)return next},+ setTiles: (_state: AccountsOverviewTile[], { tiles }: { tiles: AccountsOverviewTile[] }) => tiles,resetTiles: () => [...DEFAULT_TILES],},],@@ -294,4 +316,13 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([actions.setTileFilter(values.tileFilter?.tileId === tile.id ? null : next)},})),+ afterMount(({ actions }) => {+ // Seed from any legacy localStorage tiles (read-only) and emit a tombstone so we can tell+ // when the localStorage read path is safe to remove. Saved views are the durable store.+ const legacyTiles = readLegacyOverviewTiles()+ if (legacyTiles) {+ actions.setTiles(legacyTiles)+ posthog.capture(AccountsEvents.OverviewTilesLocalStorageRead, { tile_count: legacyTiles.length })+ }+ }),])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.tsnew file mode 100644index 000000000000..642ca4e6df12--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts@@ -0,0 +1,103 @@+import { ACCOUNTS_HOGQL_DEFAULT_SELECT } from './accountsColumnConfigLogic'+import {+ deserializeAccountsView,+ normalizeRoleFilter,+ orderByToSortOrder,+ serializeAccountsView,+ sortOrderToOrderBy,+} from './accountsViewState'+import { DEFAULT_TILES } from './constants'++describe('sortOrderToOrderBy / orderByToSortOrder', () => {+ it('round-trips a plain ascending column', () => {+ expect(sortOrderToOrderBy({ column: 'name', direction: 'asc' })).toEqual(['name ASC'])+ expect(orderByToSortOrder(['name ASC'])).toEqual({ column: 'name', direction: 'asc' })+ })++ it('round-trips a descending role/tuple column by its logical name', () => {+ expect(sortOrderToOrderBy({ column: 'csm', direction: 'desc' })).toEqual(['csm DESC'])+ expect(orderByToSortOrder(['csm DESC'])).toEqual({ column: 'csm', direction: 'desc' })+ })++ it('treats null / empty as no sort', () => {+ expect(sortOrderToOrderBy(null)).toEqual([])+ expect(orderByToSortOrder([])).toBeNull()+ expect(orderByToSortOrder(null)).toBeNull()+ })++ it('defaults to ascending when the direction token is missing', () => {+ expect(orderByToSortOrder(['health_score'])).toEqual({ column: 'health_score', direction: 'asc' })+ })+})++describe('normalizeRoleFilter', () => {+ it('coerces a scalar (legacy link) to an array', () => {+ expect(normalizeRoleFilter(7)).toEqual([7])+ })++ it('drops non-number array entries', () => {+ expect(normalizeRoleFilter([1, 'x', 2])).toEqual([1, 2])+ })++ it('falls back to empty for nullish/garbage', () => {+ expect(normalizeRoleFilter(undefined)).toEqual([])+ expect(normalizeRoleFilter('nope')).toEqual([])+ })+})++describe('serializeAccountsView / deserializeAccountsView', () => {+ it('round-trips a fully populated view', () => {+ const state = {+ columns: ['name', 'csm'],+ sortOrder: { column: 'csm' as const, direction: 'desc' as const },+ filters: {+ search: 'acme',+ tags: ['enterprise'],+ unassigned: false,+ assignedTo: [1, 2, 3],+ tileFilter: { tileId: 't1', expression: 'mrr > 100' },+ },+ tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' as const } }],+ }+ const payload = serializeAccountsView(state)+ expect(payload.order_by).toEqual(['csm DESC'])+ expect(payload.columns).toEqual(['name', 'csm'])+ expect(payload.properties).toEqual({ tiles: state.tiles })+ expect(deserializeAccountsView(payload)).toEqual(state)+ })++ it('omits empty filters and serializes no sort', () => {+ const payload = serializeAccountsView({+ columns: [...ACCOUNTS_HOGQL_DEFAULT_SELECT],+ sortOrder: null,+ filters: {+ search: '',+ tags: [],+ unassigned: false,+ assignedTo: [],+ tileFilter: null,+ },+ tiles: [...DEFAULT_TILES],+ })+ expect(payload.filters).toEqual({})+ expect(payload.order_by).toEqual([])+ })++ it('treats a legacy columns-only row (filters [], no properties) as defaults', () => {+ const state = deserializeAccountsView({ columns: ['name'], order_by: null, filters: [], properties: {} })+ expect(state.filters).toEqual({+ search: '',+ tags: [],+ unassigned: false,+ assignedTo: [],+ tileFilter: null,+ })+ expect(state.tiles).toEqual(DEFAULT_TILES)+ expect(state.sortOrder).toBeNull()+ })++ it('falls back to default columns when a row has none', () => {+ const state = deserializeAccountsView({ columns: [], order_by: [], filters: {}, properties: {} })+ expect(state.columns).toEqual(ACCOUNTS_HOGQL_DEFAULT_SELECT)+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.tsnew file mode 100644index 000000000000..76c8684b8a82--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts@@ -0,0 +1,110 @@+import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'++import { ACCOUNTS_HOGQL_DEFAULT_SELECT } from './accountsColumnConfigLogic'+import type { AccountSortOrder, RoleFilterValue } from './accountsLogic'+import type { AccountsOverviewTile, TileFilter } from './accountsOverviewTilesLogic'+import { DEFAULT_TILES } from './constants'++export interface AccountsViewFilters {+ search: string+ tags: string[]+ unassigned: boolean+ assignedTo: RoleFilterValue+ tileFilter: TileFilter | null+}++export interface AccountsViewProperties {+ tiles?: AccountsOverviewTile[]+}++export interface AccountsViewState {+ columns: string[]+ sortOrder: AccountSortOrder+ filters: AccountsViewFilters+ tiles: AccountsOverviewTile[]+}++type AccountsViewPayload = Pick<ColumnConfigurationApi, 'columns' | 'order_by'> & {+ filters: Partial<AccountsViewFilters>+ properties: AccountsViewProperties+}++// A persisted filter may be a single id (e.g. `assignedTo: 7`) from before the filter+// became multi-select. Coerce any scalar (or malformed value) into a `number[]`+// so restoring a legacy link/view can't poison the array.+export function normalizeRoleFilter(value: unknown): RoleFilterValue {+ if (Array.isArray(value)) {+ return value.filter((entry): entry is number => typeof entry === 'number')+ }+ return typeof value === 'number' ? [value] : []+}++// Sort persists as a single `["<column> <ASC|DESC>"]` entry using the LOGICAL+// column name (e.g. `csm`); `deriveAccountsOrderByExpr` re-derives the tuple+// expression at query-build time.+export function sortOrderToOrderBy(sortOrder: AccountSortOrder): string[] {+ if (!sortOrder) {+ return []+ }+ return [`${sortOrder.column} ${sortOrder.direction === 'desc' ? 'DESC' : 'ASC'}`]+}++export function orderByToSortOrder(orderBy: string[] | null | undefined): AccountSortOrder {+ if (!orderBy || orderBy.length === 0) {+ return null+ }+ const match = orderBy[0].match(/^(.*?)\s+(ASC|DESC)$/i)+ if (!match) {+ return { column: orderBy[0].trim(), direction: 'asc' }+ }+ return { column: match[1].trim(), direction: match[2].toUpperCase() === 'DESC' ? 'desc' : 'asc' }+}++export function serializeAccountsView(state: AccountsViewState): AccountsViewPayload {+ const filters: Partial<AccountsViewFilters> = {}+ const search = state.filters.search.trim()+ if (search) {+ filters.search = search+ }+ if (state.filters.tags.length > 0) {+ filters.tags = state.filters.tags+ }+ if (state.filters.unassigned) {+ filters.unassigned = true+ }+ if (state.filters.assignedTo.length > 0) {+ filters.assignedTo = state.filters.assignedTo+ }+ if (state.filters.tileFilter) {+ filters.tileFilter = state.filters.tileFilter+ }+ return {+ columns: state.columns,+ order_by: sortOrderToOrderBy(state.sortOrder),+ filters,+ properties: { tiles: state.tiles },+ }+}++export function deserializeAccountsView(view: Partial<ColumnConfigurationApi>): AccountsViewState {+ // The backend normalizes empty filters to `[]`; treat any non-object as empty.+ const rawFilters = (+ view.filters && !Array.isArray(view.filters) ? view.filters : {}+ ) as Partial<AccountsViewFilters>+ const rawProperties = (+ view.properties && typeof view.properties === 'object' ? view.properties : {}+ ) as AccountsViewProperties++ return {+ columns: view.columns && view.columns.length > 0 ? view.columns : [...ACCOUNTS_HOGQL_DEFAULT_SELECT],+ sortOrder: orderByToSortOrder(view.order_by),+ filters: {+ search: rawFilters.search ?? '',+ tags: rawFilters.tags ?? [],+ unassigned: rawFilters.unassigned ?? false,+ assignedTo: normalizeRoleFilter(rawFilters.assignedTo),+ tileFilter: rawFilters.tileFilter ?? null,+ },+ tiles: rawProperties.tiles && rawProperties.tiles.length > 0 ? rawProperties.tiles : [...DEFAULT_TILES],+ }+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.tsnew file mode 100644index 000000000000..687d0684b6e6--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts@@ -0,0 +1,259 @@+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from '~/lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { userLogic } from 'scenes/userLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'++import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'+import { accountsLogic } from './accountsLogic'+import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'+import { accountsViewsLogic } from './accountsViewsLogic'+import { DEFAULT_TILES } from './constants'++const CURRENT_USER_ID = MOCK_DEFAULT_USER.id++const buildView = (overrides: Partial<ColumnConfigurationApi> = {}): ColumnConfigurationApi =>+ ({+ id: 'view-1',+ context_key: 'customer_analytics_accounts_columns',+ columns: ['name', 'csm'],+ name: 'Enterprise',+ filters: { search: 'acme', assignedTo: [1] },+ order_by: ['csm DESC'],+ properties: { tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' } }] },+ visibility: 'shared',+ created_by: CURRENT_USER_ID,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ ...overrides,+ }) as ColumnConfigurationApi++describe('accountsViewsLogic', () => {+ let logic: ReturnType<typeof accountsViewsLogic.build>++ const mountAll = (): void => {+ accountsColumnConfigLogic().mount()+ accountsOverviewTilesLogic().mount()+ accountsLogic().mount()+ logic = accountsViewsLogic()+ logic.mount()+ }++ beforeEach(() => {+ // Set up POSTHOG_APP_CONTEXT with MOCK_DEFAULT_USER before initKeaTests so+ // the user is pre-loaded (mirrors how the app bootstraps in production).+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ current_team: MOCK_DEFAULT_TEAM,+ current_user: MOCK_DEFAULT_USER,+ } as any+ initKeaTests()+ userLogic.mount()+ })++ afterEach(() => {+ localStorage.clear()+ })++ it('lists views on mount', async () => {+ useMocks({ get: { '/api/environments/:team_id/column_configurations/': { count: 1, results: [buildView()] } } })+ mountAll()+ await expectLogic(logic)+ .toDispatchActions(['loadViewsSuccess'])+ .toMatchValues({+ views: [expect.objectContaining({ id: 'view-1' })],+ })+ })++ it('applyView hydrates columns, filters, sort, and tiles', async () => {+ useMocks({ get: { '/api/environments/:team_id/column_configurations/': { count: 0, results: [] } } })+ mountAll()+ const view = buildView({+ filters: {+ search: 'acme',+ tags: ['enterprise'],+ unassigned: false,+ assignedTo: [1, 2, 3],+ tileFilter: { tileId: 't1', expression: 'mrr > 100' },+ },+ })+ await expectLogic(logic, () => logic.actions.applyView(view)).toFinishAllListeners()++ expect(accountsColumnConfigLogic.values.selectColumns).toEqual(['name', 'csm'])+ expect(accountsLogic.values.searchQuery).toEqual('acme')+ expect(accountsLogic.values.tagsFilter).toEqual(['enterprise'])+ expect(accountsLogic.values.allRolesUnassigned).toBe(false)+ expect(accountsLogic.values.assignedToFilter).toEqual([1, 2, 3])+ expect(accountsLogic.values.sortOrder).toEqual({ column: 'csm', direction: 'desc' })+ expect(accountsOverviewTilesLogic.values.tiles).toEqual([+ { id: 't1', label: 'Accounts', metric: { type: 'count' } },+ ])+ expect(accountsOverviewTilesLogic.values.tileFilter).toEqual({ tileId: 't1', expression: 'mrr > 100' })+ expect(logic.values.currentViewId).toEqual('view-1')+ })++ it('isDirty flips when live state diverges from the applied view and clears on re-apply', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/column_configurations/': { count: 1, results: [buildView()] },+ },+ })+ mountAll()+ // Wait for loadViewsSuccess so the view is in views, then select it+ await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])+ logic.actions.applyView(buildView())+ await expectLogic(logic).toMatchValues({ isDirty: false })++ accountsLogic.actions.setSearchQuery('changed')+ await expectLogic(logic).toMatchValues({ isDirty: true })++ logic.actions.applyView(buildView())+ await expectLogic(logic).toMatchValues({ isDirty: false })+ })++ it('deleteView clears currentViewId when the active view is removed', async () => {+ useMocks({+ get: { '/api/environments/:team_id/column_configurations/': { count: 1, results: [buildView()] } },+ delete: { '/api/environments/:team_id/column_configurations/:id/': [204] },+ })+ mountAll()+ await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])+ logic.actions.applyView(buildView())+ await expectLogic(logic, () => logic.actions.deleteView({ id: 'view-1' }))+ .toDispatchActions(['deleteViewSuccess'])+ .toMatchValues({ currentViewId: null })+ })++ it('rename seeds the form with the current name and patches the trimmed name on submit', async () => {+ let patchedBody: any = null+ useMocks({+ get: { '/api/environments/:team_id/column_configurations/': { count: 1, results: [buildView()] } },+ patch: {+ '/api/environments/:team_id/column_configurations/:id/': async (req: any) => {+ patchedBody = await req.json()+ return [200, buildView({ name: patchedBody.name })]+ },+ },+ })+ mountAll()+ await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])++ await expectLogic(logic, () => logic.actions.setViewToRename('view-1'))+ .toDispatchActions(['setRenameViewFormValue'])+ .toMatchValues({ viewToRename: 'view-1', renameViewForm: { name: 'Enterprise' } })++ logic.actions.setRenameViewFormValue('name', ' Renamed ')+ await expectLogic(logic, () => logic.actions.submitRenameViewForm())+ .toDispatchActions(['updateView', 'updateViewSuccess'])+ .toMatchValues({ viewToRename: null })+ expect(patchedBody.name).toBe('Renamed')+ })++ it('migrates localStorage tiles into the creator-owned default row exactly once', async () => {+ const customTiles = [{ id: 'mine', label: 'Mine', metric: { type: 'count' as const } }]+ let patchedBody: any = null+ useMocks({+ get: {+ '/api/environments/:team_id/column_configurations/': {+ count: 1,+ results: [buildView({ properties: {} })],+ },+ },+ patch: {+ '/api/environments/:team_id/column_configurations/:id/': async (req: any) => {+ patchedBody = await req.json()+ return [200, buildView({ properties: patchedBody.properties })]+ },+ },+ })+ accountsColumnConfigLogic().mount()+ accountsOverviewTilesLogic().mount()+ accountsOverviewTilesLogic.actions.setTiles(customTiles)+ accountsLogic().mount()+ logic = accountsViewsLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions([+ 'loadViewsSuccess',+ 'patchViewProperties',+ 'patchViewPropertiesSuccess',+ ])+ expect(patchedBody.properties).toEqual({ tiles: customTiles })+ })++ it('does not migrate when localStorage tiles are the defaults', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/column_configurations/': {+ count: 1,+ results: [buildView({ properties: {} })],+ },+ },+ })+ accountsColumnConfigLogic().mount()+ accountsOverviewTilesLogic().mount()+ accountsOverviewTilesLogic.actions.setTiles([...DEFAULT_TILES])+ accountsLogic().mount()+ logic = accountsViewsLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadViewsSuccess']).toFinishAllListeners()+ expect(logic.values.views[0].properties).toEqual({})+ })++ it('does not migrate into a row the user did not create', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/column_configurations/': {+ count: 1,+ results: [buildView({ properties: {}, created_by: 999 })],+ },+ },+ })+ accountsColumnConfigLogic().mount()+ accountsOverviewTilesLogic().mount()+ accountsOverviewTilesLogic.actions.setTiles([{ id: 'mine', label: 'Mine', metric: { type: 'count' as const } }])+ accountsLogic().mount()+ logic = accountsViewsLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadViewsSuccess']).toFinishAllListeners()+ expect(logic.values.views[0].properties).toEqual({})+ })++ it('preserves migrated tiles when the migrated row is the restored current view', async () => {+ const customTiles = [{ id: 'mine', label: 'Mine', metric: { type: 'count' as const } }]+ localStorage.setItem(+ `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,+ JSON.stringify('view-1')+ )+ useMocks({+ get: {+ '/api/environments/:team_id/column_configurations/': {+ count: 1,+ results: [buildView({ properties: {} })],+ },+ },+ patch: {+ '/api/environments/:team_id/column_configurations/:id/': async (req: any) => {+ const body = await req.json()+ return [200, buildView({ properties: body.properties })]+ },+ },+ })+ accountsColumnConfigLogic().mount()+ accountsOverviewTilesLogic().mount()+ accountsOverviewTilesLogic.actions.setTiles(customTiles)+ accountsLogic().mount()+ logic = accountsViewsLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadViewsSuccess', 'patchViewProperties', 'applyView'])+ expect(accountsOverviewTilesLogic.values.tiles).toEqual(customTiles)+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.tsnew file mode 100644index 000000000000..db14356734bd--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts@@ -0,0 +1,303 @@+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { objectsEqual } from 'lib/utils'+import { getCurrentTeamId } from 'lib/utils/getAppContext'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'++import { ACCOUNTS_COLUMN_CONFIG_KEY, accountsColumnConfigLogic } from './accountsColumnConfigLogic'+import { accountsLogic } from './accountsLogic'+import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'+import type { accountsViewsLogicType } from './accountsViewsLogicType'+import {+ AccountsViewProperties,+ AccountsViewState,+ deserializeAccountsView,+ serializeAccountsView,+} from './accountsViewState'+import { AccountsEvents, DEFAULT_TILES } from './constants'++export type ViewVisibility = 'private' | 'shared'++export const accountsViewsLogic = kea<accountsViewsLogicType>([+ path(['scenes', 'customerAnalytics', 'accounts', 'accountsViewsLogic']),+ connect(() => ({+ values: [+ teamLogic,+ ['currentTeamId'],+ userLogic,+ ['user'],+ accountsColumnConfigLogic,+ ['selectColumns'],+ accountsLogic,+ ['searchQuery', 'tagsFilter', 'allRolesUnassigned', 'assignedToFilter', 'sortOrder'],+ accountsOverviewTilesLogic,+ ['tiles', 'tileFilter'],+ ],+ actions: [+ accountsColumnConfigLogic,+ ['setSelectColumns'],+ accountsLogic,+ ['setSearchQuery', 'setTagsFilter', 'setAllRolesUnassigned', 'setAssignedToFilter', 'setSortOrder'],+ accountsOverviewTilesLogic,+ ['setTiles', 'setTileFilter'],+ ],+ })),+ actions({+ selectView: (id: string) => ({ id }),+ applyView: (view: ColumnConfigurationApi) => ({ view }),+ setCurrentViewId: (id: string | null) => ({ id }),+ setIsCreating: (isCreating: boolean) => ({ isCreating }),+ setViewToDelete: (id: string | null) => ({ id }),+ setViewToRename: (id: string | null) => ({ id }),+ }),+ loaders(({ values }) => ({+ views: [+ [] as ColumnConfigurationApi[],+ {+ loadViews: async (): Promise<ColumnConfigurationApi[]> => {+ const response = await api.columnConfigurations.list({ context_key: ACCOUNTS_COLUMN_CONFIG_KEY })+ return response.results+ },+ updateView: async ({+ id,+ updates,+ }: {+ id: string+ updates: Partial<ColumnConfigurationApi>+ }): Promise<ColumnConfigurationApi[]> => {+ const data =+ Object.keys(updates).length === 0 ? serializeAccountsView(values.liveViewState) : updates+ const response = await api.columnConfigurations.update({ id, data })+ return values.views.map((view) => (view.id === id ? response : view))+ },+ deleteView: async ({ id }: { id: string }): Promise<ColumnConfigurationApi[]> => {+ await api.columnConfigurations.delete({ id })+ return values.views.filter((view) => view.id !== id)+ },+ patchViewProperties: async ({+ id,+ properties,+ }: {+ id: string+ properties: AccountsViewProperties+ }): Promise<ColumnConfigurationApi[]> => {+ const response = await api.columnConfigurations.update({ id, data: { properties } })+ return values.views.map((view) => (view.id === id ? response : view))+ },+ },+ ],+ })),+ reducers(() => ({+ currentViewId: [+ null as string | null,+ {+ persist: true,+ storageKey: `customerAnalytics.accounts.accountsViewsLogic.${getCurrentTeamId()}.currentViewId`,+ },+ {+ setCurrentViewId: (_, { id }) => id,+ deleteViewSuccess: (state, { views }) => (state && !views.find((v) => v.id === state) ? null : state),+ },+ ],+ isCreating: [+ false,+ {+ setIsCreating: (_, { isCreating }) => isCreating,+ submitNewViewFormSuccess: () => false,+ },+ ],+ viewToDelete: [+ null as string | null,+ {+ setViewToDelete: (_, { id }) => id,+ },+ ],+ viewToRename: [+ null as string | null,+ {+ setViewToRename: (_, { id }) => id,+ updateViewSuccess: () => null,+ },+ ],+ })),+ selectors({+ liveViewState: [+ (s) => [+ s.selectColumns,+ s.searchQuery,+ s.tagsFilter,+ s.allRolesUnassigned,+ s.assignedToFilter,+ s.sortOrder,+ s.tileFilter,+ s.tiles,+ ],+ (+ selectColumns,+ searchQuery,+ tagsFilter,+ allRolesUnassigned,+ assignedToFilter,+ sortOrder,+ tileFilter,+ tiles+ ): AccountsViewState => ({+ columns: selectColumns,+ sortOrder,+ filters: {+ search: searchQuery,+ tags: tagsFilter,+ unassigned: allRolesUnassigned,+ assignedTo: assignedToFilter,+ tileFilter,+ },+ tiles,+ }),+ ],+ currentView: [+ (s) => [s.views, s.currentViewId],+ (views, currentViewId): ColumnConfigurationApi | null =>+ views.find((view) => view.id === currentViewId) ?? null,+ ],+ isDirty: [+ (s) => [s.currentView, s.liveViewState],+ (currentView, liveViewState): boolean =>+ currentView+ ? !objectsEqual(+ serializeAccountsView(deserializeAccountsView(currentView)),+ serializeAccountsView(liveViewState)+ )+ : false,+ ],+ canEditCurrentView: [+ (s) => [s.currentView, s.user],+ (currentView, user): boolean => !!currentView && !!user && currentView.created_by === user.id,+ ],+ }),+ forms(({ actions, values }) => ({+ newViewForm: {+ defaults: { name: '', visibility: 'private' as ViewVisibility },+ errors: ({ name }: { name: string }) => ({ name: !name?.trim() ? 'Name is required' : undefined }),+ submit: async ({ name, visibility }: { name: string; visibility: ViewVisibility }) => {+ const response = await api.columnConfigurations.create({+ data: {+ ...serializeAccountsView(values.liveViewState),+ context_key: ACCOUNTS_COLUMN_CONFIG_KEY,+ name: name.trim(),+ visibility,+ },+ })+ actions.loadViews()+ actions.applyView(response)+ actions.resetNewViewForm()+ posthog.capture(AccountsEvents.ViewSaved, { visibility })+ },+ },+ renameViewForm: {+ defaults: { name: '' },+ errors: ({ name }: { name: string }) => ({ name: !name?.trim() ? 'Name is required' : undefined }),+ submit: ({ name }: { name: string }) => {+ if (values.viewToRename) {+ actions.updateView({ id: values.viewToRename, updates: { name: name.trim() } })+ }+ },+ },+ })),+ listeners(({ actions, values }) => ({+ selectView: ({ id }) => {+ const view = values.views.find((v) => v.id === id)+ if (view) {+ actions.applyView(view)+ }+ },+ applyView: ({ view }) => {+ const state = deserializeAccountsView(view)+ actions.setSelectColumns(state.columns)+ actions.setSearchQuery(state.filters.search)+ actions.setTagsFilter(state.filters.tags)+ // accountsLogic cross-clears the assigned-to filter vs "unassigned only", so set the+ // unassigned flag first so the assigned-to filter below isn't wiped by that cross-listener.+ actions.setAllRolesUnassigned(state.filters.unassigned)+ actions.setAssignedToFilter(state.filters.assignedTo)+ actions.setSortOrder(state.sortOrder)+ actions.setTiles(state.tiles)+ actions.setTileFilter(state.filters.tileFilter)+ actions.setCurrentViewId(view.id)+ posthog.capture(AccountsEvents.ViewSelected, { visibility: view.visibility })+ },+ setViewToRename: ({ id }) => {+ const view = id ? values.views.find((v) => v.id === id) : undefined+ if (view) {+ actions.setRenameViewFormValue('name', view.name)+ }+ },+ updateViewSuccess: () => {+ lemonToast.success('View updated')+ posthog.capture(AccountsEvents.ViewUpdated)+ actions.resetRenameViewForm()+ },+ updateViewFailure: ({ error }) => {+ posthog.captureException(error)+ lemonToast.error('Failed to update view')+ },+ deleteViewSuccess: () => {+ lemonToast.success('View deleted')+ posthog.capture(AccountsEvents.ViewDeleted)+ },+ deleteViewFailure: ({ error }) => {+ posthog.captureException(error)+ lemonToast.error('Failed to delete view')+ },+ loadViewsFailure: ({ error }) => {+ posthog.captureException(error)+ lemonToast.error('Failed to load views')+ },+ submitNewViewFormFailure: ({ error }) => {+ posthog.captureException(error)+ lemonToast.error('Failed to save view')+ },+ patchViewPropertiesFailure: ({ error }) => {+ // Silent background migration — no toast, just capture the exception.+ posthog.captureException(error)+ },+ loadViewsSuccess: ({ views }) => {+ let migratedView: ColumnConfigurationApi | null = null+ if (!objectsEqual(values.tiles, DEFAULT_TILES)) {+ const candidate = views.find(+ (view) =>+ view.created_by === values.user?.id &&+ !(view.properties as AccountsViewProperties | undefined)?.tiles?.length+ )+ if (candidate) {+ actions.patchViewProperties({ id: candidate.id, properties: { tiles: values.tiles } })+ // The async patch hasn't landed in `views` yet; restoring the stale row below+ // would make applyView reset the working tiles to defaults and lose the migration.+ migratedView = { ...candidate, properties: { tiles: values.tiles } }+ }+ }++ const hashHasView = !!router.values.hashParams?.view+ if (values.currentViewId && !hashHasView) {+ const view =+ migratedView?.id === values.currentViewId+ ? migratedView+ : views.find((v) => v.id === values.currentViewId)+ if (view) {+ actions.applyView(view)+ }+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadViews()+ }),+])diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex b236e4eaeee0..a770d47fdde6 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -11,11 +11,13 @@ export const DEFAULT_TILES: AccountsOverviewTile[] = [{ id: 'default-accounts', label: 'Accounts', metric: { type: 'count' } },]-const teamIdForPersistence = window.POSTHOG_APP_CONTEXT?.current_team?.id-export const ACCOUNTS_OVERVIEW_PERSIST_CONFIG = {- persist: true,- prefix: `${teamIdForPersistence}_customer_analytics_accounts_overview__`,-}+// Overview tiles used to be persisted per-team in localStorage; they now live in saved views+// (`properties.tiles`). We no longer WRITE this key — `accountsOverviewTilesLogic` only reads any+// pre-existing value once on mount (to seed the working state) and emits an+// `OverviewTilesLocalStorageRead` tombstone. Once that event stops firing, no browser still carries+// a legacy value and this read path (plus the prefix) can be deleted.+const overviewTilesTeamId = window.POSTHOG_APP_CONTEXT?.current_team?.id+export const ACCOUNTS_OVERVIEW_LEGACY_TILES_PREFIX = `${overviewTilesTeamId}_customer_analytics_accounts_overview__`// Canonical analytics event names for the accounts list. Every `posthog.capture`// in this directory must reference these — a mistyped string silently forks a new@@ -29,6 +31,11 @@ export const AccountsEvents = {Sorted: 'customer analytics accounts sorted',ColumnsSaved: 'customer analytics accounts columns saved',OverviewTilesEdited: 'customer analytics accounts overview tiles edited',+ OverviewTilesLocalStorageRead: 'customer analytics accounts overview tiles localstorage read',+ ViewSaved: 'customer analytics accounts view saved',+ ViewUpdated: 'customer analytics accounts view updated',+ ViewSelected: 'customer analytics accounts view selected',+ ViewDeleted: 'customer analytics accounts view deleted',RoleAssigned: 'customer analytics account role assigned',LinkClicked: 'customer analytics account link clicked',NoteClicked: 'customer analytics account note clicked',diff --git a/products/customer_analytics/package.json b/products/customer_analytics/package.jsonindex 583d1666448f..8e3d9532ae7d 100644--- a/products/customer_analytics/package.json+++ b/products/customer_analytics/package.json@@ -5,6 +5,7 @@},"dependencies": {"kea": "catalog:",+ "kea-forms": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:","kea-test-utils": "catalog:",diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex a2cf370fcc7c..e6a38b61ccbc 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -25,12 +25,15 @@ export interface ColumnConfigurationApi {columns?: string[]/** @maxLength 255 */name?: string+ /** Column filter state persisted with this view configuration. */filters?: unknown/*** Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.* @nullable*/order_by?: string[] | null+ /** Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display). */+ properties?: unknownvisibility?: VisibilityEnumApi/** @nullable */readonly created_by: number | null@@ -54,12 +57,15 @@ export interface PatchedColumnConfigurationApi {columns?: string[]/** @maxLength 255 */name?: string+ /** Column filter state persisted with this view configuration. */filters?: unknown/*** Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.* @nullable*/order_by?: string[] | null+ /** Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display). */+ properties?: unknownvisibility?: VisibilityEnumApi/** @nullable */readonly created_by?: number | nulldiff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.tsindex f05d62bd6c76..6cb33d9cd3cd 100644--- a/products/product_analytics/frontend/generated/api.zod.ts+++ b/products/product_analytics/frontend/generated/api.zod.ts@@ -17,13 +17,19 @@ export const ColumnConfigurationsCreateBody = /* @__PURE__ */ zod.object({context_key: zod.string().max(columnConfigurationsCreateBodyContextKeyMax),columns: zod.array(zod.string()).optional(),name: zod.string().max(columnConfigurationsCreateBodyNameMax).optional(),- filters: zod.unknown().optional(),+ filters: zod.unknown().optional().describe('Column filter state persisted with this view configuration.'),order_by: zod.array(zod.string()).nullish().describe('Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.'),+ properties: zod+ .unknown()+ .optional()+ .describe(+ 'Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display).'+ ),visibility: zod.enum(['private', 'shared']).optional()@@ -38,13 +44,19 @@ export const ColumnConfigurationsUpdateBody = /* @__PURE__ */ zod.object({context_key: zod.string().max(columnConfigurationsUpdateBodyContextKeyMax),columns: zod.array(zod.string()).optional(),name: zod.string().max(columnConfigurationsUpdateBodyNameMax).optional(),- filters: zod.unknown().optional(),+ filters: zod.unknown().optional().describe('Column filter state persisted with this view configuration.'),order_by: zod.array(zod.string()).nullish().describe('Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.'),+ properties: zod+ .unknown()+ .optional()+ .describe(+ 'Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display).'+ ),visibility: zod.enum(['private', 'shared']).optional()@@ -59,13 +71,19 @@ export const ColumnConfigurationsPartialUpdateBody = /* @__PURE__ */ zod.object(context_key: zod.string().max(columnConfigurationsPartialUpdateBodyContextKeyMax).optional(),columns: zod.array(zod.string()).optional(),name: zod.string().max(columnConfigurationsPartialUpdateBodyNameMax).optional(),- filters: zod.unknown().optional(),+ filters: zod.unknown().optional().describe('Column filter state persisted with this view configuration.'),order_by: zod.array(zod.string()).nullish().describe('Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.'),+ properties: zod+ .unknown()+ .optional()+ .describe(+ 'Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display).'+ ),visibility: zod.enum(['private', 'shared']).optional()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d47789fe0433..0cf9a158bf0c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12552,12 +12552,15 @@ export namespace Schemas {columns?: string[];/** @maxLength 255 */name?: string;+ /** Column filter state persisted with this view configuration. */filters?: unknown;/*** Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.* @nullable*/order_by?: string[] | null;+ /** Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display). */+ properties?: unknown;visibility?: VisibilityEnum;/** @nullable */readonly created_by: number | null;@@ -32894,12 +32897,15 @@ export namespace Schemas {columns?: string[];/** @maxLength 255 */name?: string;+ /** Column filter state persisted with this view configuration. */filters?: unknown;/*** Ordered list of HogQL expressions describing the table sort. Null preserves the current sort on apply (legacy rows); an empty list explicitly means no sort.* @nullable*/order_by?: string[] | null;+ /** Product-specific view state that does not fit the columnar fields (e.g. Customer analytics overview tiles and column display). */+ properties?: unknown;visibility?: VisibilityEnum;/** @nullable */readonly created_by?: number | null;