: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): add custom property filters to the accounts list (#69506)
Arthur Moreira de Deusf7135123bc6e
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 5cdb867e23b5..ce6d6008bed7 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -21,7 +21,8 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc└─ 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) /-│ "my accounts" on the left, AccountsOverviewTilesButton + AccountsColumnConfigurator on the right+│ "my accounts" / custom-property PropertyFilters on the left,+│ AccountsOverviewTilesButton + AccountsColumnConfigurator on the right├── AccountsOverviewTiles metric tiles across the filtered set└── AccountsHogQLTable the DataTable; per-column renderers; controlled row expansion└── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities)@@ -37,9 +38,9 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc| Logic | Owns || ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `accountsLogic` | The hub. Search (debounced), tag and assigned-to/unassigned filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property 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). |+| `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), and the custom-property definitions: it loads them, seeds `propertyDefinitionsModel` (so the filter UI resolves per-type operator sets), and exposes `customPropertyTaxonomicOptions` / `customPropertyDefinitionsById`. || `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). |@@ -60,6 +61,14 @@ Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship co**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.+**Custom property filters** let users filter the list by custom properties, with the same look and feel as property filters elsewhere (the persons list): `AccountsTabFilters` renders the shared `PropertyFilters` component restricted to the `TaxonomicFilterGroupType.AccountCustomProperties` group (rendered only when the team has definitions).+The picker options come from `accountsColumnConfigLogic.customPropertyTaxonomicOptions` via `optionsFromProp` — the filter `key` is the definition **id** (stable across renames), and the definition name rides on the filter's `label` for display.+Operator sets honor the property's display type (numeric/boolean/date/string) because `accountsColumnConfigLogic` seeds `propertyDefinitionsModel` under `PropertyDefinitionType.AccountCustomProperty`; the dropdown is further narrowed to `ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST` — exactly the operators `accountsCustomPropertyFilters.ts` can compile.+That module compiles each `AccountCustomPropertyFilter` into a HogQL predicate over `accounts.custom_properties.values."<definition-id>"` (numeric ops via `toFloatOrNull`, date ops via `parseDateTimeBestEffort`, select equality against the stored option **label**, boolean equality against both string renderings of the stored bool — `'true'/'false'` and `'1'/'0'`, the same hedge the cell renderer uses), which `applyAccountFilters` ANDs into `filterExpression` — so the list rows and the overview tiles stay consistent.+Negative operators (is not / doesn't contain / doesn't match regex) are wrapped in `ifNull(..., true)` so accounts where the property is unset (the join yields NULL) stay in the result, matching canonical property-filter semantics; multi-value contains/regex filters match "any of the values" (negated: "none of them").+Filters for deleted definitions or with incomplete values compile to nothing rather than breaking the query, and only validated UUID keys are ever interpolated (quoted via the shared `escapePropertyAsHogQLIdentifier`).+Value suggestions load from`GET /api/projects/:team_id/custom_property_definitions/values/?key=<definition-id>&value=<search>`(the group's`valuesEndpoint`): select → option labels, boolean → true/false, text/numeric → distinct active values; date pickers need no suggestions.+Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`), else the backend gets an `orderBy` referencing a missing alias.## The expanded row@@ -80,7 +89,7 @@ The Notes tab is server-paginated, searchable, and sortable (all via `accountNot## Shareable view state-`accountsLogic` mirrors the full view (search, tags, unassigned, assigned-to, sort, columns, tile filter) into the URL hash `#view=...` via `actionToUrl`/`urlToAction`, so a copied URL reproduces the exact list. Only non-default values are serialized. The "assigned to" filter persists as concrete `assignedTo` ids (not a `mine` flag), so a link shared with a colleague resolves to the **same** accounts for them as for the sharer; the legacy `mine: true` hash is still read and resolved to the current user's id for backward compatibility. A shared link's `columns` win over the per-user saved column config (`accountsColumnConfigLogic` enforces this when its async saved-config load resolves by checking the live URL).+`accountsLogic` mirrors the full view (search, tags, unassigned, assigned-to, custom-property filters, sort, columns, tile filter) into the URL hash `#view=...` via `actionToUrl`/`urlToAction`, so a copied URL reproduces the exact list. Only non-default values are serialized. The "assigned to" filter persists as concrete `assignedTo` ids (not a `mine` flag), so a link shared with a colleague resolves to the **same** accounts for them as for the sharer; the legacy `mine: true` hash is still read and resolved to the current user's id for backward compatibility. A shared link's `columns` win over the per-user saved column config (`accountsColumnConfigLogic` enforces this when its async saved-config load resolves by checking the live URL).### Deep-link to one account (path route)@@ -106,7 +115,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(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)+- `filters` ← search text, tags, unassigned toggle, assigned-to filter, tile filter, custom-property filters (JSON; custom-property filters key by definition **id**, so they survive renames)- `properties` ← `{ tiles }` — overview tile configuration (a `properties` field added to the `ColumnConfiguration` model)**Visibility** is `private` or `shared`; only the creator can edit or delete a view (enforced by the backend viewset).@@ -161,35 +170,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` 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` |+| 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` \| `custom_property`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assigned_to` also `role_count`; for `custom_property` only `filter_count` + `is_cleared` (no `value` — property values can carry customer data) |+| `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/AccountsTabFilters.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsxindex 7cdc8c57e1d9..22ae74322714 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx@@ -11,18 +11,29 @@ import {} from '@posthog/lemon-ui'import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { tagsModel } from '~/models/tagsModel'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import type { AccountCustomPropertyFilter } from '~/types'+import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'import { AccountsColumnConfigurator } from './AccountsColumnConfigurator'+import { ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST } from './accountsCustomPropertyFilters'import { accountsLogic, RoleFilterValue } from './accountsLogic'import { AccountsOverviewTilesButton } from './AccountsOverviewTilesButton'import { AccountsViewSelector } from './AccountsViewSelector'export function AccountsTabFilters(): JSX.Element {- const { searchInput, tagsFilter, allRolesUnassigned, assignedToCurrentUser, assignedToFilter } =- useValues(accountsLogic)+ const {+ searchInput,+ tagsFilter,+ allRolesUnassigned,+ assignedToCurrentUser,+ assignedToFilter,+ customPropertyFilters,+ } = useValues(accountsLogic)const { responseLoading: accountsLoading } = useValues(dataNodeLogic)const {setSearchInput,@@ -30,10 +41,12 @@ export function AccountsTabFilters(): JSX.Element {setAllRolesUnassigned,setAssignedToCurrentUser,setAssignedToFilter,+ setCustomPropertyFilters,refresh,reportFilterChange,} = useActions(accountsLogic)const { tags: tagsAvailable } = useValues(tagsModel)+ const { customPropertyTaxonomicOptions } = useValues(accountsColumnConfigLogic)const tagsButtonLabel =tagsFilter.length === 0 ? 'All tags' : tagsFilter.length === 1 ? tagsFilter[0] : `${tagsFilter.length} tags`@@ -127,6 +140,24 @@ export function AccountsTabFilters(): JSX.Element {disabledReason={accountsLoading ? 'Loading…' : undefined}data-attr="accounts-my-accounts-filter"/>++ {customPropertyTaxonomicOptions.length > 0 && (+ <PropertyFilters+ propertyFilters={customPropertyFilters}+ onChange={(filters) => {+ setCustomPropertyFilters(filters as AccountCustomPropertyFilter[])+ reportFilterChange('custom_property')+ }}+ pageKey="customer-analytics-accounts-custom-properties"+ taxonomicGroupTypes={[TaxonomicFilterGroupType.AccountCustomProperties]}+ taxonomicFilterOptionsFromProp={{+ [TaxonomicFilterGroupType.AccountCustomProperties]: customPropertyTaxonomicOptions,+ }}+ operatorAllowlist={ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST}+ buttonSize="small"+ hasRowOperator={false}+ />+ )}</div><div className="flex flex-wrap gap-2 items-center"><AccountsOverviewTilesButton />diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.tsindex 11e77e229614..93a7cbbf9180 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts@@ -1,13 +1,16 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import type { SimpleOption } from 'lib/components/TaxonomicFilter/types'import { objectsEqual } from 'lib/utils/objects'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'+import { propertyDefinitionsModel, updatePropertyDefinitions } from '~/models/propertyDefinitionsModel'import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'import { DatabaseSchemaField, DatabaseSchemaTable } from '~/queries/schema/schema-general'+import { PropertyDefinitionType, PropertyType } from '~/types'import type { DataWarehouseViewLink } from '~/types'import {@@ -20,6 +23,8 @@ import type {} from 'products/customer_analytics/frontend/generated/api.schemas'import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'+import { propertyTypeForDisplayType } from './accountsCustomPropertyFilters'+// 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'@@ -317,7 +322,12 @@ export interface accountsColumnConfigLogicValues {aliasToRelationshipDefinition: Record<string, AccountRelationshipDefinitionApi>columnConfiguratorVisible: booleancustomPropertyDefinitions: CustomPropertyDefinitionApi[]+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>customPropertyDefinitionsLoading: boolean+ customPropertyTaxonomicOptions: (SimpleOption & {+ id: string+ property_type: PropertyType+ })[]defaultSelectColumns: string[]querySelectColumns: string[]relationshipDefinitions: AccountRelationshipDefinitionApi[]@@ -417,9 +427,16 @@ export interface accountsColumnConfigLogicMeta {customPropertyDefinitions: CustomPropertyDefinitionApi[],relationshipDefinitions: AccountRelationshipDefinitionApi[]) => AccountColumnGroup[]- aliasToDefinition: (+ customPropertyDefinitionsById: (customPropertyDefinitions: CustomPropertyDefinitionApi[]) => Record<string, CustomPropertyDefinitionApi>+ aliasToDefinition: (+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>+ ) => Record<string, CustomPropertyDefinitionApi>+ customPropertyTaxonomicOptions: (customPropertyDefinitions: CustomPropertyDefinitionApi[]) => (SimpleOption & {+ id: string+ property_type: PropertyType+ })[]aliasToRelationshipDefinition: (relationshipDefinitions: AccountRelationshipDefinitionApi[],roleKeyToDefinition: Partial<@@ -450,6 +467,9 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([['joins as warehouseJoins', 'joinsLoading as warehouseJoinsLoading'],],actions: [databaseTableListLogic, ['loadDatabase'], joinsLogic, ['loadJoins']],+ // Keep propertyDefinitionsModel mounted so the seeded custom-property definitions+ // (see loadCustomPropertyDefinitionsSuccess) survive until the filter UI reads them.+ logic: [propertyDefinitionsModel],})),actions({setSelectColumns: (columns: string[]) => ({ columns }),@@ -568,13 +588,38 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([relationshipDefinitions),],- aliasToDefinition: [+ customPropertyDefinitionsById: [(s) => [s.customPropertyDefinitions],(customPropertyDefinitions: CustomPropertyDefinitionApi[]): Record<string, CustomPropertyDefinitionApi> =>+ Object.fromEntries(customPropertyDefinitions.map((definition) => [definition.id, definition])),+ ],+ // The same map re-keyed by the cp_<id> column alias — resolves visible column+ // names back to their definition (table header, configurator labels).+ aliasToDefinition: [+ (s) => [s.customPropertyDefinitionsById],+ (+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>+ ): Record<string, CustomPropertyDefinitionApi> =>Object.fromEntries(- customPropertyDefinitions.map((definition) => [customPropertyAlias(definition.id), definition])+ Object.values(customPropertyDefinitionsById).map((definition) => [+ customPropertyAlias(definition.id),+ definition,+ ])),],+ // Items for the custom-properties taxonomic group (fed via `optionsFromProp`): the+ // definition id is the stable filter key, the name is what's displayed and searched.+ customPropertyTaxonomicOptions: [+ (s) => [s.customPropertyDefinitions],+ (+ customPropertyDefinitions: CustomPropertyDefinitionApi[]+ ): (SimpleOption & { id: string; property_type: PropertyType })[] =>+ customPropertyDefinitions.map((definition) => ({+ id: definition.id,+ name: definition.name,+ property_type: propertyTypeForDisplayType(definition.display_type),+ })),+ ],// Resolves a visible column name (legacy role key or rel_ alias) back to its// relationship definition — drives the cell renderer and header label.aliasToRelationshipDefinition: [@@ -591,6 +636,20 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([],}),listeners(({ actions, values, selectors }) => ({+ // Seed the shared propertyDefinitionsModel so OperatorValueSelect resolves each+ // custom property's type (numeric/boolean/datetime/string) to the right operator set.+ loadCustomPropertyDefinitionsSuccess: () => {+ updatePropertyDefinitions(+ Object.fromEntries(+ values.customPropertyTaxonomicOptions.map((option) => [+ `${PropertyDefinitionType.AccountCustomProperty}/${option.id}`,+ // name is the id, not the display name: OperatorValueSelect resolves+ // the definition by matching `name` against the filter key (the id).+ { id: option.id, name: option.id, property_type: option.property_type },+ ])+ )+ )+ },// Customized columns (user edits, saved view, shared URL) no longer equal the// default they diverged from, so only still-default columns get upgraded.loadRelationshipDefinitionsSuccess: (_, __, ___, previousState) => {diff --git a/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.test.tsnew file mode 100644index 000000000000..3116ff031bcf--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.test.ts@@ -0,0 +1,149 @@+import { AccountCustomPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'++import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { customPropertyFiltersToExpressions, customPropertyFilterToExpression } from './accountsCustomPropertyFilters'++const TEXT_ID = '11111111-2222-3333-4444-555555555555'+const NUMBER_ID = '66666666-7777-8888-9999-aaaaaaaaaaaa'++function definition(overrides: Partial<CustomPropertyDefinitionApi>): CustomPropertyDefinitionApi {+ return { id: TEXT_ID, name: 'Prop', display_type: 'text', ...overrides } as CustomPropertyDefinitionApi+}++function filter(overrides: Partial<AccountCustomPropertyFilter>): AccountCustomPropertyFilter {+ return {+ type: PropertyFilterType.AccountCustomProperty,+ key: TEXT_ID,+ operator: PropertyOperator.Exact,+ ...overrides,+ }+}++// The shared identifier escaper double-quotes the (non-simple) UUID key.+const TEXT_COLUMN = `accounts.custom_properties.values."${TEXT_ID}"`+const NUMBER_COLUMN = `accounts.custom_properties.values."${NUMBER_ID}"`++describe('accountsCustomPropertyFilters', () => {+ it.each([+ ['text exact', 'text', { value: 'Enterprise' }, `${TEXT_COLUMN} = 'Enterprise'`],+ ['escapes quotes and backslashes', 'text', { value: "O'Brien \\ co" }, `${TEXT_COLUMN} = 'O\\'Brien \\\\ co'`],+ ['exact with multiple values', 'text', { value: ['a', 'b'] }, `${TEXT_COLUMN} IN ('a', 'b')`],+ // Negative operators keep accounts where the property is unset (the join yields NULL there).+ [+ 'is_not includes unset accounts',+ 'text',+ { operator: PropertyOperator.IsNot, value: 'Churned' },+ `ifNull(${TEXT_COLUMN} != 'Churned', true)`,+ ],+ [+ 'is_not with multiple values',+ 'text',+ { operator: PropertyOperator.IsNot, value: ['a', 'b'] },+ `ifNull(${TEXT_COLUMN} NOT IN ('a', 'b'), true)`,+ ],+ ['icontains', 'text', { operator: PropertyOperator.IContains, value: 'acme' }, `${TEXT_COLUMN} ILIKE '%acme%'`],+ [+ 'icontains matches any of multiple values',+ 'text',+ { operator: PropertyOperator.IContains, value: ['acme', 'beta'] },+ `(${TEXT_COLUMN} ILIKE '%acme%' OR ${TEXT_COLUMN} ILIKE '%beta%')`,+ ],+ [+ 'not_icontains includes unset accounts',+ 'text',+ { operator: PropertyOperator.NotIContains, value: 'acme' },+ `ifNull(NOT (${TEXT_COLUMN} ILIKE '%acme%'), true)`,+ ],+ [+ 'not_icontains matches none of multiple values',+ 'text',+ { operator: PropertyOperator.NotIContains, value: ['acme', 'beta'] },+ `ifNull(NOT (${TEXT_COLUMN} ILIKE '%acme%' OR ${TEXT_COLUMN} ILIKE '%beta%'), true)`,+ ],+ ['regex', 'text', { operator: PropertyOperator.Regex, value: '^acme' }, `match(${TEXT_COLUMN}, '^acme')`],+ [+ 'not_regex includes unset accounts',+ 'text',+ { operator: PropertyOperator.NotRegex, value: '^acme' },+ `ifNull(NOT (match(${TEXT_COLUMN}, '^acme')), true)`,+ ],+ ['is_set', 'text', { operator: PropertyOperator.IsSet, value: null }, `${TEXT_COLUMN} IS NOT NULL`],+ ['is_not_set', 'text', { operator: PropertyOperator.IsNotSet, value: null }, `${TEXT_COLUMN} IS NULL`],+ [+ 'select equality compares the stored label',+ 'select',+ { value: 'Enterprise' },+ `${TEXT_COLUMN} = 'Enterprise'`,+ ],+ // Booleans match both string renderings of the stored bool ('true'/'false' and '1'/'0').+ ['boolean exact matches either rendering', 'boolean', { value: 'true' }, `${TEXT_COLUMN} IN ('true', '1')`],+ ['boolean false', 'boolean', { value: 'false' }, `${TEXT_COLUMN} IN ('false', '0')`],+ [+ 'boolean is_not includes unset accounts',+ 'boolean',+ { operator: PropertyOperator.IsNot, value: 'true' },+ `ifNull(${TEXT_COLUMN} NOT IN ('true', '1'), true)`,+ ],+ ['numeric exact casts the column', 'number', { value: '42' }, `toFloatOrNull(${TEXT_COLUMN}) = 42`],+ ['numeric multi-value IN', 'currency', { value: [10, '20.5'] }, `toFloatOrNull(${TEXT_COLUMN}) IN (10, 20.5)`],+ [+ 'numeric is_not includes unset accounts',+ 'number',+ { operator: PropertyOperator.IsNot, value: '42' },+ `ifNull(toFloatOrNull(${TEXT_COLUMN}) != 42, true)`,+ ],+ [+ 'numeric greater than',+ 'percent',+ { operator: PropertyOperator.GreaterThan, value: '0.8' },+ `toFloatOrNull(${TEXT_COLUMN}) > 0.8`,+ ],+ [+ 'date before',+ 'date',+ { operator: PropertyOperator.IsDateBefore, value: '2026-01-15' },+ `parseDateTimeBestEffort(${TEXT_COLUMN}) < parseDateTimeBestEffort('2026-01-15')`,+ ],+ [+ 'datetime exact',+ 'datetime',+ { operator: PropertyOperator.IsDateExact, value: '2026-01-15 10:00:00' },+ `parseDateTimeBestEffort(${TEXT_COLUMN}) = parseDateTimeBestEffort('2026-01-15 10:00:00')`,+ ],+ ])('%s', (_name, displayType, filterOverrides, expected) => {+ expect(+ customPropertyFilterToExpression(+ filter(filterOverrides as Partial<AccountCustomPropertyFilter>),+ definition({ display_type: displayType as CustomPropertyDefinitionApi['display_type'] })+ )+ ).toBe(expected)+ })++ it.each([+ ['missing value', 'number', { value: null }],+ ['empty string value', 'number', { value: '' }],+ ['non-UUID key never reaches the query', 'number', { key: 'accounts.name); DROP', value: 'x' }],+ ['numeric operator with non-numeric value', 'number', { operator: PropertyOperator.GreaterThan, value: 'abc' }],+ ['boolean with an unrecognized value', 'boolean', { value: 'maybe' }],+ ])('returns null for %s', (_name, displayType, filterOverrides) => {+ expect(+ customPropertyFilterToExpression(+ filter(filterOverrides as Partial<AccountCustomPropertyFilter>),+ definition({ display_type: displayType as CustomPropertyDefinitionApi['display_type'] })+ )+ ).toBeNull()+ })++ it('drops filters for unknown definitions and keeps compilable ones', () => {+ const definitionsById = { [NUMBER_ID]: definition({ id: NUMBER_ID, display_type: 'number' }) }+ const expressions = customPropertyFiltersToExpressions(+ [+ filter({ key: NUMBER_ID, operator: PropertyOperator.LessThanOrEqual, value: 5 }),+ filter({ key: TEXT_ID, value: 'orphaned' }),+ ],+ definitionsById+ )+ expect(expressions).toEqual([`toFloatOrNull(${NUMBER_COLUMN}) <= 5`])+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.tsnew file mode 100644index 000000000000..89322ec9b35b--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts@@ -0,0 +1,196 @@+import { isUUIDLike } from 'lib/utils/guards'++import { escapeHogQLString, escapePropertyAsHogQLIdentifier } from '~/queries/utils'+import { AccountCustomPropertyFilter, PropertyOperator, PropertyType } from '~/types'++import type {+ CustomPropertyDefinitionApi,+ CustomPropertyDisplayTypeEnumApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++export function propertyTypeForDisplayType(displayType: CustomPropertyDisplayTypeEnumApi): PropertyType {+ switch (displayType) {+ case 'number':+ case 'currency':+ case 'percent':+ return PropertyType.Numeric+ case 'boolean':+ return PropertyType.Boolean+ case 'date':+ case 'datetime':+ return PropertyType.DateTime+ default:+ return PropertyType.String+ }+}++// Only the operators the expression builder below can compile — keeps the operator+// dropdown in sync with what the query can actually run (e.g. no semver operators).+export const ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST: PropertyOperator[] = [+ PropertyOperator.Exact,+ PropertyOperator.IsNot,+ PropertyOperator.IContains,+ PropertyOperator.NotIContains,+ PropertyOperator.Regex,+ PropertyOperator.NotRegex,+ PropertyOperator.GreaterThan,+ PropertyOperator.GreaterThanOrEqual,+ PropertyOperator.LessThan,+ PropertyOperator.LessThanOrEqual,+ PropertyOperator.IsSet,+ PropertyOperator.IsNotSet,+ PropertyOperator.IsDateExact,+ PropertyOperator.IsDateBefore,+ PropertyOperator.IsDateAfter,+]++const RANGE_OPERATOR_SYMBOLS: Partial<Record<PropertyOperator, string>> = {+ [PropertyOperator.GreaterThan]: '>',+ [PropertyOperator.GreaterThanOrEqual]: '>=',+ [PropertyOperator.LessThan]: '<',+ [PropertyOperator.LessThanOrEqual]: '<=',+}++const DATE_OPERATOR_SYMBOLS: Partial<Record<PropertyOperator, string>> = {+ [PropertyOperator.IsDateExact]: '=',+ [PropertyOperator.IsDateBefore]: '<',+ [PropertyOperator.IsDateAfter]: '>',+}++function normalizeFilterValues(filter: AccountCustomPropertyFilter): (string | number)[] {+ const raw = Array.isArray(filter.value) ? filter.value : filter.value == null ? [] : [filter.value]+ return raw.filter((value): value is string | number => value !== '' && value !== null && value !== undefined)+}++// The join yields NULL for accounts where the property is unset, and a bare negation+// propagates it (NULL → row excluded) — but "is not X" must keep accounts with no value+// at all. Same fix as posthog/hogql/property.py wrapping NOT_REGEX in ifNull(..., 1).+function includeUnset(predicate: string): string {+ return `ifNull(${predicate}, true)`+}++// The join coalesces the boolean column to a string, but whether that renders as+// 'true'/'false' or '1'/'0' depends on the federated engine — match either, the same+// hedge the boolean cell renderer uses.+const BOOLEAN_LITERALS: Record<string, string[]> = {+ true: ["'true'", "'1'"],+ '1': ["'true'", "'1'"],+ false: ["'false'", "'0'"],+ '0': ["'false'", "'0'"],+}++function booleanLiterals(values: (string | number)[]): string[] {+ return [...new Set(values.flatMap((value) => BOOLEAN_LITERALS[String(value).toLowerCase()] ?? []))]+}++// The join coalesces every value to a string, so equality/ILIKE work on the column directly;+// numeric and date comparisons re-type it (toFloatOrNull / parseDateTimeBestEffort) —+// the same casts the overview tiles use for aggregation.+export function customPropertyFilterToExpression(+ filter: AccountCustomPropertyFilter,+ definition: CustomPropertyDefinitionApi+): string | null {+ // The key round-trips through saved views and the URL hash before landing in raw HogQL,+ // so only ever interpolate a validated UUID (the shared escaper is defense in depth).+ if (!filter.key || !isUUIDLike(filter.key)) {+ return null+ }+ const column = `accounts.custom_properties.values.${escapePropertyAsHogQLIdentifier(filter.key)}`+ const operator = filter.operator++ if (operator === PropertyOperator.IsSet) {+ return `${column} IS NOT NULL`+ }+ if (operator === PropertyOperator.IsNotSet) {+ return `${column} IS NULL`+ }++ const values = normalizeFilterValues(filter)+ if (values.length === 0) {+ return null+ }+ const propertyType = propertyTypeForDisplayType(definition.display_type)++ switch (operator) {+ case PropertyOperator.Exact:+ case PropertyOperator.IsNot: {+ const negated = operator === PropertyOperator.IsNot+ if (propertyType === PropertyType.Numeric) {+ const numbers = values.map(Number).filter(Number.isFinite)+ if (numbers.length === 0) {+ return null+ }+ const target = `toFloatOrNull(${column})`+ const comparison =+ numbers.length === 1+ ? `${target} ${negated ? '!=' : '='} ${numbers[0]}`+ : `${target} ${negated ? 'NOT IN' : 'IN'} (${numbers.join(', ')})`+ return negated ? includeUnset(comparison) : comparison+ }+ const literals =+ propertyType === PropertyType.Boolean+ ? booleanLiterals(values)+ : values.map((value) => escapeHogQLString(String(value)))+ if (literals.length === 0) {+ return null+ }+ const comparison =+ literals.length === 1+ ? `${column} ${negated ? '!=' : '='} ${literals[0]}`+ : `${column} ${negated ? 'NOT IN' : 'IN'} (${literals.join(', ')})`+ return negated ? includeUnset(comparison) : comparison+ }+ case PropertyOperator.IContains:+ case PropertyOperator.NotIContains: {+ // Several values match "contains any of them" (so the negation is "contains none"),+ // mirroring posthog/hogql/property.py's multi-value search semantics.+ const anyMatch = values.map((value) => `${column} ILIKE ${escapeHogQLString(`%${value}%`)}`).join(' OR ')+ if (operator === PropertyOperator.NotIContains) {+ return includeUnset(`NOT (${anyMatch})`)+ }+ return values.length === 1 ? anyMatch : `(${anyMatch})`+ }+ case PropertyOperator.Regex:+ case PropertyOperator.NotRegex: {+ const anyMatch = values.map((value) => `match(${column}, ${escapeHogQLString(String(value))})`).join(' OR ')+ if (operator === PropertyOperator.NotRegex) {+ return includeUnset(`NOT (${anyMatch})`)+ }+ return values.length === 1 ? anyMatch : `(${anyMatch})`+ }+ case PropertyOperator.GreaterThan:+ case PropertyOperator.GreaterThanOrEqual:+ case PropertyOperator.LessThan:+ case PropertyOperator.LessThanOrEqual: {+ const threshold = Number(values[0])+ if (!Number.isFinite(threshold)) {+ return null+ }+ return `toFloatOrNull(${column}) ${RANGE_OPERATOR_SYMBOLS[operator]} ${threshold}`+ }+ case PropertyOperator.IsDateExact:+ case PropertyOperator.IsDateBefore:+ case PropertyOperator.IsDateAfter:+ // parseDateTimeBestEffort is the HogQL name (it maps to the ClickHouse+ // ...OrNull variant); the OrNull-suffixed name isn't registered in HogQL.+ return `parseDateTimeBestEffort(${column}) ${+ DATE_OPERATOR_SYMBOLS[operator]+ } parseDateTimeBestEffort(${escapeHogQLString(String(values[0]))})`+ default:+ return null+ }+}++/** One HogQL predicate per compilable filter; filters for deleted definitions or with+ * incomplete values are dropped rather than breaking the query. */+export function customPropertyFiltersToExpressions(+ filters: AccountCustomPropertyFilter[],+ definitionsById: Record<string, CustomPropertyDefinitionApi>+): string[] {+ return filters+ .map((filter) => {+ const definition = filter.key ? definitionsById[filter.key] : undefined+ return definition ? customPropertyFilterToExpression(filter, definition) : null+ })+ .filter((expression): expression is string => !!expression)+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex 4a73b2aef807..95f3a3f21781 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -12,7 +12,7 @@ import { userLogic } from 'scenes/userLogic'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { AccountsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'-import type { UserBasicType } from '~/types'+import type { AccountCustomPropertyFilter, UserBasicType } from '~/types'import {accountsRelationshipsCreate,@@ -30,6 +30,7 @@ import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import type { AccountRelationshipDefinitionApi, CustomPropertyDefinitionApi } from '../../generated/api.schemas'import { isNumericDisplayType } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic, isLegacyRoleColumn } from './accountsColumnConfigLogic'+import { customPropertyFiltersToExpressions } from './accountsCustomPropertyFilters'import {ACCOUNT_EXPANSION_TABS,AccountExpansionTab,@@ -82,7 +83,7 @@ function orderByExpression(column: string, aliasToDefinition: Record<string, Cusexport type RoleFilterValue = number[]-export type AccountFilterType = 'tag' | 'unassigned_only' | 'my_accounts' | 'assigned_to'+export type AccountFilterType = 'tag' | 'unassigned_only' | 'my_accounts' | 'assigned_to' | 'custom_property'// `column` matches the visible column name (alias-stripped) so any selected// column can drive the sort.@@ -99,6 +100,8 @@ interface AccountQueryFilters {assignedToFilter: RoleFilterValueaccountIdFilter: string | nulltileFilter: TileFilter | null+ customPropertyFilters: AccountCustomPropertyFilter[]+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>}// Shared filter clauses for the list-rows query and the overview-metrics query,@@ -127,6 +130,9 @@ function applyAccountFilters(source: AccountsQuery, filters: AccountQueryFiltersif (filters.accountIdFilter) {filterExpressions.push(`toString(id) = '${filters.accountIdFilter}'`)}+ filterExpressions.push(+ ...customPropertyFiltersToExpressions(filters.customPropertyFilters, filters.customPropertyDefinitionsById)+ )if (filterExpressions.length > 0) {source.filterExpression = filterExpressions.map((expr) => `(${expr})`).join(' AND ')}@@ -150,12 +156,14 @@ export interface AccountsViewUrlState {sort?: NonNullable<AccountSortOrder>columns?: string[]tileFilter?: TileFilter+ customProperties?: AccountCustomPropertyFilter[]}// 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> // accountsColumnConfigLogic+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi> // accountsColumnConfigLogicdefaultSelectColumns: string[] // accountsColumnConfigLogicquerySelectColumns: string[] // accountsColumnConfigLogicrelationshipDefinitionsLoaded: boolean // accountsColumnConfigLogic@@ -173,6 +181,7 @@ export interface accountsLogicValues {assignedToCurrentUser: booleanassignedToFilter: RoleFilterValuecurrentUserId: number | null+ customPropertyFilters: AccountCustomPropertyFilter[]hogqlQuery: DataTableNodeisRoleSaving: (accountId: string, column: string) => booleanmetricsQuery: AccountsQuery | null@@ -278,6 +287,9 @@ export interface accountsLogicActions {setAssignedToFilter: (value: RoleFilterValue) => {value: RoleFilterValue}+ setCustomPropertyFilters: (filters: AccountCustomPropertyFilter[]) => {+ filters: AccountCustomPropertyFilter[]+ }setRelationshipOverride: (accountId: string,column: string,@@ -323,7 +335,8 @@ export interface accountsLogicMeta {searchQuery: string,tagsFilter: string[],allRolesUnassigned: boolean,- assignedToFilter: RoleFilterValue+ assignedToFilter: RoleFilterValue,+ customPropertyFilters: AccountCustomPropertyFilter[]) => numberviewUrlState: (searchQuery: string,@@ -333,7 +346,8 @@ export interface accountsLogicMeta {sortOrder: AccountSortOrder,selectColumns: string[],defaultSelectColumns: string[],- tileFilter: TileFilter | null+ tileFilter: TileFilter | null,+ customPropertyFilters: AccountCustomPropertyFilter[]) => AccountsViewUrlStatehogqlQuery: (searchQuery: string,@@ -345,6 +359,8 @@ export interface accountsLogicMeta {sortOrder: AccountSortOrder,querySelectColumns: string[],visibleColumnNames: string[],+ customPropertyFilters: AccountCustomPropertyFilter[],+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,aliasToDefinition: Record<string, CustomPropertyDefinitionApi>) => DataTableNodeaccountsQuerySource: (hogqlQuery: DataTableNode, relationshipDefinitionsLoaded: boolean) => AccountsQuery | null@@ -356,6 +372,8 @@ export interface accountsLogicMeta {assignedToFilter: RoleFilterValue,accountIdFilter: string | null,tileFilter: TileFilter | null,+ customPropertyFilters: AccountCustomPropertyFilter[],+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,relationshipDefinitionsLoaded: boolean) => AccountsQuery | null}@@ -385,6 +403,7 @@ export const accountsLogic = kea<accountsLogicType>(['aliasToRelationshipDefinition','aliasToDefinition','relationshipDefinitionsLoaded',+ 'customPropertyDefinitionsById',],accountsOverviewTilesLogic,['metrics as overviewMetrics', 'tileFilter'],@@ -410,6 +429,7 @@ export const accountsLogic = kea<accountsLogicType>([setSearchInput: (query: string) => ({ query }),setSearchQuery: (query: string) => ({ query }),setTagsFilter: (tags: string[]) => ({ tags }),+ setCustomPropertyFilters: (filters: AccountCustomPropertyFilter[]) => ({ filters }),setAllRolesUnassigned: (value: boolean) => ({ value }),setAssignedToFilter: (value: RoleFilterValue) => ({ value }),// Shortcut for the "My accounts" checkbox — resolves to the current@@ -464,6 +484,12 @@ export const accountsLogic = kea<accountsLogicType>([setTagsFilter: (_, { tags }) => tags,},],+ customPropertyFilters: [+ [] as AccountCustomPropertyFilter[],+ {+ setCustomPropertyFilters: (_, { filters }) => filters,+ },+ ],allRolesUnassigned: [false,{@@ -531,16 +557,21 @@ export const accountsLogic = kea<accountsLogicType>([!!savingRoles[savingRoleKey(accountId, column)],],activeFilterCount: [- (s) => [s.searchQuery, s.tagsFilter, s.allRolesUnassigned, s.assignedToFilter],+ (s) => [s.searchQuery, s.tagsFilter, s.allRolesUnassigned, s.assignedToFilter, s.customPropertyFilters],(searchQuery: string,tagsFilter: string[],allRolesUnassigned: boolean,- assignedToFilter: RoleFilterValue+ assignedToFilter: RoleFilterValue,+ customPropertyFilters: AccountCustomPropertyFilter[]): number =>- [!!searchQuery.trim(), tagsFilter.length > 0, allRolesUnassigned, assignedToFilter.length > 0].filter(- Boolean- ).length,+ [+ !!searchQuery.trim(),+ tagsFilter.length > 0,+ allRolesUnassigned,+ assignedToFilter.length > 0,+ customPropertyFilters.length > 0,+ ].filter(Boolean).length,],viewUrlState: [(s) => [@@ -552,6 +583,7 @@ export const accountsLogic = kea<accountsLogicType>([s.selectColumns,s.defaultSelectColumns,s.tileFilter,+ s.customPropertyFilters,],(searchQuery: string,@@ -561,7 +593,8 @@ export const accountsLogic = kea<accountsLogicType>([sortOrder: AccountSortOrder,selectColumns: string[],defaultSelectColumns: string[],- tileFilter: TileFilter | null+ tileFilter: TileFilter | null,+ customPropertyFilters: AccountCustomPropertyFilter[]): AccountsViewUrlState => {const state: AccountsViewUrlState = {}const trimmedSearch = searchQuery.trim()@@ -586,6 +619,9 @@ export const accountsLogic = kea<accountsLogicType>([if (tileFilter) {state.tileFilter = tileFilter}+ if (customPropertyFilters.length > 0) {+ state.customProperties = customPropertyFilters+ }return state},],@@ -600,6 +636,8 @@ export const accountsLogic = kea<accountsLogicType>([s.sortOrder,s.querySelectColumns,s.visibleColumnNames,+ s.customPropertyFilters,+ s.customPropertyDefinitionsById,s.aliasToDefinition,],(@@ -612,6 +650,8 @@ export const accountsLogic = kea<accountsLogicType>([sortOrder: AccountSortOrder,querySelectColumns: string[],visibleColumnNames: string[],+ customPropertyFilters: AccountCustomPropertyFilter[],+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,aliasToDefinition: Record<string, CustomPropertyDefinitionApi>): DataTableNode => {const source: AccountsQuery = {@@ -626,6 +666,8 @@ export const accountsLogic = kea<accountsLogicType>([assignedToFilter,accountIdFilter,tileFilter,+ customPropertyFilters,+ customPropertyDefinitionsById,})// HogQL ORDER BY resolves SELECT aliases by name, so the visible column// name works directly. Skip sorts on columns the translation dropped@@ -666,6 +708,8 @@ export const accountsLogic = kea<accountsLogicType>([s.assignedToFilter,s.accountIdFilter,s.tileFilter,+ s.customPropertyFilters,+ s.customPropertyDefinitionsById,s.relationshipDefinitionsLoaded,],(@@ -676,6 +720,8 @@ export const accountsLogic = kea<accountsLogicType>([assignedToFilter: RoleFilterValue,accountIdFilter: string | null,tileFilter: TileFilter | null,+ customPropertyFilters: AccountCustomPropertyFilter[],+ customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,relationshipDefinitionsLoaded: boolean): AccountsQuery | null => {if (overviewMetrics.length === 0 || !relationshipDefinitionsLoaded) {@@ -693,6 +739,8 @@ export const accountsLogic = kea<accountsLogicType>([assignedToFilter,accountIdFilter,tileFilter,+ customPropertyFilters,+ customPropertyDefinitionsById,})return source},@@ -733,6 +781,11 @@ export const accountsLogic = kea<accountsLogicType>([properties.role_count = values.assignedToFilter.lengthproperties.is_cleared = values.assignedToFilter.length === 0break+ // Only the shape is logged — property values can carry customer data.+ case 'custom_property':+ properties.filter_count = values.customPropertyFilters.length+ properties.is_cleared = values.customPropertyFilters.length === 0+ break}posthog.capture(AccountsEvents.FilterChanged, properties)},@@ -872,6 +925,9 @@ export const accountsLogic = kea<accountsLogicType>([if (values.assignedToFilter.length > 0) {actions.setAssignedToFilter([])}+ if (values.customPropertyFilters.length > 0) {+ actions.setCustomPropertyFilters([])+ }const term = externalId || nameif (term) {actions.setSearchQuery(term)@@ -921,6 +977,7 @@ export const accountsLogic = kea<accountsLogicType>([return {setSearchQuery: toUrl,setTagsFilter: toUrl,+ setCustomPropertyFilters: toUrl,setAllRolesUnassigned: toUrl,setAssignedToFilter: toUrl,setSortOrder: toUrl,@@ -964,6 +1021,11 @@ export const accountsLogic = kea<accountsLogicType>([actions.setTagsFilter(tags)}+ const customProperties = Array.isArray(view.customProperties) ? view.customProperties : []+ if (!objectsEqual(customProperties, values.customPropertyFilters)) {+ actions.setCustomPropertyFilters(customProperties)+ }+const unassigned = view.unassigned ?? falseif (unassigned !== values.allRolesUnassigned) {actions.setAllRolesUnassigned(unassigned)diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.tsindex 642ca4e6df12..12bc1c1102b7 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts@@ -1,3 +1,5 @@+import { PropertyFilterType, PropertyOperator } from '~/types'+import { ACCOUNTS_HOGQL_DEFAULT_SELECT } from './accountsColumnConfigLogic'import {deserializeAccountsView,@@ -56,6 +58,15 @@ describe('serializeAccountsView / deserializeAccountsView', () => {unassigned: false,assignedTo: [1, 2, 3],tileFilter: { tileId: 't1', expression: 'mrr > 100' },+ customProperties: [+ {+ type: PropertyFilterType.AccountCustomProperty as const,+ key: '11111111-2222-3333-4444-555555555555',+ operator: PropertyOperator.Exact,+ value: 'Enterprise',+ label: 'Tier',+ },+ ],},tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' as const } }],}@@ -76,6 +87,7 @@ describe('serializeAccountsView / deserializeAccountsView', () => {unassigned: false,assignedTo: [],tileFilter: null,+ customProperties: [],},tiles: [...DEFAULT_TILES],})@@ -91,6 +103,7 @@ describe('serializeAccountsView / deserializeAccountsView', () => {unassigned: false,assignedTo: [],tileFilter: null,+ customProperties: [],})expect(state.tiles).toEqual(DEFAULT_TILES)expect(state.sortOrder).toBeNull()diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.tsindex 4639e06dff37..6d8a2567bc1f 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts@@ -1,3 +1,5 @@+import type { AccountCustomPropertyFilter } from '~/types'+import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'import { ACCOUNTS_HOGQL_DEFAULT_SELECT } from './accountsColumnConfigLogic'@@ -11,6 +13,7 @@ export interface AccountsViewFilters {unassigned: booleanassignedTo: RoleFilterValuetileFilter: TileFilter | null+ customProperties: AccountCustomPropertyFilter[]}export interface AccountsViewProperties {@@ -78,6 +81,9 @@ export function serializeAccountsView(state: AccountsViewState): AccountsViewPayif (state.filters.tileFilter) {filters.tileFilter = state.filters.tileFilter}+ if (state.filters.customProperties.length > 0) {+ filters.customProperties = state.filters.customProperties+ }return {columns: state.columns,order_by: sortOrderToOrderBy(state.sortOrder),@@ -104,6 +110,7 @@ export function deserializeAccountsView(view: Partial<ColumnConfigurationApi>):unassigned: rawFilters.unassigned ?? false,assignedTo: normalizeRoleFilter(rawFilters.assignedTo),tileFilter: rawFilters.tileFilter ?? null,+ customProperties: Array.isArray(rawFilters.customProperties) ? rawFilters.customProperties : [],},tiles: rawProperties.tiles && rawProperties.tiles.length > 0 ? rawProperties.tiles : [...DEFAULT_TILES],}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.tsindex e59e60e02a05..fe768b56d7ce 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts@@ -15,6 +15,7 @@ import { userLogic } from 'scenes/userLogic'import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'import type { UserType } from '../../../../../frontend/src/types'+import type { AccountCustomPropertyFilter } from '../../../../../frontend/src/types'import { ACCOUNTS_COLUMN_CONFIG_KEY, accountsColumnConfigLogic } from './accountsColumnConfigLogic'import { accountsLogic } from './accountsLogic'import type { AccountSortOrder, RoleFilterValue } from './accountsLogic'@@ -35,6 +36,7 @@ export interface accountsViewsLogicValues {selectColumns: string[] // accountsColumnConfigLogicallRolesUnassigned: boolean // accountsLogicassignedToFilter: RoleFilterValue // accountsLogic+ customPropertyFilters: AccountCustomPropertyFilter[] // accountsLogicsearchQuery: string // accountsLogicsortOrder: AccountSortOrder // accountsLogictagsFilter: string[] // accountsLogic@@ -116,6 +118,9 @@ export interface accountsViewsLogicActions {setAssignedToFilter: (value: RoleFilterValue) => {value: RoleFilterValue} // accountsLogic+ setCustomPropertyFilters: (filters: AccountCustomPropertyFilter[]) => {+ filters: AccountCustomPropertyFilter[]+ } // accountsLogicsetSearchQuery: (query: string) => {query: string} // accountsLogic@@ -345,7 +350,8 @@ export interface accountsViewsLogicMeta {assignedToFilter: RoleFilterValue,sortOrder: AccountSortOrder,tileFilter: TileFilter | null,- tiles: AccountsOverviewTile[]+ tiles: AccountsOverviewTile[],+ customPropertyFilters: AccountCustomPropertyFilter[]) => AccountsViewStatecurrentView: (views: ColumnConfigurationApi[], currentViewId: string | null) => ColumnConfigurationApi | nullisDirty: (currentView: ColumnConfigurationApi | null, liveViewState: AccountsViewState) => boolean@@ -371,7 +377,14 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([accountsColumnConfigLogic,['selectColumns'],accountsLogic,- ['searchQuery', 'tagsFilter', 'allRolesUnassigned', 'assignedToFilter', 'sortOrder'],+ [+ 'searchQuery',+ 'tagsFilter',+ 'allRolesUnassigned',+ 'assignedToFilter',+ 'sortOrder',+ 'customPropertyFilters',+ ],accountsOverviewTilesLogic,['tiles', 'tileFilter'],],@@ -379,7 +392,14 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([accountsColumnConfigLogic,['setSelectColumns'],accountsLogic,- ['setSearchQuery', 'setTagsFilter', 'setAllRolesUnassigned', 'setAssignedToFilter', 'setSortOrder'],+ [+ 'setSearchQuery',+ 'setTagsFilter',+ 'setAllRolesUnassigned',+ 'setAssignedToFilter',+ 'setSortOrder',+ 'setCustomPropertyFilters',+ ],accountsOverviewTilesLogic,['setTiles', 'setTileFilter'],],@@ -473,6 +493,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([s.sortOrder,s.tileFilter,s.tiles,+ s.customPropertyFilters,],(selectColumns: string[],@@ -482,7 +503,8 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([assignedToFilter: import('./accountsLogic').RoleFilterValue,sortOrder: import('./accountsLogic').AccountSortOrder,tileFilter: null | import('./accountsOverviewTilesLogic').TileFilter,- tiles: import('./accountsOverviewTilesLogic').AccountsOverviewTile[]+ tiles: import('./accountsOverviewTilesLogic').AccountsOverviewTile[],+ customPropertyFilters: import('~/types').AccountCustomPropertyFilter[]): AccountsViewState => ({columns: selectColumns,sortOrder,@@ -492,6 +514,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([unassigned: allRolesUnassigned,assignedTo: assignedToFilter,tileFilter,+ customProperties: customPropertyFilters,},tiles,}),@@ -562,6 +585,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([// unassigned flag first so the assigned-to filter below isn't wiped by that cross-listener.actions.setAllRolesUnassigned(state.filters.unassigned)actions.setAssignedToFilter(state.filters.assignedTo)+ actions.setCustomPropertyFilters(state.filters.customProperties)actions.setSortOrder(state.sortOrder)actions.setTiles(state.tiles)actions.setTileFilter(state.filters.tileFilter)