: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
fix(customer-analytics): sort numeric custom property columns numerically (#72288)
Arthur Moreira de Deus84004f204e53
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex e6b21f79c5ac..5cdb867e23b5 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -58,7 +58,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, accDefault 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`). Sorting a numeric custom property (display type `number`/`currency`/`percent`) casts the (string) JSON value with `toFloatOrNull(...)` in the `orderBy` — see `orderByExpression` in `accountsLogic`, driven by `aliasToDefinition` — so numbers sort by magnitude rather than lexically; non-numeric types sort by the alias directly. The stored sort state (URL hash, saved views) keeps the clean column name; the cast is applied only at query-build time. Numeric custom properties are also selectable in the **overview tiles** sum/avg/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the value in `toFloatOrNull(...)` the same way so aggregation is numeric.Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`), else the backend gets an `orderBy` referencing a missing alias.diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex 6fa779ca88e5..ab00f6c559fa 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -20,6 +20,8 @@ import {import type {AccountRelationshipApi,AccountRelationshipDefinitionApi,+ CustomPropertyDefinitionApi,+ CustomPropertyDisplayTypeEnumApi,} from 'products/customer_analytics/frontend/generated/api.schemas'import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'@@ -27,6 +29,7 @@ import {ACCOUNTS_HOGQL_DEFAULT_SELECT,ACCOUNTS_NAME_COLUMN,accountsColumnConfigLogic,+ customPropertyAlias,relationshipAlias,} from './accountsColumnConfigLogic'import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'@@ -368,6 +371,49 @@ describe('accountsLogic', () => {accountsColumnConfigLogic.findMounted()?.actions.loadRelationshipDefinitionsSuccess([])expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()})++ describe('custom property columns', () => {+ const PROP_ID = '11111111-2222-3333-4444-555555555555'+ const alias = customPropertyAlias(PROP_ID)+ const floatExpr = `toFloatOrNull(accounts.custom_properties.values.\`${PROP_ID}\`)`++ const selectCustomProperty = (displayType: CustomPropertyDisplayTypeEnumApi): void => {+ const config = accountsColumnConfigLogic.findMounted()!+ config.actions.loadCustomPropertyDefinitionsSuccess([+ {+ id: PROP_ID,+ name: 'ARR',+ display_type: displayType,+ is_big_number: false,+ description: null,+ source: null,+ } as CustomPropertyDefinitionApi,+ ])+ config.actions.setSelectColumns([+ ACCOUNTS_NAME_COLUMN,+ `accounts.custom_properties.values.\`${PROP_ID}\` AS ${alias}`,+ ])+ }++ // The value is stored in a JSON string column; without the float cast the+ // backend ORDER BY sorts "55.3" before "5.5" lexically.+ it.each(['number', 'currency', 'percent'] as const)(+ 'sorts a %s column by its value cast to a float',+ (displayType) => {+ selectCustomProperty(displayType)+ logic.actions.toggleSort(alias)+ expect(orderByOf(logic.values.hogqlQuery.source)).toEqual([floatExpr])+ logic.actions.toggleSort(alias) // desc+ expect(orderByOf(logic.values.hogqlQuery.source)).toEqual([`${floatExpr} DESC`])+ }+ )++ it('sorts a non-numeric custom property lexically by its alias', () => {+ selectCustomProperty('text')+ logic.actions.toggleSort(alias)+ expect(orderByOf(logic.values.hogqlQuery.source)).toEqual([alias])+ })+ })})describe('selectColumns', () => {diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex 3c65048ac042..4a73b2aef807 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -27,7 +27,8 @@ import {CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,} from '../../constants'import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'-import type { AccountRelationshipDefinitionApi } from '../../generated/api.schemas'+import type { AccountRelationshipDefinitionApi, CustomPropertyDefinitionApi } from '../../generated/api.schemas'+import { isNumericDisplayType } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic, isLegacyRoleColumn } from './accountsColumnConfigLogic'import {ACCOUNT_EXPANSION_TABS,@@ -68,6 +69,17 @@ function clearSortIfColumnRemoved(values: SortLikeValues, actions: SortLikeActio}}+// Custom property values live in a JSON string column, so a plain `ORDER BY <alias>` sorts+// them lexically ("55.3" before "5.5"). For numeric display types, sort by the value cast to+// a float — mirroring how the overview tiles aggregate these columns via `toFloatOrNull(...)`.+function orderByExpression(column: string, aliasToDefinition: Record<string, CustomPropertyDefinitionApi>): string {+ const definition = aliasToDefinition[column]+ if (definition && isNumericDisplayType(definition.display_type)) {+ return `toFloatOrNull(accounts.custom_properties.values.\`${definition.id}\`)`+ }+ return column+}+export type RoleFilterValue = number[]export type AccountFilterType = 'tag' | 'unassigned_only' | 'my_accounts' | 'assigned_to'@@ -142,6 +154,7 @@ export interface AccountsViewUrlState {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountsLogicValues {+ aliasToDefinition: Record<string, CustomPropertyDefinitionApi> // accountsColumnConfigLogicaliasToRelationshipDefinition: Record<string, AccountRelationshipDefinitionApi> // accountsColumnConfigLogicdefaultSelectColumns: string[] // accountsColumnConfigLogicquerySelectColumns: string[] // accountsColumnConfigLogic@@ -331,7 +344,8 @@ export interface accountsLogicMeta {tileFilter: TileFilter | null,sortOrder: AccountSortOrder,querySelectColumns: string[],- visibleColumnNames: string[]+ visibleColumnNames: string[],+ aliasToDefinition: Record<string, CustomPropertyDefinitionApi>) => DataTableNodeaccountsQuerySource: (hogqlQuery: DataTableNode, relationshipDefinitionsLoaded: boolean) => AccountsQuery | nullmetricsQuery: (@@ -369,6 +383,7 @@ export const accountsLogic = kea<accountsLogicType>(['visibleColumnNames','querySelectColumns','aliasToRelationshipDefinition',+ 'aliasToDefinition','relationshipDefinitionsLoaded',],accountsOverviewTilesLogic,@@ -585,6 +600,7 @@ export const accountsLogic = kea<accountsLogicType>([s.sortOrder,s.querySelectColumns,s.visibleColumnNames,+ s.aliasToDefinition,],(searchQuery: string,@@ -595,7 +611,8 @@ export const accountsLogic = kea<accountsLogicType>([tileFilter: TileFilter | null,sortOrder: AccountSortOrder,querySelectColumns: string[],- visibleColumnNames: string[]+ visibleColumnNames: string[],+ aliasToDefinition: Record<string, CustomPropertyDefinitionApi>): DataTableNode => {const source: AccountsQuery = {kind: NodeKind.AccountsQuery,@@ -614,7 +631,8 @@ export const accountsLogic = kea<accountsLogicType>([// 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`]+ const expr = orderByExpression(sortOrder.column, aliasToDefinition)+ source.orderBy = [sortOrder.direction === 'asc' ? expr : `${expr} DESC`]}return {kind: NodeKind.DataTableNode,