Skip to content

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

refactor(customer-analytics): collapse accounts id/external_id into the name column tuple (#60680)

Arthur Moreira de Deus2440f3695d6f
diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsx
index e60dd09dd072..9e2919302f5f 100644
--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx
@@ -304,12 +304,6 @@ export function DataTable({
const lemonColumns: LemonTableColumn<DataTableRow, any>[] = [
...columnsInLemonTable.map((key, index) => {
- // Result tuples for array-of-arrays responses are positionally
- // aligned with `allColumns` (the unfiltered list from the response
- // / query). When hidden columns precede visible ones, the position
- // in `columnsInLemonTable` (`index`) no longer matches the result
- // tuple, so look up by the column's index in `allColumns` instead.
- const resultIndex = allColumns.indexOf(key)
return {
dataIndex: key as any,
...renderColumnMeta(key, query, context),
@@ -329,7 +323,7 @@ export function DataTable({
return { props: { colSpan: 0 } }
} else if (result) {
const value = sourceFeatures.has(QueryFeature.resultIsArrayOfArrays)
- ? (result as any[])[resultIndex]
+ ? (result as any[])[index]
: (result as Record<string, any>)[key]
return renderColumn(key, value, result, recordIndex, rowCount, query, setQuery, context)
}
@@ -345,7 +339,7 @@ export function DataTable({
return null
}
const value = sourceFeatures.has(QueryFeature.resultIsArrayOfArrays)
- ? (record.result as any[])[resultIndex]
+ ? (record.result as any[])[index]
: (record.result as Record<string, any>)[key]
return <NonIntegratedConversionsCellActions columnName={key} value={value} />
}
diff --git a/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
index d11bd8856bb2..fcc8e7cf17d8 100644
--- a/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
@@ -8,7 +8,9 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.models import User
from posthog.rbac.user_access_control import UserAccessControl
-DEFAULT_COLUMNS = ("id", "name", "external_id", "created_at")
+NAME_COLUMN = "name"
+
+DEFAULT_COLUMNS = (NAME_COLUMN, "created_at")
DEFAULT_ORDER_BY = "created_at DESC"
@@ -35,21 +37,21 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- if self.query.select:
- seen: set[str] = set()
- self.columns: list[str] = []
- self._select_exprs: list[ast.Expr] = []
- for col in self.query.select:
- expr = parse_expr(col)
- column_name = expr.alias if isinstance(expr, ast.Alias) else col
- if column_name in seen:
- continue
- seen.add(column_name)
- self.columns.append(column_name)
- self._select_exprs.append(expr)
- else:
- self.columns = list(DEFAULT_COLUMNS)
- self._select_exprs = [parse_expr(col) for col in self.columns]
+ raw_selects = list(self.query.select) if self.query.select else list(DEFAULT_COLUMNS)
+
+ seen: set[str] = set()
+ self.columns: list[str] = []
+ self._select_exprs: list[ast.Expr] = []
+ for raw in raw_selects:
+ column_name, expr = self._resolve_column(raw)
+ if column_name in seen:
+ continue
+ seen.add(column_name)
+ self.columns.append(column_name)
+ self._select_exprs.append(expr)
+ if NAME_COLUMN not in seen:
+ self.columns.insert(0, NAME_COLUMN)
+ self._select_exprs.insert(0, self._name_tuple_expr())
self.paginator = HogQLHasMorePaginator.from_limit_context(
limit_context=self.limit_context,
@@ -62,6 +64,30 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
"customer_analytics", "viewer"
)
+ def _resolve_column(self, raw: str) -> tuple[str, ast.Expr]:
+ if raw == NAME_COLUMN:
+ return NAME_COLUMN, self._name_tuple_expr()
+ expr = parse_expr(raw)
+ column_name = expr.alias if isinstance(expr, ast.Alias) else raw
+ return column_name, expr
+
+ def _name_tuple_expr(self) -> ast.Expr:
+ # Single cell carries the display name, external_id (for copy
+ # affordance) and id (for row expansion / role updates), so the
+ # frontend doesn't need to pin id and external_id as separate
+ # hidden columns. Mirrors groups_query_runner's `group_name`.
+ return ast.Alias(
+ alias=NAME_COLUMN,
+ expr=ast.Call(
+ name="tuple",
+ args=[
+ ast.Field(chain=["name"]),
+ ast.Field(chain=["external_id"]),
+ ast.Call(name="toString", args=[ast.Field(chain=["id"])]),
+ ],
+ ),
+ )
+
def to_query(self) -> ast.SelectQuery:
where_exprs: list[ast.Expr] = []
@@ -69,7 +95,7 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
pattern = f"%{self.query.search.strip()}%"
where_exprs.append(
parse_expr(
- "name ILIKE {pattern} OR external_id ILIKE {pattern}",
+ "accounts.name ILIKE {pattern} OR accounts.external_id ILIKE {pattern}",
{"pattern": ast.Constant(value=pattern)},
)
)
@@ -144,10 +170,19 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
modifiers=self.modifiers,
)
+ name_index = self.columns.index(NAME_COLUMN)
+ results = [
+ [
+ {"name": cell[0], "external_id": cell[1], "id": cell[2]} if index == name_index else cell
+ for index, cell in enumerate(row)
+ ]
+ for row in self.paginator.results
+ ]
+
return AccountsQueryResponse(
kind="AccountsQuery",
columns=list(self.columns),
- results=self.paginator.results,
+ results=results,
types=[t for _, t in response.types] if response.types else [],
hogql=response.hogql or "",
timings=response.timings,
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
index e32377f1acb4..55a395801b37 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
@@ -31,8 +31,13 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
def _ids(self, **query_kwargs) -> list[str]:
runner, response = self._run_query(**query_kwargs)
- id_index = runner.columns.index("id")
- return [str(row[id_index]) for row in response.results]
+ name_idx = runner.columns.index("name")
+ return [row[name_idx]["id"] for row in response.results]
+
+ def _names(self, **query_kwargs) -> list[str]:
+ runner, response = self._run_query(**query_kwargs)
+ name_idx = runner.columns.index("name")
+ return [row[name_idx]["name"] for row in response.results]
def test_team_isolation(self):
mine_1 = create_account(team_id=self.team.id, name="Mine 1")
@@ -62,9 +67,7 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")
create_account(team_id=self.team.id, name="Globex", external_id="glx-99")
- runner, response = self._run_query(search=search)
- name_idx = runner.columns.index("name")
- self.assertEqual(sorted(r[name_idx] for r in response.results), sorted(expected_names))
+ self.assertEqual(sorted(self._names(search=search)), sorted(expected_names))
def test_blank_search_returns_all(self):
create_account(team_id=self.team.id, name="A")
@@ -327,20 +330,14 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
expected_reverse = list(reversed(ids))
page_one_runner, page_one_response = self._run_query(limit=2, offset=0)
+ name_idx = page_one_runner.columns.index("name")
+ self.assertEqual([row[name_idx]["id"] for row in page_one_response.results], expected_reverse[:2])
self.assertTrue(page_one_response.hasMore)
- id_idx = page_one_runner.columns.index("id")
- self.assertEqual(
- [str(row[id_idx]) for row in page_one_response.results],
- expected_reverse[:2],
- )
page_three_runner, page_three_response = self._run_query(limit=2, offset=4)
+ name_idx = page_three_runner.columns.index("name")
+ self.assertEqual([row[name_idx]["id"] for row in page_three_response.results], expected_reverse[4:])
self.assertFalse(page_three_response.hasMore)
- id_idx = page_three_runner.columns.index("id")
- self.assertEqual(
- [str(row[id_idx]) for row in page_three_response.results],
- expected_reverse[4:],
- )
def test_empty_result_set(self):
create_account(team_id=self.team.id, name="Acme")
@@ -349,10 +346,18 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
self.assertFalse(response.hasMore)
self.assertEqual(response.offset, 0)
- def test_external_id_is_in_default_columns(self):
- create_account(team_id=self.team.id, name="A", external_id="ext-A")
- runner = AccountsQueryRunner(query=AccountsQuery(), team=self.team)
- self.assertIn("external_id", runner.columns)
+ def test_name_column_carries_id_external_id_and_display_name(self):
+ account = create_account(team_id=self.team.id, name="A", external_id="ext-A")
+ runner, response = self._run_query()
+ name_idx = runner.columns.index("name")
+ self.assertEqual(
+ response.results[0][name_idx],
+ {"name": "A", "external_id": "ext-A", "id": str(account.id)},
+ )
+
+ def test_name_column_is_prepended_when_not_in_select(self):
+ runner = AccountsQueryRunner(query=AccountsQuery(select=["external_id"]), team=self.team)
+ self.assertEqual(runner.columns, ["name", "external_id"])
def test_set_tags_on_object_helper_matches(self):
# Mirror existing API test setup that uses set_tags_on_object.
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
index 339b0866603a..4abeef592dab 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
@@ -15,7 +15,12 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'
-import { AccountColumnGroup, AccountColumnGroupKey, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import {
+ ACCOUNTS_NAME_COLUMN,
+ AccountColumnGroup,
+ AccountColumnGroupKey,
+ accountsColumnConfigLogic,
+} from './accountsColumnConfigLogic'
const HOGQL_DOCS_URL = 'https://posthog.com/docs/hogql'
@@ -135,6 +140,9 @@ function SelectedAccountColumn({
}): JSX.Element {
const { setNodeRef, attributes, transform, transition, listeners } = useSortable({ id: column })
const label = extractDisplayLabel(column)
+ // `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_COLUMN
return (
<div
@@ -151,13 +159,20 @@ function SelectedAccountColumn({
{label}
</span>
<div className="flex-1" />
- <Tooltip title="Edit">
- <LemonButton onClick={() => onEdit(column, dataIndex)} size="small">
- <IconPencil data-attr="column-display-item-edit-icon" />
- </LemonButton>
- </Tooltip>
- <Tooltip title="Remove">
- <LemonButton onClick={() => onRemove(column)} status="danger" size="small">
+ {isMandatory ? null : (
+ <Tooltip title="Edit">
+ <LemonButton onClick={() => onEdit(column, dataIndex)} size="small">
+ <IconPencil data-attr="column-display-item-edit-icon" />
+ </LemonButton>
+ </Tooltip>
+ )}
+ <Tooltip title={isMandatory ? 'This column is required' : 'Remove'}>
+ <LemonButton
+ onClick={() => onRemove(column)}
+ status="danger"
+ size="small"
+ disabledReason={isMandatory ? 'This column is required' : undefined}
+ >
<IconX data-attr="column-display-item-remove-icon" />
</LemonButton>
</Tooltip>
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
index d782302e1f58..8f6c3f6db842 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
@@ -15,12 +15,15 @@ import { DataTableNode } from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumn, QueryContextColumnComponent } from '~/queries/types'
import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'
-import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import { AccountsColumnConfigurator } from './AccountsColumnConfigurator'
import { ACCOUNTS_HOGQL_DATA_NODE_KEY, AccountRoleKey, accountsLogic } from './accountsLogic'
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',
@@ -36,37 +39,26 @@ const COLUMN_WIDTHS = {
account_owner: '220px',
} as const
-// Maps logical column names used by the cell renderers to the actual column
-// names in the HogQL response. `id` and `external_id` come back under the
-// `context.columns.X` prefix so DataTable's existing hidden-flag path filters
-// them out of the visible columns — we still need them in the row tuple for
-// the row-expand id and the Account cell's external_id rendering. The pinned
-// columns are always present in the SELECT (see ACCOUNTS_HOGQL_PINNED_SELECT
-// in accountsLogic.ts).
-const COLUMN_KEY_OVERRIDES: Record<string, string> = {
- id: 'context.columns.id',
- external_id: 'context.columns.external_id',
-}
-
function getCellAt(record: unknown, names: string[], column: string): unknown {
if (!Array.isArray(record)) {
return undefined
}
- const index = names.indexOf(COLUMN_KEY_OVERRIDES[column] ?? column)
+ const index = names.indexOf(column)
return index >= 0 ? record[index] : undefined
}
-// Pinned columns prepended to the SELECT in this order — see ACCOUNTS_HOGQL_PINNED_SELECT.
-const PINNED_COLUMN_NAMES = ['context.columns.id', 'context.columns.external_id']
-
-function useColumnNames(): string[] {
+function useGetCell(): (record: unknown, column: string) => unknown {
const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
- return [...PINNED_COLUMN_NAMES, ...visibleColumnNames]
+ return (record, column) => getCellAt(record, visibleColumnNames, column)
}
-function useGetCell(): (record: unknown, column: string) => unknown {
- const names = useColumnNames()
- return (record, column) => getCellAt(record, names, column)
+function getNameCell(record: unknown, visibleColumnNames: string[]): AccountNameCell | undefined {
+ const value = getCellAt(record, visibleColumnNames, ACCOUNTS_NAME_COLUMN)
+ if (!value || typeof value !== 'object') {
+ return undefined
+ }
+ const cell = value as Partial<AccountNameCell>
+ return typeof cell.id === 'string' && typeof cell.name === 'string' ? (cell as AccountNameCell) : undefined
}
function tupleToAssignment(value: unknown): AccountAssignment {
@@ -85,13 +77,14 @@ function tupleToAssignment(value: unknown): AccountAssignment {
}
function NameCell({ record }: { record: unknown }): JSX.Element {
- const getCell = useGetCell()
- const name = String(getCell(record, 'name') ?? '')
- const externalId = getCell(record, 'external_id')
+ const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
+ const cell = getNameCell(record, visibleColumnNames)
+ const name = cell?.name ?? ''
+ const externalId = cell?.external_id ?? ''
return (
<div className="flex flex-col min-w-40">
<span className="font-medium">{name}</span>
- {typeof externalId === 'string' && externalId ? (
+ {externalId ? (
<CopyToClipboardInline
explicitValue={externalId}
iconStyle={{ color: 'var(--color-accent)' }}
@@ -119,9 +112,10 @@ function NotebookCountCell({ record }: { record: unknown }): JSX.Element {
function RoleAssignmentCell({ record, role }: { record: unknown; role: AccountRoleKey }): JSX.Element {
const { isRoleSaving, accountOverrides } = useValues(accountsLogic)
+ const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
const { updateAccountRole } = useActions(accountsLogic)
const getCell = useGetCell()
- const accountId = String(getCell(record, 'id') ?? '')
+ const accountId = getNameCell(record, visibleColumnNames)?.id ?? ''
const overrideProperties = accountId ? accountOverrides[accountId]?.properties : undefined
const overrideRole = overrideProperties != null ? overrideProperties[role] : undefined
const assignment: AccountAssignment =
@@ -161,8 +155,6 @@ function RoleAssignmentCell({ record, role }: { record: unknown; role: AccountRo
)
}
-const HIDDEN_COLUMN: QueryContextColumn = { hidden: true }
-
function SortableColumnHeader({ column, label }: { column: string; label: string }): JSX.Element {
const { sortOrder } = useValues(accountsLogic)
const { toggleSort } = useActions(accountsLogic)
@@ -234,10 +226,7 @@ const KNOWN_COLUMN_TEMPLATES: Record<string, KnownColumnTemplate> = {
function useContextColumns(): Record<string, QueryContextColumn> {
const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
return useMemo(() => {
- const columns: Record<string, QueryContextColumn> = {
- id: HIDDEN_COLUMN,
- external_id: HIDDEN_COLUMN,
- }
+ const columns: Record<string, QueryContextColumn> = {}
for (const key of visibleColumnNames) {
const template = KNOWN_COLUMN_TEMPLATES[key]
const label = template?.label ?? key
@@ -251,14 +240,18 @@ function useContextColumns(): Record<string, QueryContextColumn> {
}, [visibleColumnNames])
}
-const EXPANDABLE: QueryContext<DataTableNode>['expandable'] = {
- noIndent: true,
- // id is the first pinned column in ACCOUNTS_HOGQL_PINNED_SELECT, so it's
- // always at position 0 in the row tuple regardless of user column choices.
- expandedRowRender: ({ result }) => {
- const accountId = Array.isArray(result) ? String(result[0] ?? '') : ''
- return accountId ? <AccountNotebooksExpansion accountId={accountId} /> : null
- },
+function useExpandable(): QueryContext<DataTableNode>['expandable'] {
+ const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
+ return useMemo(
+ () => ({
+ noIndent: true,
+ expandedRowRender: ({ result }) => {
+ const accountId = getNameCell(result, visibleColumnNames)?.id
+ return accountId ? <AccountNotebooksExpansion accountId={accountId} /> : null
+ },
+ }),
+ [visibleColumnNames]
+ )
}
const SKELETON_ROW_COUNT = 5
@@ -320,6 +313,7 @@ function AccountsHogQLSkeleton(): JSX.Element {
function AccountsHogQLDataTable({ query }: { query: DataTableNode }): JSX.Element {
const { responseLoading, response } = useValues(dataNodeLogic)
const contextColumns = useContextColumns()
+ const expandable = useExpandable()
if (responseLoading && !response) {
return <AccountsHogQLSkeleton />
}
@@ -332,7 +326,7 @@ function AccountsHogQLDataTable({ query }: { query: DataTableNode }): JSX.Elemen
}}
context={{
columns: contextColumns,
- expandable: EXPANDABLE,
+ expandable,
dataNodeLogicKey: ACCOUNTS_HOGQL_DATA_NODE_KEY,
}}
readOnly
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index dc82b9097af6..7d4986577e8b 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -15,18 +15,12 @@ import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joins
import type { accountsColumnConfigLogicType } from './accountsColumnConfigLogicType'
-// Columns aliased into the `context.columns.X` namespace are always included in the
-// SELECT — the table cell renderers depend on them for row identity (id) and the
-// external_id display in the Account cell, but they're hidden from the visible
-// columns via QueryContextColumn.hidden = true.
-export const ACCOUNTS_HOGQL_PINNED_SELECT: string[] = [
- 'id AS `context.columns.id`',
- 'external_id AS `context.columns.external_id`',
-]
+// Mandatory — the backend emits it as `tuple(name, external_id, id)` so the
+// row identity (id) and copy-able external_id ride along with the display name.
+export const ACCOUNTS_NAME_COLUMN = 'name'
-// User-configurable defaults — the shape the table ships with out of the box.
export const ACCOUNTS_HOGQL_DEFAULT_SELECT: string[] = [
- 'name',
+ ACCOUNTS_NAME_COLUMN,
'accounts.tags.names AS tag_names',
'accounts.notebooks.count AS notebook_count',
'csm',
@@ -34,6 +28,10 @@ export const ACCOUNTS_HOGQL_DEFAULT_SELECT: string[] = [
'account_owner',
]
+function ensureNameColumn(columns: string[]): string[] {
+ return columns.includes(ACCOUNTS_NAME_COLUMN) ? columns : [ACCOUNTS_NAME_COLUMN, ...columns]
+}
+
export const ACCOUNTS_COLUMN_CONFIG_KEY = 'customer_analytics_accounts_columns'
// `allTablesMap` keys system tables by their fully qualified name (e.g.
@@ -193,9 +191,10 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
selectColumns: [
[...ACCOUNTS_HOGQL_DEFAULT_SELECT],
{
- setSelectColumns: (_, { columns }) => columns,
+ setSelectColumns: (_, { columns }) => ensureNameColumn(columns),
selectColumn: (state, { column }) => (state.includes(column) ? state : [...state, column]),
- unselectColumn: (state, { column }) => state.filter((c) => c !== column),
+ unselectColumn: (state, { column }) =>
+ column === ACCOUNTS_NAME_COLUMN ? state : state.filter((c) => c !== column),
moveColumn: (state, { oldIndex, newIndex }) => {
if (oldIndex === newIndex || oldIndex < 0 || oldIndex >= state.length) {
return state
@@ -207,7 +206,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
},
resetColumns: () => [...ACCOUNTS_HOGQL_DEFAULT_SELECT],
loadSavedColumnConfigurationSuccess: (state, { savedColumnConfiguration }) =>
- savedColumnConfiguration ? savedColumnConfiguration.columns : state,
+ savedColumnConfiguration ? ensureNameColumn(savedColumnConfiguration.columns) : state,
},
],
columnConfiguratorVisible: [
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 8b2e1ccd4a3a..526cb415d7a9 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -9,6 +9,11 @@ import type { UserBasicType } from '~/types'
import { accountsList, accountsPartialUpdate } from 'products/customer_analytics/frontend/generated/api'
import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import {
+ ACCOUNTS_HOGQL_DEFAULT_SELECT,
+ ACCOUNTS_NAME_COLUMN,
+ accountsColumnConfigLogic,
+} from './accountsColumnConfigLogic'
import { ACCOUNTS_PAGE_SIZE, accountsLogic, savingRoleKey } from './accountsLogic'
// `hogqlQuery.source` is typed as the full DataTableNode source union; this logic
@@ -244,6 +249,38 @@ describe('accountsLogic', () => {
})
})
+ describe('selectColumns', () => {
+ it('starts with the default select and includes the mandatory name column', () => {
+ const config = accountsColumnConfigLogic.findMounted()
+ expect(config?.values.selectColumns).toEqual(ACCOUNTS_HOGQL_DEFAULT_SELECT)
+ expect(config?.values.selectColumns).toContain(ACCOUNTS_NAME_COLUMN)
+ })
+
+ it('hogqlQuery.source.select equals selectColumns verbatim — no pinned aliases', () => {
+ const config = accountsColumnConfigLogic.findMounted()
+ const source = logic.values.hogqlQuery.source as AccountsQuery
+ expect(source.select).toEqual(config?.values.selectColumns)
+ })
+
+ it('refuses to remove the name column via unselectColumn', () => {
+ const config = accountsColumnConfigLogic.findMounted()
+ config?.actions.unselectColumn(ACCOUNTS_NAME_COLUMN)
+ expect(config?.values.selectColumns).toContain(ACCOUNTS_NAME_COLUMN)
+ })
+
+ it('re-inserts the name column when setSelectColumns omits it', () => {
+ const config = accountsColumnConfigLogic.findMounted()
+ config?.actions.setSelectColumns(['csm', 'account_executive'])
+ expect(config?.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm', 'account_executive'])
+ })
+
+ it('keeps user ordering when setSelectColumns already contains name', () => {
+ const config = accountsColumnConfigLogic.findMounted()
+ config?.actions.setSelectColumns(['csm', ACCOUNTS_NAME_COLUMN, 'account_executive'])
+ expect(config?.values.selectColumns).toEqual(['csm', ACCOUNTS_NAME_COLUMN, 'account_executive'])
+ })
+ })
+
it('setCurrentPage updates the offset in the next request', async () => {
logic.actions.setCurrentPage(3)
await expectLogic(logic).toFinishAllListeners()
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index c4af1a4dc129..2b9240b94a40 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -16,7 +16,7 @@ import type {
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
-import { ACCOUNTS_HOGQL_PINNED_SELECT, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import type { accountsLogicType } from './accountsLogicType'
export const ACCOUNTS_PAGE_SIZE = 20
@@ -280,7 +280,7 @@ export const accountsLogic = kea<accountsLogicType>([
): DataTableNode => {
const source: AccountsQuery = {
kind: NodeKind.AccountsQuery,
- select: [...ACCOUNTS_HOGQL_PINNED_SELECT, ...selectColumns],
+ select: selectColumns,
tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_list' },
}
const trimmed = searchQuery.trim()