Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(customer-analytics): preserve unsaved account filters (#99545)

jake sciottob6996abf097c
diff --git a/docs/internal/customer-analytics-accounts-table.md b/docs/internal/customer-analytics-accounts-table.md
index 0875d8911e2c..605a1e6a4350 100644
--- a/docs/internal/customer-analytics-accounts-table.md
+++ b/docs/internal/customer-analytics-accounts-table.md
@@ -1,4 +1,35 @@
-# Accounts table column widths
+# Accounts table
+
+## Unsaved filters and views
+
+The Accounts list keeps unsaved filters when a user opens an account and returns to the list.
+The draft includes search, tags, assignment filters, account property and relationship filters, and the selected overview tile filter.
+It also keeps sorting, selected columns, column display settings, and overview tile settings.
+
+The browser stores one draft per project and user in `sessionStorage`.
+Draft restoration waits for the loaded project and user IDs before deciding whether to apply a saved view.
+Automatic column updates do not replace the pending draft with default URL state.
+The draft survives list remounts and page reloads in the same tab.
+It does not update a saved view or store account rows.
+Closing the browser tab ends the draft session.
+
+Restoration uses this order:
+
+1. An explicit `#view` in the URL takes priority over the draft, including an empty view.
+2. Without a view hash, the list restores the draft.
+3. Without a draft, the list restores the last selected saved view, if available.
+4. Otherwise, the list uses its defaults and the shared My accounts preference.
+
+Selecting a saved view replaces the draft.
+Clearing filters keeps them cleared on return, even when a saved view remains selected.
+Saving or updating a view still requires an explicit action.
+If browser storage is unavailable or invalid, the list uses URL state and saved views without failing.
+
+`accountsLogic.viewState` supplies the shared snapshot for drafts and saved views.
+`applyViewState` restores it without intermediate URL writes.
+The parent scene preserves the view hash when changing date or test-account filters.
+
+## Column widths
The Customer analytics Accounts list sizes new columns to their rendered header and loaded values.
Automatic widths have an 80px minimum and a 200px maximum.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index da6f6a6203aa..cb7554feb742 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6173,9 +6173,9 @@ snapshots:
products-workflows-reputation--shared-sending-domain--light:
hash: v1.k794b7964.95181ed4e0a17456b9e62c3e467ddc605b1a733c81ea6f7c6e0c61928aa3f22d.ZMctRK-G6wUmjfa2paqyxhRtmF0TG_WVyOPLWhFWXyU
products-workflows-steps-customer-task-reference-input--account--dark:
- hash: v1.k794b7964.c83bf0997a28fd49e6d3dbae06e5ee75aa10a76365a5cb39c530324ecf112875.addysRvtjXvOb8pPGo4RZl1HL2_YcGnvqrpSB067bNs
+ hash: v1.k794b7964.835bf9b0ff1b7768ce199ca0d32952cb9fa278dd063a985849bb648ec9b655bd.W4Xi4ysAnLzglAUcc-NmmQ883jFKKE5zbV3JqZDfh3Y
products-workflows-steps-customer-task-reference-input--account--light:
- hash: v1.k794b7964.a373f14a674936c9fd76f26ce8abbf735b977f4a4dbaf90ff3c785cd16eb9ea8.toZvK0UtefEnMcf994SYInWq-s3Vhtju6U-rMzq5E9Q
+ hash: v1.k794b7964.360aadf7704195ebe1620ac71737c9954c4f0158a20e64cd79f95c2beff959f8.5OJ3uKSE3ak1E67pgaD8Bz1aldYzDuT921U8cp6scOc
products-workflows-steps-customer-task-reference-input--assignee--dark:
hash: v1.k794b7964.6aba25e0cf13e9f0851aab52c7e13e4f849a386bae1e387c9931e5aeb2c1d445.vdRw1Brlx8435mOkTj6OS8IhQslGTaZ2BBExKMLnRNI
products-workflows-steps-customer-task-reference-input--assignee--light:
@@ -6841,9 +6841,9 @@ snapshots:
scenes-app-customer-analytics-accounts--default--light:
hash: v1.k794b7964.b986d24c5b87d97314d1b6fcd605ef453d56ffef2c2f3d6408722db977cf1fb2.1CjtHSZqb1ZDLB_hE3PLlIdf4IE4oCpn_BhAJh_DsQs
scenes-app-customer-analytics-accounts--empty--dark:
- hash: v1.k794b7964.8fcd9fb5b85daa321159db0495f6eff17e81c41db13a132c6600506a88476f89.I6cRb24I_X1dd6XnkTh03BfpNuowY_Tl3phT9K4i_lc
+ hash: v1.k794b7964.438df1869b5277d02ec0f8f8dc6ffda458f257203a885dc34d0cdf6681665f4b.MfhdrLGE7U65Q0md0ydoz254zQmGDPW4Xilis8C8gxc
scenes-app-customer-analytics-accounts--empty--light:
- hash: v1.k794b7964.3833ace8ef40228fe67853ed97f183807bdb64a2c28b750822d311d986ec9f6c.QsSmBvyfg2-9I9jdYbxvHC4o0cSuZFhnQHtIsRJ7Eek
+ hash: v1.k794b7964.d440a51b1fea226d13d070be68297057ec12bbd72ee7ac4ba61fe41b9ed53cb3.dEhN6yGCfnCaECmg3tof6UcHiHCk2k5XBtTE6xDmezQ
scenes-app-customer-analytics-accounts--feature-gate-off--dark:
hash: v1.k794b7964.4b8d5226ee154debdf333ff93d65a90ca766bcb25951e1baf36affb8b84b548d.dWZSHssPc83RkHVE-JPJA562bJR7MUim2yfqhjfNE50
scenes-app-customer-analytics-accounts--feature-gate-off--light:
@@ -6853,45 +6853,45 @@ snapshots:
scenes-app-customer-analytics-accounts--many-columns--light:
hash: v1.k794b7964.41369848fe476522e301d6e10665de13e88a1a8a64c4a17a2adc81306f24b64e.kaZ8ldUFXD5oEmnfoaB6ag8wg77wYPwSi0dCsHVX6Lk
scenes-app-customer-analytics-accounts--row-expanded-conversations--dark:
- hash: v1.k794b7964.8ff40502a6dee9453d8bdff2350aa96b20c7c241a7ce2d69325e2d0e754f4428.LP6kVjCyhWYU85XTY8Fi5v6H_pdS8hu27wxDUCv_yCc
+ hash: v1.k794b7964.bd5d33f06635b1fa2ac401e370dfad9e7c125e349f41bd172cafb5e38aeab721.7jRlvWfxiKE6Dp9YRZQ9MWzbZlKypIJd7WQbE-Zscjw
scenes-app-customer-analytics-accounts--row-expanded-conversations--light:
- hash: v1.k794b7964.f2d44fd0549e2fa8bbc1ebc0fa533c80681d59afaf2f5ee1c3d7ec9cdfa32d02.cTPXhB1CmxHFVvDo01-_QlU7FU2Fd_I_AntpUTtWdCk
+ hash: v1.k794b7964.fb56da84bf7207f04b189874dde79eb0e001e5e370429a9796b1e4c0b3d0099f.LYDaaQIU0fct9Q-q-hTr6r4XWlbHRqAfhRQ1bL2KCQE
scenes-app-customer-analytics-accounts--row-expanded-empty--dark:
- hash: v1.k794b7964.29607bee93ae98e4333700dd5bdc02468aaa7962bd5e8c9c11c68a2fcecd0500.9NYrLmodwfzvPX32lADBb9E2Pt1Sd-aIyjaICjJzo7I
+ hash: v1.k794b7964.090b5451367cbc88e18653dc1899467cefe5f44e55d181a4837a9ba028e30ead.PMoKZW79l2Ve6A_haEZtirAB2EbBXGoQylPzm1jUyb0
scenes-app-customer-analytics-accounts--row-expanded-empty--light:
- hash: v1.k794b7964.6cad6b9a256482bae27919396c1e0e220f91fe187a6c00863b66d57a05dacd47.p23fCm9EIYytbqGvqYkzHQrTxJQW_ZZjMoNUg6T3M6M
+ hash: v1.k794b7964.a91ffd7fc2442f3dbb6be4c84701345b72b2359420cc7e6f9039a1ac5ff4d063.c7Tg3Wa9BIaqhkxnOPPDAZcfAX5amRz2xlcK33TVvg0
scenes-app-customer-analytics-accounts--row-expanded-feature-requests--dark:
- hash: v1.k794b7964.22059f7f48b0b9d8f2239c5b39db812ca1fc4b96a2e1dd3819e9e28a782d6310.savfzCdHPDJXGsMCCJbm-aWLBnyjHQJ1UinQEyfmo8k
+ hash: v1.k794b7964.ecbed5422bc8cd789bf9b455cf0ddecb47092d3da59dcd28ad47c83afac648ba.1rDHj438lRhPOmE_J7QHobW6I0fx318RqMK3PIEBFns
scenes-app-customer-analytics-accounts--row-expanded-feature-requests--light:
- hash: v1.k794b7964.2379806be50888eaf2e0194d51772ef9c980b51e5daede8d1734cf21c181f972.wnpx0rEnz9_cGzxPKECx6PktPM06h9ulnrC2DLRKfFo
+ hash: v1.k794b7964.99974e44f77fc4ed83a182763355f604cbdc3a85b5cca849a8cacc410a655346.BDjnpHkdZ-V2_x74U-Y8UBRNUe_XBHnXB8PUP_iaWVU
scenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:
- hash: v1.k794b7964.3f0b9cf7a5f73764b4255caeb9fd1408f3bebaded5ecc56f0b2c72622e62a85c.UYyJSPEbo6T_S585H9z27Kx4EizBtQXbvMB7Xv0l5gA
+ hash: v1.k794b7964.4c0c753752f96153f8d35b0a0e276223e56f31c473f05bfd045dc65afebc8a93.uXxcKILaw61jSsFBo6h6uH7Udwu2esrWIEpAuKxlE7Y
scenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:
- hash: v1.k794b7964.fecc6437de11626b0cf0cc5bfcf3aad070a1e5d27aae512ce69f570201b48755.G4A3DOHjjKcZw2_uHgJMiQQ_cd5Z8dKJfsUE5jakicU
+ hash: v1.k794b7964.3357c1d1e85dcf873b250fe5cc19f695a5d82301ac2bf5dc8c71b9c48993ef5a.Ni88T6lNxljQO27P-1Sr9qGkehA6tN-pcrI93tPO634
scenes-app-customer-analytics-accounts--row-expanded-no-pinned-properties--dark:
- hash: v1.k794b7964.56d8b186f08668f3047f49f605465062735328453b6bb73bf34ccdde70ec11a6.GSd68pAu60P7fbhVwsa-tHzn72Dwi09a5WHZ5wSuxFg
+ hash: v1.k794b7964.88c560218198aeef0e61775c4b3087f7a0111d53d4aa9873e7e28c8df7cedbe9.KVXryNv9x89Q3hGic4DdnU-ALGPGQ6dzMqnrQ--frIw
scenes-app-customer-analytics-accounts--row-expanded-no-pinned-properties--light:
- hash: v1.k794b7964.ed01fa4e6aab01c7b257acabeea1c56c3ba31bfb8a8428ab699f4454b6c059bc.vQmrjSd93LVjfZMHWJ2SWoizJ1BIQtvXbIU1qx7iWYw
+ hash: v1.k794b7964.d1bbe7fadec01dcf5468bc307e5ddaf120c0a05cf354a8107be95a3d08cba094.a-jmv3Srry1RzTZNouTKL2SWYazNQqcwBvP2fWbCGgE
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties--dark:
- hash: v1.k794b7964.ac0790e90174fb5efd6483dc6baf16faa2ba2af73be21b90f314abb4a6bba9fd.KE6ECCpuBo2nZwLLU761SRPopER_xfg2zHXKJoW7sGo
+ hash: v1.k794b7964.0ba788c8004420790805420e9fda4e5aff7d7998e1fd99a727aaf7bbcfdca91d.LSIRN0fG5xJ2vaBijLX79E90sMHQjE60Hv0b-5upebQ
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties--light:
- hash: v1.k794b7964.892c8c4da5f2f2c956b7def2828ba9ae8784d1a5750f9d0eb22883cea0be3fe4.qCeMIWaEHzrhhZQgt6gtpGwNWuH3KqbpKhkKbd1ln5A
+ hash: v1.k794b7964.d8070b3478d26d3b52732d8aaba87a87d8bcbd48d69bd393058ac8c00c0b8bb4.2ByzGyRTZ8iYL0G9DunC3aP2yNPGjHsXDLMN0zya1hA
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--dark:
- hash: v1.k794b7964.3e1b407b49bd893a9fb9be047d649a9f81dc808f7d0ed8955085b2569a26f7a6.NOJ1KaCBUuXEgswiXi3Flh1IS3YF4A0RpsPGCPIeqIc
+ hash: v1.k794b7964.48fbedcb90e1b63a9f3472a750d84a9aed6226671a529eaacf20c832dd33be29.dPfzWKCqVueqTXahDik4Xgw_2dxOau-s9rE-AMbHegQ
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--light:
- hash: v1.k794b7964.04f0591b5e63beb094f749d3b878f3a7eda3a8574d9010c074412ba59066db20.RG6m392829qV5zThnr4-5RmO6U7SZR3sjilQP_z44TE
+ hash: v1.k794b7964.5a08aeda76cd76b0203cdfaa8976522682bc1e83c70e62e4707f2b04cffb0634.zh56uPyuehDrM76JRt6h_aO3DdwqMUhE14dAx8BsUJ8
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-narrow--dark:
hash: v1.k794b7964.0744617a1ccc1001d37549505a05ddd841e38c271b3dd074613a35cf89e510a3.YLhXPX1yCfuxgSj0xqsu5IIObl76j1_K83LsT9RFmSY
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-narrow--light:
hash: v1.k794b7964.5912ee881d6495f775a5249c9bc22a83707e68596688d859ff88af7b9d2cf6db.PVsL-j2sGlo7PBa7CLDfvUzf8yMgy9g5UnCUvRBZ67w
scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:
- hash: v1.k794b7964.7d1acf4345f2ee184544bfee7048d1d0ad1d19c0c65bdb40bddfd662d582f395._y4rxyYg67P4b92wYq1k36vGSPXjjez0JDvb6enO0_g
+ hash: v1.k794b7964.c52ec75dc9d1a1395448ca3a58bba70b8c43f8b676bff58dbdd7ae681256047a.PyQHfa6BWGInmt3T2c_8rZdl_ZO3Gi3Ruz7cOh-MGAI
scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:
- hash: v1.k794b7964.f4c5975d4feb66aa5af3db61390f3413211279828a36ab3bfa095bf00a3f2278.QzMeIdxkMlBeJA8ixWW3xwiQNXLjwMxm8lv-YDG8-AU
+ hash: v1.k794b7964.7e2ff4de82c53bcefa5cb3fcfa1447eed42c528b60bec062e277b5e2e6eb9554.MiAv2PZu3TrJ2oTuUAJf96rKt1zGdU2HHaOBv0dl2lM
scenes-app-customer-analytics-accounts--row-expanded-with-note--dark:
- hash: v1.k794b7964.844fff084c587550dbba83ba6304b80205309905cff4feddfa4ab17a71a9dc5d.4pZxCwpuFbz9by6Z_XUtRNYdqbE4-iwLPSt8aO15tKY
+ hash: v1.k794b7964.e8866368c6f77514a1668f447c4286cb54223561a75532cd9b3dbe635153ff0d.4XhzwWuCbAiOobD5GWyLEFqLucISfDr0gvaFXDbSZME
scenes-app-customer-analytics-accounts--row-expanded-with-note--light:
- hash: v1.k794b7964.f617faf6a1a4488b4d082a2e883b9d8f89d98b41b7b341e4e48132397c5a5144.3OSquo7HF7WG_3RxcLD04sI_knR6JYM-_jiPwX2yJsk
+ hash: v1.k794b7964.d2eba0241e41de35bea04e4de46914e70df9f95f48e3a28f31a85b313b3a5663.hMr_iWK7eUn2kq7m4pvVnB7BcOHg_--Yv7fphuUrhwo
scenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--dark:
hash: v1.k794b7964.676001075ee700388d9cdd0c7ec45430e7fc40c5b7aedbb7e26efe0e01ccee30.9lZ1hXCdIHbJEf7RqEWimEYspfWdC8UsIE8LKrK6c7c
scenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--light:
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 6099e7a963bc..12f45c8cf17a 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -238,6 +238,22 @@ The Notes tab is server-paginated, searchable, and sortable (all via `accountNot
`accountsLogic` mirrors the full view (search, tags, assignment status, assigned-to, native-field and custom-property filters, sort, columns, tile filter) into the URL hash `#view=...` via `actionToUrl`/`urlToAction`, so a copied URL reproduces the exact list. Column widths stay in browser-local preferences instead of the URL because they are display preferences. 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).
+A list URL without a `#view=` hash must not erase the shared "mine only" toggle.
+The tab link, account breadcrumb, and older history entries can return to the list without a view hash.
+`restoreViewStateFromRoute` restores the session draft first. Without a draft, it uses the shared `mineOnly` preference.
+Resolve assignment intent before calling `applyViewState`, because assignment setters also update the shared preference.
+For the same reason, anything that rewrites the Customer analytics URL (the scene's date and test-account writers in `customerAnalyticsSceneLogic`) must carry the current hash through.
+
+### Unsaved drafts
+
+`accountsLogic.viewState` owns the full snapshot used by session drafts and saved views.
+`applyViewState` restores the snapshot without intermediate URL writes.
+Drafts use project-and-user-scoped `sessionStorage`, including cleared filters and unsaved changes to a selected view.
+The draft key comes from loaded `teamLogic` and `userLogic` state. Draft hydration and automatic saved-view restoration wait for both IDs.
+An explicit shared URL wins over the draft. The draft wins over automatic saved-view restoration.
+Selecting a saved view explicitly replaces the draft.
+See [Accounts table](../../../../../docs/internal/customer-analytics-accounts-table.md) when changing persistence or navigation.
+
### Deep-link to one account (path route)
`/customer_analytics/accounts/:accountId/:tab` opens the account detail scene when `CUSTOMER_ANALYTICS_ACCOUNT_SCENE` is enabled.
@@ -282,7 +298,7 @@ Views are persisted as `ColumnConfiguration` rows under `context_key = 'customer
**Visibility** is `private` or `shared`. The owner can see and change a private view. Any team member who can see a shared view can edit or delete it. When a team member makes a shared view private, the view becomes that member's private view.
**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`.
+A shared link's `#view=` URL hash or a session draft takes priority over the saved `currentViewId`.
When saved views exist but the viewer has no last-used view, the selector remains available without applying a view automatically.
`isDirty` is true when the live state diverges from the selected view's saved state.
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index 829764a9f0b4..f506d9a57399 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -23,14 +23,10 @@ import type {
import { ACCOUNT_FIELD_TAXONOMIC_OPTIONS, propertyTypeForDisplayType } from './accountsPropertyFilters'
-// 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.
export const ACCOUNTS_NAME_COLUMN = 'name'
-// The three role columns predate relationship definitions, so saved views and shared
-// URLs store them as bare names. They map by name onto the team's seeded relationship
-// definitions and translate into the relationships lazy join at query-build time
-// (`translateSelectColumns`).
+// Legacy role names remain serialized for saved views and shared URLs.
+// Query planning maps them to seeded relationship definitions.
export const LEGACY_ROLE_COLUMNS = {
csm: 'CSM',
account_executive: 'Account executive',
@@ -43,8 +39,6 @@ export function isLegacyRoleColumn(column: string): column is AccountRoleKey {
return column in LEGACY_ROLE_COLUMNS
}
-// Pre-load seed only — `defaultSelectColumns` appends one relationship column per
-// definition once the team's definitions load.
export const ACCOUNTS_DEFAULT_COLUMNS: string[] = [
ACCOUNTS_NAME_COLUMN,
'accounts.tags.names AS tag_names',
@@ -72,8 +66,6 @@ export function diffColumnConfiguration(
export const ACCOUNTS_COLUMN_CONFIG_KEY = 'customer_analytics_accounts_columns'
-// `allTablesMap` keys system tables by their fully qualified name (e.g.
-// `system.accounts`), matching `resolve_visible_table_names()` on the backend.
export const ACCOUNTS_ACCOUNTS_TABLE_NAME = 'system.accounts'
export type AccountColumnGroupKey = 'account_properties' | 'custom_properties' | 'relationships' | `accounts.${string}`
@@ -81,9 +73,7 @@ export type AccountColumnGroupKey = 'account_properties' | 'custom_properties' |
export const ALL_COLUMNS_KEY = 'all'
export type PickerGroupKey = AccountColumnGroupKey | typeof ALL_COLUMNS_KEY
-// Custom property definition ids are UUIDs, which aren't valid HogQL identifiers (hyphens).
-// Strip them so the column alias is a clean identifier, and so the renderer can map a visible
-// column name back to its definition.
+// Persisted aliases must keep this format so saved views can resolve their columns.
export function customPropertyAlias(id: string): string {
return `cp_${id.replace(/-/g, '')}`
}
@@ -99,8 +89,7 @@ export interface AccountColumnDisplayConfig {
window_days: number
}
-// Keyed by custom property definition id (not alias) so the config survives column
-// removal/re-add and matches how saved views key custom-property filters.
+// Use definition IDs so the config survives column removal and re-addition.
export type AccountColumnDisplayState = Record<string, AccountColumnDisplayConfig>
export const COLUMN_DISPLAY_WINDOW_OPTIONS = [7, 14, 30, 90] as const
@@ -108,9 +97,7 @@ export const DEFAULT_COLUMN_DISPLAY_WINDOW_DAYS = 7
const CUSTOM_PROPERTY_COLUMN_REGEX = /^accounts\.custom_properties\.values\.`([0-9a-fA-F-]+)` AS (cp_[0-9a-fA-F]+)$/
-// Sparkline/trend columns select the write history instead of the current value. The swap
-// happens at query-build time so the stored column string (saved views, shared URLs) stays
-// in the stable scalar form.
+// Keep stored column strings scalar so saved views and shared URLs stay stable.
export function applyColumnDisplayToSelect(columns: string[], columnDisplay: AccountColumnDisplayState): string[] {
if (Object.keys(columnDisplay).length === 0) {
return columns
@@ -142,10 +129,7 @@ export function roleKeyToDefinitionMap(
)
}
-// Legacy role names resolve through the relationships lazy join, keeping the stored
-// column name (and thus saved views, URL state, and cell renderers) stable. A legacy
-// role with no matching definition is dropped from the query — the definition was
-// renamed or never seeded, so there is nothing to select.
+// Keep legacy role names stable in persisted state. Omit roles without a matching definition.
export function translateSelectColumns(
columns: string[],
roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>
@@ -173,7 +157,6 @@ export type AccountColumnGroup = {
export type AccountPickerColumnOption = AccountColumnOption & { groupLabel: string; isSelected: boolean }
-// Null activeGroup means "All columns": search spans every non-freeform group.
export function filterColumnOptions(
groups: AccountColumnGroup[],
activeGroup: AccountColumnGroup | null,
@@ -194,19 +177,13 @@ export function filterColumnOptions(
)
}
-// Field types that point at joined tables/views (lazy joins, virtual tables,
-// user-defined data warehouse joins, saved queries). Each one surfaces as a
-// dedicated dropdown entry in the column configurator.
const JOIN_FIELD_TYPES = new Set(['lazy_table', 'virtual_table', 'view', 'materialized_view'])
-// Joins that already have a friendly, definition-driven picker group — surfacing
-// their raw backing tables (account_id + a JSON blob) would just duplicate them.
+// Definition-driven groups replace these raw joins.
const HIDDEN_JOIN_GROUPS = new Set(['custom_properties', 'relationships'])
const POSTGRES_BACKED_JOIN_GROUPS = new Set(['tags', 'notebooks'])
const POSTGRES_BACKED_ACCOUNT_FIELDS = new Set<string>(Object.values(AccountsTableAccountField))
-// Field types we omit from the "Account properties" group — these are
-// navigation aliases, joined tables (handled separately), or unknown types.
const SKIPPED_DIRECT_FIELD_TYPES = new Set([
'lazy_table',
'virtual_table',
@@ -223,9 +200,6 @@ function buildJoinOptions(
): AccountColumnOption[] {
return fields.map((name) => ({
name,
- // `accounts.<join>.<col> AS <col>` — alias keeps the visible column
- // name human-readable while disambiguating columns that collide with
- // direct fields (e.g. `name` on a joined table).
expression: `accounts.${fieldName}.${name} AS ${name}`,
type: joinedTable?.fields?.[name]?.type,
}))
@@ -243,14 +217,11 @@ function customPropertyOptions(definitions: CustomPropertyDefinitionApi[]): Acco
return definitions.map((definition) => ({
name: definition.name,
type: definition.display_type,
- // JSON dot-access through the lazy join (`events.person.properties.foo` analog), aliased to a
- // clean identifier so the alias round-trips through `visibleColumnNames` / `aliasToDefinition`.
expression: `accounts.custom_properties.values.\`${definition.id}\` AS ${customPropertyAlias(definition.id)}`,
}))
}
-// Seeded definitions keep their legacy bare name as the picker expression so selecting
-// them dedupes against the default columns; other definitions get a rel_ alias.
+// Keep seeded role names compatible with default columns and persisted selections.
function relationshipOptions(definitions: AccountRelationshipDefinitionApi[]): AccountColumnOption[] {
return definitions.map((definition) => ({
name: definition.name,
@@ -275,8 +246,7 @@ export function buildAccountColumnGroups(
return
}
seenJoinKeys.add(key)
- // Every join under `system.accounts` carries the `accounts.` prefix
- // — drop it from the user-facing label since it's just visual noise.
+ // Hide the internal accounts prefix from picker labels.
joinGroups.push({ key, label: fieldName, options })
}
@@ -301,8 +271,6 @@ export function buildAccountColumnGroups(
}
}
- // Omit definition-driven groups entirely when the team has no definitions, so the
- // category dropdown doesn't show empty entries.
const customPropertyGroups: AccountColumnGroup[] =
customPropertyDefinitions.length > 0
? [
@@ -434,6 +402,9 @@ export interface accountsColumnConfigLogicActions {
resetColumns: () => {
value: true
}
+ restoreSelectColumns: (columns: string[]) => {
+ columns: string[]
+ }
selectColumn: (column: string) => {
column: string
}
@@ -547,12 +518,12 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
['allTablesMap', 'databaseLoading'],
],
actions: [databaseTableListLogic, ['loadDatabase', 'ensureAllTableFields']],
- // Keep propertyDefinitionsModel mounted so the seeded custom-property definitions
- // (see loadCustomPropertyDefinitionsSuccess) survive until the filter UI reads them.
+ // Keep seeded property definitions mounted for the filter picker.
logic: [propertyDefinitionsModel],
})),
actions({
setSelectColumns: (columns: string[]) => ({ columns }),
+ restoreSelectColumns: (columns: string[]) => ({ columns }),
selectColumn: (column: string) => ({ column }),
unselectColumn: (column: string) => ({ column }),
moveColumn: (oldIndex: number, newIndex: number) => ({ oldIndex, newIndex }),
@@ -573,6 +544,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
[...ACCOUNTS_DEFAULT_COLUMNS],
{
setSelectColumns: (_, { columns }) => ensureNameColumn(columns),
+ restoreSelectColumns: (_, { columns }) => ensureNameColumn(columns),
selectColumn: (state, { column }) => (state.includes(column) ? state : [...state, column]),
unselectColumn: (state, { column }) =>
column === ACCOUNTS_NAME_COLUMN ? state : state.filter((c) => c !== column),
@@ -588,13 +560,13 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
resetColumns: () => [...ACCOUNTS_DEFAULT_COLUMNS],
},
],
- // Which visible-column row the configurator's edit section targets. Any action that
- // reshuffles or replaces the column list closes the editor so the index can't go stale.
+ // Clear the editor when the column index can change.
editingColumnIndex: [
null as number | null,
{
setEditingColumnIndex: (_, { index }) => index,
setSelectColumns: () => null,
+ restoreSelectColumns: () => null,
unselectColumn: () => null,
moveColumn: () => null,
resetColumns: () => null,
@@ -618,7 +590,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
'',
{
setPickerSearch: (_, { search }) => search,
- // A stale query from another category would silently hide results.
+ // Clear searches when changing categories to avoid hiding results.
setPickerGroupKey: () => '',
},
],
@@ -635,9 +607,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
setColumnDisplayConfig: (_, { config }) => config,
},
],
- // Queries wait for this so the list fetches once with its final columns,
- // instead of fetching with the base columns and refetching after the
- // definitions land (a wasted query and a visible column pop).
+ // Wait for definitions to avoid a second query and visible column changes.
relationshipDefinitionsLoaded: [
false,
{
@@ -667,8 +637,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
],
})),
selectors({
- // Seeded definitions keep their legacy bare name so existing saved views and
- // shared URLs dedupe against them.
+ // Keep legacy names so defaults dedupe persisted selections.
defaultSelectColumns: [
(s) => [s.relationshipDefinitions],
(relationshipDefinitions: AccountRelationshipDefinitionApi[]): string[] => [
@@ -687,9 +656,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
): Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>> =>
roleKeyToDefinitionMap(relationshipDefinitions),
],
- // What the AccountsQuery actually selects: `selectColumns` with legacy role
- // names resolved through the relationships lazy join (or dropped when the
- // matching definition doesn't exist). Row cells align to THIS list.
querySelectColumns: [
(s) => [s.selectColumns, s.roleKeyToDefinition, s.columnDisplay],
(
@@ -744,8 +710,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
(selectColumns: string[], editingColumnIndex: number | null): string | null =>
editingColumnIndex !== null ? (selectColumns[editingColumnIndex] ?? null) : null,
],
- // Re-keyed by the cp_<id> column alias so cell renderers can look up their
- // display mode by visible column name.
displayByAlias: [
(s) => [s.columnDisplay],
(columnDisplay: AccountColumnDisplayState): AccountColumnDisplayState =>
@@ -756,8 +720,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
])
),
],
- // The same map re-keyed by the cp_<id> column alias — resolves visible column
- // names back to their definition (table header, configurator labels).
aliasToDefinition: [
(s) => [s.customPropertyDefinitionsById],
(
@@ -791,8 +753,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
property_type: PropertyType.Assignee,
})),
],
- // Items for the custom-properties taxonomic group (fed via `optionsFromProp`): the
- // definition id is the stable filter key, the name is what's displayed and searched.
customPropertyTaxonomicOptions: [
(s) => [s.customPropertyDefinitions],
(
@@ -811,8 +771,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
property_type: propertyTypeForDisplayType(definition.display_type),
})),
],
- // Resolves a visible column name (legacy role key or rel_ alias) back to its
- // relationship definition — drives the cell renderer and header label.
aliasToRelationshipDefinition: [
(s) => [s.relationshipDefinitions, s.roleKeyToDefinition],
(
@@ -826,23 +784,23 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
}),
],
}),
- listeners(({ actions, values, selectors }) => ({
- // Seed the shared propertyDefinitionsModel so OperatorValueSelect resolves each
- // custom property's type (numeric/boolean/datetime/string) to the right operator set.
+ listeners(({ actions, values, selectors, cache }) => ({
+ // Seed property types so filters show valid operators.
loadCustomPropertyDefinitionsSuccess: () => {
updatePropertyDefinitions(
Object.fromEntries(
values.customPropertyTaxonomicOptions.map((option) => [
`${PropertyDefinitionType.AccountCustomProperty}/${option.id}`,
- // name is the id, not the display name: OperatorValueSelect resolves
- // the definition by matching `name` against the filter key (the id).
+ // Filters resolve definitions by ID, not the display name.
{ id: option.id, name: option.id, property_type: option.property_type },
])
)
)
},
- // Customized columns (user edits, saved view, shared URL) no longer equal the
- // default they diverged from, so only still-default columns get upgraded.
+ restoreSelectColumns: () => {
+ cache.hasRestoredColumns = true
+ },
+ // Only upgrade unchanged defaults. Never replace restored selections.
loadRelationshipDefinitionsSuccess: (_, __, ___, previousState) => {
updatePropertyDefinitions(
Object.fromEntries(
@@ -854,6 +812,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
)
const previousDefault = selectors.defaultSelectColumns(previousState)
if (
+ !cache.hasRestoredColumns &&
objectsEqual(values.selectColumns, previousDefault) &&
!objectsEqual(values.defaultSelectColumns, values.selectColumns)
) {
@@ -861,6 +820,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
}
},
resetColumns: () => {
+ cache.hasRestoredColumns = false
if (!objectsEqual(values.selectColumns, values.defaultSelectColumns)) {
actions.setSelectColumns(values.defaultSelectColumns)
}
@@ -875,13 +835,10 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
])
)
)
- // 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) {
actions.loadDatabase()
} else {
- // The store may hold a shallow (fields-less) schema left by the SQL editor; the
- // column picker needs every table's fields.
+ // The picker needs fields when the SQL editor loaded only shallow schemas.
actions.ensureAllTableFields()
}
actions.loadCustomPropertyDefinitions()
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 55646c7890ab..e28eb52716ae 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -1,9 +1,12 @@
-import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'
+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from '~/lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { setOAuthContextIds } from 'lib/oauth/oauthClient'
+import { getCurrentTeamIdOrNone, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -42,8 +45,10 @@ import {
relationshipAlias,
} from './accountsColumnConfigLogic'
import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'
-import { accountsLogic, customPropertySavingKey, savingRoleKey } from './accountsLogic'
-import { AccountsEvents } from './constants'
+import { accountsLogic, customPropertySavingKey, savingRoleKey, SEARCH_DEBOUNCE_MS } from './accountsLogic'
+import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'
+import { readAccountsViewDraft, writeAccountsViewDraft } from './accountsViewState'
+import { AccountsEvents, DEFAULT_TILES } from './constants'
const assignedToFilterOf = (query: AccountsTableQuery | null): number[] | undefined =>
query?.filters?.find((filter) => filter.kind === 'assigned_to')?.userIds
@@ -90,6 +95,34 @@ const TILE_FILTER = {
},
}
+const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'
+
+const ACCOUNT_FILTERS = [
+ {
+ type: PropertyFilterType.Account as const,
+ key: AccountsTableAccountField.IgnoredAt,
+ label: 'Ignored at',
+ operator: PropertyOperator.IsSet,
+ value: null,
+ },
+ {
+ type: PropertyFilterType.AccountCustomProperty as const,
+ key: CSM_DEFINITION_ID,
+ label: 'Health score',
+ operator: PropertyOperator.GreaterThan,
+ value: 5,
+ },
+ {
+ type: PropertyFilterType.AccountRelationship as const,
+ key: CSM_DEFINITION_ID,
+ label: 'CSM',
+ operator: PropertyOperator.Exact,
+ value: [42],
+ },
+]
+
+const CUSTOM_TILES = [{ id: 'tile-1', label: 'Accounts', metric: { type: 'count' as const } }]
+
const DEFINITIONS: AccountRelationshipDefinitionApi[] = [
{ id: CSM_DEFINITION_ID, name: 'CSM', description: null, is_single_holder: true },
{ id: AE_DEFINITION_ID, name: 'Account executive', description: null, is_single_holder: true },
@@ -165,11 +198,18 @@ describe('accountsLogic', () => {
let logic: ReturnType<typeof accountsLogic.build>
beforeEach(async () => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ current_team: MOCK_DEFAULT_TEAM,
+ current_user: MOCK_DEFAULT_USER,
+ } as any
initKeaTests()
+ router.actions.push(urls.customerAnalyticsAccounts())
jest.resetAllMocks()
// accountsLogic connects to the (localStorage-persisted) shared scene logic;
// clear it so a "mine only" write in one test can't leak into the next.
localStorage.clear()
+ sessionStorage.clear()
mockDefinitionsList.mockResolvedValue({ count: DEFINITIONS.length, results: DEFINITIONS })
mockCustomPropertiesList.mockResolvedValue({ count: 0, results: [] })
logic = accountsLogic()
@@ -181,6 +221,8 @@ describe('accountsLogic', () => {
afterEach(() => {
logic.unmount()
localStorage.clear()
+ sessionStorage.clear()
+ jest.useRealTimers()
resumeKeaLoadersErrors()
})
@@ -303,11 +345,14 @@ describe('accountsLogic', () => {
expect(logic.values.searchQuery).toBe('acme')
})
- it('setSearchInput updates the input immediately but defers the committed searchQuery', () => {
+ it('setSearchInput updates the input immediately but defers the committed searchQuery', async () => {
+ jest.useFakeTimers()
logic.actions.setSearchInput('acme')
expect(logic.values.searchInput).toBe('acme')
// Debounced: the query-driving value is not committed synchronously.
expect(logic.values.searchQuery).toBe('')
+ await jest.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)
+ expect(logic.values.searchQuery).toBe('acme')
})
it('withholds the list and metrics queries until relationship definitions settle', async () => {
@@ -327,6 +372,67 @@ describe('accountsLogic', () => {
expect(logic.values.metricsQuery).not.toBeNull()
})
+ it.each([
+ ['the user before the team', ['user', 'team']],
+ ['the team before the user', ['team', 'user']],
+ ])('restores a draft when %s resolves without bootstrap or OAuth identity helpers', async (_, arrivals) => {
+ logic.unmount()
+ window.POSTHOG_APP_CONTEXT = undefined
+ setOAuthContextIds(null)
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+ userLogic.actions.loadUserSuccess(null)
+ writeAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid, {
+ columns: [...ACCOUNTS_DEFAULT_COLUMNS],
+ sortOrder: null,
+ filters: {
+ search: 'restored after identity',
+ assignmentStatus: 'all',
+ assignedTo: [],
+ tags: [],
+ tileFilter: null,
+ customProperties: [],
+ },
+ tiles: [...DEFAULT_TILES],
+ columnDisplay: {},
+ })
+
+ expect(getCurrentTeamIdOrNone()).toBeNull()
+ expect(getCurrentUserIdOrNone()).toBeNull()
+
+ logic = accountsLogic()
+ logic.mount()
+ expect(logic.values.viewStateHydrated).toBe(false)
+ expect(logic.values.accountsQuerySource).toBeNull()
+
+ accountsColumnConfigLogic.findMounted()!.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(router.values.hashParams.view).toBeUndefined()
+
+ for (const arrival of arrivals) {
+ if (arrival === 'user') {
+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)
+ } else {
+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ expect(logic.values.viewStateHydrated).toBe(true)
+ expect(logic.values.searchQuery).toBe('restored after identity')
+ expect(logic.values.accountsQuerySource).not.toBeNull()
+
+ const otherUser = { ...MOCK_DEFAULT_USER, uuid: 'other-user-uuid' }
+ await expectLogic(logic, () => userLogic.actions.loadUserSuccess(otherUser)).toFinishAllListeners()
+ expect(logic.values.searchQuery).toBe('')
+
+ logic.actions.setSearchQuery('other user draft')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.filters.search).toBe(
+ 'restored after identity'
+ )
+ expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, otherUser.uuid)?.filters.search).toBe('other user draft')
+ })
+
it('removes relationship filters when relationship definitions fail to load', async () => {
logic.unmount()
silenceKeaLoadersErrors()
@@ -500,6 +606,8 @@ describe('accountsLogic', () => {
it('restores "my accounts" from the shared toggle when the URL has no view hash', async () => {
customerAnalyticsSceneLogic.actions.setMineOnly(true)
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
+ await expectLogic(logic).toFinishAllListeners()
router.actions.push(urls.customerAnalyticsAccounts())
await expectLogic(logic).toFinishAllListeners()
@@ -507,6 +615,22 @@ describe('accountsLogic', () => {
expect(logic.values.assignedToCurrentUser).toBe(true)
})
+ // Regression: returning to the list on a URL with no view hash (the browser back
+ // button onto an entry written before the filter was picked, the tab link, or the
+ // breadcrumb) reset the status to "all", which cross-cleared the assigned-to filter
+ // and cascaded into setMineOnly(false), so the choice was gone for good.
+ it('keeps "my accounts" when the list URL loses the view hash', async () => {
+ logic.actions.setAssignedToCurrentUser(true)
+ await expectLogic(logic).toFinishAllListeners()
+
+ router.actions.push(urls.customerAnalyticsAccounts())
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])
+ expect(logic.values.assignmentStatus).toBe('assigned')
+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)
+ })
+
it('an explicit shared link still wins over the shared toggle', async () => {
customerAnalyticsSceneLogic.actions.setMineOnly(true)
router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: { assignedTo: [7] } })
@@ -520,6 +644,7 @@ describe('accountsLogic', () => {
// resolves the user (currentUserId null), so the persisted choice can't be applied
// then. The user resolving later must apply it, without clearing the preference.
it('applies the persisted "my accounts" choice when the user resolves after restore', async () => {
+ userLogic.actions.loadUserSuccess(null)
customerAnalyticsSceneLogic.actions.setMineOnly(true)
expect(logic.values.assignedToFilter).toEqual([])
@@ -688,15 +813,26 @@ describe('accountsLogic', () => {
expect(router.values.hashParams.view).toBeUndefined()
})
- it('restores filters, sort, and tile filter from the view hash param', async () => {
+ it('restores filters, sort, and tile filter when browser back returns to the original view hash', async () => {
const tileFilter = TILE_FILTER
- router.actions.push(
- urls.customerAnalyticsAccounts(),
- {},
- {
- view: { search: 'beta', assignedTo: [7], sort: { column: 'name', direction: 'desc' }, tileFilter },
- }
- )
+ const view = {
+ search: 'beta',
+ assignedTo: [7],
+ sort: { column: 'name', direction: 'desc' as const },
+ tileFilter,
+ }
+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { view })
+ await expectLogic(logic).toFinishAllListeners()
+ const listLocation = router.values.currentLocation
+ logic.actions.setTiles(CUSTOM_TILES)
+
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
+ await expectLogic(logic).toFinishAllListeners()
+ router.actions.locationChanged({
+ ...listLocation,
+ url: `${listLocation.pathname}${listLocation.search}${listLocation.hash}`,
+ method: 'POP',
+ })
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.searchQuery).toBe('beta')
@@ -704,6 +840,49 @@ describe('accountsLogic', () => {
expect(logic.values.assignedToFilter).toEqual([7])
expect(logic.values.sortOrder).toEqual({ column: 'name', direction: 'desc' })
expect(logic.values.tileFilter).toEqual(tileFilter)
+ expect(logic.values.tiles).toEqual(CUSTOM_TILES)
+ })
+
+ it.each(['name', 'csm'])('keeps the %s sort while default columns load after Back', async (column) => {
+ logic.actions.setSortOrder({ column, direction: 'desc' })
+ const listLocation = router.values.currentLocation
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))
+ logic.unmount()
+ initKeaTests()
+
+ let resolveDefinitions!: (value: { count: number; results: AccountRelationshipDefinitionApi[] }) => void
+ mockDefinitionsList.mockReturnValue(new Promise((resolve) => (resolveDefinitions = resolve)))
+ router.actions.locationChanged({
+ ...listLocation,
+ url: `${listLocation.pathname}${listLocation.search}${listLocation.hash}`,
+ method: 'POP',
+ })
+ logic = accountsLogic()
+ logic.mount()
+ expect(logic.values.sortOrder).toEqual({ column, direction: 'desc' })
+
+ resolveDefinitions({ count: DEFINITIONS.length, results: DEFINITIONS })
+ await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()
+ expect(logic.values.sortOrder).toEqual({ column, direction: 'desc' })
+ const rows = ['a', 'b'].map((id, index) => ({
+ result: {
+ id,
+ name: id,
+ accountFields: {},
+ relationships: { [CSM_DEFINITION_ID]: [index + 1] },
+ customProperties: {},
+ customPropertyHistory: {},
+ },
+ }))
+ expect(logic.values.sortedRowsTransformer?.(rows)).toEqual([rows[1], rows[0]])
+ logic.actions.listLoadNextData()
+ expect(logic.values.accountsQuerySource?.sort).toEqual({
+ column:
+ column === 'name'
+ ? { kind: 'account_field', field: 'name' }
+ : { kind: 'relationship', definitionId: CSM_DEFINITION_ID },
+ direction: 'desc',
+ })
})
it('coerces a malformed scalar assignedTo from the view hash into an array', async () => {
@@ -756,6 +935,149 @@ describe('accountsLogic', () => {
const config = accountsColumnConfigLogic.findMounted()
expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm'])
})
+
+ it.each([
+ ['a mounted list', false],
+ ['a remounted list', true],
+ ['a remounted account detail', 'detail'],
+ ])('keeps every unsaved view setting after detail navigation through %s', async (_, remountOnDetail) => {
+ mockCustomPropertiesList.mockResolvedValue({
+ count: 1,
+ results: [buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID })],
+ })
+ logic.actions.loadCustomPropertyDefinitionsSuccess([
+ buildCustomPropertyDefinition({ id: CSM_DEFINITION_ID }),
+ ])
+ const columnConfig = accountsColumnConfigLogic.findMounted()!
+ columnConfig.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
+ columnConfig.actions.moveColumn(0, 1)
+ expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.columns).toEqual([
+ 'csm',
+ ACCOUNTS_NAME_COLUMN,
+ ])
+ columnConfig.actions.setColumnDisplay(CSM_DEFINITION_ID, { mode: 'sparkline', window_days: 30 })
+ logic.actions.setSearchQuery('draft search')
+ logic.actions.setTagsFilter(['enterprise'])
+ logic.actions.setAssignedToFilter([7])
+ logic.actions.updateAccountFilters(ACCOUNT_FILTERS)
+ logic.actions.setSortOrder({ column: 'csm', direction: 'desc' })
+ const overviewTiles = accountsOverviewTilesLogic.findMounted()!
+ overviewTiles.actions.addTile(CUSTOM_TILES[0])
+ expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.tiles).toEqual([
+ ...DEFAULT_TILES,
+ CUSTOM_TILES[0],
+ ])
+ overviewTiles.actions.moveTile(0, 1)
+ expect(readAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid)?.tiles).toEqual([
+ CUSTOM_TILES[0],
+ ...DEFAULT_TILES,
+ ])
+ logic.actions.setTileFilter(TILE_FILTER)
+ await expectLogic(logic).toFinishAllListeners()
+ const expectedViewState = logic.values.viewState
+
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
+ await expectLogic(logic).toFinishAllListeners()
+ if (remountOnDetail) {
+ logic.unmount()
+ logic = accountsLogic()
+ }
+ if (remountOnDetail === 'detail') {
+ logic.mount()
+ await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()
+ }
+ router.actions.push(urls.customerAnalyticsAccounts())
+ if (remountOnDetail === true) {
+ logic.mount()
+ }
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.viewState).toEqual(expectedViewState)
+ expect(logic.values.accountsQuerySource?.filters).toEqual(
+ expect.arrayContaining([
+ { kind: 'search', query: 'draft search' },
+ { kind: 'tags', tagNames: ['enterprise'] },
+ { kind: 'assigned_to', userIds: [7] },
+ expect.objectContaining({ kind: 'account_field' }),
+ expect.objectContaining({ kind: 'custom_property' }),
+ expect.objectContaining({ kind: 'relationship' }),
+ ])
+ )
+
+ logic.actions.setTagsFilter(['renewal'])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(router.values.hashParams.view).toEqual(
+ expect.objectContaining({
+ search: 'draft search',
+ tags: ['renewal'],
+ assignedTo: [7],
+ sort: { column: 'csm', direction: 'desc' },
+ columns: ['csm', ACCOUNTS_NAME_COLUMN],
+ tileFilter: TILE_FILTER,
+ customProperties: ACCOUNT_FILTERS,
+ })
+ )
+ })
+
+ it.each([
+ ['an empty shared view', {}, '', 'all'],
+ ['a populated shared view', { search: 'shared', assignmentStatus: 'all' }, 'shared', 'all'],
+ ])(
+ 'uses %s instead of the saved draft and keeps it as the next draft',
+ async (_, sharedView, search, status) => {
+ logic.actions.setSearchQuery('draft')
+ logic.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
+ logic.actions.setAssignedToFilter([7])
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+
+ const customerAnalyticsScene = customerAnalyticsSceneLogic()
+ customerAnalyticsScene.mount()
+ customerAnalyticsScene.actions.setMineOnly(true)
+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: sharedView })
+ logic = accountsLogic()
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.searchQuery).toBe(search)
+ expect(logic.values.assignmentStatus).toBe(status)
+ expect(logic.values.assignedToFilter).toEqual([])
+ expect(logic.values.selectColumns).toEqual(logic.values.defaultSelectColumns)
+ expect(
+ capture.mock.calls.some(([event]) =>
+ [
+ AccountsEvents.FilterChanged,
+ AccountsEvents.OverviewTilesEdited,
+ AccountsEvents.Searched,
+ AccountsEvents.Sorted,
+ ].some((interactionEvent) => interactionEvent === event)
+ )
+ ).toBe(false)
+
+ logic.unmount()
+ router.actions.push(urls.customerAnalyticsAccounts())
+ logic = accountsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.searchQuery).toBe(search)
+ expect(logic.values.assignmentStatus).toBe(status)
+ expect(logic.values.assignedToFilter).toEqual([])
+ customerAnalyticsScene.unmount()
+ }
+ )
+
+ it('does not let a pending search overwrite a shared view restored from browser navigation', async () => {
+ jest.useFakeTimers()
+ logic.actions.setSearchInput('stale search')
+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: { search: 'shared search' } })
+ await jest.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.searchQuery).toBe('shared search')
+ expect(logic.values.searchInput).toBe('shared search')
+ })
})
describe('deep link (path route)', () => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index afd11ea263e2..c0838b64449a 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -57,6 +57,7 @@ import {
DEFAULT_ACCOUNT_TAB,
} from './accountsExpansionLogic'
import { accountsOverviewTilesLogic, TileFilter } from './accountsOverviewTilesLogic'
+import type { AccountsOverviewTile } from './accountsOverviewTilesLogic'
import type { AccountFilter } from './accountsPropertyFilters'
import { sortAccountRows } from './accountsSort'
import {
@@ -67,17 +68,20 @@ import {
isAccountsTableRow,
supportedAccountFilters,
} from './accountsTableQuery'
-import { normalizeRoleFilter } from './accountsViewState'
-import { AccountsEvents } from './constants'
+import {
+ AccountsViewState,
+ normalizeRoleFilter,
+ readAccountsViewDraft,
+ writeAccountsViewDraft,
+} from './accountsViewState'
+import { AccountsEvents, DEFAULT_TILES } from './constants'
export const SEARCH_DEBOUNCE_MS = 300
-// ObjectTags fires onChange per added/removed tag; the debounce collapses an
-// editing burst into one full-list PATCH.
+// Debounce tag edits because ObjectTags emits each addition and removal separately.
export const TAGS_SAVE_DEBOUNCE_MS = 300
-// Revealing an off-screen account triggers an async refetch, so its row may not
-// be in the DOM yet — poll briefly for it before scrolling.
+// Wait for refetched rows before scrolling to an account.
const SCROLL_TO_ACCOUNT_POLL_MS = 100
const SCROLL_TO_ACCOUNT_MAX_ATTEMPTS = 40
@@ -90,9 +94,7 @@ interface SortLikeActions {
setSortOrder: (sortOrder: AccountSortOrder) => void
}
-// Sort safety: if the user removes the column currently being sorted on, drop
-// the sort — otherwise the backend receives an `orderBy` that references a
-// non-existent alias.
+// A removed column cannot supply a client sort key or a typed server sort reference.
function clearSortIfColumnRemoved(values: SortLikeValues, actions: SortLikeActions): void {
const sort = values.sortOrder
if (!sort) {
@@ -107,8 +109,6 @@ export type RoleFilterValue = number[]
export type AccountFilterType = 'tag' | 'assignment_status' | 'my_accounts' | 'assigned_to'
-// `column` matches the visible column name (alias-stripped) so any selected
-// column can drive the sort.
export type AccountSortableColumn = string
export type AccountSortDirection = 'asc' | 'desc'
@@ -120,30 +120,61 @@ export const savingRoleKey = (accountId: string, column: string): string => `${a
export const customPropertySavingKey = (accountId: string, definitionId: string): string =>
`${accountId}:${definitionId}`
-// Which accounts path the shareable view state gets written back to. It must be the path we are
-// already on: the setters that mirror view state into the URL also fire while state is being
-// restored (the default-column upgrade once relationship definitions load, the auto-restored saved
-// view), so pointing them at the list would bounce a single-account deep link to the unfiltered
-// list moments after it opened. Returns the live pathname so the deep link keeps its `/:tab`.
-function accountsPathToWriteBackTo(accountIdFilter: string | null): string {
+// Late list updates must not leave an account detail route or navigate back from another scene.
+function accountsPathToWriteBackTo(accountIdFilter: string | null): string | null {
const pathname = removeProjectIdIfPresent(router.values.location.pathname)
+ if (pathname === urls.customerAnalyticsAccounts()) {
+ return pathname
+ }
const deepLinkPath = accountIdFilter ? urls.customerAnalyticsAccount(accountIdFilter) : null
- return deepLinkPath && pathname.startsWith(deepLinkPath) ? pathname : urls.customerAnalyticsAccounts()
+ return deepLinkPath && pathname.startsWith(deepLinkPath) ? pathname : null
+}
+
+function isAccountsListPath(): boolean {
+ return removeProjectIdIfPresent(router.values.location.pathname) === urls.customerAnalyticsAccounts()
+}
+
+function hasSharedView(hashParams: Record<string, any> | undefined): boolean {
+ return (
+ !!hashParams &&
+ typeof hashParams.view === 'object' &&
+ hashParams.view !== null &&
+ !Array.isArray(hashParams.view)
+ )
+}
+
+interface AccountsViewDraftIdentity {
+ teamId: number
+ userId: string
+}
+
+function getAccountsViewDraftIdentity(
+ currentTeamId: number | null,
+ user: UserType | null
+): AccountsViewDraftIdentity | null {
+ return currentTeamId !== null && user?.uuid ? { teamId: currentTeamId, userId: user.uuid } : null
+}
+
+function persistViewStateAndUrl(
+ actions: { persistViewState: (search?: string) => unknown; syncViewStateToUrl: () => unknown },
+ isRestoring: boolean,
+ viewStateHydrated: boolean
+): void {
+ if (isRestoring || !viewStateHydrated) {
+ return
+ }
+ actions.persistViewState()
+ actions.syncViewStateToUrl()
}
-// Shareable view state encoded into the URL hash (`#view=...`) so a copied URL
-// reproduces the exact accounts list a colleague is looking at. Only non-default
-// values are serialized, keeping the hash empty for the default view.
export interface AccountsViewUrlState {
search?: string
tags?: string[]
- /** The canonical assignment status. Absent on legacy links, which resolve to
- * assigned-only so they never silently broaden. */
+ /** Legacy nonempty links without a status remain assigned-only. */
assignmentStatus?: AssignmentStatus
/** @deprecated Legacy unassigned-only flag; still read for old shared links. Never written. */
unassigned?: boolean
- /** Concrete user ids for the "Assigned to" / "My accounts" filter — explicit
- * (not viewer-relative) so a shared link resolves identically for everyone. */
+ /** Concrete user IDs make shared links independent of the viewer. */
assignedTo?: number[]
/** @deprecated Legacy viewer-relative flag; still read so old shared links
* resolve to the opener's own id. Never written. */
@@ -155,6 +186,73 @@ export interface AccountsViewUrlState {
customProperties?: AccountFilter[]
}
+export type AccountsViewStateSource = 'defaults' | 'draft' | 'saved_view' | 'shared_url'
+
+export interface ApplyAccountsViewStateOptions {
+ source: AccountsViewStateSource
+ columns: 'restore' | 'defaults'
+}
+
+function viewStateWithMineOnly(
+ viewState: AccountsViewState,
+ mineOnly: boolean,
+ currentUserId: number | null
+): AccountsViewState {
+ if (currentUserId === null) {
+ return viewState
+ }
+ const assignedToCurrentUser =
+ viewState.filters.assignedTo.length === 1 && viewState.filters.assignedTo[0] === currentUserId
+ if (mineOnly) {
+ return {
+ ...viewState,
+ filters: { ...viewState.filters, assignmentStatus: 'assigned', assignedTo: [currentUserId] },
+ }
+ }
+ return assignedToCurrentUser ? { ...viewState, filters: { ...viewState.filters, assignedTo: [] } } : viewState
+}
+
+function accountsViewStateFromUrl(
+ view: AccountsViewUrlState,
+ defaultColumns: string[],
+ currentUserId: number | null,
+ tiles: AccountsOverviewTile[]
+): AccountsViewState {
+ const explicitStatus = isAssignmentStatus(view.assignmentStatus) ? view.assignmentStatus : undefined
+ const assignedTo = normalizeRoleFilter(view.assignedTo)
+ const legacyMine = !assignedTo.length && view.mine && currentUserId !== null ? [currentUserId] : []
+ const hasViewKeys = Object.keys(view).length > 0
+ const assignmentStatus: AssignmentStatus = explicitStatus
+ ? explicitStatus
+ : hasViewKeys
+ ? view.unassigned
+ ? 'unassigned'
+ : 'assigned'
+ : 'all'
+ return {
+ columns:
+ Array.isArray(view.columns) && view.columns.every((column) => typeof column === 'string')
+ ? view.columns
+ : defaultColumns,
+ sortOrder:
+ view.sort &&
+ typeof view.sort.column === 'string' &&
+ (view.sort.direction === 'asc' || view.sort.direction === 'desc')
+ ? view.sort
+ : null,
+ filters: {
+ search: typeof view.search === 'string' ? view.search : '',
+ assignmentStatus,
+ assignedTo: assignmentStatus === 'assigned' ? (assignedTo.length ? assignedTo : legacyMine) : [],
+ tags: Array.isArray(view.tags) ? view.tags.filter((tag): tag is string => typeof tag === 'string') : [],
+ tileFilter: view.tileFilter && typeof view.tileFilter === 'object' ? view.tileFilter : null,
+ customProperties: Array.isArray(view.customProperties) ? view.customProperties : [],
+ },
+ tiles,
+ columnDisplay: view.columnDisplay && typeof view.columnDisplay === 'object' ? view.columnDisplay : {},
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsLogicValues {
aliasToDefinition: Record<string, CustomPropertyDefinitionApi> // accountsColumnConfigLogic
@@ -169,6 +267,7 @@ export interface accountsLogicValues {
visibleColumnNames: string[] // accountsColumnConfigLogic
overviewMetrics: AccountsTableMetric[] // accountsOverviewTilesLogic
tileFilter: TileFilter | null // accountsOverviewTilesLogic
+ tiles: AccountsOverviewTile[] // accountsOverviewTilesLogic
mineOnly: boolean // customerAnalyticsSceneLogic
listHasMoreData: boolean // dataNodeLogic
currentTeamId: number | null // teamLogic
@@ -187,6 +286,7 @@ export interface accountsLogicValues {
canSortClientSide: boolean
currentUserId: number | null
customPropertyOverrides: Record<string, CustomPropertyValueWriteApi['value']>
+ draftRestored: boolean
isCustomPropertySaving: (accountId: string, definitionId: string) => boolean
isRoleSaving: (accountId: string, column: string) => boolean
isTagsSaving: (accountId: string) => boolean
@@ -202,6 +302,8 @@ export interface accountsLogicValues {
sortedRowsTransformer: ((rows: DataTableRow[]) => DataTableRow[]) | undefined
tagOverrides: Record<string, string[]>
tagsFilter: string[]
+ viewState: AccountsViewState
+ viewStateHydrated: boolean
viewUrlState: AccountsViewUrlState
}
@@ -228,16 +330,12 @@ export interface accountsLogicActions {
payload?: any
relationshipDefinitions: AccountRelationshipDefinitionApi[]
} // accountsColumnConfigLogic
- moveColumn: (
- oldIndex: number,
- newIndex: number
- ) => {
- newIndex: number
- oldIndex: number
- } // accountsColumnConfigLogic
resetColumns: () => {
value: true
} // accountsColumnConfigLogic
+ restoreSelectColumns: (columns: string[]) => {
+ columns: string[]
+ } // accountsColumnConfigLogic
selectColumn: (column: string) => {
column: string
} // accountsColumnConfigLogic
@@ -267,6 +365,9 @@ export interface accountsLogicActions {
setTileFilter: (filter: TileFilter | null) => {
filter: TileFilter | null
} // accountsOverviewTilesLogic
+ setTiles: (tiles: AccountsOverviewTile[]) => {
+ tiles: AccountsOverviewTile[]
+ } // accountsOverviewTilesLogic
setMineOnly: (mineOnly: boolean) => {
mineOnly: boolean
} // customerAnalyticsSceneLogic
@@ -349,6 +450,13 @@ export interface accountsLogicActions {
addTagToFilter: (tag: string) => {
tag: string
}
+ applyViewState: (
+ viewState: AccountsViewState,
+ options: ApplyAccountsViewStateOptions
+ ) => {
+ options: ApplyAccountsViewStateOptions
+ viewState: AccountsViewState
+ }
clearCustomPropertyOverrides: () => {
value: true
}
@@ -377,12 +485,18 @@ export interface accountsLogicActions {
name: string
tab: AccountExpansionTab
}
+ persistViewState: (search?: string) => {
+ search: string | undefined
+ }
refresh: () => {
value: true
}
reportFilterChange: (filterType: AccountFilterType) => {
filterType: AccountFilterType
}
+ restoreViewStateFromRoute: (method?: 'POP' | 'PUSH' | 'REPLACE') => {
+ method: 'POP' | 'PUSH' | 'REPLACE' | undefined
+ }
roleUpdateFinished: (
accountId: string,
column: string
@@ -424,6 +538,9 @@ export interface accountsLogicActions {
definitionId: string
value: boolean | number | string | null
}
+ setDraftRestored: (restored: boolean) => {
+ restored: boolean
+ }
setRelationshipOverride: (
accountId: string,
column: string,
@@ -452,6 +569,12 @@ export interface accountsLogicActions {
accountId: string
tags: string[] | null
}
+ setViewStateHydrated: (hydrated: boolean) => {
+ hydrated: boolean
+ }
+ syncViewStateToUrl: () => {
+ value: true
+ }
tagsUpdateFinished: (accountId: string) => {
accountId: string
}
@@ -507,6 +630,18 @@ export interface accountsLogicMeta {
assignmentStatus: AssignmentStatus,
accountFilters: AccountFilter[]
) => number
+ viewState: (
+ selectColumns: string[],
+ searchQuery: string,
+ tagsFilter: string[],
+ assignmentStatus: AssignmentStatus,
+ assignedToFilter: RoleFilterValue,
+ sortOrder: AccountSortOrder,
+ tileFilter: TileFilter | null,
+ tiles: AccountsOverviewTile[],
+ accountFilters: AccountFilter[],
+ columnDisplay: AccountColumnDisplayState
+ ) => AccountsViewState
viewUrlState: (
searchQuery: string,
tagsFilter: string[],
@@ -547,7 +682,8 @@ export interface accountsLogicMeta {
accountsQuerySource: (
accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean,
- awaitingSavedView: boolean
+ awaitingSavedView: boolean,
+ viewStateHydrated: boolean
) => AccountsTableQuery | null
accountsDataTableQuery: (
accountsTableQueryPlan: AccountsTableQueryPlan,
@@ -557,7 +693,8 @@ export interface accountsLogicMeta {
overviewMetrics: AccountsTableMetric[],
accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean,
- awaitingSavedView: boolean
+ awaitingSavedView: boolean,
+ viewStateHydrated: boolean
) => AccountsTableQuery | null
}
}
@@ -591,7 +728,7 @@ export const accountsLogic = kea<accountsLogicType>([
'columnDisplay',
],
accountsOverviewTilesLogic,
- ['metrics as overviewMetrics', 'tileFilter'],
+ ['metrics as overviewMetrics', 'tileFilter', 'tiles'],
customerAnalyticsSceneLogic,
['mineOnly'],
dataNodeLogic({ key: ACCOUNTS_TABLE_DATA_NODE_KEY } as DataNodeLogicProps),
@@ -606,13 +743,13 @@ export const accountsLogic = kea<accountsLogicType>([
'setSelectColumns',
'selectColumn',
'unselectColumn',
- 'moveColumn',
'resetColumns',
+ 'restoreSelectColumns',
'setColumnDisplay',
'setColumnDisplayConfig',
],
accountsOverviewTilesLogic,
- ['setTileFilter'],
+ ['setTileFilter', 'setTiles'],
accountsExpansionLogic,
['openAccountTab'],
customerAnalyticsSceneLogic,
@@ -628,20 +765,23 @@ export const accountsLogic = kea<accountsLogicType>([
actions({
setSearchInput: (query: string) => ({ query }),
setSearchQuery: (query: string) => ({ query }),
+ applyViewState: (viewState: AccountsViewState, options: ApplyAccountsViewStateOptions) => ({
+ viewState,
+ options,
+ }),
+ persistViewState: (search?: string) => ({ search }),
+ syncViewStateToUrl: true,
setTagsFilter: (tags: string[]) => ({ tags }),
setAccountFilters: (filters: AccountFilter[]) => ({ filters }),
updateAccountFilters: (filters: AccountFilter[]) => ({ filters }),
setAssignmentStatus: (status: AssignmentStatus) => ({ status }),
setAssignedToFilter: (value: RoleFilterValue) => ({ value }),
- // Shortcut for the "My accounts" checkbox — resolves to the current
- // user's id and routes through setAssignedToFilter.
setAssignedToCurrentUser: (value: boolean) => ({ value }),
setSortOrder: (sortOrder: AccountSortOrder) => ({ sortOrder }),
toggleSort: (column: AccountSortableColumn) => ({ column }),
refresh: true,
- // Dispatched by the filter controls on genuine user interaction only.
- // The raw filter setters are also fired by URL sync and cross-filter
- // cascades, so capturing analytics here keeps phantom events out.
+ restoreViewStateFromRoute: (method?: 'POP' | 'PUSH' | 'REPLACE') => ({ method }),
+ // Separate user interactions from restore actions so restores do not emit filter-change events.
reportFilterChange: (filterType: AccountFilterType) => ({ filterType }),
updateAccountCustomProperty: (
accountId: string,
@@ -669,11 +809,9 @@ export const accountsLogic = kea<accountsLogicType>([
userIds,
}),
updateAccountTags: (accountId: string, tags: string[]) => ({ accountId, tags }),
- // Clicking a tag in a row's tags cell adds it to the tags filter (compounding).
addTagToFilter: (tag: string) => ({ tag }),
tagsUpdateStarted: (accountId: string) => ({ accountId }),
tagsUpdateFinished: (accountId: string) => ({ accountId }),
- // null drops the override, falling back to the fetched cell value.
setTagsOverride: (accountId: string, tags: string[] | null) => ({ accountId, tags }),
openAccount: (accountId: string, externalId: string | null, name: string, tab: AccountExpansionTab) => ({
accountId,
@@ -681,10 +819,10 @@ export const accountsLogic = kea<accountsLogicType>([
name,
tab,
}),
- // Restrict the list to a single account by id — drives the `/accounts/:accountId/:tab`
- // path route. null clears it (back to the full list).
setAccountIdFilter: (accountId: string | null) => ({ accountId }),
setAwaitingSavedView: (awaiting: boolean) => ({ awaiting }),
+ setDraftRestored: (restored: boolean) => ({ restored }),
+ setViewStateHydrated: (hydrated: boolean) => ({ hydrated }),
}),
reducers({
searchInput: [
@@ -736,17 +874,26 @@ export const accountsLogic = kea<accountsLogicType>([
setAwaitingSavedView: (_, { awaiting }) => awaiting,
},
],
+ draftRestored: [
+ false,
+ {
+ setDraftRestored: (_, { restored }) => restored,
+ },
+ ],
+ viewStateHydrated: [
+ false,
+ {
+ setViewStateHydrated: (_, { hydrated }) => hydrated,
+ },
+ ],
sortOrder: [
null as AccountSortOrder,
{
setSortOrder: (_, { sortOrder }) => sortOrder,
},
],
- // Keeps server-side sort while paging, so reaching the last page never drops the
- // orderBy and collapses the accumulated rows back to page one. Resetting on every
- // listLoadData is deliberate even for the refetch a sort-while-paginated triggers:
- // that request already carries the new orderBy, and its response replaces the
- // accumulated pages with one server-sorted page that is safe to client-sort next.
+ // Keep server sorting through the last page so a query change does not discard accumulated rows.
+ // A fresh load replaces those rows and permits client sorting again.
listPaginated: [
false,
{
@@ -798,8 +945,7 @@ export const accountsLogic = kea<accountsLogicType>([
},
},
],
- // Assignments written from the list, keyed `${accountId}:${column}` — masks the
- // stale fetched cell until the async refetch lands.
+ // Keep saved assignments visible until the refetch replaces stale cells.
relationshipOverrides: [
{} as Record<string, number[]>,
{
@@ -820,8 +966,7 @@ export const accountsLogic = kea<accountsLogicType>([
},
},
],
- // Tags written from the list, keyed by account id, mask the stale fetched
- // cell until the async refetch lands.
+ // Keep saved tags visible until the refetch replaces stale cells.
tagOverrides: [
{} as Record<string, string[]>,
{
@@ -839,9 +984,6 @@ export const accountsLogic = kea<accountsLogicType>([
}),
selectors({
currentUserId: [(s) => [s.user], (user: null | import('~/types').UserType): number | null => user?.id ?? null],
- // The "My accounts" checkbox is checked exactly when the assigned-to
- // filter is just the current user — i.e. the user-agnostic id filter
- // happens to point at you.
assignedToCurrentUser: [
(s) => [s.assignedToFilter, s.currentUserId],
(assignedToFilter: RoleFilterValue, currentUserId: number | null): boolean =>
@@ -876,12 +1018,42 @@ export const accountsLogic = kea<accountsLogicType>([
[
!!searchQuery.trim(),
tagsFilter.length > 0,
- // `all` is the default, so any other status (including assigned-to
- // narrowing, which forces `assigned`) is one active filter.
assignmentStatus !== 'all',
accountFilters.length > 0,
].filter(Boolean).length,
],
+ viewState: [
+ (s) => [
+ s.selectColumns,
+ s.searchQuery,
+ s.tagsFilter,
+ s.assignmentStatus,
+ s.assignedToFilter,
+ s.sortOrder,
+ s.tileFilter,
+ s.tiles,
+ s.accountFilters,
+ s.columnDisplay,
+ ],
+ (
+ columns: string[],
+ search: string,
+ tags: string[],
+ assignmentStatus: AssignmentStatus,
+ assignedTo: RoleFilterValue,
+ sortOrder: AccountSortOrder,
+ tileFilter: TileFilter | null,
+ tiles: import('./accountsOverviewTilesLogic').AccountsOverviewTile[],
+ customProperties: AccountFilter[],
+ columnDisplay: AccountColumnDisplayState
+ ): AccountsViewState => ({
+ columns,
+ sortOrder,
+ filters: { search, assignmentStatus, assignedTo, tags, tileFilter, customProperties },
+ tiles,
+ columnDisplay,
+ }),
+ ],
viewUrlState: [
(s) => [
s.searchQuery,
@@ -938,9 +1110,7 @@ export const accountsLogic = kea<accountsLogicType>([
if (accountFilters.length > 0) {
state.customProperties = accountFilters
}
- // The default `all` status is omitted so a pure-default view keeps an empty
- // hash. But a legacy hash without the field reads as assigned-only, so once
- // any other filter is present we mark `all` explicitly to avoid that mislabel.
+ // Without an explicit status, a nonempty hash would restore as a legacy assigned-only view.
if (assignmentStatus === 'all' && Object.keys(state).length > 0) {
state.assignmentStatus = 'all'
}
@@ -1019,13 +1189,21 @@ export const accountsLogic = kea<accountsLogicType>([
(input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan => buildAccountsTableQueryPlan(input),
],
accountsQuerySource: [
- (s) => [s.accountsTableQueryPlan, s.relationshipDefinitionsLoaded, s.awaitingSavedView],
+ (s) => [
+ s.accountsTableQueryPlan,
+ s.relationshipDefinitionsLoaded,
+ s.awaitingSavedView,
+ s.viewStateHydrated,
+ ],
(
accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean,
- awaitingSavedView: boolean
+ awaitingSavedView: boolean,
+ viewStateHydrated: boolean
): AccountsTableQuery | null =>
- relationshipDefinitionsLoaded && !awaitingSavedView ? accountsTableQueryPlan.query : null,
+ relationshipDefinitionsLoaded && !awaitingSavedView && viewStateHydrated
+ ? accountsTableQueryPlan.query
+ : null,
],
accountsDataTableQuery: [
(s) => [s.accountsTableQueryPlan, s.accountsQuerySource],
@@ -1041,14 +1219,26 @@ export const accountsLogic = kea<accountsLogicType>([
}),
],
metricsQuery: [
- (s) => [s.overviewMetrics, s.accountsTableQueryPlan, s.relationshipDefinitionsLoaded, s.awaitingSavedView],
+ (s) => [
+ s.overviewMetrics,
+ s.accountsTableQueryPlan,
+ s.relationshipDefinitionsLoaded,
+ s.awaitingSavedView,
+ s.viewStateHydrated,
+ ],
(
overviewMetrics: AccountsTableMetric[],
accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean,
- awaitingSavedView: boolean
+ awaitingSavedView: boolean,
+ viewStateHydrated: boolean
): AccountsTableQuery | null => {
- if (overviewMetrics.length === 0 || !relationshipDefinitionsLoaded || awaitingSavedView) {
+ if (
+ overviewMetrics.length === 0 ||
+ !relationshipDefinitionsLoaded ||
+ awaitingSavedView ||
+ !viewStateHydrated
+ ) {
return null
}
return {
@@ -1062,6 +1252,74 @@ export const accountsLogic = kea<accountsLogicType>([
],
}),
listeners(({ actions, values, cache, selectors }) => ({
+ applyViewState: ({ viewState, options }) => {
+ cache.assignmentStateResolved = true
+ if (options.source === 'draft') {
+ actions.setDraftRestored(true)
+ }
+ cache.searchGeneration = (cache.searchGeneration ?? 0) + 1
+ cache.applyingViewState = true
+ try {
+ if (options.columns === 'restore') {
+ actions.restoreSelectColumns(viewState.columns)
+ } else {
+ actions.resetColumns()
+ }
+ actions.setColumnDisplayConfig(viewState.columnDisplay)
+ actions.setSearchQuery(viewState.filters.search)
+ actions.setTagsFilter(viewState.filters.tags)
+ actions.setAssignmentStatus(viewState.filters.assignmentStatus)
+ actions.setAssignedToFilter(
+ viewState.filters.assignmentStatus === 'assigned' ? viewState.filters.assignedTo : []
+ )
+ actions.setAccountFilters(viewState.filters.customProperties)
+ actions.setSortOrder(viewState.sortOrder)
+ actions.setTiles(viewState.tiles)
+ actions.setTileFilter(viewState.filters.tileFilter)
+ } finally {
+ cache.applyingViewState = false
+ }
+ actions.persistViewState()
+ },
+ persistViewState: ({ search }) => {
+ const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)
+ if (
+ !values.viewStateHydrated ||
+ cache.applyingViewState ||
+ !draftIdentity ||
+ !objectsEqual(cache.viewStateDraftIdentity, draftIdentity) ||
+ !accountsPathToWriteBackTo(values.accountIdFilter)
+ ) {
+ return
+ }
+ const viewState = {
+ ...values.viewState,
+ filters: { ...values.viewState.filters, search: search ?? values.searchInput },
+ }
+ writeAccountsViewDraft(draftIdentity.teamId, draftIdentity.userId, viewState)
+ },
+ setSearchQuery: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ setTagsFilter: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ setSortOrder: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ restoreSelectColumns: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ selectColumn: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ [accountsColumnConfigLogic.actionTypes.moveColumn]: () =>
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ setColumnDisplay: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ setColumnDisplayConfig: () =>
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ setTileFilter: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ setTiles: () => persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ [accountsOverviewTilesLogic.actionTypes.addTile]: () =>
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ [accountsOverviewTilesLogic.actionTypes.updateTile]: () =>
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ [accountsOverviewTilesLogic.actionTypes.removeTile]: () =>
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ [accountsOverviewTilesLogic.actionTypes.moveTile]: () =>
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
+ [accountsOverviewTilesLogic.actionTypes.resetTiles]: () =>
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated),
listLoadData: ({ queryId }) => {
if (cache.awaitingCustomPropertyRefresh) {
cache.awaitingCustomPropertyRefresh = false
@@ -1111,6 +1369,7 @@ export const accountsLogic = kea<accountsLogicType>([
actions.setAccountFilters(values.accountFilters)
},
setAccountFilters: ({ filters }) => {
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
if (!cache.customPropertyDefinitionsLoaded || !cache.relationshipDefinitionsLoaded) {
return
}
@@ -1153,7 +1412,12 @@ export const accountsLogic = kea<accountsLogicType>([
})
},
setSearchInput: async ({ query }, breakpoint) => {
+ const searchGeneration = cache.searchGeneration ?? 0
+ actions.persistViewState(query)
await breakpoint(SEARCH_DEBOUNCE_MS)
+ if (searchGeneration !== (cache.searchGeneration ?? 0)) {
+ return
+ }
actions.setSearchQuery(query)
const trimmed = query.trim()
posthog.capture(AccountsEvents.Searched, {
@@ -1189,37 +1453,76 @@ export const accountsLogic = kea<accountsLogicType>([
}
posthog.capture(AccountsEvents.FilterChanged, properties)
},
- // The assigned-to narrowing only applies within the assigned status, so leaving
- // that status clears any selected users. This keeps the canonical status and the
- // user filter from ever describing contradictory sets.
+ // Selected users apply only to assigned accounts.
setAssignmentStatus: ({ status }) => {
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
if (status !== 'assigned' && values.assignedToFilter.length > 0) {
actions.setAssignedToFilter([])
}
},
- // "My accounts" is a shortcut: filter by the current user's own id. The
- // user-agnostic id then rides in the URL, so a shared link shows the
- // sharer's accounts to whoever opens it (not the opener's own).
setAssignedToCurrentUser: ({ value }) => {
actions.setAssignedToFilter(value && values.currentUserId !== null ? [values.currentUserId] : [])
},
- // Selecting users narrows assigned accounts, so it forces the assigned status.
setAssignedToFilter: ({ value }) => {
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
if (value.length > 0 && values.assignmentStatus !== 'assigned') {
actions.setAssignmentStatus('assigned')
}
- // Keep the shared "mine only" toggle in step with the assigned-to filter
- // (set via the "My accounts" shortcut or the assigned-to picker) so
- // switching to the Notes tab reflects the same choice.
- actions.setMineOnly(values.assignedToCurrentUser)
+ // Notes uses the same My accounts preference.
+ if (!cache.pendingMineOnlyRestore) {
+ cache.mirroringMineOnly = true
+ try {
+ actions.setMineOnly(values.assignedToCurrentUser)
+ } finally {
+ cache.mirroringMineOnly = false
+ }
+ }
},
- // The "My accounts" restore needs the current user's id. On a fresh page load this
- // logic can mount before userLogic resolves the user (currentUserId still null during
- // URL restore), so the persisted choice can't be applied then. Re-apply it once the
- // user arrives — only when the URL carried no explicit assignment and nothing else has
- // set the filter, so a shared link or an explicit pick always wins.
- loadUserSuccess: () => {
+ setMineOnly: ({ mineOnly }) => {
+ if (cache.mirroringMineOnly) {
+ return
+ }
+ if (!isAccountsListPath()) {
+ cache.mineOnlyChangedOutsideAccounts = mineOnly
+ return
+ }
+ if (cache.userUnavailable) {
+ cache.pendingMineOnlyRestore = mineOnly
+ return
+ }
+ if (mineOnly && values.currentUserId !== null) {
+ actions.setAssignedToFilter([values.currentUserId])
+ } else if (!mineOnly && values.assignedToCurrentUser) {
+ actions.setAssignedToFilter([])
+ }
+ },
+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => {
+ const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)
+ if (
+ !values.viewStateHydrated ||
+ (draftIdentity && !objectsEqual(cache.viewStateDraftIdentity, draftIdentity))
+ ) {
+ actions.restoreViewStateFromRoute()
+ }
+ },
+ // Viewer-relative preferences and legacy mine links must wait for the user ID.
+ loadUserSuccess: ({ user }) => {
+ cache.userUnavailable = user === null
+ const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)
if (
+ !values.viewStateHydrated ||
+ (draftIdentity && !objectsEqual(cache.viewStateDraftIdentity, draftIdentity))
+ ) {
+ actions.restoreViewStateFromRoute()
+ return
+ }
+ if (cache.pendingMineOnlyRestore && values.currentUserId !== null) {
+ cache.pendingMineOnlyRestore = false
+ actions.setAssignedToFilter([values.currentUserId])
+ return
+ }
+ if (
+ !cache.assignmentStateResolved &&
values.mineOnly &&
values.currentUserId !== null &&
!values.assignedToFilter.length &&
@@ -1245,12 +1548,15 @@ export const accountsLogic = kea<accountsLogicType>([
})
},
setSelectColumns: () => {
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
clearSortIfColumnRemoved(values, actions)
},
unselectColumn: () => {
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
clearSortIfColumnRemoved(values, actions)
},
resetColumns: () => {
+ persistViewStateAndUrl(actions, cache.applyingViewState, values.viewStateHydrated)
clearSortIfColumnRemoved(values, actions)
},
refresh: () => {
@@ -1262,6 +1568,95 @@ export const accountsLogic = kea<accountsLogicType>([
dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
},
+ restoreViewStateFromRoute: ({ method }) => {
+ const pathname = removeProjectIdIfPresent(router.values.location.pathname)
+ const sharedView = hasSharedView(router.values.hashParams)
+ ? (router.values.hashParams.view as AccountsViewUrlState)
+ : null
+ const pendingUrlRestore = cache.pendingUrlRestore
+ cache.pendingUrlRestore = undefined
+ if (
+ method === 'REPLACE' &&
+ pendingUrlRestore &&
+ pendingUrlRestore.pathname === pathname &&
+ objectsEqual(pendingUrlRestore.view, sharedView ?? {})
+ ) {
+ return
+ }
+
+ const draftIdentity = getAccountsViewDraftIdentity(values.currentTeamId, values.user)
+ if (!sharedView && !draftIdentity) {
+ actions.setViewStateHydrated(false)
+ return
+ }
+
+ const previousDraftIdentity = cache.viewStateDraftIdentity
+ cache.assignmentStateResolved = false
+ cache.pendingMineOnlyRestore = false
+ cache.viewStateDraftIdentity = draftIdentity
+ actions.setDraftRestored(false)
+ let restored = false
+ const draft = draftIdentity ? readAccountsViewDraft(draftIdentity.teamId, draftIdentity.userId) : null
+ if (sharedView) {
+ cache.mineOnlyChangedOutsideAccounts = undefined
+ cache.pendingMineOnlyRestore = !!sharedView.mine && values.currentUserId === null
+ actions.applyViewState(
+ accountsViewStateFromUrl(
+ sharedView,
+ values.defaultSelectColumns,
+ values.currentUserId,
+ draft?.tiles ?? values.tiles
+ ),
+ { source: 'shared_url', columns: Array.isArray(sharedView.columns) ? 'restore' : 'defaults' }
+ )
+ restored = true
+ } else if (isAccountsListPath() || pathname.startsWith(`${urls.customerAnalyticsAccounts()}/`)) {
+ const mineOnly = cache.mineOnlyChangedOutsideAccounts
+ cache.mineOnlyChangedOutsideAccounts = undefined
+ if (mineOnly !== undefined) {
+ cache.pendingMineOnlyRestore = mineOnly && values.currentUserId === null
+ actions.applyViewState(
+ viewStateWithMineOnly(draft ?? values.viewState, mineOnly, values.currentUserId),
+ {
+ source: draft ? 'draft' : 'defaults',
+ columns: 'restore',
+ }
+ )
+ restored = true
+ } else if (draft) {
+ actions.applyViewState(draft, { source: 'draft', columns: 'restore' })
+ restored = true
+ } else if (previousDraftIdentity && !objectsEqual(previousDraftIdentity, draftIdentity)) {
+ actions.applyViewState(
+ viewStateWithMineOnly(
+ accountsViewStateFromUrl(
+ {},
+ values.defaultSelectColumns,
+ values.currentUserId,
+ DEFAULT_TILES
+ ),
+ values.mineOnly,
+ values.currentUserId
+ ),
+ { source: 'defaults', columns: 'defaults' }
+ )
+ } else if (values.mineOnly) {
+ if (values.currentUserId === null) {
+ cache.pendingMineOnlyRestore = true
+ } else {
+ actions.applyViewState(viewStateWithMineOnly(values.viewState, true, values.currentUserId), {
+ source: 'defaults',
+ columns: 'restore',
+ })
+ restored = true
+ }
+ }
+ }
+ actions.setViewStateHydrated(true)
+ if (restored) {
+ actions.persistViewState()
+ }
+ },
updateAccountCustomProperty: async ({ accountId, definition, value }) => {
if (
definition.is_canonical ||
@@ -1346,18 +1741,14 @@ export const accountsLogic = kea<accountsLogicType>([
},
updateAccountTags: async ({ accountId, tags }, breakpoint) => {
const previous = values.tagOverrides[accountId] ?? null
- // Optimistic: ObjectTags is a controlled input firing per added/removed tag,
- // so its value must reflect each change immediately or the editor reverts.
+ // Reflect edits before the debounce so the controlled tag input does not revert.
actions.setTagsOverride(accountId, tags)
- // ponytail: the breakpoint is per-action, not per-account — editing two
- // accounts' tags within 300ms drops the first save. Key it per account if
- // that ever becomes a real interaction.
+ // This breakpoint is shared across accounts. A second account edit cancels the first pending save.
await breakpoint(TAGS_SAVE_DEBOUNCE_MS)
actions.tagsUpdateStarted(accountId)
try {
await accountsPartialUpdate(String(values.currentTeamId), accountId, { tags })
posthog.capture(AccountsEvents.TagsUpdated, { tag_count: tags.length })
- // A newly created tag should show up in the available-tags pickers right away.
tagsModel.findMounted()?.actions.loadTags()
dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
@@ -1377,7 +1768,7 @@ export const accountsLogic = kea<accountsLogicType>([
(row) =>
row && typeof row === 'object' && !Array.isArray(row) && (row as { id?: string }).id === accountId
)
- // Reveal the account if it isn't currently shown, so the expanded row actually renders.
+ // Remove excluding filters so the requested account can render.
if (!isVisible) {
if (values.tagsFilter.length > 0) {
actions.setTagsFilter([])
@@ -1397,8 +1788,7 @@ export const accountsLogic = kea<accountsLogicType>([
}
}
actions.openAccountTab(accountId, tab)
- // Keyed so a second open cancels a still-pending scroll. One-shot, so
- // it opts out of pause-on-hidden rather than re-scrolling on tab return.
+ // Cancel earlier scrolls and do not repeat a completed scroll when the browser tab resumes.
cache.disposables.add(
() => {
let attempts = 0
@@ -1424,42 +1814,38 @@ export const accountsLogic = kea<accountsLogicType>([
})),
afterMount(({ actions }) => {
posthog.capture(AccountsEvents.ListViewed)
- // Relationship cells resolve assigned user ids against the org member list,
- // so it must be loaded up front rather than on first dropdown open.
+ // Relationship cells need member names before an editor opens.
actions.ensureAllMembersLoaded()
+ actions.restoreViewStateFromRoute()
}),
- actionToUrl(({ values }) => {
- // Mirror the full view into the URL hash so the link is shareable.
- // Search params are preserved untouched — the parent scene owns those.
- const toUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => [
- accountsPathToWriteBackTo(values.accountIdFilter),
- router.values.searchParams,
- objectsEqual(values.viewUrlState, {}) ? {} : { view: values.viewUrlState },
- { replace: true },
- ]
- return {
- setSearchQuery: toUrl,
- setTagsFilter: toUrl,
- setAccountFilters: toUrl,
- setAssignmentStatus: toUrl,
- setAssignedToFilter: toUrl,
- setSortOrder: toUrl,
- setSelectColumns: toUrl,
- selectColumn: toUrl,
- unselectColumn: toUrl,
- moveColumn: toUrl,
- resetColumns: toUrl,
- setColumnDisplay: toUrl,
- setColumnDisplayConfig: toUrl,
- setTileFilter: toUrl,
- }
- }),
+ actionToUrl(({ values, cache }) => ({
+ syncViewStateToUrl: () => {
+ const pathname = accountsPathToWriteBackTo(values.accountIdFilter)
+ if (!pathname) {
+ return undefined
+ }
+ const view = objectsEqual(values.viewUrlState, {}) ? {} : values.viewUrlState
+ const currentView = hasSharedView(router.values.hashParams)
+ ? (router.values.hashParams.view as AccountsViewUrlState)
+ : {}
+ if (objectsEqual(currentView, view)) {
+ return undefined
+ }
+ const pendingUrlRestore = {
+ pathname: removeProjectIdIfPresent(pathname),
+ view,
+ }
+ cache.pendingUrlRestore = pendingUrlRestore
+ queueMicrotask(() => {
+ if (cache.pendingUrlRestore === pendingUrlRestore) {
+ cache.pendingUrlRestore = undefined
+ }
+ })
+ return [pathname, router.values.searchParams, objectsEqual(view, {}) ? {} : { view }, { replace: true }]
+ },
+ })),
urlToAction(({ actions, values }) => {
- // Path route `/accounts/:accountId/:tab`: filter the list to one account and open the tab.
- // The URL stays on the path — neither setter is wired into actionToUrl, and the setters that
- // are keep the current path (see `accountsPathToWriteBackTo`).
const openAccountByPath = (accountId: string | undefined, rawTab?: string): void => {
- // Invalid path ids must not reach the typed account filter.
if (!accountId || !isUUIDLike(accountId)) {
return
}
@@ -1472,116 +1858,20 @@ export const accountsLogic = kea<accountsLogicType>([
}
actions.openAccountTab(accountId, tab)
}
- const restoreView = (view: AccountsViewUrlState): void => {
- const search = view.search ?? ''
- if (search !== values.searchQuery) {
- actions.setSearchQuery(search)
- }
-
- const tags = view.tags ?? []
- if (!objectsEqual(tags, values.tagsFilter)) {
- actions.setTagsFilter(tags)
- }
-
- const customProperties = Array.isArray(view.customProperties) ? view.customProperties : []
- if (!objectsEqual(customProperties, values.accountFilters)) {
- actions.setAccountFilters(customProperties)
- }
-
- // Resolve the canonical status: an explicit field wins; a legacy hash with any
- // key but no field is assigned-only (never broadens); an empty hash is the pure
- // default and shows all.
- const explicitStatus = isAssignmentStatus(view.assignmentStatus) ? view.assignmentStatus : undefined
- const hasViewKeys = Object.keys(view).length > 0
- const nextStatus: AssignmentStatus = explicitStatus
- ? explicitStatus
- : hasViewKeys
- ? view.unassigned
- ? 'unassigned'
- : 'assigned'
- : 'all'
- if (nextStatus !== values.assignmentStatus) {
- actions.setAssignmentStatus(nextStatus)
- }
-
- const assignedTo = normalizeRoleFilter(view.assignedTo)
- // Back-compat: legacy links encoded the viewer-relative `mine: true`;
- // resolve it to the opener's own id so old shared links still work.
- const legacyMine =
- !assignedTo.length && view.mine && values.currentUserId !== null ? [values.currentUserId] : []
- // With no assignment intent in the hash at all (no status, no assignedTo, no
- // mine — e.g. arriving via the tab link), fall back to the shared "mine only"
- // toggle so the choice made on the Notes tab carries over. An explicit status
- // always wins over that toggle.
- const sharedMine =
- explicitStatus === undefined &&
- !assignedTo.length &&
- !view.mine &&
- values.mineOnly &&
- values.currentUserId !== null
- ? [values.currentUserId]
- : []
- // The persisted "my accounts" intent can't be resolved until the user id is
- // known. If the user hasn't loaded yet, leave the filter untouched (rather than
- // writing an empty one, which would cascade to setMineOnly(false) and clobber the
- // preference) and let the loadUserSuccess listener apply it once the user resolves.
- const mineRestorePending =
- explicitStatus === undefined &&
- !assignedTo.length &&
- !view.mine &&
- values.mineOnly &&
- values.currentUserId === null
- const nextAssignedTo = assignedTo.length ? assignedTo : legacyMine.length ? legacyMine : sharedMine
- if (!mineRestorePending && !objectsEqual(nextAssignedTo, values.assignedToFilter)) {
- actions.setAssignedToFilter(nextAssignedTo)
- }
-
- const sort = view.sort ?? null
- if (!objectsEqual(sort, values.sortOrder)) {
- actions.setSortOrder(sort)
- }
-
- // A shared link's columns win over the per-user saved column config;
- // accountsColumnConfigLogic enforces this by reading the URL when its
- // async saved-config load resolves.
- if (view.columns && !objectsEqual(view.columns, values.selectColumns)) {
- actions.setSelectColumns(view.columns)
- }
-
- const columnDisplay = view.columnDisplay && typeof view.columnDisplay === 'object' ? view.columnDisplay : {}
- if (!objectsEqual(columnDisplay, values.columnDisplay)) {
- actions.setColumnDisplayConfig(columnDisplay)
- }
-
- const tileFilter = view.tileFilter ?? null
- if (!objectsEqual(tileFilter, values.tileFilter)) {
- actions.setTileFilter(tileFilter)
- }
- }
- const viewFromHash = (hashParams: Record<string, any> | undefined): AccountsViewUrlState =>
- hashParams?.view && typeof hashParams.view === 'object' ? hashParams.view : {}
return {
- [urls.customerAnalyticsAccounts()]: (_, __, hashParams): void => {
- restoreView(viewFromHash(hashParams))
-
- // Back on the bare list — drop any single-account path filter.
+ [urls.customerAnalyticsAccounts()]: (_, __, ___, { method }): void => {
+ actions.restoreViewStateFromRoute(method)
if (values.accountIdFilter !== null) {
actions.setAccountIdFilter(null)
}
},
- // A deep link carries the same shareable `#view=` hash, but only restore it when it's
- // actually there — an absent hash on this route means "just open the account", not
- // "reset the list", so the saved view stays in charge.
- [urls.customerAnalyticsAccount(':accountId')]: ({ accountId }, __, hashParams): void => {
- if (hashParams?.view) {
- restoreView(viewFromHash(hashParams))
- }
+ // Keep the list draft while the account ID controls the detail query.
+ [urls.customerAnalyticsAccount(':accountId')]: ({ accountId }, __, ___, { method }): void => {
+ actions.restoreViewStateFromRoute(method)
openAccountByPath(accountId)
},
- [urls.customerAnalyticsAccount(':accountId', ':tab')]: ({ accountId, tab }, __, hashParams): void => {
- if (hashParams?.view) {
- restoreView(viewFromHash(hashParams))
- }
+ [urls.customerAnalyticsAccount(':accountId', ':tab')]: ({ accountId, tab }, __, ___, { method }): void => {
+ actions.restoreViewStateFromRoute(method)
openAccountByPath(accountId, tab)
},
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
index fe31754cd1e9..e79a7732e67e 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
@@ -4,14 +4,69 @@ import { PropertyFilterType, PropertyOperator } from '~/types'
import { ACCOUNTS_DEFAULT_COLUMNS } from './accountsColumnConfigLogic'
import {
AccountsViewState,
+ accountsViewDraftStorageKey,
deserializeAccountsView,
normalizeRoleFilter,
orderByToSortOrder,
+ readAccountsViewDraft,
serializeAccountsView,
sortOrderToOrderBy,
+ writeAccountsViewDraft,
} from './accountsViewState'
import { DEFAULT_TILES } from './constants'
+const draft: AccountsViewState = {
+ columns: ['name'],
+ sortOrder: null,
+ filters: {
+ search: 'acme',
+ assignmentStatus: 'all',
+ assignedTo: [],
+ tags: [],
+ tileFilter: null,
+ customProperties: [],
+ },
+ tiles: [...DEFAULT_TILES],
+ columnDisplay: {},
+}
+
+describe('accounts view drafts', () => {
+ beforeEach(() => {
+ sessionStorage.clear()
+ })
+
+ afterEach(() => {
+ sessionStorage.clear()
+ jest.restoreAllMocks()
+ })
+
+ it('scopes drafts to the current project and user', () => {
+ writeAccountsViewDraft(1, 'user-a', draft)
+ writeAccountsViewDraft(1, 'user-b', { ...draft, filters: { ...draft.filters, search: 'other user' } })
+ writeAccountsViewDraft(2, 'user-a', { ...draft, filters: { ...draft.filters, search: 'other project' } })
+
+ expect(readAccountsViewDraft(1, 'user-a')).toEqual(draft)
+ expect(readAccountsViewDraft(1, 'user-b')?.filters.search).toBe('other user')
+ expect(readAccountsViewDraft(2, 'user-a')?.filters.search).toBe('other project')
+ })
+
+ it('fails closed for malformed or unavailable session storage', () => {
+ sessionStorage.setItem(accountsViewDraftStorageKey(1, 'user-a'), '{invalid')
+ expect(readAccountsViewDraft(1, 'user-a')).toBeNull()
+
+ jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('storage denied')
+ })
+ expect(readAccountsViewDraft(1, 'user-a')).toBeNull()
+ jest.restoreAllMocks()
+
+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('storage denied')
+ })
+ expect(() => writeAccountsViewDraft(1, 'user-a', draft)).not.toThrow()
+ })
+})
+
describe('sortOrderToOrderBy / orderByToSortOrder', () => {
it('round-trips a plain ascending column', () => {
expect(sortOrderToOrderBy({ column: 'name', direction: 'asc' })).toEqual(['name ASC'])
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
index fe1183a5a973..c367840530c3 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
@@ -1,3 +1,5 @@
+import { z } from 'zod'
+
import {
type AssignmentStatus,
isAssignmentStatus,
@@ -20,15 +22,12 @@ export interface AccountsViewFilters {
customProperties: AccountFilter[]
}
-// A raw persisted filter object may predate `assignmentStatus` and carry only the legacy
-// `unassigned` boolean. Read both so restoring an old view can resolve a status.
interface AccountsViewFiltersRaw extends Partial<AccountsViewFilters> {
/** @deprecated Legacy field, superseded by `assignmentStatus`. Read for back-compat. */
unassigned?: boolean
}
-// A saved view or shared link created before `assignmentStatus` existed defaulted to
-// assigned-only. Resolve legacy filters to that status so they never silently broaden.
+// Legacy views and links defaulted to assigned-only. Do not silently broaden them.
function assignmentStatusFromRaw(raw: AccountsViewFiltersRaw): AssignmentStatus {
if (isAssignmentStatus(raw.assignmentStatus)) {
return raw.assignmentStatus
@@ -49,14 +48,14 @@ export interface AccountsViewState {
columnDisplay: AccountColumnDisplayState
}
+const ACCOUNTS_VIEW_DRAFT_STORAGE_KEY = 'customerAnalytics.accounts.viewDraft'
+
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.
+// Older views store a single assignee ID.
export function normalizeRoleFilter(value: unknown): RoleFilterValue {
if (Array.isArray(value)) {
return value.filter((entry): entry is number => typeof entry === 'number')
@@ -64,8 +63,7 @@ export function normalizeRoleFilter(value: unknown): RoleFilterValue {
return typeof value === 'number' ? [value] : []
}
-// Sort persists under the logical column name so saved views do not depend on
-// the typed query's relationship or custom-property references.
+// Persist logical column names so views do not depend on typed query references.
export function sortOrderToOrderBy(sortOrder: AccountSortOrder): string[] {
if (!sortOrder) {
return []
@@ -93,8 +91,7 @@ export function serializeAccountsView(state: AccountsViewState): AccountsViewPay
if (state.filters.tags.length > 0) {
filters.tags = state.filters.tags
}
- // Always store the status so a new "all" view is distinct from a legacy view with no
- // field (which restores as assigned-only). Assigned-to only narrows the assigned status.
+ // Store `all` so new views differ from field-less legacy views.
filters.assignmentStatus = state.filters.assignmentStatus
if (state.filters.assignmentStatus === 'assigned' && state.filters.assignedTo.length > 0) {
filters.assignedTo = state.filters.assignedTo
@@ -117,8 +114,85 @@ export function serializeAccountsView(state: AccountsViewState): AccountsViewPay
}
}
+const StoredTile = z.object({
+ id: z.string(),
+ label: z.string(),
+ metric: z.discriminatedUnion('type', [
+ z.object({ type: z.literal('count') }),
+ z.object({
+ type: z.enum(['sum', 'avg', 'min', 'max', 'median']),
+ columnExpression: z.string(),
+ columnLabel: z.string(),
+ scale: z.number().optional(),
+ }),
+ z.object({
+ type: z.literal('count_threshold'),
+ columnExpression: z.string(),
+ columnLabel: z.string(),
+ operator: z.string(),
+ value: z.number(),
+ }),
+ ]),
+ caption: z.string().optional(),
+ format: z.enum(['unit', 'currency', 'percentage']).optional(),
+})
+
+const AccountsViewDraft = z.object({
+ columns: z.array(z.string()),
+ sortOrder: z.object({ column: z.string(), direction: z.enum(['asc', 'desc']) }).nullable(),
+ filters: z.object({
+ search: z.string(),
+ assignmentStatus: z.enum(['all', 'assigned', 'unassigned']),
+ assignedTo: z.array(z.number()),
+ tags: z.array(z.string()),
+ tileFilter: z
+ .object({
+ tileId: z.string(),
+ filter: z.object({
+ kind: z.literal('custom_property'),
+ definitionId: z.string(),
+ operator: z.string(),
+ values: z.array(z.number()),
+ }),
+ })
+ .nullable(),
+ customProperties: z.array(z.object({}).passthrough()),
+ }),
+ tiles: z.array(StoredTile),
+ columnDisplay: z.record(z.string(), z.object({ mode: z.enum(['sparkline', 'trend']), window_days: z.number() })),
+})
+
+export function accountsViewDraftStorageKey(teamId: number, userId: string): string {
+ // Changing this storage key strands existing drafts.
+ return `${ACCOUNTS_VIEW_DRAFT_STORAGE_KEY}.${teamId}.${userId}`
+}
+
+export function readAccountsViewDraft(teamId: number | null, userId: string | null): AccountsViewState | null {
+ if (teamId === null || userId === null || typeof window === 'undefined') {
+ return null
+ }
+ try {
+ const raw = window.sessionStorage.getItem(accountsViewDraftStorageKey(teamId, userId))
+ const draft = AccountsViewDraft.safeParse(raw ? JSON.parse(raw) : null)
+ return draft.success ? (draft.data as AccountsViewState) : null
+ } catch {
+ return null
+ }
+}
+
+export function writeAccountsViewDraft(teamId: number | null, userId: string | null, draft: AccountsViewState): void {
+ if (teamId === null || userId === null || typeof window === 'undefined') {
+ return
+ }
+ try {
+ window.sessionStorage.setItem(accountsViewDraftStorageKey(teamId, userId), JSON.stringify(draft))
+ } catch {
+ // Browsers can deny session storage. List navigation must still work.
+ }
+}
+
export function deserializeAccountsView(view: Partial<ColumnConfigurationApi>): AccountsViewState {
- // The backend normalizes empty filters to `[]`; treat any non-object as empty.
+ // The backend represents empty filters as an array.
const rawFilters = (view.filters && !Array.isArray(view.filters) ? view.filters : {}) as AccountsViewFiltersRaw
const rawProperties = (
view.properties && typeof view.properties === 'object' ? view.properties : {}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
index 4b09a5f39eba..336fb1c4fadc 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
@@ -1,7 +1,9 @@
import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from '~/lib/api.mock'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
@@ -11,10 +13,11 @@ import { initKeaTests } from '~/test/init'
import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'
-import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
-import { accountsLogic } from './accountsLogic'
+import { ACCOUNTS_DEFAULT_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import { accountsLogic, SEARCH_DEBOUNCE_MS } from './accountsLogic'
import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'
import { accountsViewsLogic } from './accountsViewsLogic'
+import { type AccountsViewState, writeAccountsViewDraft } from './accountsViewState'
import { DEFAULT_TILES } from './constants'
const CURRENT_USER_ID = MOCK_DEFAULT_USER.id
@@ -55,11 +58,15 @@ describe('accountsViewsLogic', () => {
current_user: MOCK_DEFAULT_USER,
} as any
initKeaTests()
+ router.actions.push(urls.customerAnalyticsAccounts())
+ sessionStorage.clear()
userLogic.mount()
})
afterEach(() => {
localStorage.clear()
+ sessionStorage.clear()
+ jest.useRealTimers()
})
it('lists views on mount', async () => {
@@ -72,19 +79,31 @@ describe('accountsViewsLogic', () => {
})
})
- it('holds the first accounts fetch until the persisted view is applied', async () => {
+ it('holds the first accounts fetch until a delayed draft decision permits the persisted view', async () => {
useMocks({ get: { '/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] } } })
localStorage.setItem(
`customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,
JSON.stringify('view-1')
)
- mountAll()
+ accountsColumnConfigLogic().mount()
+ accountsOverviewTilesLogic().mount()
+ accountsLogic().mount()
+ accountsLogic.actions.setViewStateHydrated(false)
+ logic = accountsViewsLogic()
+ logic.mount()
expect(accountsLogic.values.awaitingSavedView).toBe(true)
expect(accountsLogic.values.accountsQuerySource).toBeNull()
expect(accountsLogic.values.metricsQuery).toBeNull()
- await expectLogic(logic).toDispatchActions(['loadViewsSuccess', 'applyView']).toFinishAllListeners()
+ await expectLogic(logic).toDispatchActions(['loadViewsSuccess', 'restoreSavedView']).toFinishAllListeners()
+
+ expect(accountsLogic.values.awaitingSavedView).toBe(true)
+ expect(accountsLogic.values.searchQuery).toBe('')
+
+ await expectLogic(logic, () => accountsLogic.actions.setViewStateHydrated(true))
+ .toDispatchActions(['restoreSavedView', 'applyView'])
+ .toFinishAllListeners()
expect(accountsLogic.values.awaitingSavedView).toBe(false)
expect(accountsColumnConfigLogic.values.selectColumns).toEqual(['name', 'csm'])
@@ -197,14 +216,14 @@ describe('accountsViewsLogic', () => {
await expectLogic(logic).toMatchValues({ columnWidths: { name: 320 } })
})
- it('isDirty flips when live state diverges from the applied view and clears on re-apply', async () => {
+ it('keeps dirty edits over automatic saved-view restore, then replaces them when the user selects the view', async () => {
useMocks({
get: {
'/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] },
},
})
mountAll()
- // Wait for loadViewsSuccess so the view is in views, then select it
+ // 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 })
@@ -212,8 +231,70 @@ describe('accountsViewsLogic', () => {
accountsLogic.actions.setSearchQuery('changed')
await expectLogic(logic).toMatchValues({ isDirty: true })
- logic.actions.applyView(buildView())
- await expectLogic(logic).toMatchValues({ isDirty: false })
+ logic.unmount()
+ accountsLogic.findMounted()?.unmount()
+ accountsOverviewTilesLogic.findMounted()?.unmount()
+ accountsColumnConfigLogic.findMounted()?.unmount()
+ router.actions.push(urls.customerAnalyticsAccounts())
+ mountAll()
+ await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])
+
+ expect(accountsLogic.values.searchQuery).toBe('changed')
+ expect(logic.values.isDirty).toBe(true)
+
+ jest.useFakeTimers()
+ accountsLogic.actions.setSearchInput('stale search')
+ logic.actions.selectView('view-1')
+ await jest.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(accountsLogic.values.searchQuery).toBe('acme')
+ expect(logic.values.isDirty).toBe(false)
+
+ logic.unmount()
+ accountsLogic.findMounted()?.unmount()
+ accountsOverviewTilesLogic.findMounted()?.unmount()
+ accountsColumnConfigLogic.findMounted()?.unmount()
+ router.actions.push(urls.customerAnalyticsAccounts())
+ mountAll()
+ await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])
+
+ expect(accountsLogic.values.searchQuery).toBe('acme')
+ expect(logic.values.isDirty).toBe(false)
+ })
+
+ it('keeps a cleared all-default draft instead of auto-applying the selected saved view', async () => {
+ const clearedDraft: AccountsViewState = {
+ columns: [...ACCOUNTS_DEFAULT_COLUMNS],
+ sortOrder: null,
+ filters: {
+ search: '',
+ assignmentStatus: 'all',
+ assignedTo: [],
+ tags: [],
+ tileFilter: null,
+ customProperties: [],
+ },
+ tiles: [...DEFAULT_TILES],
+ columnDisplay: {},
+ }
+ writeAccountsViewDraft(MOCK_DEFAULT_TEAM.id, MOCK_DEFAULT_USER.uuid, clearedDraft)
+ localStorage.setItem(
+ `customerAnalytics.accounts.accountsViewsLogic.${MOCK_DEFAULT_TEAM.id}.currentViewId`,
+ JSON.stringify('view-1')
+ )
+ useMocks({
+ get: {
+ '/api/projects/:team_id/column_configurations/': { count: 1, results: [buildView()] },
+ },
+ })
+ mountAll()
+ await expectLogic(logic).toDispatchActions(['loadViewsSuccess'])
+
+ expect(accountsLogic.values.searchQuery).toBe('')
+ expect(accountsLogic.values.assignmentStatus).toBe('all')
+ expect(logic.values.currentViewId).toBe('view-1')
+ expect(logic.values.isDirty).toBe(true)
})
it('deleteView clears currentViewId when the active view is removed', async () => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
index 95102c6e98a8..56b01e57de1d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
@@ -5,11 +5,12 @@ import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'
-import type { AssignmentStatus } from 'lib/components/AccountAssignmentFilter/accountAssignmentFilterTypes'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import {
@@ -24,13 +25,8 @@ import type {
} from 'products/product_analytics/frontend/generated/api.schemas'
import type { UserType } from '../../../../../frontend/src/types'
-import { ACCOUNTS_COLUMN_CONFIG_KEY, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
-import type { AccountColumnDisplayState } from './accountsColumnConfigLogic'
-import { accountsLogic } from './accountsLogic'
-import type { AccountSortOrder, RoleFilterValue } from './accountsLogic'
-import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'
-import type { AccountsOverviewTile, TileFilter } from './accountsOverviewTilesLogic'
-import type { AccountFilter } from './accountsPropertyFilters'
+import { ACCOUNTS_COLUMN_CONFIG_KEY } from './accountsColumnConfigLogic'
+import { accountsLogic, type ApplyAccountsViewStateOptions } from './accountsLogic'
import {
AccountsViewProperties,
AccountsViewState,
@@ -42,18 +38,21 @@ import { AccountsEvents, DEFAULT_TILES } from './constants'
export type ViewVisibility = 'private' | 'shared'
export type AccountColumnWidthState = Record<string, number>
+function shouldAutoApplySavedView(): boolean {
+ const hasSharedView =
+ typeof router.values.hashParams?.view === 'object' &&
+ router.values.hashParams.view !== null &&
+ !Array.isArray(router.values.hashParams.view)
+ return (
+ removeProjectIdIfPresent(router.values.location.pathname) === urls.customerAnalyticsAccounts() && !hasSharedView
+ )
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsViewsLogicValues {
- columnDisplay: AccountColumnDisplayState // accountsColumnConfigLogic
- selectColumns: string[] // accountsColumnConfigLogic
- accountFilters: AccountFilter[] // accountsLogic
- assignedToFilter: RoleFilterValue // accountsLogic
- assignmentStatus: AssignmentStatus // accountsLogic
- searchQuery: string // accountsLogic
- sortOrder: AccountSortOrder // accountsLogic
- tagsFilter: string[] // accountsLogic
- tileFilter: TileFilter | null // accountsOverviewTilesLogic
- tiles: AccountsOverviewTile[] // accountsOverviewTilesLogic
+ draftRestored: boolean // accountsLogic
+ viewState: AccountsViewState // accountsLogic
+ viewStateHydrated: boolean // accountsLogic
currentTeamId: number | null // teamLogic
user: UserType | null // userLogic
canEditCurrentView: boolean
@@ -98,39 +97,19 @@ export interface accountsViewsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsViewsLogicActions {
- setColumnDisplayConfig: (config: AccountColumnDisplayState) => {
- config: AccountColumnDisplayState
- } // accountsColumnConfigLogic
- setSelectColumns: (columns: string[]) => {
- columns: string[]
- } // accountsColumnConfigLogic
- setAccountFilters: (filters: AccountFilter[]) => {
- filters: AccountFilter[]
- } // accountsLogic
- setAssignedToFilter: (value: RoleFilterValue) => {
- value: RoleFilterValue
- } // accountsLogic
- setAssignmentStatus: (status: AssignmentStatus) => {
- status: AssignmentStatus
+ applyViewState: (
+ viewState: AccountsViewState,
+ options: ApplyAccountsViewStateOptions
+ ) => {
+ options: ApplyAccountsViewStateOptions
+ viewState: AccountsViewState
} // accountsLogic
setAwaitingSavedView: (awaiting: boolean) => {
awaiting: boolean
} // accountsLogic
- setSearchQuery: (query: string) => {
- query: string
- } // accountsLogic
- setSortOrder: (sortOrder: AccountSortOrder) => {
- sortOrder: AccountSortOrder
- } // accountsLogic
- setTagsFilter: (tags: string[]) => {
- tags: string[]
+ syncViewStateToUrl: () => {
+ value: true
} // accountsLogic
- setTileFilter: (filter: TileFilter | null) => {
- filter: TileFilter | null
- } // accountsOverviewTilesLogic
- setTiles: (tiles: AccountsOverviewTile[]) => {
- tiles: AccountsOverviewTile[]
- } // accountsOverviewTilesLogic
applyView: (view: ColumnConfigurationApi) => {
view: ColumnConfigurationApi
}
@@ -203,6 +182,9 @@ export interface accountsViewsLogicActions {
visibility: ViewVisibility
}
}
+ restoreSavedView: () => {
+ value: true
+ }
selectView: (id: string) => {
id: string
}
@@ -300,18 +282,7 @@ export interface accountsViewsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsViewsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- liveViewState: (
- selectColumns: string[],
- searchQuery: string,
- tagsFilter: string[],
- assignmentStatus: AssignmentStatus,
- assignedToFilter: RoleFilterValue,
- sortOrder: AccountSortOrder,
- tileFilter: TileFilter | null,
- tiles: AccountsOverviewTile[],
- accountFilters: AccountFilter[],
- columnDisplay: AccountColumnDisplayState
- ) => AccountsViewState
+ liveViewState: (viewState: AccountsViewState) => AccountsViewState
currentView: (views: ColumnConfigurationApi[], currentViewId: string | null) => ColumnConfigurationApi | null
isDirty: (currentView: ColumnConfigurationApi | null, liveViewState: AccountsViewState) => boolean
canEditCurrentView: (currentView: ColumnConfigurationApi | null) => boolean
@@ -333,29 +304,10 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
['currentTeamId'],
userLogic,
['user'],
- accountsColumnConfigLogic,
- ['selectColumns', 'columnDisplay'],
- accountsLogic,
- ['searchQuery', 'tagsFilter', 'assignmentStatus', 'assignedToFilter', 'sortOrder', 'accountFilters'],
- accountsOverviewTilesLogic,
- ['tiles', 'tileFilter'],
- ],
- actions: [
- accountsColumnConfigLogic,
- ['setSelectColumns', 'setColumnDisplayConfig'],
accountsLogic,
- [
- 'setSearchQuery',
- 'setTagsFilter',
- 'setAssignmentStatus',
- 'setAssignedToFilter',
- 'setSortOrder',
- 'setAccountFilters',
- 'setAwaitingSavedView',
- ],
- accountsOverviewTilesLogic,
- ['setTiles', 'setTileFilter'],
+ ['viewState', 'draftRestored', 'viewStateHydrated'],
],
+ actions: [accountsLogic, ['applyViewState', 'setAwaitingSavedView', 'syncViewStateToUrl']],
})),
actions({
selectView: (id: string) => ({ id }),
@@ -366,6 +318,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
setIsCreating: (isCreating: boolean) => ({ isCreating }),
setViewToDelete: (id: string | null) => ({ id }),
setViewToEdit: (id: string | null) => ({ id }),
+ restoreSavedView: true,
}),
loaders(({ values }) => ({
views: [
@@ -454,45 +407,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
],
})),
selectors({
- liveViewState: [
- (s) => [
- s.selectColumns,
- s.searchQuery,
- s.tagsFilter,
- s.assignmentStatus,
- s.assignedToFilter,
- s.sortOrder,
- s.tileFilter,
- s.tiles,
- s.accountFilters,
- s.columnDisplay,
- ],
- (
- selectColumns: string[],
- searchQuery: string,
- tagsFilter: string[],
- assignmentStatus: AssignmentStatus,
- assignedToFilter: import('./accountsLogic').RoleFilterValue,
- sortOrder: import('./accountsLogic').AccountSortOrder,
- tileFilter: null | import('./accountsOverviewTilesLogic').TileFilter,
- tiles: import('./accountsOverviewTilesLogic').AccountsOverviewTile[],
- accountFilters: import('./accountsPropertyFilters').AccountFilter[],
- columnDisplay: import('./accountsColumnConfigLogic').AccountColumnDisplayState
- ): AccountsViewState => ({
- columns: selectColumns,
- sortOrder,
- filters: {
- search: searchQuery,
- assignmentStatus,
- assignedTo: assignedToFilter,
- tags: tagsFilter,
- tileFilter,
- customProperties: accountFilters,
- },
- tiles,
- columnDisplay,
- }),
- ],
+ liveViewState: [(s) => [s.viewState], (viewState: AccountsViewState): AccountsViewState => viewState],
currentView: [
(s) => [s.views, s.currentViewId],
(views: ColumnConfigurationApi[], currentViewId: string | null): ColumnConfigurationApi | null =>
@@ -547,19 +462,8 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
},
applyView: ({ view }) => {
const state = deserializeAccountsView(view)
- actions.setSelectColumns(state.columns)
- actions.setColumnDisplayConfig(state.columnDisplay)
- actions.setSearchQuery(state.filters.search)
- actions.setTagsFilter(state.filters.tags)
- // accountsLogic cross-clears the assigned-to filter when the status is not
- // `assigned`, so set the status first, then restore the users (only meaningful
- // within the assigned status) so they aren't wiped by that cross-listener.
- actions.setAssignmentStatus(state.filters.assignmentStatus)
- actions.setAssignedToFilter(state.filters.assignmentStatus === 'assigned' ? state.filters.assignedTo : [])
- actions.setAccountFilters(state.filters.customProperties)
- actions.setSortOrder(state.sortOrder)
- actions.setTiles(state.tiles)
- actions.setTileFilter(state.filters.tileFilter)
+ actions.applyViewState(state, { source: 'saved_view', columns: 'restore' })
+ actions.syncViewStateToUrl()
actions.setCurrentViewId(view.id)
posthog.capture(AccountsEvents.ViewSelected, { visibility: view.visibility }) // [PostHog] Event: dynamic event name
},
@@ -598,31 +502,39 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
lemonToast.error('Failed to save view')
},
patchViewPropertiesFailure: ({ error }) => {
- // Silent background migration — no toast, just capture the exception.
+ // Background migration failures report the exception without a toast.
posthog.captureException(error)
},
- loadViewsSuccess: ({ views }) => {
+ [accountsLogic.actionTypes.setViewStateHydrated]: () => {
+ actions.restoreSavedView()
+ },
+ loadViewsSuccess: () => {
+ actions.restoreSavedView()
+ },
+ restoreSavedView: () => {
+ if (!values.viewStateHydrated || values.viewsLoading) {
+ return
+ }
+
let migratedView: ColumnConfigurationApi | null = null
- if (!objectsEqual(values.tiles, DEFAULT_TILES)) {
- const candidate = views.find(
+ if (!values.draftRestored && !objectsEqual(values.liveViewState.tiles, DEFAULT_TILES)) {
+ const candidate = values.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 } }
+ actions.patchViewProperties({ id: candidate.id, properties: { tiles: values.liveViewState.tiles } })
+ // Use patched tiles because `views` still holds the stale row.
+ migratedView = { ...candidate, properties: { tiles: values.liveViewState.tiles } }
}
}
- const hashHasView = !!router.values.hashParams?.view
- if (values.currentViewId && !hashHasView) {
+ if (values.currentViewId && !values.draftRestored && shouldAutoApplySavedView()) {
const view =
migratedView?.id === values.currentViewId
? migratedView
- : views.find((v) => v.id === values.currentViewId)
+ : values.views.find((v) => v.id === values.currentViewId)
if (view) {
actions.applyView(view)
}
@@ -631,7 +543,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
},
})),
afterMount(({ actions, values }) => {
- if (values.currentViewId && !router.values.hashParams?.view) {
+ if (values.currentViewId && !values.draftRestored && shouldAutoApplySavedView()) {
actions.setAwaitingSavedView(true)
}
actions.loadViews()
diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts
index 550fd0131b46..2816d2ff74f6 100644
--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts
@@ -72,6 +72,16 @@ describe('customerAnalyticsSceneLogic', () => {
expectLogic(logic).toMatchValues({ activeTab: 'accounts' })
})
+ // Regression: the date and test-account writers rebuilt the URL from the path and the
+ // search params alone, so they silently dropped the Accounts tab's `#view=` state.
+ it('keeps the view hash when writing filter_test_accounts back to the URL', () => {
+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: { assignmentStatus: 'assigned' } })
+
+ logic.actions.setFilterTestAccounts(false)
+
+ expect(router.values.hashParams.view).toEqual({ assignmentStatus: 'assigned' })
+ })
+
it('reads filter_test_accounts from URL', () => {
expectLogic(logic).toMatchValues({
filterTestAccounts: true,
diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
index 82333de71b6d..f5fe9ffa6dd9 100644
--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
@@ -97,7 +97,9 @@ const setQueryParams = (params: Record<string, string>): string => {
})
const currentPath = router.values.location.pathname
- return `${currentPath}${urlParams.toString() ? '?' + urlParams.toString() : ''}`
+ // Preserve the Accounts hash so URL updates retain shared view state.
+ const currentHash = router.values.location.hash
+ return `${currentPath}${urlParams.toString() ? '?' + urlParams.toString() : ''}${currentHash}`
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -298,9 +300,7 @@ export const customerAnalyticsSceneLogic = kea<customerAnalyticsSceneLogicType>(
setBusinessType: (businessType: BusinessType) => ({ businessType }),
setSelectedGroupType: (selectedGroupType: number) => ({ selectedGroupType }),
setFilterTestAccounts: (filterTestAccounts: boolean) => ({ filterTestAccounts }),
- // Shared "My accounts" (assigned-to-me) toggle backing the checkbox on both the
- // Accounts and Notes tabs. Held here (not per-tab) so the choice persists as the
- // user switches between them.
+ // Share the toggle across Accounts and Notes.
setMineOnly: (mineOnly: boolean) => ({ mineOnly }),
}),
reducers(() => ({
@@ -566,7 +566,6 @@ export const customerAnalyticsSceneLogic = kea<customerAnalyticsSceneLogicType>(
dateRange: { date_from: string | null; date_to: string | null },
filterTestAccounts: boolean
): InsightDefinition[] => {
- // Backend guarantees activity event exists, but add safety check
if (!dauSeries || !wauSeries || !mauSeries) {
return []
}
@@ -579,8 +578,7 @@ export const customerAnalyticsSceneLogic = kea<customerAnalyticsSceneLogicType>(
source: {
kind: NodeKind.TrendsQuery,
tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
- // Label each line distinctly here rather than on the shared
- // selectors, which are reused by other single-metric charts.
+ // Set labels here because other charts reuse the individual series.
series: [
{ ...dauSeries, custom_name: 'Daily active' },
{ ...wauSeries, custom_name: 'Weekly active' },