:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): cut accounts list role columns over to relationships (#69064)
Arthur Moreira de Deus5d347d611922
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 29a6a6b764ed..d14d12f453c2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5019,9 +5019,9 @@ snapshots:scenes-app-batchexports--runs-with-data--light:hash: v1.k794b7964.4c1646577dc53efffd814b1a2e723f9da6b10d3641e979f48c5d0447859e2348.fkHuUw1l_9c3rJKSi467jx-6Nv81nNp-PjeRmsgU7l0scenes-app-customer-analytics-accounts--default--dark:- hash: v1.k794b7964.c9c370b05fbbd44a9e387412dba111b38e4ba97fdc6c59e01a42ff3adb5492ef.XjoStLPNP7yOd4GOuEQsqwJ16Q1nxxxq4bKJ_fmfaic+ hash: v1.k794b7964.b580fe58b5ea91870e497ed4874da65a0885931374d5ef3a900895c8d1a2c26c.R7EXGKqeW0l9CV2CVI5_EqvV6d6H0IAtNH7RPOBM4tIscenes-app-customer-analytics-accounts--default--light:- hash: v1.k794b7964.a8d7c019f2dc54de0dbc718203ff8198e8a21b6ad9825bcba03d18fb3bfc72d6.KKOhq4Q5XQMplujdgO1GALvINjHnWlL2KUNSocSlQe8+ hash: v1.k794b7964.129b877d7f5535d72e0b834059ec989aa80494ccbc5345d258c03ab9abe1163c.77iaQiDBhgh_b_Ed0U2Xof14_2pqQlz-fyHQw_hwC78scenes-app-customer-analytics-accounts--empty--dark:hash: v1.k794b7964.892b7da6722a32bd8383152a945e4bbc30eefebf1b9daa79d615e55a969e1a52._oCcXCKvTuiGNNd4h0WZ2YoMvWXtHmgHCxHmljYucH0scenes-app-customer-analytics-accounts--empty--light:@@ -5031,25 +5031,25 @@ snapshots:scenes-app-customer-analytics-accounts--feature-gate-off--light:hash: v1.k794b7964.e8b91bf6a0dd1b5d31064f4cbb94e9791e999c210831c455a498d0c7cc7e6bbb.IkZPJrJz33sKS8zzKwoy8V3s0GvmKpe5EGYTCIljhLsscenes-app-customer-analytics-accounts--row-expanded-empty--dark:- hash: v1.k794b7964.e2b28b311e14ce6200bac645bddf30c8b97874abd12aca653be7793bebfad902.SGe1vS0-upwRSQigc8WTeVONKGHjwZJD3G5L5PyF9Ps+ hash: v1.k794b7964.83cfbb84f16c3d0ef3abc3482d39f05b6f370ddceda6a575f4cdad3de2a48592.XU8BEsPctrrW5BDHOAAseUOUEKN4uaXWN6bmdlqGTSQscenes-app-customer-analytics-accounts--row-expanded-empty--light:- hash: v1.k794b7964.ffa47e19f0e59d52f31dc7a978cf944b99b4a9b67906928acffd7bc4af6bfc9a.PORS9supgsHgzAYUclrgIoW-7v8cyPcZti1pFalNFxc+ hash: v1.k794b7964.f3960b655dedb62b3d7b0a807e65d24b2688b2770e5c1c76f49f1d14841d86fc.Kyl-jkCUoFrfuqKGelDegqf8r3bskXIMdirKAVWES3gscenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:- hash: v1.k794b7964.eb82c630f551bcf603b6ae6993e3bba7b40c2a8e44751b2eb4268b3ec933daa7.Wi33tmhx6YssHXKkt7xHdmg2Meu_RF6kIvTw3b1yqxU+ hash: v1.k794b7964.97520330492106e18e17465da86b5871772b9eccb4b8708d75f1437e9cea693f.ES1BsntsZKFYAHcfd5KQ2WNAoxhU7oG6jhfDK4teUfMscenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:- hash: v1.k794b7964.73635ec0fe5ba7adcee656e61aa707fa86f31d999c779fe8a3a49ad728cc7888.29U_MqSrw4nraIw62cWdUY2EORZiGiBpCR1Vlx3i7F4+ hash: v1.k794b7964.773b061ddeb81cddf27973258ca773905fe5d3e04d71d7fb5bea5d3567df3b39._NwLnY6RY6RB5IyDTvQG-6YS7yippEG9pbd9y8xl_n4scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:- hash: v1.k794b7964.f965d4d9a8f03be382b333ec7dbd94ce2c7c00dcc171ecbbfdcefcb7540b2b19.mao2KMKgwVvpsrCFRFC7YDJFlXExDNilD9Rqb5GKilY+ hash: v1.k794b7964.8e92b27c0a63fafbd74a631f60b1bdea1b9983c7abbd30a4258e1f818ef63ecb.wvCGmys9jG3ZUP_O-3_k5uuNda7hMWnCsRypRDGtrBMscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:- hash: v1.k794b7964.c2405c1fa64d258225471d9ddb9bf7eb15671abf495a31f9785e0527979442d1.V2s9g14XL2ogDHNCRCcksEppG4zUC9ccLL2tnpwfRRg+ hash: v1.k794b7964.9b934a54cfcdee0d1448d2d8bfd579acd6ef2898d844498a8b06688b54c891fa.SK_-r5YH_iaVhdenzRzQMZK7XFMnOuBGUrMxXA9A-Hcscenes-app-customer-analytics-accounts--row-expanded-usage-populated--dark:- hash: v1.k794b7964.6229daa23ae552cc003a0e9d21dff2c73a5b936743c73111e6aafe8f6e0cc70f.4N0y1wBNjq0WE9ZIMdBoDm7UtXwdnDDZKNwx7n954As+ hash: v1.k794b7964.592cdf275469f3860c47e207f3eafe64e4cbd4403153b67aa677184b2b608e01.RA0z4KST7z6GQ8OaV2hPNkv_xPk1azsfWS0Wzh3t7usscenes-app-customer-analytics-accounts--row-expanded-usage-populated--light:- hash: v1.k794b7964.609c43870977f4ba190826fb6d1d6610b3a1dca1ff0fd7cca448c93da2d0b2d5.Jo-IL9MSKtTdh83GzfovqcJOuKsyNpWb2-PkPVXbNXo+ hash: v1.k794b7964.a5c5405f99c368124545f0f6dd5eca5442145b39c35a51d9230ab614a40d20d3.OGLkB5pB_o2HI56DCbuk4G-WUuHK25QQuwAKnSsqRf8scenes-app-customer-analytics-accounts--row-expanded-with-note--dark:- hash: v1.k794b7964.887dba0561cd312a76a9fd99fa9d743a804ee9d00a177f808105051cc05ae42f.V_SoLpt6TITgxjyE3yBIoiJ2U4aRVmv__AskXUpY_tQ+ hash: v1.k794b7964.c9b6f7b53e6c726a4578c832e45190e25544b8393de528d30edbed057ac44791.Ly4hzt_3vfZKOBOWl_agi_l3br3UxMEIRN9qfmLO1Jsscenes-app-customer-analytics-accounts--row-expanded-with-note--light:- hash: v1.k794b7964.663478981ad43ec73d1d72dff9a77feb2da02f3c48007190cb6fed8f164e8e22.ZJ1YXEVCqttMKWB00r-GWgf4PqQsfljS_ZsEYXCdtjg+ hash: v1.k794b7964.d8bf466f479ff1d959eb4bcc623791a9bb5d0679bb4603551330a41b195d21ca.OrdGvoj-FidEK77CCv6wrGfEKYjLduhFHA9Zft14W3Iscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--dark:hash: v1.k794b7964.cf03f6a65f846aec287042028193b834c567f01226d2e91f6389df5af935530d.bXzRv9MkU0nXN-4tvGbenagVaJuhFr86goke8HVYFJYscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--light:diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex fcf382859560..894530290669 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -2643,36 +2643,6 @@"table": null,"type": "string"},- "csm": {- "chain": null,- "fields": null,- "hogql_value": "csm",- "id": null,- "name": "csm",- "schema_valid": true,- "table": null,- "type": "string"- },- "account_executive": {- "chain": null,- "fields": null,- "hogql_value": "account_executive",- "id": null,- "name": "account_executive",- "schema_valid": true,- "table": null,- "type": "string"- },- "account_owner": {- "chain": null,- "fields": null,- "hogql_value": "account_owner",- "id": null,- "name": "account_owner",- "schema_valid": true,- "table": null,- "type": "string"- },"created_by_id": {"chain": null,"fields": null,@@ -11428,36 +11398,6 @@"table": null,"type": "string"},- "csm": {- "chain": null,- "fields": null,- "hogql_value": "csm",- "id": null,- "name": "csm",- "schema_valid": true,- "table": null,- "type": "string"- },- "account_executive": {- "chain": null,- "fields": null,- "hogql_value": "account_executive",- "id": null,- "name": "account_executive",- "schema_valid": true,- "table": null,- "type": "string"- },- "account_owner": {- "chain": null,- "fields": null,- "hogql_value": "account_owner",- "id": null,- "name": "account_owner",- "schema_valid": true,- "table": null,- "type": "string"- },"created_by_id": {"chain": null,"fields": null,diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.pyindex 22abd0807424..f45c39b26d89 100644--- a/products/customer_analytics/backend/facade/hogql.py+++ b/products/customer_analytics/backend/facade/hogql.py@@ -525,22 +525,6 @@ accounts: PostgresTable = PostgresTable(name="zendesk_id",expr=parse_expr("JSONExtractString(properties, 'zendesk_id')"),),- "csm": ExpressionField(- name="csm",- expr=parse_expr("JSONExtract(properties, 'csm', 'Tuple(id Nullable(Int64), email Nullable(String))')"),- ),- "account_executive": ExpressionField(- name="account_executive",- expr=parse_expr(- "JSONExtract(properties, 'account_executive', 'Tuple(id Nullable(Int64), email Nullable(String))')"- ),- ),- "account_owner": ExpressionField(- name="account_owner",- expr=parse_expr(- "JSONExtract(properties, 'account_owner', 'Tuple(id Nullable(Int64), email Nullable(String))')"- ),- ),"created_by_id": IntegerDatabaseField(name="created_by_id", nullable=True, description="User who created the account record."),diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 6bc517d2f7c3..e6b21f79c5ac 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -14,10 +14,10 @@ An **Account** is a customer organization. The list is a HogQL-backed table over## Architecture-The scene renders `AccountsTabContent`, which binds **two** `dataNodeLogic` instances (keys from `../../constants`): `ACCOUNTS_HOGQL_DATA_NODE_KEY` for the list rows (`accountsLogic.hogqlQuery.source`) and `ACCOUNTS_METRICS_DATA_NODE_KEY` for the overview-tile aggregations (`accountsLogic.metricsQuery`). They are deliberately split so the tiles' slower aggregations never block the list rows from rendering — each fires its own request and carries its own loading state. The table reads the list node; `accountsOverviewTilesLogic` reads the metrics node. Both queries share the same filters via `applyAccountFilters`, so they always describe the same set of accounts. Everything else reads from those bound data nodes or from the logics below.+The scene renders `AccountsTabContent`, which binds **two** `dataNodeLogic` instances (keys from `../../constants`): `ACCOUNTS_HOGQL_DATA_NODE_KEY` for the list rows (`accountsLogic.accountsQuerySource` — `hogqlQuery.source`, held at null until the relationship definitions settle so the list fetches exactly once with its final columns) and `ACCOUNTS_METRICS_DATA_NODE_KEY` for the overview-tile aggregations (`accountsLogic.metricsQuery`). They are deliberately split so the tiles' slower aggregations never block the list rows from rendering — each fires its own request and carries its own loading state. The table reads the list node; `accountsOverviewTilesLogic` reads the metrics node. Both queries share the same filters via `applyAccountFilters`, so they always describe the same set of accounts. Everything else reads from those bound data nodes or from the logics below.```text-AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, accountsLogic.hogqlQuery.source) [list rows]+AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, accountsLogic.accountsQuerySource) [list rows]└─ binds dataNodeLogic(ACCOUNTS_METRICS_DATA_NODE_KEY, accountsLogic.metricsQuery) [overview tiles, metrics-only]├── AccountsMaxTools registers the `open_account` Max contextual tool → accountsLogic.openAccount├── AccountsTabFilters two rows: (1) search + Refresh; (2) tags / "assigned to" (incl. unassigned-only) /@@ -27,7 +27,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc└── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities)├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)- ├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated, read-only)+ ├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/end controls + definition filter, current assignments sorted on top)├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)@@ -35,30 +35,30 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc### Logics and what each owns-| Logic | Owns |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `accountsLogic` | The hub. Search (debounced), tag and assigned-to/unassigned filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |-| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |-| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API). |-| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |-| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |-| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |-| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). |-| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the full list feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Read-only until the relationships cutover. |-| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables. |-| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |-| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |+| Logic | Owns |+| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `accountsLogic` | The hub. Search (debounced), tag and assigned-to/unassigned filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API). |+| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |+| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |+| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |+| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). |+| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |+| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables. |+| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |+| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |## Data & query model-`accountsLogic.hogqlQuery` builds a `DataTableNode` wrapping an `AccountsQuery` for the list rows (`select`, plus optional `search`, `tagNames`, `allRolesUnassigned`, `assignedToUserIds`, `filterExpression`, `orderBy`). The overview-tile `metrics` are **not** on this query — `accountsLogic.metricsQuery` is a separate metrics-only `AccountsQuery` (`metrics` set, no `select`; `null` when there are no tiles) that the backend runner answers with its own aggregation query, so the tiles load without blocking the rows. Both queries share filters via `applyAccountFilters`. The backend runner (`accounts_query_runner`) returns **rows as arrays** aligned to `visibleColumnNames`, and tile aggregations in `metricsResults`. `assignedToUserIds` is the "assigned to" filter — a list of user ids the runner expands into `csm IN ids OR account_executive IN ids` (the single user-facing role filter; there are no separate per-role CSM/AE/owner filters). The `allRolesUnassigned` flag (the "Unassigned only" option, surfaced inside the "Assigned to" picker — mutually exclusive with picking people via the cascade in `accountsLogic` listeners) restricts to accounts with no csm/AE/owner. The "My accounts" checkbox is a client-side shortcut: `accountsLogic` resolves it to `[currentUserId]` (from `userLogic`) before the query is sent, so the backend only ever receives explicit ids and a shared URL resolves to the same accounts for every viewer. Its on/off state is mirrored into a shared `mineOnly` toggle on `customerAnalyticsSceneLogic` (localStorage-persisted, like `filterTestAccounts`) so the choice carries over to the Notes tab's own "My accounts" checkbox and back — `setAssignedToFilter` keeps `mineOnly` in step, and when the accounts URL carries no explicit `assignedTo` in its `#view` hash the filter falls back to `mineOnly` → `[currentUserId]`. (On the Notes tab "My accounts" filters notes to those on accounts assigned to you, via the `assigned_to` param on the account-notes endpoint; "My notes" there is the separate created-by shortcut and is not shared.) Two cell shapes matter:+`accountsLogic.hogqlQuery` builds a `DataTableNode` wrapping an `AccountsQuery` for the list rows (`select`, plus optional `search`, `tagNames`, `allRolesUnassigned`, `assignedToUserIds`, `filterExpression`, `orderBy`). The overview-tile `metrics` are **not** on this query — `accountsLogic.metricsQuery` is a separate metrics-only `AccountsQuery` (`metrics` set, no `select`; `null` when there are no tiles or while definitions are still loading) that the backend runner answers with its own aggregation query, so the tiles load without blocking the rows. Both queries share filters via `applyAccountFilters`. The backend runner (`accounts_query_runner`) returns **rows as arrays** aligned to `visibleColumnNames`, and tile aggregations in `metricsResults`. `assignedToUserIds` is the "assigned to" filter — a list of user ids the runner matches against accounts with an ACTIVE relationship assignment held by any of them (the single user-facing role filter; there are no separate per-role filters). The `allRolesUnassigned` flag (the "Unassigned only" option, surfaced inside the "Assigned to" picker — mutually exclusive with picking people via the cascade in `accountsLogic` listeners) restricts to accounts with no active relationship assignments at all. The "My accounts" checkbox is a client-side shortcut: `accountsLogic` resolves it to `[currentUserId]` (from `userLogic`) before the query is sent, so the backend only ever receives explicit ids and a shared URL resolves to the same accounts for every viewer. Its on/off state is mirrored into a shared `mineOnly` toggle on `customerAnalyticsSceneLogic` (localStorage-persisted, like `filterTestAccounts`) so the choice carries over to the Notes tab's own "My accounts" checkbox and back — `setAssignedToFilter` keeps `mineOnly` in step, and when the accounts URL carries no explicit `assignedTo` in its `#view` hash the filter falls back to `mineOnly` → `[currentUserId]`. (On the Notes tab "My accounts" filters notes to those on accounts assigned to you, via the `assigned_to` param on the account-notes endpoint; "My notes" there is the separate created-by shortcut and is not shared.) Two cell shapes matter:- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — emitted as `tuple(name, external_id, id)`, read as `{ name, external_id, id }`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `external_id` is the copy-able group key. `getNameCell()` in `AccountsHogQLTable.tsx` is the canonical accessor; never assume a column index. In `NameCell` the name renders as the prominent (`font-semibold`) primary label: a plain click opens the account details inline (toggles the row's expansion via `accountsExpansionLogic`, firing `AccountOpened` on open), while the `<Link>` href points at `urls.customerAnalyticsAccount(id)` so cmd/ctrl-click opens the account's deep-link page in a new tab. The `external_id` sits beneath it as de-emphasized (`text-xs text-muted`) copy-to-clipboard text.-- **role columns** (`csm`, `account_executive`, `account_owner`) — emitted as `tuple(id, email)`, rendered with `MemberSelect`. Sorting these uses `tupleElement(col, 2)` (email) so visual order matches.+- **relationship columns** — backed by the ``accounts.relationships.values.`<definition_id>` `` lazy join, emitted as the **array of active assignee user ids** (`[]` when unassigned). The legacy names `csm`/`account_executive`/`account_owner` remain the STORED column names (in defaults, saved views, and URL state) and are translated into the lazy-join expression at query-build time by `translateSelectColumns` in `accountsColumnConfigLogic`, matched by seeded definition name (`LEGACY_ROLE_COLUMNS`); a legacy column with no matching definition is dropped from the query. Other definitions are pickable from the "Relationships" column group with opaque `rel_<id>` aliases, resolved back via `aliasToRelationshipDefinition`. Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Sorting uses the alias directly (arrays of ids — deterministic but not email order).-Default columns (`ACCOUNTS_HOGQL_DEFAULT_SELECT`): `name`, `tag_names`, `notebook_count`, `csm`, `account_executive`, `account_owner`. The name column is force-kept (`ensureNameColumn`) — removing it breaks identity, scroll, and role edits. Extra columns come from account properties, lazy/virtual-table joins under `system.accounts`, data-warehouse joins, freeform SQL, or **custom properties** — all assembled by `buildAccountColumnGroups`.+Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship column per team definition. `ACCOUNTS_HOGQL_DEFAULT_SELECT` (base columns only) is just the pre-load seed; once `loadRelationshipDefinitionsSuccess` fires, still-default columns are upgraded to the `defaultSelectColumns` selector (seeded definitions keep their legacy bare names, others get `rel_<id>` expressions) — anything already customized by the user, a saved view, or a shared URL is left alone, and the URL hash serializes columns only when they differ from `defaultSelectColumns`. The name column is force-kept (`ensureNameColumn`) — removing it breaks identity, scroll, and role edits. Extra columns come from account properties, lazy/virtual-table joins under `system.accounts`, data-warehouse joins, freeform SQL, or **custom properties** — all assembled by `buildAccountColumnGroups`.-**Custom property columns** surface the team's `CustomPropertyDefinition`s (loaded in `accountsColumnConfigLogic` via the generated `customPropertyDefinitionsList`) as a "Custom properties" picker group. Each is selected as `accounts.custom_properties.values.\`<definition-id>\` AS cp*<id>`— a JSON dot-access through the`custom_properties`lazy join on`system.accounts`(backed by the`customer_analytics_custompropertyvalue`EAV table; one JOIN regardless of column count). Because the alias is an opaque`cp*<id>`, every label-bearing surface must resolve it back via the`aliasToDefinition`selector: the table header (`useContextColumns`in`AccountsHogQLTable`) and the configurator's "Visible columns" list (`SelectedAccountColumn`). Cells render by display type (`CustomPropertyCell`: date→`TZLabel`, boolean→icon, select→`LemonColorGlyph`+ label, numeric→`formatCustomPropertyValue`). v1 is display-only with lexical sort (the JSON value is a string). Numeric custom properties (display type`number`/`currency`/`percent`) are also selectable in the **overview tiles** sum/avg/threshold pickers —`numericColumnOptions`recognizes the display type and wraps the (string) value in`toFloatOrNull(...)` so aggregation is numeric.+**Custom property columns** surface the team's `CustomPropertyDefinition`s (loaded in `accountsColumnConfigLogic` via the generated `customPropertyDefinitionsList`) as a "Custom properties" picker group. Each is selected as ``accounts.custom_properties.values.`<definition-id>` AS cp_<id>`` — a JSON dot-access through the `custom_properties` lazy join on `system.accounts` (backed by the `customer_analytics_custompropertyvalue` EAV table; one JOIN regardless of column count). Because the alias is an opaque `cp_<id>`, every label-bearing surface must resolve it back via the `aliasToDefinition` selector: the table header (`useContextColumns` in `AccountsHogQLTable`) and the configurator's "Visible columns" list (`SelectedAccountColumn`). Cells render by display type (`CustomPropertyCell`: date→`TZLabel`, boolean→icon, select→`LemonColorGlyph` + label, numeric→`formatCustomPropertyValue`). v1 is display-only with lexical sort (the JSON value is a string). Numeric custom properties (display type `number`/`currency`/`percent`) are also selectable in the **overview tiles** sum/avg/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the (string) value in `toFloatOrNull(...)` so aggregation is numeric.Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`), else the backend gets an `orderBy` referencing a missing alias.@@ -105,7 +105,7 @@ Views are persisted as `ColumnConfiguration` rows under `context_key = 'customer- `columns` ← `selectColumns` (column names in order)- `order_by` ← sort, stored as `["<column> <ASC|DESC>"]` using the logical column name- (query-time `deriveAccountsOrderByExpr` wraps role/tuple columns at build time; the stored name stays clean)+ (HogQL resolves the name against the SELECT alias at query-build time; the stored name stays clean)- `filters` ← search text, tags, unassigned toggle, assigned-to filter, tile filter (JSON)- `properties` ← `{ tiles }` — overview tile configuration (a `properties` field added to the `ColumnConfiguration` model)@@ -161,35 +161,35 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions### Tracked events-| Event | Fires from | Properties |-| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |-| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `unassigned_only` \| `my_accounts` \| `assigned_to`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assigned_to` also `role_count` |-| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |-| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |-| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics accounts account opened` | `AccountsHogQLTable.tsx` `NameCell` account-name `<Link>` `onClick` (only when the row expands, not when it collapses) | _(none — the row's `id` is customer PII-adjacent and kept out)_ |-| ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ |-| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |-| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |-| `customer analytics accounts view saved` | `accountsViewsLogic` `submitNewViewForm` listener (success) | `visibility` (`private` \| `shared`) |-| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener | _(none)_ |-| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |-| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |-| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |-| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |-| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |-| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |-| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |-| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities`) |-| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |-| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |-| `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |-| `customer analytics notes tab searched` | `accountNotesLogic` `setSearch` listener (post-debounce) | `has_query`, `query_length` (no raw text) |-| `customer analytics notes tab filtered` | `accountNotesLogic` `reportFilterChange` listener (dispatched by the filter controls only, so the "My notes"/"My accounts" cascade doesn't double-fire) | `filter_type` (`created_by` \| `account` \| `my_notes` \| `my_accounts`), `is_cleared`; for `created_by` also `user_count`; for `my_notes`/`my_accounts` also `value` (no account id/name logged) |-| `customer analytics notes tab note clicked` | `AccountNotesTabContent.tsx` note title `<Link>` `onClick` (opens side panel) | `notebook_short_id` |-| `customer analytics notes tab account clicked` | `AccountNotesTabContent.tsx` account `<Link>` `onClick` | `account_id` |+| Event | Fires from | Properties |+| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |+| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `unassigned_only` \| `my_accounts` \| `assigned_to`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assigned_to` also `role_count` |+| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |+| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |+| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |+| `customer analytics accounts account opened` | `AccountsHogQLTable.tsx` `NameCell` account-name `<Link>` `onClick` (only when the row expands, not when it collapses) | _(none — the row's `id` is customer PII-adjacent and kept out)_ |+| ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ |+| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |+| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |+| `customer analytics accounts view saved` | `accountsViewsLogic` `submitNewViewForm` listener (success) | `visibility` (`private` \| `shared`) |+| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener | _(none)_ |+| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |+| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |+| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner` for the seeded definitions, else the definition name), `is_assigned`, `assigned_user_id`, `source` (`list_row` from `accountsLogic.updateAccountRole` \| `relationships_tab` from `accountRelationshipsLogic` assign/end) |+| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |+| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |+| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |+| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |+| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities`) |+| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |+| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |+| `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |+| `customer analytics notes tab searched` | `accountNotesLogic` `setSearch` listener (post-debounce) | `has_query`, `query_length` (no raw text) |+| `customer analytics notes tab filtered` | `accountNotesLogic` `reportFilterChange` listener (dispatched by the filter controls only, so the "My notes"/"My accounts" cascade doesn't double-fire) | `filter_type` (`created_by` \| `account` \| `my_notes` \| `my_accounts`), `is_cleared`; for `created_by` also `user_count`; for `my_notes`/`my_accounts` also `value` (no account id/name logged) |+| `customer analytics notes tab note clicked` | `AccountNotesTabContent.tsx` note title `<Link>` `onClick` (opens side panel) | `notebook_short_id` |+| `customer analytics notes tab account clicked` | `AccountNotesTabContent.tsx` account `<Link>` `onClick` | `account_id` |> **Keep this table up to date.** Whenever you add, rename, or remove a `posthog.capture()` event in the Accounts area — or change its properties — update this table in the same change. An agent reading this file should be able to trust it as the source of truth for what the Accounts list reports.diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsxindex 57992e30d48d..7ccec8ae436a 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx@@ -1,7 +1,9 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { LemonTable, LemonTableColumns, LemonTag, ProfilePicture } from '@posthog/lemon-ui'+import { IconX } from '@posthog/icons'+import { LemonButton, LemonSelect, LemonTable, LemonTableColumns, LemonTag, ProfilePicture } from '@posthog/lemon-ui'+import { MemberSelect } from 'lib/components/MemberSelect'import { TZLabel } from 'lib/components/TZLabel'import type { AccountRelationshipApi } from 'products/customer_analytics/frontend/generated/api.schemas'@@ -11,7 +13,20 @@ import { accountRelationshipsLogic } from './accountRelationshipsLogic'const PAGE_SIZE = 10export function AccountRelationshipsExpansion({ accountId }: { accountId: string }): JSX.Element {- const { relationships, relationshipsLoading } = useValues(accountRelationshipsLogic({ accountId }))+ const {+ relationships,+ relationshipsLoading,+ displayedRelationships,+ definitionFilter,+ definitionFilterOptions,+ relationshipDefinitions,+ assignDefinition,+ assignDefinitionId,+ relationshipSaving,+ } = useValues(accountRelationshipsLogic({ accountId }))+ const { setDefinitionFilter, setAssignDefinitionId, assignRelationship, endRelationship } = useActions(+ accountRelationshipsLogic({ accountId })+ )const columns: LemonTableColumns<AccountRelationshipApi> = [{@@ -49,20 +64,87 @@ export function AccountRelationshipsExpansion({ accountId }: { accountId: string<LemonTag type="success">Current</LemonTag>),},+ {+ key: 'actions',+ width: 0,+ render: (_, relationship) =>+ relationship.ended_at ? null : (+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ tooltip={`End this ${relationship.definition.name} assignment`}+ disabledReason={relationshipSaving ? 'Saving…' : undefined}+ onClick={() => endRelationship(relationship)}+ />+ ),+ },]return (- <LemonTable<AccountRelationshipApi>- size="small"- embedded- dataSource={relationships ?? []}- rowKey="id"- loading={relationshipsLoading}- columns={columns}- pagination={{ pageSize: PAGE_SIZE }}- emptyState={- relationships === null ? 'Failed to load relationships.' : 'No assignments on this account yet.'- }- />+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <LemonSelect+ size="small"+ placeholder="All relationships"+ allowClear+ value={definitionFilter}+ onChange={(value) => setDefinitionFilter(value ?? null)}+ options={definitionFilterOptions.map((definition) => ({+ value: definition.id,+ label: definition.name,+ }))}+ data-attr="account-relationships-definition-filter"+ />+ <div className="flex items-center gap-2">+ <LemonSelect+ size="small"+ placeholder="Relationship to assign"+ allowClear+ value={assignDefinitionId}+ onChange={(value) => setAssignDefinitionId(value ?? null)}+ options={relationshipDefinitions.map((definition) => ({+ value: definition.id,+ label: definition.name,+ }))}+ data-attr="account-relationships-assign-definition"+ />+ <MemberSelect+ value={null}+ allowNone={false}+ onChange={(user) => user && assignDefinition && assignRelationship(assignDefinition, user)}+ >+ {() => (+ <LemonButton+ type="primary"+ size="small"+ loading={relationshipSaving}+ disabledReason={+ !assignDefinition+ ? 'Pick a relationship to assign first'+ : relationshipSaving+ ? 'Saving…'+ : undefined+ }+ data-attr="account-relationships-assign-button"+ >+ Assign+ </LemonButton>+ )}+ </MemberSelect>+ </div>+ </div>+ <LemonTable<AccountRelationshipApi>+ size="small"+ embedded+ dataSource={displayedRelationships}+ rowKey="id"+ loading={relationshipsLoading}+ columns={columns}+ pagination={{ pageSize: PAGE_SIZE }}+ emptyState={+ relationships === null ? 'Failed to load relationships.' : 'No assignments on this account yet.'+ }+ />+ </div>)}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsxindex 640ff4092ad0..8e4880c4f65d 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx@@ -127,11 +127,12 @@ function SelectedAccountColumn({onEdit: (column: string, index: number) => voidonRemove: (column: string) => void}): JSX.Element {- const { aliasToDefinition } = useValues(accountsColumnConfigLogic)+ const { aliasToDefinition, aliasToRelationshipDefinition } = useValues(accountsColumnConfigLogic)const { setNodeRef, attributes, transform, transition, listeners } = useSortable({ id: column })const alias = extractDisplayLabel(column)- // Custom-property columns are aliased to an opaque `cp_<id>`; show the definition name instead.- const label = aliasToDefinition[alias]?.name ?? alias+ // Custom-property and relationship columns are aliased to opaque `cp_<id>` / `rel_<id>`+ // (or legacy role keys); show the definition name instead.+ const label = aliasToDefinition[alias]?.name ?? aliasToRelationshipDefinition[alias]?.name ?? alias// `name` carries the row identity (account id) and external_id for the// Account cell — removing it would break row expansion and role updates.const isMandatory = column === ACCOUNTS_NAME_COLUMNdiff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsxindex b521de241714..772578a5bd20 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx@@ -13,6 +13,7 @@ import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'import { Link } from 'lib/lemon-ui/Link'+import { membersLogic } from 'scenes/organization/membersLogic'import { urls } from 'scenes/urls'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'@@ -20,34 +21,27 @@ import { DataTable } from '~/queries/nodes/DataTable/DataTable'import { DataTableNode } from '~/queries/schema/schema-general'import { QueryContext, QueryContextColumn, QueryContextColumnComponent } from '~/queries/types'-import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import type {+ AccountRelationshipDefinitionApi,+ CustomPropertyDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'import { formatCustomPropertyValue } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'-import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic } from './accountsColumnConfigLogic'+import { ACCOUNTS_NAME_COLUMN, LEGACY_ROLE_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'import { accountsExpansionLogic } from './accountsExpansionLogic'-import { AccountRoleKey, accountsLogic } from './accountsLogic'+import { accountsLogic, savingRoleKey } from './accountsLogic'import { AccountsEvents } from './constants'-type AccountAssignment = { id: number; email: string } | null-// Shape the backend emits for the `name` column — see accounts_query_runner._calculate.type AccountNameCell = { name: string; external_id: string | null; id: string }-const ROLE_LABELS: Record<AccountRoleKey, string> = {- csm: 'CSM',- account_executive: 'Account executive',- account_owner: 'Account owner',-}-const COLUMN_WIDTHS = {name: '240px',tag_names: '280px',notebook_count: '80px',- csm: '220px',- account_executive: '220px',- account_owner: '220px',+ relationship: '220px',} as constfunction getCellAt(record: unknown, names: string[], column: string): unknown {@@ -72,19 +66,13 @@ function getNameCell(record: unknown, visibleColumnNames: string[]): AccountNamereturn typeof cell.id === 'string' && typeof cell.name === 'string' ? (cell as AccountNameCell) : undefined}-function tupleToAssignment(value: unknown): AccountAssignment {+// Relationship cells arrive as the array of ACTIVE assignee user ids from the+// `accounts.relationships.values` lazy join ([] when nobody holds the relationship).+function parseAssignedUserIds(value: unknown): number[] {if (!Array.isArray(value)) {- return null- }- const [id, email] = value as [unknown, unknown]- if (id === null || id === undefined || typeof email !== 'string' || !email) {- return null+ return []}- const numericId = typeof id === 'number' ? id : Number(id)- if (!Number.isFinite(numericId)) {- return null- }- return { id: numericId, email }+ return value.map((id) => (typeof id === 'number' ? id : Number(id))).filter((id) => Number.isFinite(id))}function NameCell({ record }: { record: unknown }): JSX.Element {@@ -148,24 +136,51 @@ function NotebookCountCell({ record }: { record: unknown }): JSX.Element {return count > 0 ? <span>{count}</span> : <span className="text-muted">—</span>}-function RoleAssignmentCell({ record, role }: { record: unknown; role: AccountRoleKey }): JSX.Element {- const { isRoleSaving, accountOverrides } = useValues(accountsLogic)+function RelationshipCell({+ record,+ column,+ definition,+}: {+ record: unknown+ column: string+ definition: AccountRelationshipDefinitionApi+}): JSX.Element {+ const { isRoleSaving, relationshipOverrides } = useValues(accountsLogic)const { visibleColumnNames } = useValues(accountsColumnConfigLogic)const { updateAccountRole } = useActions(accountsLogic)+ const { meFirstMembers } = useValues(membersLogic)const getCell = useGetCell()const accountId = getNameCell(record, visibleColumnNames)?.id ?? ''- const overrideProperties = accountId ? accountOverrides[accountId]?.properties : undefined- const overrideRole = overrideProperties != null ? overrideProperties[role] : undefined- const assignment: AccountAssignment =- overrideRole === undefined ? tupleToAssignment(getCell(record, role)) : (overrideRole as AccountAssignment)- const saving = accountId ? isRoleSaving(accountId, role) : false+ const override = accountId ? relationshipOverrides[savingRoleKey(accountId, column)] : undefined+ const userIds = override ?? parseAssignedUserIds(getCell(record, column))++ if (!definition.is_single_holder) {+ // ponytail: multi-holder relationships are read-only here; manage them on the+ // account's relationships tab. Add inline multi-assign if it's ever needed.+ const users = userIds.map((id) => meFirstMembers.find((member) => member.user.id === id)?.user ?? null)+ return (+ <div data-attr={`accounts-${column}-cell`} className="flex flex-wrap items-center gap-2">+ {users.length === 0 ? (+ <span className="text-muted">Unassigned</span>+ ) : (+ users.map((user, index) => (+ <span key={userIds[index]} className="inline-flex items-center gap-1 text-sm">+ {user ? <ProfilePicture user={user} size="sm" /> : null}+ {user?.email ?? 'Unknown user'}+ </span>+ ))+ )}+ </div>+ )+ }+ const saving = accountId ? isRoleSaving(accountId, column) : falsereturn (- <div data-attr={`accounts-${role}-cell`}>+ <div data-attr={`accounts-${column}-cell`}><MemberSelect- value={assignment?.id ?? null}+ value={userIds[0] ?? null}defaultLabel="Unassigned"- onChange={(user) => accountId && updateAccountRole(accountId, role, user)}+ onChange={(user) => accountId && updateAccountRole(accountId, column, user)}>{(selectedUser) => (<LemonButton@@ -173,16 +188,12 @@ function RoleAssignmentCell({ record, role }: { record: unknown; role: AccountRosize="small"loading={saving}disabledReason={saving ? 'Saving…' : undefined}- icon={- selectedUser ? (- <ProfilePicture user={selectedUser} size="sm" />- ) : assignment ? (- <ProfilePicture user={{ email: assignment.email }} size="sm" />- ) : undefined- }+ icon={selectedUser ? <ProfilePicture user={selectedUser} size="sm" /> : undefined}>- {assignment ? (- <span className="text-sm">{assignment.email}</span>+ {selectedUser ? (+ <span className="text-sm">{selectedUser.email}</span>+ ) : userIds.length > 0 ? (+ <span className="text-sm">Unknown user</span>) : (<span className="text-muted">Unassigned</span>)}@@ -278,25 +289,11 @@ const KNOWN_COLUMN_TEMPLATES: Record<string, KnownColumnTemplate> = {width: COLUMN_WIDTHS.notebook_count,render: ({ record }) => <NotebookCountCell record={record} />,},- csm: {- label: ROLE_LABELS.csm,- width: COLUMN_WIDTHS.csm,- render: ({ record }) => <RoleAssignmentCell record={record} role="csm" />,- },- account_executive: {- label: ROLE_LABELS.account_executive,- width: COLUMN_WIDTHS.account_executive,- render: ({ record }) => <RoleAssignmentCell record={record} role="account_executive" />,- },- account_owner: {- label: ROLE_LABELS.account_owner,- width: COLUMN_WIDTHS.account_owner,- render: ({ record }) => <RoleAssignmentCell record={record} role="account_owner" />,- },}function useContextColumns(): Record<string, QueryContextColumn> {- const { visibleColumnNames, aliasToDefinition } = useValues(accountsColumnConfigLogic)+ const { visibleColumnNames, aliasToDefinition, aliasToRelationshipDefinition } =+ useValues(accountsColumnConfigLogic)return useMemo(() => {const columns: Record<string, QueryContextColumn> = {}for (const key of visibleColumnNames) {@@ -308,6 +305,17 @@ function useContextColumns(): Record<string, QueryContextColumn> {}continue}+ const relationshipDefinition = aliasToRelationshipDefinition[key]+ if (relationshipDefinition) {+ columns[key] = {+ renderTitle: () => <SortableColumnHeader column={key} label={relationshipDefinition.name} />,+ width: COLUMN_WIDTHS.relationship,+ render: ({ record }) => (+ <RelationshipCell record={record} column={key} definition={relationshipDefinition} />+ ),+ }+ continue+ }const template = KNOWN_COLUMN_TEMPLATES[key]const label = template?.label ?? keycolumns[key] = {@@ -317,7 +325,7 @@ function useContextColumns(): Record<string, QueryContextColumn> {}}return columns- }, [visibleColumnNames, aliasToDefinition])+ }, [visibleColumnNames, aliasToDefinition, aliasToRelationshipDefinition])}function useExpandable(): QueryContext<DataTableNode>['expandable'] {@@ -383,9 +391,9 @@ const SKELETON_COLUMNS: LemonTableColumns<{ key: number }> = [width: COLUMN_WIDTHS.notebook_count,render: () => <LemonSkeleton className="h-4 w-4" />,},- ...(['csm', 'account_executive', 'account_owner'] as const).map((role) => ({- title: ROLE_LABELS[role],- width: COLUMN_WIDTHS[role],+ ...Object.values(LEGACY_ROLE_COLUMNS).map((label) => ({+ title: label,+ width: COLUMN_WIDTHS.relationship,render: () => (<div className="flex items-center gap-2"><LemonSkeleton.Circle className="h-5 w-5" />@@ -412,11 +420,13 @@ function AccountsHogQLSkeleton(): JSX.Element {}export function AccountsHogQLTable(): JSX.Element {- const { hogqlQuery } = useValues(accountsLogic)+ const { hogqlQuery, accountsQuerySource } = useValues(accountsLogic)const { responseLoading, response } = useValues(dataNodeLogic)const contextColumns = useContextColumns()const expandable = useExpandable()- if (responseLoading && !response) {+ // A null source means the query is still waiting on the relationship+ // definitions — same skeleton as the initial fetch, not an empty table.+ if ((responseLoading || !accountsQuerySource) && !response) {return <AccountsHogQLSkeleton />}return (diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex 5a7fd1719b3f..d91cc670b6a5 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -12,12 +12,33 @@ import type { MockResolverInfo } from '~/mocks/utils'const QUERY_ENDPOINT = '/api/environments/:team_id/query/:kind/'const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'+const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relationship_definitions/'const WAREHOUSE_VIEW_LINK_ENDPOINT = 'api/environments/:team_id/warehouse_view_link/'const INSIGHTS_ENDPOINT = 'api/environments/:team_id/insights/'type AccountNameCell = { name: string; external_id: string | null; id: string }-type AccountRoleCell = [number, string] | null-type AccountRow = [AccountNameCell, string[], number, AccountRoleCell, AccountRoleCell, AccountRoleCell]+// Active assignee user ids from the relationships lazy join. Ids 178 and 202 match+// the default org-members mock so the cells resolve to john.doe / jane.mcdoe.+type AccountRelationshipCell = number[]+type AccountRow = [+ AccountNameCell,+ string[],+ number,+ AccountRelationshipCell,+ AccountRelationshipCell,+ AccountRelationshipCell,+]++const RELATIONSHIP_DEFINITIONS = {+ count: 3,+ next: null,+ previous: null,+ results: [+ { id: 'def-csm', name: 'CSM', description: null, is_single_holder: true },+ { id: 'def-ae', name: 'Account executive', description: null, is_single_holder: true },+ { id: 'def-owner', name: 'Account owner', description: null, is_single_holder: true },+ ],+}function buildAccountsQueryResponse(rows: AccountRow[]): Record<string, unknown> {return {@@ -35,34 +56,13 @@ function buildAccountsQueryResponse(rows: AccountRow[]): Record<string, unknown>}const SAMPLE_ROWS: AccountRow[] = [- [- { name: 'Acme Inc', external_id: 'cust_acme_001', id: 'acc-1' },- ['enterprise', 'priority'],- 0,- [1, '[email protected]'],- [2, '[email protected]'],- null,- ],- [{ name: 'Globex', external_id: 'cust_globex_002', id: 'acc-2' }, [], 0, null, null, null],- [- { name: 'Hooli', external_id: null, id: 'acc-3' },- ['scaleup'],- 0,- [1, '[email protected]'],- null,- [3, '[email protected]'],- ],+ [{ name: 'Acme Inc', external_id: 'cust_acme_001', id: 'acc-1' }, ['enterprise', 'priority'], 0, [178], [202], []],+ [{ name: 'Globex', external_id: 'cust_globex_002', id: 'acc-2' }, [], 0, [], [], []],+ [{ name: 'Hooli', external_id: null, id: 'acc-3' }, ['scaleup'], 0, [178], [], [202]],]const SINGLE_ROW: AccountRow[] = [- [- { name: 'Acme Inc', external_id: 'cust_acme_001', id: 'acc-1' },- ['enterprise', 'priority'],- 1,- [1, '[email protected]'],- [2, '[email protected]'],- null,- ],+ [{ name: 'Acme Inc', external_id: 'cust_acme_001', id: 'acc-1' }, ['enterprise', 'priority'], 1, [178], [202], []],]const ACCOUNT_WITH_LINKS = {@@ -240,6 +240,7 @@ const meta: Meta = {mswDecorator({get: {[WAREHOUSE_VIEW_LINK_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ [RELATIONSHIP_DEFINITIONS_ENDPOINT]: RELATIONSHIP_DEFINITIONS,},}),],diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsxindex 4743bd113027..2e6ada12f8fa 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx@@ -10,14 +10,14 @@ import { AccountsOverviewTiles } from './AccountsOverviewTiles'import { AccountsTabFilters } from './AccountsTabFilters'export function AccountsTabContent(): JSX.Element {- const { hogqlQuery, metricsQuery } = useValues(accountsLogic)+ const { accountsQuerySource, metricsQuery } = useValues(accountsLogic)return (<BindLogiclogic={dataNodeLogic}props={{key: ACCOUNTS_HOGQL_DATA_NODE_KEY,- query: hogqlQuery.source,+ query: accountsQuerySource,}}><BindLogicdiff --git a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.tsindex 348de57967e0..7671cb5393cb 100644--- a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts@@ -29,7 +29,7 @@ const buildAccount = (overrides: Partial<AccountApi> = {}): AccountApi => ({name: 'Acme',external_id: 'ext-1',properties: {- csm: { id: 1, email: '[email protected]' },+ hubspot_deal_id: 'deal-1',billing_id: 'cus_123',},tags: [],@@ -80,7 +80,7 @@ describe('accountLinksLogic', () => {await mountWith(buildAccount({external_id: 'ext-1',- properties: { csm: { id: 1, email: '[email protected]' }, billing_id: 'old' },+ properties: { hubspot_deal_id: 'deal-1', billing_id: 'old' },}))const updated = buildAccount({ external_id: 'ext-2' })@@ -100,7 +100,7 @@ describe('accountLinksLogic', () => {expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(TEAM, 'acc-1', {external_id: 'ext-2',properties: {- csm: { id: 1, email: '[email protected]' },+ hubspot_deal_id: 'deal-1',billing_id: 'new',slack_channel_id: 'C9',usage_dashboard_link: null,diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.tsindex 963a39e9dfd7..ba7118ed9232 100644--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts@@ -2,16 +2,28 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import type { UserBasicType } from '~/types'-import type { AccountRelationshipApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import type {+ AccountRelationshipApi,+ AccountRelationshipDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'import { accountRelationshipsLogic } from './accountRelationshipsLogic'const RELATIONSHIPS_URL = '/api/projects/:team_id/accounts/:account_id/relationships/'+const CSM: AccountRelationshipDefinitionApi = { id: 'def-1', name: 'CSM', description: null, is_single_holder: true }+const AE: AccountRelationshipDefinitionApi = {+ id: 'def-2',+ name: 'Account executive',+ description: null,+ is_single_holder: true,+}+const buildRelationship = (overrides: Partial<AccountRelationshipApi> = {}): AccountRelationshipApi => ({id: 'rel-1',- definition: { id: 'def-1', name: 'CSM', description: null, is_single_holder: true },+ definition: CSM,user: { id: 1, email: '[email protected]' },started_at: '2026-01-01T00:00:00Z',ended_at: null,@@ -28,6 +40,7 @@ describe('accountRelationshipsLogic', () => {[RELATIONSHIPS_URL]: [buildRelationship(),buildRelationship({ id: 'rel-2', ended_at: '2026-02-01T00:00:00Z' }),+ buildRelationship({ id: 'rel-3', definition: AE, started_at: '2026-03-01T00:00:00Z' }),],},})@@ -37,7 +50,46 @@ describe('accountRelationshipsLogic', () => {it('loads on mount and picks the active assignments for the sidebar summary', async () => {await expectLogic(logic).toDispatchActions(['loadRelationships', 'loadRelationshipsSuccess'])- expect(logic.values.activeRelationships.map((relationship) => relationship.id)).toEqual(['rel-1'])- expect(logic.values.relationships?.map((relationship) => relationship.id)).toEqual(['rel-1', 'rel-2'])+ expect(logic.values.activeRelationships.map((relationship) => relationship.id)).toEqual(['rel-1', 'rel-3'])+ expect(logic.values.relationships?.map((relationship) => relationship.id)).toEqual(['rel-1', 'rel-2', 'rel-3'])+ })++ it('shows current assignments on top (newest first) and narrows by definition', async () => {+ await expectLogic(logic).toDispatchActions(['loadRelationshipsSuccess'])+ expect(logic.values.displayedRelationships.map((relationship) => relationship.id)).toEqual([+ 'rel-3',+ 'rel-1',+ 'rel-2',+ ])++ logic.actions.setDefinitionFilter(CSM.id)+ expect(logic.values.displayedRelationships.map((relationship) => relationship.id)).toEqual(['rel-1', 'rel-2'])+ expect(logic.values.definitionFilterOptions.map((definition) => definition.name)).toEqual([+ 'Account executive',+ 'CSM',+ ])+ })++ it('assigning posts the definition and user, then reloads the timeline', async () => {+ let postedBody: Record<string, unknown> | null = null+ useMocks({+ post: {+ [RELATIONSHIPS_URL]: async ({ request }) => {+ postedBody = (await request.json()) as Record<string, unknown>+ return [+ 201,+ buildRelationship({ id: 'rel-new', definition: AE, user: { id: 7, email: '[email protected]' } }),+ ]+ },+ },+ })++ logic.actions.assignRelationship(AE, { id: 7 } as UserBasicType)+ await expectLogic(logic).toDispatchActions([+ 'relationshipSaveStarted',+ 'loadRelationships',+ 'relationshipSaveFinished',+ ])+ expect(postedBody).toEqual({ definition: AE.id, user: 7 })})})diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.tsindex 91c63a97016f..7b236d81e25b 100644--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts@@ -1,25 +1,56 @@-import { afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { teamLogic } from 'scenes/teamLogic'-import { accountsRelationshipsList } from 'products/customer_analytics/frontend/generated/api'-import type { AccountRelationshipApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import type { UserBasicType } from '~/types'+import {+ accountsRelationshipsCreate,+ accountsRelationshipsEndCreate,+ accountsRelationshipsList,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountRelationshipApi,+ AccountRelationshipDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { ACCOUNTS_HOGQL_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'import type { accountRelationshipsLogicType } from './accountRelationshipsLogicType'+import { accountsColumnConfigLogic, ROLE_KEY_BY_NAME } from './accountsColumnConfigLogic'+import { AccountsEvents } from './constants'export interface AccountRelationshipsLogicProps {accountId: string}+// Assignments also render as list columns.+function refreshAccountsList(): void {+ dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')+ dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')+}+export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountRelationshipsLogic', key]),props({} as AccountRelationshipsLogicProps),key((props) => props.accountId),connect(() => ({- values: [teamLogic, ['currentTeamId']],+ values: [teamLogic, ['currentTeamId'], accountsColumnConfigLogic, ['relationshipDefinitions']],})),+ actions({+ assignRelationship: (definition: AccountRelationshipDefinitionApi, user: UserBasicType) => ({+ definition,+ user,+ }),+ endRelationship: (relationship: AccountRelationshipApi) => ({ relationship }),+ setDefinitionFilter: (definitionId: string | null) => ({ definitionId }),+ setAssignDefinitionId: (definitionId: string | null) => ({ definitionId }),+ relationshipSaveStarted: true,+ relationshipSaveFinished: true,+ }),loaders(({ props, values }) => ({relationships: [null as AccountRelationshipApi[] | null,@@ -33,18 +64,115 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([},],})),+ reducers({+ definitionFilter: [+ null as string | null,+ {+ setDefinitionFilter: (_, { definitionId }) => definitionId,+ },+ ],+ assignDefinitionId: [+ null as string | null,+ {+ setAssignDefinitionId: (_, { definitionId }) => definitionId,+ },+ ],+ relationshipSaving: [+ false,+ {+ relationshipSaveStarted: () => true,+ relationshipSaveFinished: () => false,+ },+ ],+ }),selectors({activeRelationships: [(s) => [s.relationships],(relationships): AccountRelationshipApi[] =>(relationships ?? []).filter((relationship) => !relationship.ended_at),],+ displayedRelationships: [+ (s) => [s.relationships, s.definitionFilter],+ (relationships, definitionFilter): AccountRelationshipApi[] =>+ (relationships ?? [])+ .filter((relationship) => !definitionFilter || relationship.definition.id === definitionFilter)+ .sort(+ (a, b) =>+ Number(!!a.ended_at) - Number(!!b.ended_at) || b.started_at.localeCompare(a.started_at)+ ),+ ],+ assignDefinition: [+ (s) => [s.assignDefinitionId, s.relationshipDefinitions],+ (assignDefinitionId, relationshipDefinitions): AccountRelationshipDefinitionApi | null =>+ relationshipDefinitions.find((definition) => definition.id === assignDefinitionId) ?? null,+ ],+ // Limited to definitions in this account's timeline — any other filter value+ // would just show an empty table.+ definitionFilterOptions: [+ (s) => [s.relationships],+ (relationships): AccountRelationshipDefinitionApi[] => {+ const byId = new Map<string, AccountRelationshipDefinitionApi>()+ for (const relationship of relationships ?? []) {+ byId.set(relationship.definition.id, relationship.definition)+ }+ return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name))+ },+ ],}),- listeners(() => ({+ listeners(({ actions, props, values }) => ({loadRelationshipsFailure: ({ error }) => {// No toast: `relationships === null` renders the table's failure empty state.posthog.captureException(error, { scope: 'accountRelationshipsLogic.loadRelationships' })},+ assignRelationship: async ({ definition, user }) => {+ if (values.relationshipSaving) {+ return+ }+ actions.relationshipSaveStarted()+ try {+ // Assigning a single-holder relationship ends the current holder server-side.+ await accountsRelationshipsCreate(String(values.currentTeamId), props.accountId, {+ definition: definition.id,+ user: user.id,+ })+ posthog.capture(AccountsEvents.RoleAssigned, {+ role: ROLE_KEY_BY_NAME[definition.name] ?? definition.name,+ is_assigned: true,+ assigned_user_id: user.id,+ source: 'relationships_tab',+ })+ actions.setAssignDefinitionId(null)+ actions.loadRelationships()+ refreshAccountsList()+ } catch (error) {+ posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.assignRelationship' })+ lemonToast.error(`Failed to assign ${definition.name}`)+ } finally {+ actions.relationshipSaveFinished()+ }+ },+ endRelationship: async ({ relationship }) => {+ if (values.relationshipSaving) {+ return+ }+ actions.relationshipSaveStarted()+ try {+ await accountsRelationshipsEndCreate(String(values.currentTeamId), props.accountId, relationship.id)+ posthog.capture(AccountsEvents.RoleAssigned, {+ role: ROLE_KEY_BY_NAME[relationship.definition.name] ?? relationship.definition.name,+ is_assigned: false,+ assigned_user_id: null,+ source: 'relationships_tab',+ })+ actions.loadRelationships()+ refreshAccountsList()+ } catch (error) {+ posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.endRelationship' })+ lemonToast.error(`Failed to end ${relationship.definition.name}`)+ } finally {+ actions.relationshipSaveFinished()+ }+ },})),afterMount(({ actions }) => {actions.loadRelationships()diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.tsindex d1d4f5726d4d..1bf01c82d2b6 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts@@ -1,8 +1,17 @@import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'-import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import type {+ AccountRelationshipDefinitionApi,+ CustomPropertyDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'-import { buildAccountColumnGroups, customPropertyAlias } from './accountsColumnConfigLogic'+import {+ buildAccountColumnGroups,+ customPropertyAlias,+ relationshipAlias,+ roleKeyToDefinitionMap,+ translateSelectColumns,+} from './accountsColumnConfigLogic'function definition(id: string,@@ -24,7 +33,19 @@ function definition(}}-describe('buildAccountColumnGroups custom properties', () => {+const relationshipDefinition = (+ id: string,+ name: string,+ overrides: Partial<AccountRelationshipDefinitionApi> = {}+): AccountRelationshipDefinitionApi => ({+ id,+ name,+ description: null,+ is_single_holder: true,+ ...overrides,+})++describe('accountsColumnConfigLogic column groups and translation', () => {it('emits a custom_properties group with one option per definition, right after account_properties', () => {const defs = [definition('11111111-2222-3333-4444-555555555555', 'Plan', { display_type: 'currency' }),@@ -68,4 +89,35 @@ describe('buildAccountColumnGroups custom properties', () => {)!expect(extractDisplayLabel(group.options[0].expression)).toBe(customPropertyAlias(id))})++ it('relationships group offers legacy names for seeded definitions and rel_ aliases for others', () => {+ const seeded = relationshipDefinition('11111111-2222-3333-4444-555555555555', 'CSM')+ const custom = relationshipDefinition('66666666-7777-8888-9999-000000000000', 'Onboarding manager')+ const group = buildAccountColumnGroups({}, [], [], [seeded, custom]).find((g) => g.key === 'relationships')!++ expect(group.options).toEqual([+ { name: 'CSM', expression: 'csm' },+ {+ name: 'Onboarding manager',+ expression: `accounts.relationships.values.\`${custom.id}\` AS ${relationshipAlias(custom.id)}`,+ },+ ])+ })++ it('omits the relationships group when the team has no definitions', () => {+ expect(buildAccountColumnGroups({}, [], [], []).map((group) => group.key)).not.toContain('relationships')+ })++ it('translateSelectColumns resolves legacy roles through the lazy join and drops unmatched ones', () => {+ const csm = relationshipDefinition('11111111-2222-3333-4444-555555555555', 'CSM')+ const map = roleKeyToDefinitionMap([+ csm,+ relationshipDefinition('99999999-0000-1111-2222-333333333333', 'Renamed'),+ ])++ expect(translateSelectColumns(['name', 'csm', 'account_owner'], map)).toEqual([+ 'name',+ `accounts.relationships.values.\`${csm.id}\` AS csm`,+ ])+ })})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.tsindex 1c6411f04c95..d3f96d472773 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts@@ -1,4 +1,4 @@-import { actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { objectsEqual } from 'lib/utils/objects'@@ -10,8 +10,14 @@ import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'import { DatabaseSchemaField, DatabaseSchemaTable } from '~/queries/schema/schema-general'import type { DataWarehouseViewLink } from '~/types'-import { customPropertyDefinitionsList } from 'products/customer_analytics/frontend/generated/api'-import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import {+ accountRelationshipDefinitionsList,+ customPropertyDefinitionsList,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountRelationshipDefinitionApi,+ CustomPropertyDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'import type { accountsColumnConfigLogicType } from './accountsColumnConfigLogicType'@@ -20,13 +26,28 @@ import type { accountsColumnConfigLogicType } from './accountsColumnConfigLogicT// 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`).+export const LEGACY_ROLE_COLUMNS = {+ csm: 'CSM',+ account_executive: 'Account executive',+ account_owner: 'Account owner',+} as const++export type AccountRoleKey = keyof typeof LEGACY_ROLE_COLUMNS++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_HOGQL_DEFAULT_SELECT: string[] = [ACCOUNTS_NAME_COLUMN,'accounts.tags.names AS tag_names','accounts.notebooks.count AS notebook_count',- 'csm',- 'account_executive',- 'account_owner',]function ensureNameColumn(columns: string[]): string[] {@@ -60,7 +81,12 @@ export const ACCOUNTS_ACCOUNTS_TABLE_NAME = 'system.accounts'// of which name the backend hands us.const ACCOUNTS_JOIN_SOURCE_TABLE_NAMES = new Set(['accounts', ACCOUNTS_ACCOUNTS_TABLE_NAME])-export type AccountColumnGroupKey = 'account_properties' | 'custom_properties' | 'sql_expression' | `accounts.${string}`+export type AccountColumnGroupKey =+ | 'account_properties'+ | 'custom_properties'+ | 'relationships'+ | 'sql_expression'+ | `accounts.${string}`// 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@@ -69,6 +95,45 @@ export function customPropertyAlias(id: string): string {return `cp_${id.replace(/-/g, '')}`}+export function relationshipAlias(id: string): string {+ return `rel_${id.replace(/-/g, '')}`+}++function relationshipExpression(definition: AccountRelationshipDefinitionApi, alias: string): string {+ return `accounts.relationships.values.\`${definition.id}\` AS ${alias}`+}++export const ROLE_KEY_BY_NAME: Record<string, AccountRoleKey> = Object.fromEntries(+ Object.entries(LEGACY_ROLE_COLUMNS).map(([key, name]) => [name, key as AccountRoleKey])+)++export function roleKeyToDefinitionMap(+ definitions: AccountRelationshipDefinitionApi[]+): Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>> {+ return Object.fromEntries(+ definitions+ .filter((definition) => ROLE_KEY_BY_NAME[definition.name])+ .map((definition) => [ROLE_KEY_BY_NAME[definition.name], definition])+ )+}++// 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.+export function translateSelectColumns(+ columns: string[],+ roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>+): string[] {+ return columns.flatMap((column) => {+ if (!isLegacyRoleColumn(column)) {+ return [column]+ }+ const definition = roleKeyToDefinition[column]+ return definition ? [relationshipExpression(definition, column)] : []+ })+}+export type AccountColumnOption = {name: stringexpression: string@@ -87,6 +152,10 @@ export type AccountColumnGroup = {// 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.+const HIDDEN_JOIN_GROUPS = new Set(['custom_properties', 'relationships'])+// 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([@@ -131,10 +200,21 @@ function customPropertyOptions(definitions: CustomPropertyDefinitionApi[]): Acco}))}+// 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.+function relationshipOptions(definitions: AccountRelationshipDefinitionApi[]): AccountColumnOption[] {+ return definitions.map((definition) => ({+ name: definition.name,+ expression:+ ROLE_KEY_BY_NAME[definition.name] ?? relationshipExpression(definition, relationshipAlias(definition.id)),+ }))+}+export function buildAccountColumnGroups(allTablesMap: Record<string, DatabaseSchemaTable> | null | undefined,warehouseJoins: DataWarehouseViewLink[],- customPropertyDefinitions: CustomPropertyDefinitionApi[] = []+ customPropertyDefinitions: CustomPropertyDefinitionApi[] = [],+ relationshipDefinitions: AccountRelationshipDefinitionApi[] = []): AccountColumnGroup[] {const accountsTable = allTablesMap?.[ACCOUNTS_ACCOUNTS_TABLE_NAME]const directOptions: AccountColumnOption[] = []@@ -155,6 +235,9 @@ export function buildAccountColumnGroups(if (accountsTable) {for (const field of Object.values(accountsTable.fields)) {if (JOIN_FIELD_TYPES.has(field.type)) {+ if (HIDDEN_JOIN_GROUPS.has(field.name)) {+ continue+ }const joinedTable = field.table ? allTablesMap?.[field.table] : undefinedaddJoinGroup(field.name, joinOptionsFromSchema(field, joinedTable))continue@@ -191,8 +274,8 @@ export function buildAccountColumnGroups(addJoinGroup(join.field_name, buildJoinOptions(join.field_name, columnNames, joinedTable))}- // Omit the group entirely when the team has no definitions, so the category dropdown- // doesn't show an empty "Custom properties" entry.+ // 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? [@@ -203,9 +286,20 @@ export function buildAccountColumnGroups(},]: []+ const relationshipGroups: AccountColumnGroup[] =+ relationshipDefinitions.length > 0+ ? [+ {+ key: 'relationships',+ label: 'Relationships',+ options: relationshipOptions(relationshipDefinitions),+ },+ ]+ : []return [{ key: 'account_properties', label: 'Account properties', options: directOptions },+ ...relationshipGroups,...customPropertyGroups,...joinGroups,{ key: 'sql_expression', label: 'SQL expression', options: [], isFreeform: true },@@ -263,6 +357,16 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([hideColumnConfigurator: () => false,},],+ // 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).+ relationshipDefinitionsLoaded: [+ false,+ {+ loadRelationshipDefinitionsSuccess: () => true,+ loadRelationshipDefinitionsFailure: () => true,+ },+ ],}),loaders(({ values }) => ({customPropertyDefinitions: [@@ -274,20 +378,65 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([},},],+ relationshipDefinitions: [+ [] as AccountRelationshipDefinitionApi[],+ {+ loadRelationshipDefinitions: async (): Promise<AccountRelationshipDefinitionApi[]> => {+ const response = await accountRelationshipDefinitionsList(String(values.currentProjectId))+ return response.results+ },+ },+ ],})),selectors({+ // Seeded definitions keep their legacy bare name so existing saved views and+ // shared URLs dedupe against them.+ defaultSelectColumns: [+ (s) => [s.relationshipDefinitions],+ (relationshipDefinitions: AccountRelationshipDefinitionApi[]): string[] => [+ ...ACCOUNTS_HOGQL_DEFAULT_SELECT,+ ...relationshipDefinitions.map(+ (definition) =>+ ROLE_KEY_BY_NAME[definition.name] ??+ relationshipExpression(definition, relationshipAlias(definition.id))+ ),+ ],+ ],+ roleKeyToDefinition: [+ (s) => [s.relationshipDefinitions],+ (+ relationshipDefinitions: AccountRelationshipDefinitionApi[]+ ): 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],+ (+ selectColumns: string[],+ roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>+ ): string[] => translateSelectColumns(selectColumns, roleKeyToDefinition),+ ],visibleColumnNames: [- (s) => [s.selectColumns],- (selectColumns: string[]): string[] => selectColumns.map((c) => extractDisplayLabel(c)),+ (s) => [s.querySelectColumns],+ (querySelectColumns: string[]): string[] => querySelectColumns.map((c) => extractDisplayLabel(c)),],accountsColumnGroups: [- (s) => [s.allTablesMap, s.warehouseJoins, s.customPropertyDefinitions],+ (s) => [s.allTablesMap, s.warehouseJoins, s.customPropertyDefinitions, s.relationshipDefinitions],(allTablesMap: Record<string, DatabaseSchemaTable>,warehouseJoins: DataWarehouseViewLink[],- customPropertyDefinitions: CustomPropertyDefinitionApi[]+ customPropertyDefinitions: CustomPropertyDefinitionApi[],+ relationshipDefinitions: AccountRelationshipDefinitionApi[]): AccountColumnGroup[] =>- buildAccountColumnGroups(allTablesMap, warehouseJoins, customPropertyDefinitions),+ buildAccountColumnGroups(+ allTablesMap,+ warehouseJoins,+ customPropertyDefinitions,+ relationshipDefinitions+ ),],aliasToDefinition: [(s) => [s.customPropertyDefinitions],@@ -296,7 +445,39 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([customPropertyDefinitions.map((definition) => [customPropertyAlias(definition.id), definition])),],+ // 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],+ (+ relationshipDefinitions: AccountRelationshipDefinitionApi[],+ roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>+ ): Record<string, AccountRelationshipDefinitionApi> => ({+ ...Object.fromEntries(+ relationshipDefinitions.map((definition) => [relationshipAlias(definition.id), definition])+ ),+ ...roleKeyToDefinition,+ }),+ ],}),+ listeners(({ actions, values, selectors }) => ({+ // Customized columns (user edits, saved view, shared URL) no longer equal the+ // default they diverged from, so only still-default columns get upgraded.+ loadRelationshipDefinitionsSuccess: (_, __, ___, previousState) => {+ const previousDefault = selectors.defaultSelectColumns(previousState)+ if (+ objectsEqual(values.selectColumns, previousDefault) &&+ !objectsEqual(values.defaultSelectColumns, values.selectColumns)+ ) {+ actions.setSelectColumns(values.defaultSelectColumns)+ }+ },+ resetColumns: () => {+ if (!objectsEqual(values.selectColumns, values.defaultSelectColumns)) {+ actions.setSelectColumns(values.defaultSelectColumns)+ }+ },+ })),afterMount(({ actions, values }) => {// Lazily fetch the database schema only if it isn't already in flight / loaded.// databaseTableListLogic dedupes concurrent calls internally.@@ -304,5 +485,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([actions.loadDatabase()}actions.loadCustomPropertyDefinitions()+ actions.loadRelationshipDefinitions()}),])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex b1ef77f793ce..6fa779ca88e5 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -11,17 +11,23 @@ import { initKeaTests } from '~/test/init'import type { UserBasicType, UserType } from '~/types'import {- accountsPartialUpdate,- accountsRetrieve,+ accountRelationshipDefinitionsList,+ accountsRelationshipsCreate,+ accountsRelationshipsEndCreate,+ accountsRelationshipsList,customPropertyDefinitionsList,} from 'products/customer_analytics/frontend/generated/api'-import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import type {+ AccountRelationshipApi,+ AccountRelationshipDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import {ACCOUNTS_HOGQL_DEFAULT_SELECT,ACCOUNTS_NAME_COLUMN,accountsColumnConfigLogic,+ relationshipAlias,} from './accountsColumnConfigLogic'import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'import { accountsLogic, savingRoleKey } from './accountsLogic'@@ -31,34 +37,40 @@ import { accountsLogic, savingRoleKey } from './accountsLogic'const orderByOf = (source: unknown): AccountsQuery['orderBy'] => (source as AccountsQuery).orderByjest.mock('products/customer_analytics/frontend/generated/api', () => ({- // Keep the real module for everything else — connected logics (e.g. column config's- // customPropertyDefinitionsList) call other generated functions on mount, and an- // absent export makes their loaders throw on every test.+ // Keep the real module for everything else — connected logics call other generated+ // functions on mount, and an absent export makes their loaders throw on every test....jest.requireActual('products/customer_analytics/frontend/generated/api'),- accountsRetrieve: jest.fn(),- accountsPartialUpdate: jest.fn(),+ accountRelationshipDefinitionsList: jest.fn(),customPropertyDefinitionsList: jest.fn(),+ accountsRelationshipsCreate: jest.fn(),+ accountsRelationshipsEndCreate: jest.fn(),+ accountsRelationshipsList: jest.fn(),}))-const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>-const mockAccountsPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>-const mockCustomPropertyDefinitionsList = customPropertyDefinitionsList as jest.MockedFunction<+const mockDefinitionsList = accountRelationshipDefinitionsList as jest.MockedFunction<+ typeof accountRelationshipDefinitionsList+>+const mockCustomPropertiesList = customPropertyDefinitionsList as jest.MockedFunction<typeof customPropertyDefinitionsList>--const buildAccount = (overrides: Partial<AccountApi> = {}): AccountApi => ({- id: 'acc-1',- name: 'Acme',- external_id: 'ext-1',- properties: {- csm: { id: 1, email: '[email protected]' },- stripe_customer_id: 'cus_123',- },- tags: [],- notebooks: [],- created_at: '2026-01-01T00:00:00Z',- created_by: null,- updated_at: '2026-01-01T00:00:00Z',+const mockRelationshipsCreate = accountsRelationshipsCreate as jest.MockedFunction<typeof accountsRelationshipsCreate>+const mockRelationshipsEnd = accountsRelationshipsEndCreate as jest.MockedFunction<+ typeof accountsRelationshipsEndCreate+>+const mockRelationshipsList = accountsRelationshipsList as jest.MockedFunction<typeof accountsRelationshipsList>++const DEFINITIONS: AccountRelationshipDefinitionApi[] = [+ { id: 'def-csm', name: 'CSM', description: null, is_single_holder: true },+ { id: 'def-ae', name: 'Account executive', description: null, is_single_holder: true },+ { id: 'def-owner', name: 'Account owner', description: null, is_single_holder: true },+]++const buildRelationship = (overrides: Partial<AccountRelationshipApi> = {}): AccountRelationshipApi => ({+ id: 'rel-1',+ definition: DEFINITIONS[0],+ user: { id: 42, email: '[email protected]' },+ started_at: '2026-01-01T00:00:00Z',+ ended_at: null,...overrides,})@@ -75,16 +87,18 @@ const buildUser = (overrides: Partial<UserBasicType> = {}): UserBasicType =>describe('accountsLogic', () => {let logic: ReturnType<typeof accountsLogic.build>- beforeEach(() => {+ beforeEach(async () => {initKeaTests()jest.resetAllMocks()- // accountsColumnConfigLogic (connected) loads custom property definitions on mount.- mockCustomPropertyDefinitionsList.mockResolvedValue({ count: 0, results: [] })// 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()+ mockDefinitionsList.mockResolvedValue({ count: DEFINITIONS.length, results: DEFINITIONS })+ mockCustomPropertiesList.mockResolvedValue({ count: 0, results: [] })logic = accountsLogic()logic.mount()+ // Legacy role columns only resolve into the query once definitions load.+ await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()})afterEach(() => {@@ -116,6 +130,23 @@ describe('accountsLogic', () => {expect(logic.values.searchQuery).toBe('')})+ it('withholds the list and metrics queries until relationship definitions settle', async () => {+ logic.unmount()+ let resolveDefinitions: (value: { count: number; results: AccountRelationshipDefinitionApi[] }) => void+ mockDefinitionsList.mockReturnValue(new Promise((resolve) => (resolveDefinitions = resolve)))+ logic = accountsLogic()+ logic.mount()++ expect(logic.values.accountsQuerySource).toBeNull()+ expect(logic.values.metricsQuery).toBeNull()++ resolveDefinitions!({ count: DEFINITIONS.length, results: DEFINITIONS })+ await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()++ expect(logic.values.accountsQuerySource).toEqual(logic.values.hogqlQuery.source)+ expect(logic.values.metricsQuery).not.toBeNull()+ })+it('keeps the overview tile metrics off the list query so it loads independently', () => {const source = logic.values.hogqlQuery.source as AccountsQueryexpect(source.metrics).toBeUndefined()@@ -322,23 +353,7 @@ describe('accountsLogic', () => {logic.actions.toggleSort('notebook_count') // desclogic.actions.toggleSort('csm')expect(logic.values.sortOrder).toEqual({ column: 'csm', direction: 'asc' })- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['tupleElement(csm, 2)'])- })-- it('csm desc produces tupleElement(csm, 2) DESC', () => {- logic.actions.toggleSort('csm')- logic.actions.toggleSort('csm')- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['tupleElement(csm, 2) DESC'])- })-- it('account_executive sort uses the tupleElement expression', () => {- logic.actions.toggleSort('account_executive')- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['tupleElement(account_executive, 2)'])- })-- it('account_owner sort uses the tupleElement expression', () => {- logic.actions.toggleSort('account_owner')- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['tupleElement(account_owner, 2)'])+ expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['csm'])})it('arbitrary column sorts by its alias directly', () => {@@ -347,19 +362,72 @@ describe('accountsLogic', () => {logic.actions.toggleSort('name')expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['name DESC'])})++ it('skips the orderBy when the sorted role column has no matching definition', () => {+ logic.actions.toggleSort('csm')+ accountsColumnConfigLogic.findMounted()?.actions.loadRelationshipDefinitionsSuccess([])+ expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()+ })})describe('selectColumns', () => {- it('starts with the default select and includes the mandatory name column', () => {+ it('defaults to the base columns plus one column per definition, name column included', () => {const config = accountsColumnConfigLogic.findMounted()- expect(config?.values.selectColumns).toEqual(ACCOUNTS_HOGQL_DEFAULT_SELECT)+ expect(config?.values.selectColumns).toEqual([+ ...ACCOUNTS_HOGQL_DEFAULT_SELECT,+ 'csm',+ 'account_executive',+ 'account_owner',+ ])expect(config?.values.selectColumns).toContain(ACCOUNTS_NAME_COLUMN)})- it('hogqlQuery.source.select equals selectColumns verbatim — no pinned aliases', () => {- const config = accountsColumnConfigLogic.findMounted()+ it('translates legacy role columns through the relationships lazy join in the query select', () => {const source = logic.values.hogqlQuery.source as AccountsQuery- expect(source.select).toEqual(config?.values.selectColumns)+ expect(source.select).toEqual([+ ACCOUNTS_NAME_COLUMN,+ 'accounts.tags.names AS tag_names',+ 'accounts.notebooks.count AS notebook_count',+ 'accounts.relationships.values.`def-csm` AS csm',+ 'accounts.relationships.values.`def-ae` AS account_executive',+ 'accounts.relationships.values.`def-owner` AS account_owner',+ ])+ })++ it('drops legacy role columns from the query when no matching definition exists', () => {+ accountsColumnConfigLogic.findMounted()?.actions.loadRelationshipDefinitionsSuccess([])+ const source = logic.values.hogqlQuery.source as AccountsQuery+ expect(source.select).toEqual([+ ACCOUNTS_NAME_COLUMN,+ 'accounts.tags.names AS tag_names',+ 'accounts.notebooks.count AS notebook_count',+ ])+ expect(logic.values.visibleColumnNames).toEqual([ACCOUNTS_NAME_COLUMN, 'tag_names', 'notebook_count'])+ })++ it('materializes pristine defaults into one column per definition once definitions load', () => {+ const config = accountsColumnConfigLogic.findMounted()!+ config.actions.loadRelationshipDefinitionsSuccess([+ ...DEFINITIONS,+ { id: 'def-os', name: 'Onboarding specialist', description: null, is_single_holder: true },+ ])+ expect(config.values.selectColumns).toEqual([+ ...ACCOUNTS_HOGQL_DEFAULT_SELECT,+ 'csm',+ 'account_executive',+ 'account_owner',+ `accounts.relationships.values.\`def-os\` AS ${relationshipAlias('def-os')}`,+ ])+ })++ it('leaves customized columns alone when definitions load', () => {+ const config = accountsColumnConfigLogic.findMounted()!+ config.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])+ config.actions.loadRelationshipDefinitionsSuccess([+ ...DEFINITIONS,+ { id: 'def-os', name: 'Onboarding specialist', description: null, is_single_holder: true },+ ])+ expect(config.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm'])})it('refuses to remove the name column via unselectColumn', () => {@@ -503,57 +571,43 @@ describe('accountsLogic', () => {})describe('updateAccountRole', () => {- const existingAccount = buildAccount()-- beforeEach(() => {- mockAccountsRetrieve.mockResolvedValue(existingAccount)- })-- it('PATCHes the merged properties payload with the new assignment', async () => {+ it('assigns via the relationships API and masks the cell with an override', async () => {const user = buildUser()- const updated = buildAccount({- properties: {- csm: { id: user.id, email: user.email },- stripe_customer_id: 'cus_123',- },- })- mockAccountsPartialUpdate.mockResolvedValue(updated)+ mockRelationshipsCreate.mockResolvedValue(buildRelationship())logic.actions.updateAccountRole('acc-1', 'csm', user)await expectLogic(logic).toFinishAllListeners()- expect(mockAccountsRetrieve).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1')- expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {- properties: {- csm: { id: user.id, email: user.email },- stripe_customer_id: 'cus_123',- },+ expect(mockRelationshipsCreate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {+ definition: 'def-csm',+ user: user.id,})- expect(logic.values.accountOverrides['acc-1']).toEqual(updated)+ expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', 'csm')]).toEqual([user.id])})- it('sends null when clearing an assignment', async () => {- mockAccountsPartialUpdate.mockResolvedValue(- buildAccount({ properties: { csm: null, stripe_customer_id: 'cus_123' } })+ it('unassigning ends only the active assignments of that definition', async () => {+ mockRelationshipsList.mockResolvedValue([+ buildRelationship({ id: 'rel-csm', definition: DEFINITIONS[0] }),+ buildRelationship({ id: 'rel-ae', definition: DEFINITIONS[1] }),+ ])+ mockRelationshipsEnd.mockResolvedValue(+ buildRelationship({ id: 'rel-csm', ended_at: '2026-01-02T00:00:00Z' }))logic.actions.updateAccountRole('acc-1', 'csm', null)await expectLogic(logic).toFinishAllListeners()- expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {- properties: {- csm: null,- stripe_customer_id: 'cus_123',- },- })+ expect(mockRelationshipsEnd).toHaveBeenCalledTimes(1)+ expect(mockRelationshipsEnd).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', 'rel-csm')+ expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', 'csm')]).toEqual([])})it('flips savingRoles during the in-flight window', async () => {const key = savingRoleKey('acc-1', 'account_executive')- let resolveUpdate!: (value: AccountApi) => void- mockAccountsPartialUpdate.mockReturnValueOnce(- new Promise<AccountApi>((resolve) => {- resolveUpdate = resolve+ let resolveCreate!: (value: AccountRelationshipApi) => void+ mockRelationshipsCreate.mockReturnValueOnce(+ new Promise<AccountRelationshipApi>((resolve) => {+ resolveCreate = resolve}))@@ -562,7 +616,7 @@ describe('accountsLogic', () => {expect(logic.values.savingRoles[key]).toBe(true)expect(logic.values.isRoleSaving('acc-1', 'account_executive')).toBe(true)- resolveUpdate(buildAccount())+ resolveCreate(buildRelationship())await expectLogic(logic).toFinishAllListeners()expect(logic.values.savingRoles[key]).toBeUndefined()@@ -570,19 +624,19 @@ describe('accountsLogic', () => {})it('leaves overrides untouched on failure', async () => {- mockAccountsPartialUpdate.mockRejectedValueOnce(new Error('boom'))+ mockRelationshipsCreate.mockRejectedValueOnce(new Error('boom'))logic.actions.updateAccountRole('acc-1', 'account_owner', buildUser())await expectLogic(logic).toFinishAllListeners()- expect(logic.values.accountOverrides['acc-1']).toBeUndefined()+ expect(logic.values.relationshipOverrides[savingRoleKey('acc-1', 'account_owner')]).toBeUndefined()expect(logic.values.isRoleSaving('acc-1', 'account_owner')).toBe(false)})it('is a no-op while a save for the same role is already in flight', async () => {- let resolveFirst!: (value: AccountApi) => void- mockAccountsPartialUpdate.mockReturnValueOnce(- new Promise<AccountApi>((resolve) => {+ let resolveFirst!: (value: AccountRelationshipApi) => void+ mockRelationshipsCreate.mockReturnValueOnce(+ new Promise<AccountRelationshipApi>((resolve) => {resolveFirst = resolve}))@@ -592,9 +646,9 @@ describe('accountsLogic', () => {logic.actions.updateAccountRole('acc-1', 'csm', buildUser({ id: 2, email: '[email protected]' }))await new Promise<void>((r) => setTimeout(r, 0))- expect(mockAccountsPartialUpdate).toHaveBeenCalledTimes(1)+ expect(mockRelationshipsCreate).toHaveBeenCalledTimes(1)- resolveFirst(buildAccount())+ resolveFirst(buildRelationship())await expectLogic(logic).toFinishAllListeners()})})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex 95ce9e6eda13..e24c393dda1b 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -5,6 +5,7 @@ import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { isUUIDLike } from 'lib/utils/guards'import { objectsEqual } from 'lib/utils/objects'+import { membersLogic } from 'scenes/organization/membersLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -13,11 +14,11 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { AccountsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'import type { UserBasicType } from '~/types'-import { accountsPartialUpdate, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'-import type {- AccountApi,- PatchedAccountApiProperties,-} from 'products/customer_analytics/frontend/generated/api.schemas'+import {+ accountsRelationshipsCreate,+ accountsRelationshipsEndCreate,+ accountsRelationshipsList,+} from 'products/customer_analytics/frontend/generated/api'import {ACCOUNTS_HOGQL_DATA_NODE_KEY,@@ -25,11 +26,7 @@ import {CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,} from '../../constants'import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'-import {- ACCOUNTS_HOGQL_DEFAULT_SELECT,- ACCOUNTS_NAME_COLUMN,- accountsColumnConfigLogic,-} from './accountsColumnConfigLogic'+import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic, isLegacyRoleColumn } from './accountsColumnConfigLogic'import {ACCOUNT_EXPANSION_TABS,AccountExpansionTab,@@ -72,8 +69,6 @@ function clearSortIfColumnRemoved(values: SortLikeValues, actions: SortLikeActioexport type RoleFilterValue = number[]-export type AccountRoleKey = 'csm' | 'account_executive' | 'account_owner'-export type AccountFilterType = 'tag' | 'unassigned_only' | 'my_accounts' | 'assigned_to'// `column` matches the visible column name (alias-stripped) so any selected@@ -84,22 +79,6 @@ export type AccountSortDirection = 'asc' | 'desc'export type AccountSortOrder = { column: AccountSortableColumn; direction: AccountSortDirection } | null-// Columns that are HogQL `Tuple(id, email)` — sort by the `email` element so the-// order matches what the user sees on screen rather than the opaque user id.-const TUPLE_SORT_COLUMNS = new Set<string>(['csm', 'account_executive', 'account_owner'])--// Resolve the HogQL expression to use in ORDER BY for a sortable column.-// HogQL ORDER BY resolves SELECT aliases by name, so the visible column name-// (which is the alias for aliased entries, or the bare expression otherwise)-// works directly — except for tuple-shaped role columns, where we sort by-// the email element so the visual order matches the rendered cell.-export function deriveAccountsOrderByExpr(column: string): string {- if (TUPLE_SORT_COLUMNS.has(column)) {- return `tupleElement(${column}, 2)`- }- return column-}-interface AccountQueryFilters {searchQuery: stringtagsFilter: string[]@@ -140,13 +119,7 @@ function applyAccountFilters(source: AccountsQuery, filters: AccountQueryFilters}}-const ROLE_LABELS: Record<AccountRoleKey, string> = {- csm: 'CSM',- account_executive: 'Account executive',- account_owner: 'Account owner',-}--export const savingRoleKey = (accountId: string, role: AccountRoleKey): string => `${accountId}:${role}`+export const savingRoleKey = (accountId: string, column: string): string => `${accountId}:${column}`// 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@@ -175,7 +148,14 @@ export const accountsLogic = kea<accountsLogicType>([userLogic,['user'],accountsColumnConfigLogic,- ['selectColumns', 'visibleColumnNames'],+ [+ 'selectColumns',+ 'defaultSelectColumns',+ 'visibleColumnNames',+ 'querySelectColumns',+ 'aliasToRelationshipDefinition',+ 'relationshipDefinitionsLoaded',+ ],accountsOverviewTilesLogic,['metrics as overviewMetrics', 'tileFilter'],customerAnalyticsSceneLogic,@@ -192,6 +172,8 @@ export const accountsLogic = kea<accountsLogicType>([['setMineOnly'],userLogic,['loadUserSuccess'],+ membersLogic,+ ['ensureAllMembersLoaded'],],})),actions({@@ -210,14 +192,18 @@ export const accountsLogic = kea<accountsLogicType>([// The raw filter setters are also fired by URL sync and cross-filter// cascades, so capturing analytics here keeps phantom events out.reportFilterChange: (filterType: AccountFilterType) => ({ filterType }),- updateAccountRole: (accountId: string, role: AccountRoleKey, user: UserBasicType | null) => ({+ updateAccountRole: (accountId: string, column: string, user: UserBasicType | null) => ({accountId,- role,+ column,user,}),- roleUpdateStarted: (accountId: string, role: AccountRoleKey) => ({ accountId, role }),- roleUpdateFinished: (accountId: string, role: AccountRoleKey) => ({ accountId, role }),- replaceAccount: (account: AccountApi) => ({ account }),+ roleUpdateStarted: (accountId: string, column: string) => ({ accountId, column }),+ roleUpdateFinished: (accountId: string, column: string) => ({ accountId, column }),+ setRelationshipOverride: (accountId: string, column: string, userIds: number[]) => ({+ accountId,+ column,+ userIds,+ }),openAccount: (accountId: string, externalId: string | null, name: string, tab: AccountExpansionTab) => ({accountId,externalId,@@ -275,21 +261,26 @@ export const accountsLogic = kea<accountsLogicType>([savingRoles: [{} as Record<string, true>,{- roleUpdateStarted: (state, { accountId, role }) => ({+ roleUpdateStarted: (state, { accountId, column }) => ({...state,- [savingRoleKey(accountId, role)]: true,+ [savingRoleKey(accountId, column)]: true,}),- roleUpdateFinished: (state, { accountId, role }) => {+ roleUpdateFinished: (state, { accountId, column }) => {const next = { ...state }- delete next[savingRoleKey(accountId, role)]+ delete next[savingRoleKey(accountId, column)]return next},},],- accountOverrides: [- {} as Record<string, AccountApi>,+ // Assignments written from the list, keyed `${accountId}:${column}` — masks the+ // stale HogQL cell until the async refetch lands.+ relationshipOverrides: [+ {} as Record<string, number[]>,{- replaceAccount: (state, { account }) => ({ ...state, [account.id]: account }),+ setRelationshipOverride: (state, { accountId, column, userIds }) => ({+ ...state,+ [savingRoleKey(accountId, column)]: userIds,+ }),},],}),@@ -306,8 +297,8 @@ export const accountsLogic = kea<accountsLogicType>([isRoleSaving: [(s) => [s.savingRoles],(savingRoles: Record<string, true>) =>- (accountId: string, role: AccountRoleKey): boolean =>- !!savingRoles[savingRoleKey(accountId, role)],+ (accountId: string, column: string): boolean =>+ !!savingRoles[savingRoleKey(accountId, column)],],activeFilterCount: [(s) => [s.searchQuery, s.tagsFilter, s.allRolesUnassigned, s.assignedToFilter],@@ -329,6 +320,7 @@ export const accountsLogic = kea<accountsLogicType>([s.assignedToFilter,s.sortOrder,s.selectColumns,+ s.defaultSelectColumns,s.tileFilter,],(@@ -338,6 +330,7 @@ export const accountsLogic = kea<accountsLogicType>([assignedToFilter: RoleFilterValue,sortOrder: AccountSortOrder,selectColumns: string[],+ defaultSelectColumns: string[],tileFilter: TileFilter | null): AccountsViewUrlState => {const state: AccountsViewUrlState = {}@@ -357,7 +350,7 @@ export const accountsLogic = kea<accountsLogicType>([if (sortOrder) {state.sort = sortOrder}- if (!objectsEqual(selectColumns, ACCOUNTS_HOGQL_DEFAULT_SELECT)) {+ if (!objectsEqual(selectColumns, defaultSelectColumns)) {state.columns = selectColumns}if (tileFilter) {@@ -375,7 +368,8 @@ export const accountsLogic = kea<accountsLogicType>([s.accountIdFilter,s.tileFilter,s.sortOrder,- s.selectColumns,+ s.querySelectColumns,+ s.visibleColumnNames,],(searchQuery: string,@@ -385,11 +379,12 @@ export const accountsLogic = kea<accountsLogicType>([accountIdFilter: string | null,tileFilter: TileFilter | null,sortOrder: AccountSortOrder,- selectColumns: string[]+ querySelectColumns: string[],+ visibleColumnNames: string[]): DataTableNode => {const source: AccountsQuery = {kind: NodeKind.AccountsQuery,- select: selectColumns,+ select: querySelectColumns,tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_list' },}applyAccountFilters(source, {@@ -400,22 +395,30 @@ export const accountsLogic = kea<accountsLogicType>([accountIdFilter,tileFilter,})- if (sortOrder) {- const expr = deriveAccountsOrderByExpr(sortOrder.column)- source.orderBy = [sortOrder.direction === 'asc' ? expr : `${expr} DESC`]+ // HogQL ORDER BY resolves SELECT aliases by name, so the visible column+ // name works directly. Skip sorts on columns the translation dropped+ // (a legacy role with no matching definition) — the alias wouldn't resolve.+ if (sortOrder && visibleColumnNames.includes(sortOrder.column)) {+ source.orderBy = [sortOrder.direction === 'asc' ? sortOrder.column : `${sortOrder.column} DESC`]}return {kind: NodeKind.DataTableNode,source,full: true,// Suppress DataTable's built-in sort indicator on column- // headers — our `SortableColumnHeader` renders its own (and- // correctly reflects sorts where the orderBy expression- // differs from the column name, e.g. `tupleElement(csm, 2)`).+ // headers — our `SortableColumnHeader` renders its own.allowSorting: true,}},],+ // What the list data node actually runs: null until the relationship+ // definitions settle, so the list fetches once with its final columns+ // instead of fetching base columns and refetching after the upgrade.+ accountsQuerySource: [+ (s) => [s.hogqlQuery, s.relationshipDefinitionsLoaded],+ (hogqlQuery: DataTableNode, relationshipDefinitionsLoaded: boolean): AccountsQuery | null =>+ relationshipDefinitionsLoaded ? (hogqlQuery.source as AccountsQuery) : null,+ ],// The overview-tile aggregations run as their own metrics-only query (no// `select`), keyed to ACCOUNTS_METRICS_DATA_NODE_KEY, so they load// independently of the list rows. Null when there are no tiles — the@@ -430,6 +433,7 @@ export const accountsLogic = kea<accountsLogicType>([s.assignedToFilter,s.accountIdFilter,s.tileFilter,+ s.relationshipDefinitionsLoaded,],(overviewMetrics: string[],@@ -438,9 +442,10 @@ export const accountsLogic = kea<accountsLogicType>([allRolesUnassigned: boolean,assignedToFilter: RoleFilterValue,accountIdFilter: string | null,- tileFilter: TileFilter | null+ tileFilter: TileFilter | null,+ relationshipDefinitionsLoaded: boolean): AccountsQuery | null => {- if (overviewMetrics.length === 0) {+ if (overviewMetrics.length === 0 || !relationshipDefinitionsLoaded) {return null}const source: AccountsQuery = {@@ -569,22 +574,36 @@ export const accountsLogic = kea<accountsLogicType>([dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')},- updateAccountRole: async ({ accountId, role, user }) => {- if (values.isRoleSaving(accountId, role)) {+ updateAccountRole: async ({ accountId, column, user }) => {+ if (values.isRoleSaving(accountId, column)) {+ return+ }+ const definition = values.aliasToRelationshipDefinition[column]+ if (!definition) {return}const projectId = String(values.currentTeamId)- actions.roleUpdateStarted(accountId, role)+ actions.roleUpdateStarted(accountId, column)try {- const current = await accountsRetrieve(projectId, accountId)- const nextProperties: PatchedAccountApiProperties = {- ...current.properties,- [role]: user ? { id: user.id, email: user.email } : null,+ if (user) {+ // Assigning a single-holder relationship ends the current holder server-side.+ await accountsRelationshipsCreate(projectId, accountId, {+ definition: definition.id,+ user: user.id,+ })+ } else {+ const active = await accountsRelationshipsList(projectId, accountId)+ await Promise.all(+ active+ .filter((relationship) => relationship.definition.id === definition.id)+ .map((relationship) =>+ accountsRelationshipsEndCreate(projectId, accountId, relationship.id)+ )+ )}- const updated = await accountsPartialUpdate(projectId, accountId, { properties: nextProperties })- actions.replaceAccount(updated)+ actions.setRelationshipOverride(accountId, column, user ? [user.id] : [])posthog.capture(AccountsEvents.RoleAssigned, {- role,+ role: isLegacyRoleColumn(column) ? column : definition.name,is_assigned: user !== null,assigned_user_id: user?.id ?? null,source: 'list_row',@@ -593,9 +612,9 @@ export const accountsLogic = kea<accountsLogicType>([dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')} catch (error) {posthog.captureException(error as Error, { scope: 'accountsLogic.updateAccountRole' })- lemonToast.error(`Failed to update ${ROLE_LABELS[role]}`)+ lemonToast.error(`Failed to update ${definition.name}`)} finally {- actions.roleUpdateFinished(accountId, role)+ actions.roleUpdateFinished(accountId, column)}},openAccount: ({ accountId, externalId, name, tab }) => {@@ -651,8 +670,11 @@ export const accountsLogic = kea<accountsLogicType>([)},})),- afterMount(() => {+ 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.+ actions.ensureAllMembersLoaded()}),actionToUrl(({ values }) => {// Mirror the full view into the URL hash so the link is shareable.diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.tsindex 76c8684b8a82..4639e06dff37 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts@@ -40,8 +40,8 @@ export function normalizeRoleFilter(value: unknown): RoleFilterValue {}// Sort persists as a single `["<column> <ASC|DESC>"]` entry using the LOGICAL-// column name (e.g. `csm`); `deriveAccountsOrderByExpr` re-derives the tuple-// expression at query-build time.+// column name (e.g. `csm`) — HogQL resolves it against the SELECT alias at+// query-build time.export function sortOrderToOrderBy(sortOrder: AccountSortOrder): string[] {if (!sortOrder) {return []