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.

feat(customer-analytics): remove accounts compatibility layer (#81169)

Arthur Moreira de Deus00de49a8c114
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index f629b787ef6d..35821f06a843 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -278,8 +278,6 @@ export const FEATURE_FLAGS = {
CREATE_FORM_TOOL: 'phai-create-form-tool', // owner: @kappa90 #team-posthog-ai
CRM_ITERATION_ONE: 'crm-iteration-one', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS: 'customer-analytics-roadmap', // owner: @arthurdedeus #team-customer-analytics
- CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP: 'customer-analytics-accounts-hogql-cleanup', // owner: @arthurdedeus #team-customer-analytics, hides account columns that require custom HogQL or data warehouse joins
- CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES: 'customer-analytics-accounts-postgres', // owner: @arthurdedeus #team-customer-analytics, runs supported Accounts list queries directly in Postgres
CUSTOMER_ANALYTICS_CSP: 'customer-analytics-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)
CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analytics
diff --git a/frontend/src/queries/nodes/DataTable/queryFeatures.test.ts b/frontend/src/queries/nodes/DataTable/queryFeatures.test.ts
index dee624125c9d..b4f887a3bca3 100644
--- a/frontend/src/queries/nodes/DataTable/queryFeatures.test.ts
+++ b/frontend/src/queries/nodes/DataTable/queryFeatures.test.ts
@@ -33,11 +33,11 @@ describe('getQueryFeatures', () => {
})
describe('resultIsArrayOfArrays', () => {
- it('uses positional rendering for translated Accounts table rows', () => {
+ it('uses keyed rendering for Accounts table rows', () => {
const query: AccountsTableQuery = { kind: NodeKind.AccountsTableQuery, columns: [], filters: [] }
const features = getQueryFeatures(query)
- expect(features.has(QueryFeature.resultIsArrayOfArrays)).toBe(true)
+ expect(features.has(QueryFeature.resultIsArrayOfArrays)).toBe(false)
})
})
diff --git a/frontend/src/queries/nodes/DataTable/queryFeatures.ts b/frontend/src/queries/nodes/DataTable/queryFeatures.ts
index e78a8bc4590b..d9c756d78d8d 100644
--- a/frontend/src/queries/nodes/DataTable/queryFeatures.ts
+++ b/frontend/src/queries/nodes/DataTable/queryFeatures.ts
@@ -165,7 +165,6 @@ export function getQueryFeatures(query: Node): Set<QueryFeature> {
}
if (isAccountsTableQuery(query)) {
- features.add(QueryFeature.resultIsArrayOfArrays)
features.add(QueryFeature.displayResponseError)
}
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 1ebde5df8ad7..76ce58edf6be 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -8,23 +8,23 @@ This file should carry the full context needed to work here — architecture, da
## What this is
-An **Account** is a customer organization. The list is a HogQL-backed table over the `system.accounts` table, with per-row expansion into Notes / Users / Relationships / Usage / Spend / Opportunities, inline role assignment (CSM, AE, owner), configurable columns, overview metric tiles, shareable views, and a Max (AI) contextual tool for opening accounts.
+An **Account** is a customer organization. The list is a Postgres-backed table over Customer analytics account models, with per-row expansion into Notes / Users / Relationships / Usage / Spend / Opportunities, inline role assignment (CSM, AE, owner), configurable columns, overview metric tiles, shareable views, and a Max (AI) contextual tool for opening accounts.
`Account.external_id` is the PostHog **group key** — it's how an account joins to its group-analytics data (usage, events, feature flags). Treat it as the account's analytics identity, not a CRM id (CRM/billing ids live in account properties). The account→group bridge lives in the backend query runner and the agent mode, not here — see [Backend touchpoints](#backend-touchpoints). Keep this mechanism out of any user-facing copy (it's a façade — see the agent mode preset).
## Architecture
-The scene renders `AccountsTabContent`, which binds **two** `dataNodeLogic` instances (keys from `../../constants`): `ACCOUNTS_HOGQL_DATA_NODE_KEY` for list rows and `ACCOUNTS_METRICS_DATA_NODE_KEY` for overview-tile aggregations. The overview uses a metrics-only `AccountsTableQuery` against Postgres whenever its filters translate to typed filters, with the existing `AccountsQuery` retained as a compatibility fallback. Each request carries its own loading state, and the metrics provider only wraps `AccountsOverviewTiles`, so slower aggregations never block list rows.
+The scene renders `AccountsTabContent`, which binds **two** keyed `dataNodeLogic` instances: `ACCOUNTS_TABLE_DATA_NODE_KEY` runs the row-loading `AccountsTableQuery`, and `ACCOUNTS_METRICS_DATA_NODE_KEY` runs a separate metrics-only `AccountsTableQuery` for overview tiles. Both execute against Postgres. The table and overview read their own keyed loading state, so a slow overview aggregation does not replace table rows with a loading skeleton.
```text
-AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, accountsLogic.accountsQuerySource) [list rows]
+AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, accountsLogic.accountsQuerySource) [list rows]
└─ binds dataNodeLogic(ACCOUNTS_METRICS_DATA_NODE_KEY, accountsLogic.metricsQuery) [overview tiles, metrics-only]
├── AccountsMaxTools registers the `open_account` Max contextual tool → accountsLogic.openAccount
├── AccountsTabFilters two rows: (1) search + Refresh; (2) tags / "assigned to" (incl. unassigned-only) /
│ "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
+└── AccountsTable the DataTable; keyed row renderers; controlled row expansion
└── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities/Summaries/Support tickets/Meetings/Event stream)
├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)
├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)
@@ -42,11 +42,11 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc
| Logic | Owns |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property filters, sort, inline role assignment, HogQL and Postgres list-query selection, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references; `tableRowsTransformer` adapts keyed Postgres rows for the existing table. `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, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `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), and the custom-property definitions: it loads them, seeds `propertyDefinitionsModel` (so the filter UI resolves per-type operator sets), and exposes `customPropertyTaxonomicOptions` / `customPropertyDefinitionsById`. When `CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP` is enabled, the picker only offers Postgres-backed account fields, tags, notes, relationships, and custom properties. |
+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |
| `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`). It exposes the existing metric expressions plus typed Postgres metrics and reads results from the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |
+| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |
| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |
| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. |
| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |
@@ -59,35 +59,33 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc
## Data & query model
-`accountsLogic.hogqlQuery` builds a `DataTableNode` wrapping the existing `AccountsQuery`. `accountsTableQueryPlan` translates the same selected columns, filters, custom-property display windows, and server-side sort into a typed `AccountsTableQuery`. When the Postgres flag is enabled and translation is complete, `accountsQuerySource` runs that query instead. The translator reads the live reducers after saved-view or URL restoration, so storage stays backward compatible. A tile filter or unsupported legacy expression returns no plan and keeps the list on HogQL. `tableRowsTransformer` converts keyed `AccountsTableRow`s into arrays aligned to `visibleColumnNames`, preserving the current table and cell components during rollout.
+`accountsLogic.accountsTableQueryPlan` translates selected columns, filters, custom-property display windows, tile filters, and server-side sort into a typed `AccountsTableQuery`. Unsupported saved columns and filters are omitted instead of switching execution engines. `AccountsTable` reads each keyed `AccountsTableRow` directly through `accountsTableCell`; there is no positional-row compatibility transform.
-Overview metrics run separately through `accountsLogic.metricsQuery`. Supported filters translate into a metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`) that calculates count, sum, average, minimum, maximum, median, scaling, and threshold counts in Postgres. Filters that still require the compatibility path retain the metrics-only `AccountsQuery` until the final migration removes those states. The "My accounts" checkbox remains a client-side shortcut that resolves to the current user's explicit ID before either list query is built, so shared URLs remain viewer-independent. Two cell shapes matter:
+Overview tiles run as a separate metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`; `null` when there are no tiles or while definitions are loading). Count, sum, average, minimum, maximum, median, scaling, and threshold counts execute in Postgres. The "My accounts" checkbox resolves to the current user's explicit ID before either query is built, so shared URLs remain viewer-independent. Two cell shapes matter:
-- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — emitted as `tuple(name, external_id, id)`, read as `{ name, external_id, id }`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `external_id` is the copy-able group key. `getNameCell()` in `AccountsHogQLTable.tsx` is the canonical accessor; never assume a column index. In `NameCell` the name renders as the prominent (`font-semibold`) primary label: a plain click opens the account details inline (toggles the row's expansion via `accountsExpansionLogic`, firing `AccountOpened` on open), while the `<Link>` href points at `urls.customerAnalyticsAccount(id)` so cmd/ctrl-click opens the account's deep-link page in a new tab. The `external_id` sits beneath it as de-emphasized (`text-xs text-muted`) copy-to-clipboard text.
-- **relationship columns** — backed by the ``accounts.relationships.values.`<definition_id>` `` lazy join, emitted as the **array of active assignee user ids** (`[]` when unassigned). The legacy names `csm`/`account_executive`/`account_owner` remain the STORED column names (in defaults, saved views, and URL state) and are translated into the lazy-join expression at query-build time by `translateSelectColumns` in `accountsColumnConfigLogic`, matched by seeded definition name (`LEGACY_ROLE_COLUMNS`); a legacy column with no matching definition is dropped from the query. Other definitions are pickable from the "Relationships" column group with opaque `rel_<id>` aliases, resolved back via `aliasToRelationshipDefinition`. Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Sorting uses the alias directly (arrays of ids — deterministic but not email order).
+- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — read directly from the keyed row's `id`, `name`, and `externalId`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `externalId` is the copy-able group key. `getNameCell()` in `AccountsTable.tsx` is the canonical accessor. In `NameCell` the name renders as the prominent (`font-semibold`) primary label: a plain click opens the account details inline (toggles the row's expansion via `accountsExpansionLogic`, firing `AccountOpened` on open), while the `<Link>` href points at `urls.customerAnalyticsAccount(id)` so cmd/ctrl-click opens the account's deep-link page in a new tab. The `external_id` sits beneath it as de-emphasized (`text-xs text-muted`) copy-to-clipboard text.
+- **relationship columns** — returned in `AccountsTableRow.relationships` as arrays of active assignee user ids keyed by definition id (`[]` when unassigned). The legacy names `csm`/`account_executive`/`account_owner` remain stored in defaults, saved views, and URL state, then translate into typed relationship columns matched by seeded definition name (`LEGACY_ROLE_COLUMNS`); a legacy column with no matching definition is dropped from the query. Other definitions are pickable from the "Relationships" column group with opaque `rel_<id>` aliases, resolved back via `aliasToRelationshipDefinition`. Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Sorting uses the alias directly (arrays of ids — deterministic but not email order).
-The `tag_names` cell is editable in place: `TagsCell` renders the editable `ObjectTags` variant (available tags from `tagsModel`), saving through the account PATCH via `accountsLogic.updateAccountTags` — optimistic per-account override (`tagOverrides`, masking the stale HogQL cell like `relationshipOverrides`), debounced full-list PATCH (`TAGS_SAVE_DEBOUNCE_MS`, since `ObjectTags` fires per added/removed tag), `savingTags` guard, revert + toast + captured exception on failure. Clicking a tag in the cell adds it to the tags filter, compounding with tags already filtered (`addTagToFilter` — dedupes, and reports through `reportFilterChange('tag')` like the filter control).
+The `tag_names` cell is editable in place: `TagsCell` renders the editable `ObjectTags` variant (available tags from `tagsModel`), saving through the account PATCH via `accountsLogic.updateAccountTags` — optimistic per-account override (`tagOverrides`, masking the stale fetched cell like `relationshipOverrides`), debounced full-list PATCH (`TAGS_SAVE_DEBOUNCE_MS`, since `ObjectTags` fires per added/removed tag), `savingTags` guard, revert + toast + captured exception on failure. Clicking a tag in the cell adds it to the tags filter, compounding with tags already filtered (`addTagToFilter` — dedupes, and reports through `reportFilterChange('tag')` like the filter control).
-Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship column per team definition. `ACCOUNTS_HOGQL_DEFAULT_SELECT` (base columns only) is just the pre-load seed; once `loadRelationshipDefinitionsSuccess` fires, still-default columns are upgraded to the `defaultSelectColumns` selector (seeded definitions keep their legacy bare names, others get `rel_<id>` expressions) — anything already customized by the user, a saved view, or a shared URL is left alone, and the URL hash serializes columns only when they differ from `defaultSelectColumns`. The name column is force-kept (`ensureNameColumn`) — removing it breaks identity, scroll, and role edits. Extra columns come from account properties, lazy/virtual-table joins under `system.accounts`, data-warehouse joins, freeform SQL, or **custom properties** — all assembled by `buildAccountColumnGroups`. `CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP` removes freeform SQL, data-warehouse joins, and arbitrary lazy/virtual-table groups from the picker while retaining the Postgres-backed tags and notebooks joins. It also removes raw-expression editing for non-custom-property columns. Existing saved views keep their stored expressions so the experiment measures existing usage without breaking those views.
+Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship column per team definition. `ACCOUNTS_DEFAULT_COLUMNS` is the stored-state seed name, but execution is fully typed. Once `loadRelationshipDefinitionsSuccess` fires, still-default columns upgrade to `defaultSelectColumns`. The name column is force-kept because removing it breaks identity, scroll, and role edits. `buildAccountColumnGroups` only offers typed account fields, tags, notes, relationships, and custom properties. Warehouse-backed columns, arbitrary lazy joins, and SQL expressions are unsupported. Older saved expressions are omitted from the query plan.
-**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/min/max/median/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the value in `toFloatOrNull(...)` the same way 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 `AccountsTable`) and the configurator's "Visible columns" list (`SelectedAccountColumn`). Cells render by display type (`CustomPropertyCell`: date→`TZLabel`, boolean→icon, select→`LemonColorGlyph` + label, numeric→`formatCustomPropertyValue`). Server-side sorting uses the typed custom property reference, and the backend chooses the value column from the definition's display type. The stored sort state (URL hash, saved views) keeps the clean column name. Numeric custom properties are also selectable in the **overview tiles** sum/avg/min/max/median/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the value in `toFloatOrNull(...)` the same way so aggregation is numeric.
**Custom property display modes (sparkline/trend)** let numeric custom property columns render their value history instead of the current value.
-The per-view config lives in `accountsColumnConfigLogic.columnDisplay` (`Record<definitionId, { mode: 'sparkline' | 'trend', window_days }>`), edited from the Configure Columns modal's edit section (the pencil on a visible-column row swaps the modal's bottom half from "Available columns" to the editor; non-custom-property columns get a raw-expression editor there instead, replacing the old `window.prompt`).
+The per-view config lives in `accountsColumnConfigLogic.columnDisplay` (`Record<definitionId, { mode: 'sparkline' | 'trend', window_days }>`), edited from the Configure Columns modal's edit section (the pencil on a custom-property row swaps the modal's bottom half from "Available columns" to the display editor).
When a mode is set, `querySelectColumns` swaps that column's expression to ``accounts.custom_properties_history.values.`<definition-id>` AS cp_<id>`` (`applyColumnDisplayToSelect`) — the stored `columns` strings stay in scalar form, so saved views and shared URLs are untouched.
-The history lazy join returns `[unix_ts, value_num]` pairs ascending (all writes in the last 180 days, superseded rows included; numeric values only), and `CustomPropertyCell` branches on `displayByAlias`: sparkline → `lib/components/Sparkline` over the in-window points; trend → latest value + colored delta vs the earliest in-window point, with a tooltip carrying both values and the window.
+The Postgres runner returns `{ timestamp, value }` history points ascending (within the selected window, with the current value included; numeric values only), and `CustomPropertyCell` branches on `displayByAlias`: sparkline → `lib/components/Sparkline` over the in-window points; trend → latest value + colored delta vs the earliest in-window point, with a tooltip carrying both values and the window.
Fewer than 2 in-window points falls back to rendering the latest value plainly.
-The config persists per view via `ColumnConfiguration.properties.column_display` (round-tripped in `accountsViewState.ts`), and sorting stays on the scalar expression (`orderByExpression` builds from the stored column string, not the swapped select).
+The config persists per view via `ColumnConfiguration.properties.column_display` (round-tripped in `accountsViewState.ts`), and sorting uses the scalar custom property even when the displayed cell loads history.
**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`).
+Operator sets honor the property's display type (numeric/boolean/date/string) because `accountsColumnConfigLogic` seeds `propertyDefinitionsModel` under `PropertyDefinitionType.AccountCustomProperty`. The dropdown is narrowed to operators the Postgres runner supports. Regex and negative regex operators are not available.
+`accountsTableQuery.ts` translates each `AccountCustomPropertyFilter` into a typed filter. The backend chooses string, numeric, boolean, or datetime storage from the definition. Negative operators include accounts where the property is unset. Filters for deleted definitions, regex operators, or incompatible display types are omitted rather than changing query engines.
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.
-**Overview tile math** (`accountsOverviewTilesLogic` / `AccountsOverviewTilesEditor`). A tile's metric is a discriminated union: `count` (`count()`), the column aggregations `sum`/`avg`/`min`/`max`/`median` (the metric-type name _is_ the HogQL aggregate fn, so `tileMetricExpression`'s one `default` branch emits `${type}(col)`), and `count_threshold` (`countIf(col op val)`, the only row-level-clickable tile). The column aggregations carry an optional `scale` multiplier (`applyScale`) rendered as `agg(col) * n`, e.g. `sum(mrr) * 12` to annualize; a `scale` of 1/undefined/non-finite is a no-op. `scaleSuffix` mirrors that guard for the `× n` label/caption suffix. Add a new aggregation by extending `COLUMN_AGGREGATE_TYPES` (must be a valid HogQL aggregate fn) plus the editor's `METRIC_TYPE_LABELS` / `COLUMN_AGGREGATE_LABEL_PREFIX`. No backend change: `accounts_query_runner` `parse_expr`s each metric string with no fn whitelist.
+**Overview tile math** (`accountsOverviewTilesLogic` / `AccountsOverviewTilesEditor`). A tile's metric is a discriminated union: `count`, the column aggregations `sum`/`avg`/`min`/`max`/`median`, and `count_threshold`. `tileQueryMetric` translates these into the typed `AccountsTableMetric` union. Column aggregations carry an optional `scale` multiplier, and threshold tiles translate into typed custom-property filters when clicked.
**Tile display** (title / subtitle / value format). A tile also carries two optional presentation fields, independent of the metric: `caption` (custom subtitle) and `format` (`TileValueFormat` = `unit`/`currency`/`percentage`, a subset of `OverviewGrid`'s `WebAnalyticsItemKind` so `format ?? 'unit'` maps 1:1 to the render `kind`). `tileCaption(tile)` resolves the subtitle: the trimmed custom `caption` when set, else `autoCaption(tile)` (the derived `agg of col × n` / `col op val` text; `count` has no derived caption, so a custom one is the only subtitle it can show). The editor edits `caption` (empty → `undefined`) and `format` (`unit` → `undefined`); both flow through the row's `emit(patch)` merge so a metric edit never drops them. Render formatting lives in `OverviewGrid.formatItem`: `currency` uses the team `baseCurrency`, `percentage` treats the value as already in percent units (`85` → "85%", combine with `scale × 100` for a 0-1 fraction). Both fields ride along in `properties.tiles` (no backend/schema/migration) and default cleanly for older saved/legacy tiles.
@@ -97,10 +95,10 @@ Clicking a column header toggles `accountsLogic.sortOrder` (asc → desc → off
How that sort is applied depends on whether the whole matching set is already loaded, tracked by the `canSortClientSide` selector (`!listHasMoreData && !listPaginated`):
- **Fully loaded (the common case — one page, no "Load more"):** `canSortClientSide` is true.
- The list query carries **no** `orderBy`, so toggling a header does not change the query and never refetches.
- Instead the loaded rows are reordered in the browser: the `accountsLogic.sortedRowsTransformer` selector (wrapping `sortAccountRows` from `accountsSort.ts`) is passed by `AccountsHogQLTable` into the DataTable's `dataTableRowsTransformer` context seam — sorting is instant.
- `sortAccountRows` reads each cell by its position in the row's result array (the name tuple sorts by `.name`, relationship/tag arrays join to a string, numbers sort numerically), is stable, and always sinks empty cells to the bottom in both directions.
-- **Paginated (more rows than one page):** `canSortClientSide` is false, so the query carries an `orderBy` (built via `orderByExpression`, so numeric custom properties sort numerically server-side too) and ClickHouse sorts the **entire** set and returns the globally-correct top page; the transformer is inactive (rows are shown in server order). Toggling a header refetches, as before.
+ The list query carries **no** `sort`, so toggling a header does not change the query and never refetches.
+ Instead the loaded rows are reordered in the browser: the `accountsLogic.sortedRowsTransformer` selector (wrapping `sortAccountRows` from `accountsSort.ts`) is passed by `AccountsTable` into the DataTable's `dataTableRowsTransformer` context seam — sorting is instant.
+ `sortAccountRows` reads each keyed row through `accountsTableCell` (the name sorts by `.name`, relationship/tag arrays join to a string, numbers sort numerically), is stable, and always sinks empty cells to the bottom in both directions.
+- **Paginated (more rows than one page):** `canSortClientSide` is false, so the query carries a typed `sort` and Postgres sorts the **entire** set before returning the globally correct page; the transformer is inactive. Toggling a header refetches, as before.
`listPaginated` is what makes this safe: it is set when the user pages past the first page (`loadNextData`, connected from the list `dataNodeLogic`) and reset on every fresh load (`loadData`).
Without it, paging to the end of a large list would flip `listHasMoreData` to false mid-session, drop the `orderBy`, and reset the query back to page one — discarding the accumulated rows.
@@ -110,7 +108,7 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove
## The expanded row
-`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` / `summaries` / `support_tickets` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).
+`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` / `summaries` / `support_tickets` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).
**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountSupportTicketsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`, `AccountMeetingsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.
@@ -196,8 +194,7 @@ Views are persisted as `ColumnConfiguration` rows under `context_key = 'customer
`accountsViewState.ts` is a pure module that maps UI state ↔ the `ColumnConfiguration` payload:
- `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)
+- `order_by` ← sort, stored as `["<column> <ASC|DESC>"]` using the logical column name, then translated into a typed sort reference at query-build time
- `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)
@@ -224,15 +221,15 @@ The Accounts list exposes one contextual tool, `open_account`, so Max can show a
3. `accountsLogic.openAccount`:
- **Reveal** — if the account isn't in the current results (checks the bound data node's rows by name-cell `id`), it clears the excluding filters and searches by `external_id`/name so the row will render. This avoids a silent no-op when Max references an account that's filtered out.
- **Expand** — dispatches `openAccountTab(accountId, tab)` (programmatic; deliberately does **not** fire the tab-viewed event).
- - **Scroll** — polls for the row's `[data-account-id]` node (revealing triggers an async refetch, so it may not exist yet) and smooth-scrolls it into view (`block: 'center'`). Runs through `cache.disposables` keyed `scrollToAccount` (a second open cancels a pending scroll), one-shot via `pauseOnPageHidden: false`. The scroll anchor is `data-account-id={id}` on the name cell in `AccountsHogQLTable.tsx` — keep it there.
+ - **Scroll** — polls for the row's `[data-account-id]` node (revealing triggers an async refetch, so it may not exist yet) and smooth-scrolls it into view (`block: 'center'`). Runs through `cache.disposables` keyed `scrollToAccount` (a second open cancels a pending scroll), one-shot via `pauseOnPageHidden: false`. The scroll anchor is `data-account-id={id}` on the name cell in `AccountsTable.tsx` — keep it there.
The tool is registered for the page regardless of agent mode. The Customer analytics agent mode and the account→group bridge live in the backend (see below); keep their mechanics out of user-facing copy.
### Backend touchpoints
- `products/customer_analytics/backend/models` — the `Account` model (`external_id` = group key).
-- `products/customer_analytics/backend/hogql_queries/accounts_query_runner.py` — the current Accounts page query runner, which builds positional list rows through HogQL.
-- `products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py` — the typed Postgres-only `AccountsTableQuery` runner. It returns keyed rows and applies typed list filters and server-side sorting. The Accounts page selects it behind `CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES` when runtime translation succeeds.
+- `products/customer_analytics/backend/hogql_queries/accounts_query_runner.py` — the legacy generic Accounts query runner used by consumers outside the Accounts list.
+- `products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py` — the Postgres-only `AccountsTableQuery` runner. It returns keyed rows and applies typed list filters, sorting, and overview metrics.
- `products/customer_analytics/backend/max_tools/` — `OpenAccountTool` and other account Max tools.
- `ee/hogai/core/agent_modes/presets/customer_analytics.py` — the Customer analytics agent mode (gated by the `customer-analytics-csp` flag).
@@ -263,7 +260,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `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 account opened` | `AccountsTable.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 |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
index 976b6c625517..cf5ead14b3cd 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
@@ -5,7 +5,6 @@ import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifi
import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { useActions, useValues } from 'kea'
-import { useState } from 'react'
import { IconPencil, IconX } from '@posthog/icons'
import {
@@ -15,11 +14,9 @@ import {
LemonSearchableSelect,
LemonSegmentedButton,
LemonSelect,
- LemonTextArea,
- Link,
} from '@posthog/lemon-ui'
-import { IconOpenInNew, IconTuning, SortableDragIcon } from 'lib/lemon-ui/icons'
+import { IconTuning, SortableDragIcon } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'
@@ -39,8 +36,6 @@ import {
} from './accountsColumnConfigLogic'
import { accountsViewsLogic } from './accountsViewsLogic'
-const HOGQL_DOCS_URL = 'https://posthog.com/docs/hogql'
-
export function AccountsColumnConfigurator(): JSX.Element {
const { columnConfiguratorVisible } = useValues(accountsColumnConfigLogic)
const { showColumnConfigurator, hideColumnConfigurator } = useActions(accountsColumnConfigLogic)
@@ -123,7 +118,6 @@ function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean;
<ColumnEditSection
key={editingColumnIndex}
column={editingColumn}
- columnIndex={editingColumnIndex}
onClose={() => setEditingColumnIndex(null)}
/>
) : (
@@ -174,19 +168,11 @@ function SaveViewButton(): JSX.Element {
)
}
-function ColumnEditSection({
- column,
- columnIndex,
- onClose,
-}: {
- column: string
- columnIndex: number
- onClose: () => void
-}): JSX.Element | null {
- const { aliasToDefinition, hogqlCleanupEnabled } = useValues(accountsColumnConfigLogic)
+function ColumnEditSection({ column, onClose }: { column: string; onClose: () => void }): JSX.Element | null {
+ const { aliasToDefinition } = useValues(accountsColumnConfigLogic)
const definition = aliasToDefinition[extractDisplayLabel(column)]
- if (!definition && hogqlCleanupEnabled) {
+ if (!definition) {
return null
}
@@ -200,11 +186,7 @@ function ColumnEditSection({
Back to available columns
</LemonButton>
</div>
- {definition ? (
- <CustomPropertyDisplayEditor definition={definition} />
- ) : (
- <ExpressionEditor column={column} columnIndex={columnIndex} />
- )}
+ <CustomPropertyDisplayEditor definition={definition} />
</div>
)
}
@@ -278,33 +260,6 @@ function CustomPropertyDisplayEditor({ definition }: { definition: CustomPropert
)
}
-function ExpressionEditor({ column, columnIndex }: { column: string; columnIndex: number }): JSX.Element {
- const { updateColumnExpression } = useActions(accountsColumnConfigLogic)
- const [expression, setExpression] = useState(column)
-
- return (
- <div className="flex flex-col gap-2">
- <LemonInput
- value={expression}
- onChange={setExpression}
- fullWidth
- data-attr="accounts-column-edit-expression"
- />
- <div className="flex justify-end">
- <LemonButton
- type="primary"
- size="small"
- onClick={() => updateColumnExpression(columnIndex, expression)}
- disabledReason={!expression.trim() ? 'Enter a column expression' : undefined}
- data-attr="accounts-column-edit-save"
- >
- Save
- </LemonButton>
- </div>
- </div>
- )
-}
-
function SelectedAccountColumn({
column,
dataIndex,
@@ -318,8 +273,7 @@ function SelectedAccountColumn({
onEdit: (index: number) => void
onRemove: (column: string) => void
}): JSX.Element {
- const { aliasToDefinition, aliasToRelationshipDefinition, hogqlCleanupEnabled } =
- useValues(accountsColumnConfigLogic)
+ const { aliasToDefinition, aliasToRelationshipDefinition } = useValues(accountsColumnConfigLogic)
const { setNodeRef, attributes, transform, transition, listeners } = useSortable({ id: column })
const alias = extractDisplayLabel(column)
// Custom-property and relationship columns are aliased to opaque `cp_<id>` / `rel_<id>`
@@ -328,7 +282,7 @@ function SelectedAccountColumn({
// `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
- const canEdit = !isMandatory && (!!aliasToDefinition[alias] || !hogqlCleanupEnabled)
+ const canEdit = !isMandatory && !!aliasToDefinition[alias]
return (
<div
@@ -368,16 +322,9 @@ function SelectedAccountColumn({
}
function AvailableColumnsPicker({ groups, loading }: { groups: AccountColumnGroup[]; loading: boolean }): JSX.Element {
- const {
- pickerGroupKey,
- pickerSearch,
- pickerSqlInput,
- pickerSearchPlaceholder,
- activePickerGroup,
- filteredColumnOptions,
- } = useValues(accountsColumnConfigLogic)
- const { selectColumn, setPickerGroupKey, setPickerSearch, setPickerSqlInput, addSqlExpression } =
- useActions(accountsColumnConfigLogic)
+ const { pickerGroupKey, pickerSearch, pickerSearchPlaceholder, filteredColumnOptions } =
+ useValues(accountsColumnConfigLogic)
+ const { selectColumn, setPickerGroupKey, setPickerSearch } = useActions(accountsColumnConfigLogic)
return (
<div className="flex flex-col gap-2">
@@ -386,51 +333,44 @@ function AvailableColumnsPicker({ groups, loading }: { groups: AccountColumnGrou
placeholder={pickerSearchPlaceholder}
value={pickerSearch}
onChange={setPickerSearch}
- disabled={activePickerGroup?.isFreeform}
fullWidth
data-attr="accounts-columns-search"
suffix={<CategoryPicker groups={groups} activeKey={pickerGroupKey} onChange={setPickerGroupKey} />}
/>
- {activePickerGroup?.isFreeform ? (
- <SqlExpressionPanel value={pickerSqlInput} onChange={setPickerSqlInput} onAdd={addSqlExpression} />
- ) : (
- <div className="AvailableColumnsList border border-border rounded">
- {loading && filteredColumnOptions.length === 0 ? (
- <div className="p-3 text-secondary">Loading schema…</div>
- ) : filteredColumnOptions.length === 0 ? (
- <div className="p-3 text-secondary">
- {pickerSearch.trim() ? 'No matching columns' : 'No columns available'}
- </div>
- ) : (
- <ul className="m-0 p-0 list-none">
- {filteredColumnOptions.map((option) => {
- return (
- <li
- key={`${option.groupLabel}::${option.expression}`}
- className="border-b border-border last:border-b-0"
- >
- <LemonButton
- fullWidth
- size="small"
- onClick={() => !option.isSelected && selectColumn(option.expression)}
- disabledReason={option.isSelected ? 'Already added' : undefined}
- data-attr={`accounts-column-option-${option.name}`}
- >
- <span className="flex-1 font-mono">{option.name}</span>
- {!activePickerGroup ? (
- <span className="ml-2 text-xs text-secondary">{option.groupLabel}</span>
- ) : null}
- {option.type ? (
- <span className="ml-2 text-xs text-secondary">{option.type}</span>
- ) : null}
- </LemonButton>
- </li>
- )
- })}
- </ul>
- )}
- </div>
- )}
+ <div className="AvailableColumnsList border border-border rounded">
+ {loading && filteredColumnOptions.length === 0 ? (
+ <div className="p-3 text-secondary">Loading schema…</div>
+ ) : filteredColumnOptions.length === 0 ? (
+ <div className="p-3 text-secondary">
+ {pickerSearch.trim() ? 'No matching columns' : 'No columns available'}
+ </div>
+ ) : (
+ <ul className="m-0 p-0 list-none">
+ {filteredColumnOptions.map((option) => (
+ <li
+ key={`${option.groupLabel}::${option.expression}`}
+ className="border-b border-border last:border-b-0"
+ >
+ <LemonButton
+ fullWidth
+ size="small"
+ onClick={() => !option.isSelected && selectColumn(option.expression)}
+ disabledReason={option.isSelected ? 'Already added' : undefined}
+ data-attr={`accounts-column-option-${option.name}`}
+ >
+ <span className="flex-1 font-mono">{option.name}</span>
+ {pickerGroupKey === ALL_COLUMNS_KEY ? (
+ <span className="ml-2 text-xs text-secondary">{option.groupLabel}</span>
+ ) : null}
+ {option.type ? (
+ <span className="ml-2 text-xs text-secondary">{option.type}</span>
+ ) : null}
+ </LemonButton>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
</div>
)
}
@@ -467,49 +407,3 @@ function CategoryPicker({
/>
)
}
-
-function SqlExpressionPanel({
- value,
- onChange,
- onAdd,
-}: {
- value: string
- onChange: (next: string) => void
- onAdd: () => void
-}): JSX.Element {
- return (
- <div className="flex flex-col gap-2 p-3 border border-border rounded">
- <div>
- <h4 className="secondary uppercase text-secondary mb-1">SQL expression</h4>
- <LemonTextArea
- value={value}
- onChange={onChange}
- placeholder="JSONExtractString(properties, 'industry') AS industry"
- minRows={3}
- data-attr="accounts-columns-sql"
- />
- </div>
- <div className="text-secondary text-xs whitespace-pre">
- {`Enter SQL expression, such as:
-- properties.industry
-- toInt(properties.\`Long Field Name\`) * 10
-- concat(name, ' (', external_id, ')')`}
- </div>
- <LemonButton
- type="primary"
- fullWidth
- center
- disabledReason={!value.trim() ? 'Enter a HogQL expression' : undefined}
- onClick={onAdd}
- data-attr="accounts-columns-sql-add"
- >
- Add SQL expression
- </LemonButton>
- <div className="flex justify-end">
- <Link to={HOGQL_DOCS_URL} target="_blank" className="text-xs flex items-center gap-1">
- Learn more about SQL <IconOpenInNew />
- </Link>
- </div>
- </div>
- )
-}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
index 693a92c2e49d..84d80314c676 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
@@ -36,21 +36,45 @@ const RELATIONSHIP_DEFINITIONS = {
next: null,
previous: null,
results: [
- { id: 'def-csm', name: 'CSM', description: null, is_single_holder: true },
- { id: 'def-ae', name: 'Account executive', description: null, is_single_holder: true },
- { id: 'def-owner', name: 'Account owner', description: null, is_single_holder: true },
+ {
+ id: '11111111-2222-3333-4444-555555555555',
+ name: 'CSM',
+ description: null,
+ is_single_holder: true,
+ },
+ {
+ id: '66666666-7777-8888-9999-aaaaaaaaaaaa',
+ name: 'Account executive',
+ description: null,
+ is_single_holder: true,
+ },
+ {
+ id: 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff',
+ name: 'Account owner',
+ description: null,
+ is_single_holder: true,
+ },
],
}
-function buildAccountsQueryResponse(rows: AccountRow[]): Record<string, unknown> {
+function buildAccountsTableQueryResponse(rows: AccountRow[]): Record<string, unknown> {
return {
- kind: 'AccountsQuery',
- columns: ['name', 'tag_names', 'notebook_count', 'csm', 'account_executive', 'account_owner'],
- results: rows,
- types: [],
- hogql: '',
- timings: [],
- modifiers: {},
+ kind: 'AccountsTableQuery',
+ results: rows.map(([account, tags, noteCount, csm, accountExecutive, accountOwner]) => ({
+ id: account.id,
+ name: account.name,
+ externalId: account.external_id,
+ accountFields: { name: account.name },
+ tags,
+ noteCount,
+ relationships: {
+ '11111111-2222-3333-4444-555555555555': csm,
+ '66666666-7777-8888-9999-aaaaaaaaaaaa': accountExecutive,
+ 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff': accountOwner,
+ },
+ customProperties: {},
+ customPropertyHistory: {},
+ })),
hasMore: false,
limit: 100,
offset: 0,
@@ -175,25 +199,26 @@ const EXPANDED_ROW_TEST_OPTIONS = {
waitForSelectorTimeout: 15000,
}
-function mockAccountsQuery(rows: AccountRow[]): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {
+function mockAccountsTableQuery(
+ rows: AccountRow[]
+): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {
return async ({ request }) => {
const body = (await request.json()) as { query?: { kind?: string; metrics?: unknown[] } }
const query = body?.query
- if (query?.kind === 'AccountsQuery') {
- return [200, buildAccountsQueryResponse(rows)]
- }
- if (query?.kind === 'AccountsTableQuery' && query.metrics) {
- return [
- 200,
- {
- kind: 'AccountsTableQuery',
- results: [],
- hasMore: false,
- limit: 100,
- offset: 0,
- metricsResults: [rows.length],
- },
- ]
+ if (query?.kind === 'AccountsTableQuery') {
+ return query.metrics
+ ? [
+ 200,
+ {
+ kind: 'AccountsTableQuery',
+ results: [],
+ hasMore: false,
+ limit: 100,
+ offset: 0,
+ metricsResults: [rows.length],
+ },
+ ]
+ : [200, buildAccountsTableQueryResponse(rows)]
}
return undefined
}
@@ -234,7 +259,7 @@ export const Default: Story = {
decorators: [
mswDecorator({
post: {
- [QUERY_ENDPOINT]: mockAccountsQuery(SAMPLE_ROWS),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SAMPLE_ROWS),
},
}),
],
@@ -245,7 +270,7 @@ export const Empty: Story = {
decorators: [
mswDecorator({
post: {
- [QUERY_ENDPOINT]: mockAccountsQuery([]),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery([]),
},
}),
],
@@ -264,7 +289,7 @@ export const FeatureGateOff: Story = {
decorators: [
mswDecorator({
post: {
- [QUERY_ENDPOINT]: mockAccountsQuery(SAMPLE_ROWS),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SAMPLE_ROWS),
},
}),
],
@@ -281,7 +306,7 @@ export const RowExpandedEmpty: Story = {
[ACCOUNT_NOTEBOOKS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },
},
post: {
- [QUERY_ENDPOINT]: mockAccountsQuery(SINGLE_ROW),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW),
},
}),
],
@@ -335,7 +360,7 @@ export const RowExpandedWithNote: Story = {
},
},
post: {
- [QUERY_ENDPOINT]: mockAccountsQuery(SINGLE_ROW),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW),
},
}),
],
@@ -355,7 +380,7 @@ export const RowExpandedLinksDisabled: Story = {
[ACCOUNT_NOTEBOOKS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },
},
post: {
- [QUERY_ENDPOINT]: mockAccountsQuery(SINGLE_ROW),
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW),
},
}),
],
@@ -372,7 +397,7 @@ export const RowExpandedUsageNotFound: Story = {
waitForSelector: ['[data-attr="accounts-refresh"]', '[data-attr="account-billing-insight-not-found"]'],
},
},
- decorators: billingTabDecorators(EMPTY_INSIGHTS, mockAccountsQuery(SINGLE_ROW)),
+ decorators: billingTabDecorators(EMPTY_INSIGHTS, mockAccountsTableQuery(SINGLE_ROW)),
play: async ({ canvasElement }) => {
await expandFirstRow(canvasElement)
const canvas = within(canvasElement)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx
index 609b1edc28a4..236d729e3eda 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx
@@ -2,12 +2,12 @@ import { BindLogic, useValues } from 'kea'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
-import { ACCOUNTS_HOGQL_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'
-import { AccountsHogQLTable } from './AccountsHogQLTable'
+import { ACCOUNTS_TABLE_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'
import { accountsLogic } from './accountsLogic'
import { AccountsMaxTools } from './AccountsMaxTools'
import { AccountsOverviewTiles } from './AccountsOverviewTiles'
import { AccountsTabFilters } from './AccountsTabFilters'
+import { AccountsTable } from './AccountsTable'
export function AccountsTabContent(): JSX.Element {
const { accountsQuerySource, metricsQuery } = useValues(accountsLogic)
@@ -16,7 +16,7 @@ export function AccountsTabContent(): JSX.Element {
<BindLogic
logic={dataNodeLogic}
props={{
- key: ACCOUNTS_HOGQL_DATA_NODE_KEY,
+ key: ACCOUNTS_TABLE_DATA_NODE_KEY,
query: accountsQuerySource,
}}
>
@@ -32,7 +32,7 @@ export function AccountsTabContent(): JSX.Element {
>
<AccountsOverviewTiles />
</BindLogic>
- <AccountsHogQLTable />
+ <AccountsTable />
</div>
</BindLogic>
)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx
index 548b724f4aa9..2114a33f6b84 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx
@@ -10,7 +10,7 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { initKeaTests } from '~/test/init'
import type { UserType } from '~/types'
-import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'
+import { ACCOUNTS_TABLE_DATA_NODE_KEY } from '../../constants'
import { accountsLogic } from './accountsLogic'
import { AccountsTabFilters } from './AccountsTabFilters'
@@ -44,7 +44,7 @@ describe('AccountsTabFilters', () => {
<Provider>
<BindLogic
logic={dataNodeLogic}
- props={{ key: ACCOUNTS_HOGQL_DATA_NODE_KEY, query: {}, autoLoad: false }}
+ props={{ key: ACCOUNTS_TABLE_DATA_NODE_KEY, query: {}, autoLoad: false }}
>
<AccountsTabFilters />
</BindLogic>
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
similarity index 99%
rename from products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts
rename to products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
index 8ba7bf143710..b8308a3549b6 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
@@ -1,6 +1,6 @@
import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
-import { buildHistoryDisplay, getCanonicalPropertyTab } from './AccountsHogQLTable'
+import { buildHistoryDisplay, getCanonicalPropertyTab } from './AccountsTable'
const DAY = 24 * 60 * 60
const NOW_MS = 1_800_000_000_000
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
similarity index 87%
rename from products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
rename to products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index 98fd467ee5b5..7206a4485d8c 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -21,7 +21,7 @@ import { membersLogic } from 'scenes/organization/membersLogic'
import { urls } from 'scenes/urls'
import { tagsModel } from '~/models/tagsModel'
-import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { DataTable } from '~/queries/nodes/DataTable/DataTable'
import { DataTableNode } from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumn, QueryContextColumnComponent } from '~/queries/types'
@@ -31,20 +31,16 @@ import type {
CustomPropertyDefinitionApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
-import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'
+import { ACCOUNTS_TABLE_DATA_NODE_KEY } from '../../constants'
import { formatCustomPropertyValue } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'
import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'
-import {
- ACCOUNTS_NAME_COLUMN,
- AccountColumnDisplayConfig,
- LEGACY_ROLE_COLUMNS,
- accountsColumnConfigLogic,
-} from './accountsColumnConfigLogic'
+import { AccountColumnDisplayConfig, LEGACY_ROLE_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'
import { accountsLogic, savingRoleKey } from './accountsLogic'
+import { accountsTableCell, isAccountsTableRow } from './accountsTableQuery'
import { AccountsEvents } from './constants'
-// Shape the backend emits for the `name` column — see accounts_query_runner._calculate.
+// Shape the name renderer uses from the keyed AccountsTableRow identity fields.
type AccountNameCell = { name: string; external_id: string | null; id: string }
const COLUMN_WIDTHS = {
@@ -54,30 +50,20 @@ const COLUMN_WIDTHS = {
relationship: '220px',
} as const
-function getCellAt(record: unknown, names: string[], column: string): unknown {
- if (!Array.isArray(record)) {
- return undefined
- }
- const index = names.indexOf(column)
- return index >= 0 ? record[index] : undefined
-}
-
function useGetCell(): (record: unknown, column: string) => unknown {
- const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
- return (record, column) => getCellAt(record, visibleColumnNames, column)
+ const { accountsTableQueryPlan } = useValues(accountsLogic)
+ return (record, column) =>
+ isAccountsTableRow(record) ? accountsTableCell(record, column, accountsTableQueryPlan) : undefined
}
-function getNameCell(record: unknown, visibleColumnNames: string[]): AccountNameCell | undefined {
- const value = getCellAt(record, visibleColumnNames, ACCOUNTS_NAME_COLUMN)
- if (!value || typeof value !== 'object') {
+function getNameCell(record: unknown): AccountNameCell | undefined {
+ if (!isAccountsTableRow(record)) {
return undefined
}
- const cell = value as Partial<AccountNameCell>
- return typeof cell.id === 'string' && typeof cell.name === 'string' ? (cell as AccountNameCell) : undefined
+ return { id: record.id, name: record.name, external_id: record.externalId ?? null }
}
-// Relationship cells arrive as the array of ACTIVE assignee user ids from the
-// `accounts.relationships.values` lazy join ([] when nobody holds the relationship).
+// Relationship cells carry active assignee user ids and use an empty array when unassigned.
function parseAssignedUserIds(value: unknown): number[] {
if (!Array.isArray(value)) {
return []
@@ -86,10 +72,9 @@ function parseAssignedUserIds(value: unknown): number[] {
}
function NameCell({ record }: { record: unknown }): JSX.Element {
- const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
const { isAccountExpanded } = useValues(accountsExpansionLogic)
const { toggleAccountExpanded } = useActions(accountsExpansionLogic)
- const cell = getNameCell(record, visibleColumnNames)
+ const cell = getNameCell(record)
const name = cell?.name ?? ''
const externalId = cell?.external_id ?? ''
const accountId = cell?.id
@@ -136,12 +121,11 @@ function NameCell({ record }: { record: unknown }): JSX.Element {
function TagsCell({ record }: { record: unknown }): JSX.Element {
const { isTagsSaving, tagOverrides } = useValues(accountsLogic)
const { updateAccountTags, addTagToFilter } = useActions(accountsLogic)
- const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
const { tags: tagsAvailable } = useValues(tagsModel)
const getCell = useGetCell()
const raw = getCell(record, 'tag_names')
const cellTags = Array.isArray(raw) ? (raw.filter((t) => typeof t === 'string') as string[]) : []
- const accountId = getNameCell(record, visibleColumnNames)?.id
+ const accountId = getNameCell(record)?.id
if (!accountId) {
return cellTags.length > 0 ? <ObjectTags tags={cellTags} staticOnly /> : <span className="text-muted">—</span>
}
@@ -174,11 +158,10 @@ function RelationshipCell({
definition: AccountRelationshipDefinitionApi
}): JSX.Element {
const { isRoleSaving, relationshipOverrides } = useValues(accountsLogic)
- const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
const { updateAccountRole } = useActions(accountsLogic)
const { meFirstMembers } = useValues(membersLogic)
const getCell = useGetCell()
- const accountId = getNameCell(record, visibleColumnNames)?.id ?? ''
+ const accountId = getNameCell(record)?.id ?? ''
const override = accountId ? relationshipOverrides[savingRoleKey(accountId, column)] : undefined
const userIds = override ?? parseAssignedUserIds(getCell(record, column))
@@ -232,19 +215,18 @@ function RelationshipCell({
)
}
-// History cells arrive as [unix timestamp, value] pairs sorted ascending from the
-// `accounts.custom_properties_history.values` lazy join.
+// History points arrive in timestamp order from the Postgres runner.
function parseHistoryPoints(raw: unknown): [number, number][] {
if (!Array.isArray(raw)) {
return []
}
const points: [number, number][] = []
for (const entry of raw) {
- if (!Array.isArray(entry) || entry.length < 2) {
+ if (typeof entry !== 'object' || entry === null || !('timestamp' in entry) || !('value' in entry)) {
continue
}
- const timestamp = Number(entry[0])
- const value = Number(entry[1])
+ const timestamp = Math.floor(Date.parse(String(entry.timestamp)) / 1000)
+ const value = Number(entry.value)
if (Number.isFinite(timestamp) && Number.isFinite(value)) {
points.push([timestamp, value])
}
@@ -361,9 +343,8 @@ function CanonicalTimestampCell({
value: string
tab: AccountExpansionTab
}): JSX.Element {
- const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
const { openAccountTab } = useActions(accountsExpansionLogic)
- const accountId = getNameCell(record, visibleColumnNames)?.id
+ const accountId = getNameCell(record)?.id
const label = <TZLabel time={value} showSeconds={definition.display_type === 'datetime'} />
if (!accountId) {
@@ -446,7 +427,7 @@ function SortableColumnHeader({ column, label }: { column: string; label: string
toggleSort(column)
}
}}
- data-attr={`accounts-hogql-sort-${column}`}
+ data-attr={`accounts-table-sort-${column}`}
>
{label}
<SortingIndicator order={order} />
@@ -457,14 +438,22 @@ function SortableColumnHeader({ column, label }: { column: string; label: string
// Per-column overrides for known visible columns. The `label` becomes the
// header text (rendered inside `SortableColumnHeader`), `width` pins the
// column width, and `render` provides the cell renderer. Any visible column
-// not in this map falls back to a sortable header with the raw column name
-// and DataTable's default cell rendering.
+// not in this map uses a sortable header and the direct keyed-cell renderer.
type KnownColumnTemplate = {
label?: string
width?: string
render?: QueryContextColumnComponent
}
+function DefaultAccountCell({ record, column }: { record: unknown; column: string }): JSX.Element {
+ const getCell = useGetCell()
+ const value = getCell(record, column)
+ if (value === null || value === undefined || value === '') {
+ return <span className="text-muted">—</span>
+ }
+ return <span>{String(value)}</span>
+}
+
const KNOWN_COLUMN_TEMPLATES: Record<string, KnownColumnTemplate> = {
name: {
label: 'Account',
@@ -516,7 +505,7 @@ function useContextColumns(): Record<string, QueryContextColumn> {
columns[key] = {
renderTitle: () => <SortableColumnHeader column={key} label={label} />,
width: template?.width,
- render: template?.render,
+ render: template?.render ?? (({ record }) => <DefaultAccountCell record={record} column={key} />),
}
}
return columns
@@ -524,7 +513,6 @@ function useContextColumns(): Record<string, QueryContextColumn> {
}
function useExpandable(): QueryContext<DataTableNode>['expandable'] {
- const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
const { expandedAccountIds } = useValues(accountsExpansionLogic)
const { toggleAccountExpanded } = useActions(accountsExpansionLogic)
return useMemo(
@@ -532,29 +520,29 @@ function useExpandable(): QueryContext<DataTableNode>['expandable'] {
noIndent: true,
expandedRowClassName: '[&>td]:overflow-visible!',
isRowExpanded: ({ result }) => {
- const cell = getNameCell(result, visibleColumnNames)
+ const cell = getNameCell(result)
return !!cell && expandedAccountIds.includes(cell.id)
},
onRowExpand: ({ result }) => {
- const cell = getNameCell(result, visibleColumnNames)
+ const cell = getNameCell(result)
if (cell) {
toggleAccountExpanded(cell.id)
}
},
onRowCollapse: ({ result }) => {
- const cell = getNameCell(result, visibleColumnNames)
+ const cell = getNameCell(result)
if (cell) {
toggleAccountExpanded(cell.id)
}
},
expandedRowRender: ({ result }) => {
- const cell = getNameCell(result, visibleColumnNames)
+ const cell = getNameCell(result)
return cell ? (
<AccountNotebooksExpansion accountId={cell.id} externalId={cell.external_id ?? ''} />
) : null
},
}),
- [visibleColumnNames, expandedAccountIds, toggleAccountExpanded]
+ [expandedAccountIds, toggleAccountExpanded]
)
}
@@ -598,7 +586,7 @@ const SKELETON_COLUMNS: LemonTableColumns<{ key: number }> = [
})),
]
-function AccountsHogQLSkeleton(): JSX.Element {
+function AccountsTableSkeleton(): JSX.Element {
return (
<LemonTable
className="DataTable"
@@ -614,20 +602,25 @@ function AccountsHogQLSkeleton(): JSX.Element {
)
}
-export function AccountsHogQLTable(): JSX.Element {
- const { accountsDataTableQuery, accountsQuerySource, tableRowsTransformer } = useValues(accountsLogic)
- const { responseLoading, response } = useValues(dataNodeLogic)
+export function AccountsTable(): JSX.Element {
+ const { accountsDataTableQuery, accountsQuerySource, sortedRowsTransformer } = useValues(accountsLogic)
+ const { responseLoading, response } = useValues(
+ dataNodeLogic({
+ key: ACCOUNTS_TABLE_DATA_NODE_KEY,
+ query: accountsQuerySource ?? accountsDataTableQuery.source,
+ } as DataNodeLogicProps)
+ )
const contextColumns = useContextColumns()
const expandable = useExpandable()
// A null source means the query is still waiting on the relationship
// definitions — same skeleton as the initial fetch, not an empty table.
if ((responseLoading || !accountsQuerySource) && !response) {
- return <AccountsHogQLSkeleton />
+ return <AccountsTableSkeleton />
}
return (
<div className="@container">
<DataTable
- uniqueKey="customer-analytics-accounts-hogql"
+ uniqueKey="customer-analytics-accounts-table"
query={accountsDataTableQuery}
setQuery={() => {
// Filters are owned by accountsLogic; column/sort changes from the DataTable are ignored on purpose.
@@ -635,8 +628,8 @@ export function AccountsHogQLTable(): JSX.Element {
context={{
columns: contextColumns,
expandable,
- dataTableRowsTransformer: tableRowsTransformer,
- dataNodeLogicKey: ACCOUNTS_HOGQL_DATA_NODE_KEY,
+ dataTableRowsTransformer: sortedRowsTransformer,
+ dataNodeLogicKey: ACCOUNTS_TABLE_DATA_NODE_KEY,
emptyStateHeading: 'There are no matching accounts for this query',
emptyStateDetail: 'Try adjusting the filters or refreshing',
}}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
index 94af5b72831b..a9120629ecbd 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
@@ -18,7 +18,7 @@ import type {
AccountRelationshipDefinitionApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
-import { ACCOUNTS_HOGQL_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'
+import { ACCOUNTS_TABLE_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'
import { accountsColumnConfigLogic, ROLE_KEY_BY_NAME } from './accountsColumnConfigLogic'
import { AccountsEvents } from './constants'
@@ -28,7 +28,7 @@ export interface AccountRelationshipsLogicProps {
// Assignments also render as list columns.
function refreshAccountsList(): void {
- dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')
+ dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
index 76cc38556cb2..98ab6d675515 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
@@ -1,6 +1,5 @@
import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'
import type { DatabaseSchemaTable } from '~/queries/schema/schema-general'
-import type { DataWarehouseViewLink } from '~/types'
import type {
AccountRelationshipDefinitionApi,
@@ -57,7 +56,7 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
definition('11111111-2222-3333-4444-555555555555', 'Plan', { display_type: 'currency' }),
definition('66666666-7777-8888-9999-000000000000', 'Renewal', { display_type: 'date' }),
]
- const groups = buildAccountColumnGroups({}, [], defs)
+ const groups = buildAccountColumnGroups({}, defs)
const keys = groups.map((group) => group.key)
expect(keys[0]).toBe('account_properties')
@@ -84,22 +83,20 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
})
it('omits the group entirely when the team has no definitions', () => {
- const groups = buildAccountColumnGroups({}, [], [])
+ const groups = buildAccountColumnGroups({})
expect(groups.map((group) => group.key)).not.toContain('custom_properties')
})
it('round-trips the alias: extractDisplayLabel of the expression yields the column alias', () => {
const id = 'abcdabcd-1234-5678-9abc-def012345678'
- const group = buildAccountColumnGroups({}, [], [definition(id, 'Plan')]).find(
- (g) => g.key === 'custom_properties'
- )!
+ const group = buildAccountColumnGroups({}, [definition(id, 'Plan')]).find((g) => g.key === 'custom_properties')!
expect(extractDisplayLabel(group.options[0].expression)).toBe(customPropertyAlias(id))
})
it('relationships group offers legacy names for seeded definitions and rel_ aliases for others', () => {
const seeded = relationshipDefinition('11111111-2222-3333-4444-555555555555', 'CSM')
const custom = relationshipDefinition('66666666-7777-8888-9999-000000000000', 'Onboarding manager')
- const group = buildAccountColumnGroups({}, [], [], [seeded, custom]).find((g) => g.key === 'relationships')!
+ const group = buildAccountColumnGroups({}, [], [seeded, custom]).find((g) => g.key === 'relationships')!
expect(group.options).toEqual([
{ name: 'CSM', expression: 'csm' },
@@ -111,10 +108,10 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
})
it('omits the relationships group when the team has no definitions', () => {
- expect(buildAccountColumnGroups({}, [], [], []).map((group) => group.key)).not.toContain('relationships')
+ expect(buildAccountColumnGroups({}).map((group) => group.key)).not.toContain('relationships')
})
- it('limits the picker to Postgres-backed groups when HogQL cleanup is enabled', () => {
+ it('only offers Postgres-backed groups', () => {
const table = (name: string, fields: Record<string, Record<string, unknown>>): DatabaseSchemaTable =>
({ name, fields }) as unknown as DatabaseSchemaTable
const allTablesMap = {
@@ -139,34 +136,14 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
account_enrichment: table('account_enrichment', { score: { name: 'score', type: 'float' } }),
'warehouse.accounts': table('warehouse.accounts', { tier: { name: 'tier', type: 'string' } }),
}
- const warehouseJoins = [
- {
- source_table_name: 'system.accounts',
- field_name: 'warehouse_account',
- joining_table_name: 'warehouse.accounts',
- } as DataWarehouseViewLink,
- ]
const customDefinition = definition('11111111-2222-3333-4444-555555555555', 'Plan')
const relationship = relationshipDefinition('66666666-7777-8888-9999-000000000000', 'CSM')
- const unrestrictedKeys = buildAccountColumnGroups(
- allTablesMap,
- warehouseJoins,
- [customDefinition],
- [relationship]
- ).map((group) => group.key)
- const restrictedKeys = buildAccountColumnGroups(
- allTablesMap,
- warehouseJoins,
- [customDefinition],
- [relationship],
- true
- ).map((group) => group.key)
-
- expect(unrestrictedKeys).toEqual(
- expect.arrayContaining(['accounts.enrichment', 'accounts.warehouse_account', 'sql_expression'])
+ const keys = buildAccountColumnGroups(allTablesMap, [customDefinition], [relationship]).map(
+ (group) => group.key
)
- expect(restrictedKeys).toEqual([
+
+ expect(keys).toEqual([
'account_properties',
'relationships',
'custom_properties',
@@ -219,7 +196,6 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
label: 'billing',
options: [{ name: 'plan_name', expression: 'accounts.billing.plan_name AS plan_name' }],
},
- { key: 'sql_expression', label: 'SQL expression', options: [], isFreeform: true },
]
it('filterColumnOptions spans all non-freeform groups and marks already-selected expressions', () => {
@@ -238,10 +214,9 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
])
})
- it('filterColumnOptions narrows to the active group and yields nothing for freeform groups', () => {
+ it('filterColumnOptions narrows to the active group', () => {
expect(filterColumnOptions(pickerGroups, pickerGroups[1], '', []).map((option) => option.name)).toEqual([
'plan_name',
])
- expect(filterColumnOptions(pickerGroups, pickerGroups[2], '', [])).toEqual([])
})
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index f8deddb83d62..fddcb2334b47 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -2,8 +2,6 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, redu
import { loaders } from 'kea-loaders'
import type { SimpleOption } from 'lib/components/TaxonomicFilter/types'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { objectsEqual } from 'lib/utils/objects'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { projectLogic } from 'scenes/projectLogic'
@@ -11,9 +9,8 @@ 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 { AccountsTableAccountField, DatabaseSchemaField, DatabaseSchemaTable } from '~/queries/schema/schema-general'
import { PropertyDefinitionType, PropertyType } from '~/types'
-import type { DataWarehouseViewLink } from '~/types'
import {
accountRelationshipDefinitionsList,
@@ -23,7 +20,6 @@ import type {
AccountRelationshipDefinitionApi,
CustomPropertyDefinitionApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
-import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
import { propertyTypeForDisplayType } from './accountsCustomPropertyFilters'
@@ -49,7 +45,7 @@ export function isLegacyRoleColumn(column: string): column is AccountRoleKey {
// Pre-load seed only — `defaultSelectColumns` appends one relationship column per
// definition once the team's definitions load.
-export const ACCOUNTS_HOGQL_DEFAULT_SELECT: string[] = [
+export const ACCOUNTS_DEFAULT_COLUMNS: string[] = [
ACCOUNTS_NAME_COLUMN,
'accounts.tags.names AS tag_names',
'accounts.notebooks.count AS notebook_count',
@@ -80,18 +76,7 @@ export const ACCOUNTS_COLUMN_CONFIG_KEY = 'customer_analytics_accounts_columns'
// `system.accounts`), matching `resolve_visible_table_names()` on the backend.
export const ACCOUNTS_ACCOUNTS_TABLE_NAME = 'system.accounts'
-// The data-warehouse-join API normalizes source_table_name via
-// `table.to_printed_hogql()` which, for system PostgresTables, returns the
-// unqualified name. Compare against both forms so we catch joins regardless
-// of which name the backend hands us.
-const ACCOUNTS_JOIN_SOURCE_TABLE_NAMES = new Set(['accounts', ACCOUNTS_ACCOUNTS_TABLE_NAME])
-
-export type AccountColumnGroupKey =
- | 'account_properties'
- | 'custom_properties'
- | 'relationships'
- | 'sql_expression'
- | `accounts.${string}`
+export type AccountColumnGroupKey = 'account_properties' | 'custom_properties' | 'relationships' | `accounts.${string}`
export const ALL_COLUMNS_KEY = 'all'
export type PickerGroupKey = AccountColumnGroupKey | typeof ALL_COLUMNS_KEY
@@ -184,7 +169,6 @@ export type AccountColumnGroup = {
key: AccountColumnGroupKey
label: string
options: AccountColumnOption[]
- isFreeform?: boolean
}
export type AccountPickerColumnOption = AccountColumnOption & { groupLabel: string; isSelected: boolean }
@@ -196,10 +180,7 @@ export function filterColumnOptions(
search: string,
selectColumns: string[]
): AccountPickerColumnOption[] {
- if (activeGroup?.isFreeform) {
- return []
- }
- const searchableGroups = activeGroup ? [activeGroup] : groups.filter((group) => !group.isFreeform)
+ const searchableGroups = activeGroup ? [activeGroup] : groups
const query = search.trim().toLowerCase()
const selected = new Set(selectColumns)
return searchableGroups.flatMap((group) =>
@@ -222,6 +203,7 @@ const JOIN_FIELD_TYPES = new Set(['lazy_table', 'virtual_table', 'view', 'materi
// their raw backing tables (account_id + a JSON blob) would just duplicate them.
const HIDDEN_JOIN_GROUPS = new Set(['custom_properties', 'relationships'])
const POSTGRES_BACKED_JOIN_GROUPS = new Set(['tags', 'notebooks'])
+const POSTGRES_BACKED_ACCOUNT_FIELDS = new Set<string>(Object.values(AccountsTableAccountField))
// Field types we omit from the "Account properties" group — these are
// navigation aliases, joined tables (handled separately), or unknown types.
@@ -279,10 +261,8 @@ function relationshipOptions(definitions: AccountRelationshipDefinitionApi[]): A
export function buildAccountColumnGroups(
allTablesMap: Record<string, DatabaseSchemaTable> | null | undefined,
- warehouseJoins: DataWarehouseViewLink[],
customPropertyDefinitions: CustomPropertyDefinitionApi[] = [],
- relationshipDefinitions: AccountRelationshipDefinitionApi[] = [],
- postgresColumnsOnly = false
+ relationshipDefinitions: AccountRelationshipDefinitionApi[] = []
): AccountColumnGroup[] {
const accountsTable = allTablesMap?.[ACCOUNTS_ACCOUNTS_TABLE_NAME]
const directOptions: AccountColumnOption[] = []
@@ -303,17 +283,14 @@ export function buildAccountColumnGroups(
if (accountsTable) {
for (const field of Object.values(accountsTable.fields)) {
if (JOIN_FIELD_TYPES.has(field.type)) {
- if (
- HIDDEN_JOIN_GROUPS.has(field.name) ||
- (postgresColumnsOnly && !POSTGRES_BACKED_JOIN_GROUPS.has(field.name))
- ) {
+ if (HIDDEN_JOIN_GROUPS.has(field.name) || !POSTGRES_BACKED_JOIN_GROUPS.has(field.name)) {
continue
}
const joinedTable = field.table ? allTablesMap?.[field.table] : undefined
addJoinGroup(field.name, joinOptionsFromSchema(field, joinedTable))
continue
}
- if (SKIPPED_DIRECT_FIELD_TYPES.has(field.type)) {
+ if (SKIPPED_DIRECT_FIELD_TYPES.has(field.type) || !POSTGRES_BACKED_ACCOUNT_FIELDS.has(field.name)) {
continue
}
directOptions.push({
@@ -324,29 +301,6 @@ export function buildAccountColumnGroups(
}
}
- // Data-warehouse joins targeting `system.accounts` are returned in the
- // separate `joins` array on the schema response (loaded by `joinsLogic`),
- // not inside the source table's `fields`. Surface them as additional
- // first-class column groups so users don't have to drop to SQL.
- if (!postgresColumnsOnly) {
- for (const join of warehouseJoins) {
- if (
- !join.source_table_name ||
- !ACCOUNTS_JOIN_SOURCE_TABLE_NAMES.has(join.source_table_name) ||
- !join.field_name ||
- !join.joining_table_name
- ) {
- continue
- }
- const joinedTable = allTablesMap?.[join.joining_table_name]
- if (!joinedTable) {
- continue
- }
- const columnNames = Object.keys(joinedTable.fields)
- addJoinGroup(join.field_name, buildJoinOptions(join.field_name, columnNames, joinedTable))
- }
- }
-
// Omit definition-driven groups entirely when the team has no definitions, so the
// category dropdown doesn't show empty entries.
const customPropertyGroups: AccountColumnGroup[] =
@@ -375,9 +329,6 @@ export function buildAccountColumnGroups(
...relationshipGroups,
...customPropertyGroups,
...joinGroups,
- ...(postgresColumnsOnly
- ? []
- : [{ key: 'sql_expression' as const, label: 'SQL expression', options: [], isFreeform: true }]),
]
}
@@ -385,9 +336,6 @@ export function buildAccountColumnGroups(
export interface accountsColumnConfigLogicValues {
allTablesMap: Record<string, DatabaseSchemaTable> // databaseTableListLogic
databaseLoading: boolean // databaseTableListLogic
- featureFlags: FeatureFlagsSet // featureFlagLogic
- warehouseJoins: DataWarehouseViewLink[] // joinsLogic
- warehouseJoinsLoading: boolean // joinsLogic
currentProjectId: number | null // projectLogic
currentTeamId: number | null // teamLogic
accountsColumnGroups: AccountColumnGroup[]
@@ -410,11 +358,9 @@ export interface accountsColumnConfigLogicValues {
editingColumn: string | null
editingColumnIndex: number | null
filteredColumnOptions: AccountPickerColumnOption[]
- hogqlCleanupEnabled: boolean
pickerGroupKey: PickerGroupKey
pickerSearch: string
pickerSearchPlaceholder: string
- pickerSqlInput: string
querySelectColumns: string[]
relationshipDefinitions: AccountRelationshipDefinitionApi[]
relationshipDefinitionsLoaded: boolean
@@ -440,10 +386,6 @@ export interface accountsColumnConfigLogicActions {
force?: boolean
shallow?: boolean
} // databaseTableListLogic
- loadJoins: () => any // joinsLogic
- addSqlExpression: () => {
- value: true
- }
hideColumnConfigurator: () => {
value: true
}
@@ -509,9 +451,6 @@ export interface accountsColumnConfigLogicActions {
setPickerSearch: (search: string) => {
search: string
}
- setPickerSqlInput: (sqlInput: string) => {
- sqlInput: string
- }
setSelectColumns: (columns: string[]) => {
columns: string[]
}
@@ -521,13 +460,6 @@ export interface accountsColumnConfigLogicActions {
unselectColumn: (column: string) => {
column: string
}
- updateColumnExpression: (
- index: number,
- expression: string
- ) => {
- expression: string
- index: number
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -545,13 +477,10 @@ export interface accountsColumnConfigLogicMeta {
columnDisplay: AccountColumnDisplayState
) => string[]
visibleColumnNames: (querySelectColumns: string[]) => string[]
- hogqlCleanupEnabled: (featureFlags: FeatureFlagsSet) => boolean
accountsColumnGroups: (
allTablesMap: Record<string, DatabaseSchemaTable>,
- warehouseJoins: DataWarehouseViewLink[],
customPropertyDefinitions: CustomPropertyDefinitionApi[],
- relationshipDefinitions: AccountRelationshipDefinitionApi[],
- hogqlCleanupEnabled: boolean
+ relationshipDefinitions: AccountRelationshipDefinitionApi[]
) => AccountColumnGroup[]
activePickerGroup: (
accountsColumnGroups: AccountColumnGroup[],
@@ -602,14 +531,10 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
['currentTeamId'],
projectLogic,
['currentProjectId'],
- featureFlagLogic,
- ['featureFlags'],
databaseTableListLogic,
['allTablesMap', 'databaseLoading'],
- joinsLogic,
- ['joins as warehouseJoins', 'joinsLoading as warehouseJoinsLoading'],
],
- actions: [databaseTableListLogic, ['loadDatabase', 'ensureAllTableFields'], joinsLogic, ['loadJoins']],
+ actions: [databaseTableListLogic, ['loadDatabase', 'ensureAllTableFields']],
// Keep propertyDefinitionsModel mounted so the seeded custom-property definitions
// (see loadCustomPropertyDefinitionsSuccess) survive until the filter UI reads them.
logic: [propertyDefinitionsModel],
@@ -628,15 +553,12 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
}),
setColumnDisplayConfig: (config: AccountColumnDisplayState) => ({ config }),
setEditingColumnIndex: (index: number | null) => ({ index }),
- updateColumnExpression: (index: number, expression: string) => ({ index, expression }),
setPickerGroupKey: (key: PickerGroupKey) => ({ key }),
setPickerSearch: (search: string) => ({ search }),
- setPickerSqlInput: (sqlInput: string) => ({ sqlInput }),
- addSqlExpression: true,
}),
reducers({
selectColumns: [
- [...ACCOUNTS_HOGQL_DEFAULT_SELECT],
+ [...ACCOUNTS_DEFAULT_COLUMNS],
{
setSelectColumns: (_, { columns }) => ensureNameColumn(columns),
selectColumn: (state, { column }) => (state.includes(column) ? state : [...state, column]),
@@ -651,14 +573,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
next.splice(newIndex, 0, removed)
return next
},
- resetColumns: () => [...ACCOUNTS_HOGQL_DEFAULT_SELECT],
- updateColumnExpression: (state, { index, expression }) => {
- const next = expression.trim()
- if (!next || index < 0 || index >= state.length || state[index] === ACCOUNTS_NAME_COLUMN) {
- return state
- }
- return state.map((column, i) => (i === index ? next : column))
- },
+ resetColumns: () => [...ACCOUNTS_DEFAULT_COLUMNS],
},
],
// Which visible-column row the configurator's edit section targets. Any action that
@@ -667,7 +582,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
null as number | null,
{
setEditingColumnIndex: (_, { index }) => index,
- updateColumnExpression: () => null,
setSelectColumns: () => null,
unselectColumn: () => null,
moveColumn: () => null,
@@ -696,12 +610,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
setPickerGroupKey: () => '',
},
],
- pickerSqlInput: [
- '',
- {
- setPickerSqlInput: (_, { sqlInput }) => sqlInput,
- },
- ],
columnDisplay: [
{} as AccountColumnDisplayState,
{
@@ -752,7 +660,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
defaultSelectColumns: [
(s) => [s.relationshipDefinitions],
(relationshipDefinitions: AccountRelationshipDefinitionApi[]): string[] => [
- ...ACCOUNTS_HOGQL_DEFAULT_SELECT,
+ ...ACCOUNTS_DEFAULT_COLUMNS,
...relationshipDefinitions.map(
(definition) =>
ROLE_KEY_BY_NAME[definition.name] ??
@@ -783,33 +691,14 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
(s) => [s.querySelectColumns],
(querySelectColumns: string[]): string[] => querySelectColumns.map((c) => extractDisplayLabel(c)),
],
- hogqlCleanupEnabled: [
- (s) => [s.featureFlags],
- (featureFlags: FeatureFlagsSet): boolean =>
- !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP],
- ],
accountsColumnGroups: [
- (s) => [
- s.allTablesMap,
- s.warehouseJoins,
- s.customPropertyDefinitions,
- s.relationshipDefinitions,
- s.hogqlCleanupEnabled,
- ],
+ (s) => [s.allTablesMap, s.customPropertyDefinitions, s.relationshipDefinitions],
(
allTablesMap: Record<string, DatabaseSchemaTable>,
- warehouseJoins: DataWarehouseViewLink[],
customPropertyDefinitions: CustomPropertyDefinitionApi[],
- relationshipDefinitions: AccountRelationshipDefinitionApi[],
- hogqlCleanupEnabled: boolean
+ relationshipDefinitions: AccountRelationshipDefinitionApi[]
): AccountColumnGroup[] =>
- buildAccountColumnGroups(
- allTablesMap,
- warehouseJoins,
- customPropertyDefinitions,
- relationshipDefinitions,
- hogqlCleanupEnabled
- ),
+ buildAccountColumnGroups(allTablesMap, customPropertyDefinitions, relationshipDefinitions),
],
activePickerGroup: [
(s) => [s.accountsColumnGroups, s.pickerGroupKey],
@@ -831,11 +720,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
pickerSearchPlaceholder: [
(s) => [s.activePickerGroup],
(activePickerGroup: AccountColumnGroup | null): string =>
- activePickerGroup?.isFreeform
- ? 'Use the SQL expression panel below'
- : activePickerGroup
- ? `Search ${activePickerGroup.label.toLowerCase()}`
- : 'Search all columns',
+ activePickerGroup ? `Search ${activePickerGroup.label.toLowerCase()}` : 'Search all columns',
],
customPropertyDefinitionsById: [
(s) => [s.customPropertyDefinitions],
@@ -939,13 +824,6 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
actions.setSelectColumns(values.defaultSelectColumns)
}
},
- addSqlExpression: () => {
- const expression = values.pickerSqlInput.trim()
- if (expression) {
- actions.selectColumn(expression)
- actions.setPickerSqlInput('')
- }
- },
})),
afterMount(({ actions, values }) => {
// Lazily fetch the database schema only if it isn't already in flight / loaded.
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.test.ts
index 3116ff031bcf..bb402210a3f9 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.test.ts
@@ -1,149 +1,22 @@
-import { AccountCustomPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+import { PropertyOperator, PropertyType } 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}"`
+import { ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST, propertyTypeForDisplayType } from './accountsCustomPropertyFilters'
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()
+ ['number', PropertyType.Numeric],
+ ['currency', PropertyType.Numeric],
+ ['percent', PropertyType.Numeric],
+ ['boolean', PropertyType.Boolean],
+ ['date', PropertyType.DateTime],
+ ['datetime', PropertyType.DateTime],
+ ['text', PropertyType.String],
+ ] as const)('maps %s definitions to %s filters', (displayType, propertyType) => {
+ expect(propertyTypeForDisplayType(displayType)).toBe(propertyType)
})
- 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`])
+ it('does not offer regex operators for Postgres account filters', () => {
+ expect(ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST).not.toContain(PropertyOperator.Regex)
+ expect(ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST).not.toContain(PropertyOperator.NotRegex)
})
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts
index 89322ec9b35b..5708b96841a2 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsCustomPropertyFilters.ts
@@ -1,12 +1,6 @@
-import { isUUIDLike } from 'lib/utils/guards'
+import { PropertyOperator, PropertyType } from '~/types'
-import { escapeHogQLString, escapePropertyAsHogQLIdentifier } from '~/queries/utils'
-import { AccountCustomPropertyFilter, PropertyOperator, PropertyType } from '~/types'
-
-import type {
- CustomPropertyDefinitionApi,
- CustomPropertyDisplayTypeEnumApi,
-} from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { CustomPropertyDisplayTypeEnumApi } from 'products/customer_analytics/frontend/generated/api.schemas'
export function propertyTypeForDisplayType(displayType: CustomPropertyDisplayTypeEnumApi): PropertyType {
switch (displayType) {
@@ -24,15 +18,11 @@ export function propertyTypeForDisplayType(displayType: CustomPropertyDisplayTyp
}
}
-// 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,
@@ -43,154 +33,3 @@ export const ACCOUNT_CUSTOM_PROPERTY_OPERATOR_ALLOWLIST: PropertyOperator[] = [
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.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 5597a21e6dfd..1ed19e964116 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -3,19 +3,12 @@ import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
-import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
-import {
- AccountsTableCustomPropertyOperator,
- type AccountsQuery,
- type AccountsTableQuery,
-} from '~/queries/schema/schema-general'
+import { AccountsTableCustomPropertyOperator, type AccountsTableQuery } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import type { UserBasicType, UserType } from '~/types'
+import { PropertyFilterType, PropertyOperator, type UserBasicType, type UserType } from '~/types'
import {
accountRelationshipDefinitionsList,
@@ -30,23 +23,20 @@ import type {
AccountRelationshipApi,
AccountRelationshipDefinitionApi,
CustomPropertyDefinitionApi,
- CustomPropertyDisplayTypeEnumApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'
import {
- ACCOUNTS_HOGQL_DEFAULT_SELECT,
+ ACCOUNTS_DEFAULT_COLUMNS,
ACCOUNTS_NAME_COLUMN,
accountsColumnConfigLogic,
- customPropertyAlias,
relationshipAlias,
} from './accountsColumnConfigLogic'
import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'
import { accountsLogic, savingRoleKey } from './accountsLogic'
-// `hogqlQuery.source` is typed as the full DataTableNode source union; this logic
-// always produces an AccountsQuery, so narrow once for the orderBy assertions.
-const orderByOf = (source: unknown): AccountsQuery['orderBy'] => (source as AccountsQuery).orderBy
+const assignedToFilterOf = (query: AccountsTableQuery | null): number[] | undefined =>
+ query?.filters?.find((filter) => filter.kind === 'assigned_to')?.userIds
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
// Keep the real module for everything else — connected logics call other generated
@@ -78,7 +68,6 @@ const AE_DEFINITION_ID = '66666666-7777-8888-9999-aaaaaaaaaaaa'
const OWNER_DEFINITION_ID = 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff'
const TILE_FILTER = {
tileId: 'tile-1',
- expression: 'count() > 5',
filter: {
kind: 'custom_property' as const,
definitionId: CSM_DEFINITION_ID,
@@ -152,21 +141,7 @@ describe('accountsLogic', () => {
expect(logic.values.assignedToFilter).toEqual([])
})
- it('removes HogQL-only column groups when the cleanup flag is enabled', () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP]: true,
- })
-
- const config = accountsColumnConfigLogic.findMounted()!
- expect(config.values.hogqlCleanupEnabled).toBe(true)
- expect(config.values.accountsColumnGroups.map((group) => group.key)).not.toContain('sql_expression')
- })
-
- it('switches supported list queries to Postgres behind the execution flag', () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,
- })
-
+ it('runs the list and overview through typed Postgres queries', () => {
const source = logic.values.accountsQuerySource as AccountsTableQuery
expect(source.kind).toBe('AccountsTableQuery')
expect(source.columns).toEqual([
@@ -177,94 +152,46 @@ describe('accountsLogic', () => {
{ kind: 'relationship', definitionId: AE_DEFINITION_ID },
{ kind: 'relationship', definitionId: OWNER_DEFINITION_ID },
])
- expect(logic.values.metricsQuery?.kind).toBe('AccountsTableQuery')
- })
-
- it('keeps the DataTable data node on the active Postgres source for refreshes', () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,
+ expect(logic.values.metricsQuery).toMatchObject({
+ kind: 'AccountsTableQuery',
+ columns: [],
+ metrics: [{ kind: 'count' }],
})
+ })
+ it('keeps the DataTable on the typed source', () => {
expect(logic.values.accountsDataTableQuery.source.kind).toBe('AccountsTableQuery')
expect(logic.values.accountsDataTableQuery.columns).toEqual(logic.values.visibleColumnNames)
})
- it('keeps the previous positional response stable while switching runners', () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,
- })
- const previousRows = [
- { result: [{ id: 'account-id', name: 'Acme', external_id: 'acme' }, [], 0, [], [], []] },
- ] as DataTableRow[]
+ it('drops unsupported saved columns instead of falling back to HogQL', () => {
+ accountsColumnConfigLogic
+ .findMounted()!
+ .actions.setSelectColumns([...logic.values.selectColumns, 'arbitrary_hogql()'])
- expect(logic.values.tableRowsTransformer?.(previousRows)).toEqual(previousRows)
+ expect(logic.values.accountsQuerySource?.kind).toBe('AccountsTableQuery')
+ expect(logic.values.accountsDataTableQuery.columns).not.toContain('arbitrary_hogql()')
})
- it('keeps retained Postgres rows translated while a tile filter switches the runner to HogQL', () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,
- })
- const keyedRows = [
+ it('removes restored unsupported custom-property filters', () => {
+ logic.actions.loadCustomPropertyDefinitionsSuccess([
{
- result: {
- id: 'account-id',
- name: 'Acme',
- externalId: 'acme',
- accountFields: { name: 'Acme' },
- tags: ['enterprise'],
- noteCount: 2,
- relationships: Object.fromEntries(DEFINITIONS.map(({ id }) => [id, []])),
- customProperties: {},
- customPropertyHistory: {},
- },
- },
- ] as DataTableRow[]
-
- logic.actions.setTileFilter({ ...TILE_FILTER, tileId: 'tile', expression: 'count() > 1' })
-
- expect(logic.values.accountsQuerySource?.kind).toBe('AccountsQuery')
- expect(logic.values.tableRowsTransformer?.(keyedRows)[0].result).toEqual([
- { id: 'account-id', name: 'Acme', external_id: 'acme' },
- ['enterprise'],
- 2,
- [],
- [],
- [],
+ id: CSM_DEFINITION_ID,
+ name: 'Plan',
+ display_type: 'currency',
+ } as CustomPropertyDefinitionApi,
])
- })
-
- it('hides incompatible retained Postgres rows while an unsupported column switches to HogQL', () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,
- })
- const keyedRows = [
+ logic.actions.setCustomPropertyFilters([
{
- result: {
- id: 'account-id',
- name: 'Acme',
- accountFields: { name: 'Acme' },
- relationships: {},
- customProperties: {},
- customPropertyHistory: {},
- },
+ type: PropertyFilterType.AccountCustomProperty,
+ key: CSM_DEFINITION_ID,
+ operator: PropertyOperator.Regex,
+ value: 'enterprise.*',
},
- ] as DataTableRow[]
-
- accountsColumnConfigLogic
- .findMounted()!
- .actions.setSelectColumns([...logic.values.selectColumns, 'arbitrary_hogql()'])
-
- expect(logic.values.accountsQuerySource?.kind).toBe('AccountsQuery')
- expect(logic.values.tableRowsTransformer?.(keyedRows)).toEqual([])
- })
-
- it('keeps unsupported list state on the HogQL runner', () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,
- })
- logic.actions.setTileFilter({ ...TILE_FILTER, tileId: 'tile', expression: 'count() > 1' })
+ ])
- expect(logic.values.accountsQuerySource?.kind).toBe('AccountsQuery')
+ expect(logic.values.customPropertyFilters).toEqual([])
+ expect(logic.values.activeFilterCount).toBe(0)
})
it('setTagsFilter updates the reducer', () => {
@@ -297,19 +224,17 @@ describe('accountsLogic', () => {
resolveDefinitions!({ count: DEFINITIONS.length, results: DEFINITIONS })
await expectLogic(accountsColumnConfigLogic.findMounted()!).toFinishAllListeners()
- expect(logic.values.accountsQuerySource).toEqual(logic.values.hogqlQuery.source)
+ expect(logic.values.accountsQuerySource?.kind).toBe('AccountsTableQuery')
expect(logic.values.metricsQuery).not.toBeNull()
})
- it('keeps the overview tile metrics off the list query so it loads independently', () => {
- const source = logic.values.hogqlQuery.source as AccountsQuery
- expect(source.metrics).toBeUndefined()
+ it('keeps overview metrics off the list query', () => {
+ expect(logic.values.accountsQuerySource?.metrics).toBeUndefined()
})
- it('exposes the overview tile metrics on a separate Postgres metrics query', () => {
- const metricsQuery = logic.values.metricsQuery as AccountsTableQuery
- expect(metricsQuery.metrics).toEqual([{ kind: 'count' }])
- expect(metricsQuery.columns).toEqual([])
+ it('exposes overview metrics on a separate metrics-only query', () => {
+ expect(logic.values.metricsQuery?.metrics).toEqual([{ kind: 'count' }])
+ expect(logic.values.metricsQuery?.columns).toEqual([])
})
it('setAllRolesUnassigned toggles the flag', () => {
@@ -327,14 +252,14 @@ describe('accountsLogic', () => {
it('starts disabled and adds nothing to the query', () => {
expect(logic.values.assignedToCurrentUser).toBe(false)
expect(logic.values.assignedToFilter).toEqual([])
- expect((logic.values.hogqlQuery.source as AccountsQuery).assignedToUserIds).toBeUndefined()
+ expect(assignedToFilterOf(logic.values.accountsQuerySource)).toBeUndefined()
})
it('the "My accounts" checkbox resolves to the current user id', () => {
logic.actions.setAssignedToCurrentUser(true)
expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])
expect(logic.values.assignedToCurrentUser).toBe(true)
- expect((logic.values.hogqlQuery.source as AccountsQuery).assignedToUserIds).toEqual([CURRENT_USER_ID])
+ expect(assignedToFilterOf(logic.values.accountsQuerySource)).toEqual([CURRENT_USER_ID])
})
it('"My accounts" is checked only when the filter is exactly the current user', () => {
@@ -350,13 +275,13 @@ describe('accountsLogic', () => {
logic.actions.setAssignedToCurrentUser(true)
logic.actions.setAssignedToCurrentUser(false)
expect(logic.values.assignedToFilter).toEqual([])
- expect((logic.values.hogqlQuery.source as AccountsQuery).assignedToUserIds).toBeUndefined()
+ expect(assignedToFilterOf(logic.values.accountsQuerySource)).toBeUndefined()
})
it('the Assigned to picker accepts explicit ids', () => {
logic.actions.setAssignedToFilter([7, 9])
expect(logic.values.assignedToFilter).toEqual([7, 9])
- expect((logic.values.hogqlQuery.source as AccountsQuery).assignedToUserIds).toEqual([7, 9])
+ expect(assignedToFilterOf(logic.values.accountsQuerySource)).toEqual([7, 9])
})
it('counts toward activeFilterCount', () => {
@@ -398,7 +323,7 @@ describe('accountsLogic', () => {
expect(logic.values.assignedToFilter).toEqual([7])
expect(logic.values.assignedToCurrentUser).toBe(false)
- expect((logic.values.hogqlQuery.source as AccountsQuery).assignedToUserIds).toEqual([7])
+ expect(assignedToFilterOf(logic.values.accountsQuerySource)).toEqual([7])
})
it('restores a legacy mine=true link as the current user', async () => {
@@ -480,110 +405,21 @@ describe('accountsLogic', () => {
})
describe('sortOrder', () => {
- it('starts unset and produces no orderBy on the AccountsQuery', () => {
- expect(logic.values.sortOrder).toBeNull()
- expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()
- })
-
- it('toggleSort on a fresh column starts ascending', () => {
+ it('adds a typed server-side sort after pagination', () => {
+ logic.actions.listLoadNextData()
logic.actions.toggleSort('notebook_count')
- expect(logic.values.sortOrder).toEqual({ column: 'notebook_count', direction: 'asc' })
- })
- it('toggleSort cycles asc -> desc -> null on repeated clicks', () => {
- logic.actions.toggleSort('notebook_count')
- expect(logic.values.sortOrder?.direction).toBe('asc')
- logic.actions.toggleSort('notebook_count')
- expect(logic.values.sortOrder).toEqual({ column: 'notebook_count', direction: 'desc' })
- logic.actions.toggleSort('notebook_count')
- expect(logic.values.sortOrder).toBeNull()
+ expect(logic.values.accountsQuerySource?.sort).toEqual({
+ column: { kind: 'note_count' },
+ direction: 'asc',
+ })
})
- it('toggleSort on a different column resets to ascending', () => {
+ it('sorts a fully loaded page in the browser without changing the query', () => {
logic.actions.toggleSort('notebook_count')
- logic.actions.toggleSort('notebook_count') // desc
- logic.actions.toggleSort('csm')
- expect(logic.values.sortOrder).toEqual({ column: 'csm', direction: 'asc' })
- })
- it('leaves orderBy off while the full list is loaded, for instant client-side sort', () => {
- expect(logic.values.canSortClientSide).toBe(true)
- logic.actions.toggleSort('notebook_count')
- expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()
+ expect(logic.values.accountsQuerySource?.sort).toBeUndefined()
expect(logic.values.sortedRowsTransformer).toEqual(expect.any(Function))
- logic.actions.toggleSort('notebook_count') // desc
- expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()
- })
-
- it('adds orderBy once the list is paginated, for a global server-side sort', () => {
- logic.actions.listLoadNextData()
- expect(logic.values.canSortClientSide).toBe(false)
- logic.actions.toggleSort('notebook_count')
- expect(logic.values.sortedRowsTransformer).toBeUndefined()
- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['notebook_count'])
- logic.actions.toggleSort('notebook_count') // desc
- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['notebook_count DESC'])
- })
-
- it('returns to client-side sort after a fresh load re-evaluates pagination', () => {
- logic.actions.listLoadNextData()
- logic.actions.toggleSort('name')
- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['name'])
- logic.actions.listLoadData()
- expect(logic.values.canSortClientSide).toBe(true)
- expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()
- })
-
- it('skips the server orderBy when the sorted role column has no matching definition', () => {
- logic.actions.listLoadNextData()
- logic.actions.toggleSort('csm')
- 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.listLoadNextData()
- 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.listLoadNextData()
- logic.actions.toggleSort(alias)
- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual([alias])
- })
})
})
@@ -591,7 +427,7 @@ describe('accountsLogic', () => {
it('defaults to the base columns plus one column per definition, name column included', () => {
const config = accountsColumnConfigLogic.findMounted()
expect(config?.values.selectColumns).toEqual([
- ...ACCOUNTS_HOGQL_DEFAULT_SELECT,
+ ...ACCOUNTS_DEFAULT_COLUMNS,
'csm',
'account_executive',
'account_owner',
@@ -599,25 +435,23 @@ describe('accountsLogic', () => {
expect(config?.values.selectColumns).toContain(ACCOUNTS_NAME_COLUMN)
})
- it('translates legacy role columns through the relationships lazy join in the query select', () => {
- const source = logic.values.hogqlQuery.source as AccountsQuery
- expect(source.select).toEqual([
- ACCOUNTS_NAME_COLUMN,
- 'accounts.tags.names AS tag_names',
- 'accounts.notebooks.count AS notebook_count',
- `accounts.relationships.values.\`${CSM_DEFINITION_ID}\` AS csm`,
- `accounts.relationships.values.\`${AE_DEFINITION_ID}\` AS account_executive`,
- `accounts.relationships.values.\`${OWNER_DEFINITION_ID}\` AS account_owner`,
+ it('translates legacy role columns into typed relationship columns', () => {
+ expect(logic.values.accountsQuerySource?.columns).toEqual([
+ { kind: 'account_field', field: 'name' },
+ { kind: 'tags' },
+ { kind: 'note_count' },
+ { kind: 'relationship', definitionId: CSM_DEFINITION_ID },
+ { kind: 'relationship', definitionId: AE_DEFINITION_ID },
+ { kind: 'relationship', definitionId: OWNER_DEFINITION_ID },
])
})
it('drops legacy role columns from the query when no matching definition exists', () => {
accountsColumnConfigLogic.findMounted()?.actions.loadRelationshipDefinitionsSuccess([])
- const source = logic.values.hogqlQuery.source as AccountsQuery
- expect(source.select).toEqual([
- ACCOUNTS_NAME_COLUMN,
- 'accounts.tags.names AS tag_names',
- 'accounts.notebooks.count AS notebook_count',
+ expect(logic.values.accountsQuerySource?.columns).toEqual([
+ { kind: 'account_field', field: 'name' },
+ { kind: 'tags' },
+ { kind: 'note_count' },
])
expect(logic.values.visibleColumnNames).toEqual([ACCOUNTS_NAME_COLUMN, 'tag_names', 'notebook_count'])
})
@@ -629,7 +463,7 @@ describe('accountsLogic', () => {
{ id: 'def-os', name: 'Onboarding specialist', description: null, is_single_holder: true },
])
expect(config.values.selectColumns).toEqual([
- ...ACCOUNTS_HOGQL_DEFAULT_SELECT,
+ ...ACCOUNTS_DEFAULT_COLUMNS,
'csm',
'account_executive',
'account_owner',
@@ -722,9 +556,6 @@ describe('accountsLogic', () => {
})
it('translates restored URL state into the Postgres query', async () => {
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {
- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,
- })
router.actions.push(
urls.customerAnalyticsAccounts(),
{},
@@ -771,14 +602,15 @@ describe('accountsLogic', () => {
// `/customer_analytics/accounts/:accountId/:tab` filters the list to one account and opens a tab.
const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'
- const filterExpressionOf = (source: unknown): string | undefined => (source as AccountsQuery).filterExpression
+ const accountIdFilterOf = (query: AccountsTableQuery | null): string | undefined =>
+ query?.filters?.find((filter) => filter.kind === 'account_id')?.accountId
it('filters the list to the account, expands it, and opens the requested tab', async () => {
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.accountIdFilter).toBe(ACCOUNT_ID)
- expect(filterExpressionOf(logic.values.hogqlQuery.source)).toContain(`toString(id) = '${ACCOUNT_ID}'`)
+ expect(accountIdFilterOf(logic.values.accountsQuerySource)).toBe(ACCOUNT_ID)
const expansion = accountsExpansionLogic.findMounted()
expect(expansion?.values.expandedAccountIds).toContain(ACCOUNT_ID)
expect(expansion?.values.activeTabByAccount[ACCOUNT_ID]).toBe('usage')
@@ -814,10 +646,7 @@ describe('accountsLogic', () => {
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))
await expectLogic(logic).toFinishAllListeners()
- const source = logic.values.hogqlQuery.source as AccountsQuery
- expect(filterExpressionOf(source)).toBe(`(toString(id) = '${ACCOUNT_ID}')`)
- expect(source.search).toBeUndefined()
- expect(source.assignedToUserIds).toBeUndefined()
+ expect(logic.values.accountsQuerySource?.filters).toEqual([{ kind: 'account_id', accountId: ACCOUNT_ID }])
})
it('survives a view-state restore rewriting the URL', async () => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index fb06115009cf..c0be1205867e 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -2,9 +2,7 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, redu
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
-import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { isUUIDLike } from 'lib/utils/guards'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
@@ -17,7 +15,6 @@ import { tagsModel } from '~/models/tagsModel'
import { type DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import {
- AccountsQuery,
AccountsTableMetric,
AccountsTableQuery,
DataNode,
@@ -36,16 +33,14 @@ import {
import type { UserType } from '../../../../../frontend/src/types'
import {
- ACCOUNTS_HOGQL_DATA_NODE_KEY,
+ ACCOUNTS_TABLE_DATA_NODE_KEY,
ACCOUNTS_METRICS_DATA_NODE_KEY,
CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
} from '../../constants'
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 { accountsColumnConfigLogic, isLegacyRoleColumn } from './accountsColumnConfigLogic'
import type { AccountColumnDisplayState } from './accountsColumnConfigLogic'
-import { customPropertyFiltersToExpressions } from './accountsCustomPropertyFilters'
import {
ACCOUNT_EXPANSION_TABS,
AccountExpansionTab,
@@ -57,9 +52,10 @@ import { sortAccountRows } from './accountsSort'
import {
AccountsTableQueryPlan,
BuildAccountsTableQueryPlanInput,
- accountsTableRowsToLegacyRows,
+ accountsTableCell,
buildAccountsTableQueryPlan,
isAccountsTableRow,
+ supportedCustomPropertyFilters,
} from './accountsTableQuery'
import { normalizeRoleFilter } from './accountsViewState'
import { AccountsEvents } from './constants'
@@ -97,17 +93,6 @@ 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' | 'custom_property'
@@ -120,54 +105,6 @@ export type AccountSortDirection = 'asc' | 'desc'
export type AccountSortOrder = { column: AccountSortableColumn; direction: AccountSortDirection } | null
-interface AccountQueryFilters {
- searchQuery: string
- tagsFilter: string[]
- allRolesUnassigned: boolean
- assignedToFilter: RoleFilterValue
- accountIdFilter: string | null
- tileFilter: TileFilter | null
- customPropertyFilters: AccountCustomPropertyFilter[]
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
-}
-
-// Shared filter clauses for the list-rows query and the overview-metrics query,
-// so both always aggregate/list over the exact same set of accounts.
-function applyAccountFilters(source: AccountsQuery, filters: AccountQueryFilters): void {
- // A deep link pins the list to one account by its PK, and it has to resolve to that account for
- // whoever opens it. The viewer's own filters — a restored saved view, the persisted "my accounts"
- // toggle — would otherwise AND with the id and leave them on an empty list, so the pin wins alone.
- // The id is only ever a validated UUID (set from the route), so it's injection-safe. Compare it
- // stringified, matching how the name-cell id is built.
- if (filters.accountIdFilter) {
- source.filterExpression = `(toString(id) = '${filters.accountIdFilter}')`
- return
- }
- const trimmed = filters.searchQuery.trim()
- if (trimmed) {
- source.search = trimmed
- }
- if (filters.tagsFilter.length > 0) {
- source.tagNames = filters.tagsFilter
- }
- if (filters.allRolesUnassigned) {
- source.allRolesUnassigned = true
- }
- if (filters.assignedToFilter.length > 0) {
- source.assignedToUserIds = filters.assignedToFilter
- }
- const filterExpressions: string[] = []
- if (filters.tileFilter) {
- filterExpressions.push(filters.tileFilter.expression)
- }
- filterExpressions.push(
- ...customPropertyFiltersToExpressions(filters.customPropertyFilters, filters.customPropertyDefinitionsById)
- )
- if (filterExpressions.length > 0) {
- source.filterExpression = filterExpressions.map((expr) => `(${expr})`).join(' AND ')
- }
-}
-
export const savingRoleKey = (accountId: string, column: string): string => `${accountId}:${column}`
// Which accounts path the shareable view state gets written back to. It must be the path we are
@@ -212,20 +149,17 @@ export interface accountsLogicValues {
relationshipDefinitionsLoaded: boolean // accountsColumnConfigLogic
selectColumns: string[] // accountsColumnConfigLogic
visibleColumnNames: string[] // accountsColumnConfigLogic
- overviewMetrics: string[] // accountsOverviewTilesLogic
- overviewPostgresMetrics: AccountsTableMetric[] // accountsOverviewTilesLogic
+ overviewMetrics: AccountsTableMetric[] // accountsOverviewTilesLogic
tileFilter: TileFilter | null // accountsOverviewTilesLogic
mineOnly: boolean // customerAnalyticsSceneLogic
listHasMoreData: boolean // dataNodeLogic
- featureFlags: FeatureFlagsSet // featureFlagLogic
currentTeamId: number | null // teamLogic
user: UserType | null // userLogic
accountIdFilter: string | null
accountsDataTableQuery: DataTableNode
- accountsQuerySource: AccountsQuery | AccountsTableQuery | null
- accountsTableQueryPlan: AccountsTableQueryPlan | null
+ accountsQuerySource: AccountsTableQuery | null
+ accountsTableQueryPlan: AccountsTableQueryPlan
accountsTableQueryPlanInput: BuildAccountsTableQueryPlanInput
- accountsTableResponsePlan: AccountsTableQueryPlan | null
activeFilterCount: number
allRolesUnassigned: boolean
assignedToCurrentUser: boolean
@@ -233,12 +167,10 @@ export interface accountsLogicValues {
canSortClientSide: boolean
currentUserId: number | null
customPropertyFilters: AccountCustomPropertyFilter[]
- hogqlQuery: DataTableNode
isRoleSaving: (accountId: string, column: string) => boolean
isTagsSaving: (accountId: string) => boolean
listPaginated: boolean
- metricsQuery: AccountsQuery | AccountsTableQuery | null
- postgresAccountsEnabled: boolean
+ metricsQuery: AccountsTableQuery | null
relationshipOverrides: Record<string, number[]>
savingRoles: Record<string, true>
savingTags: Record<string, true>
@@ -246,7 +178,6 @@ export interface accountsLogicValues {
searchQuery: string
sortOrder: AccountSortOrder
sortedRowsTransformer: ((rows: DataTableRow[]) => DataTableRow[]) | undefined
- tableRowsTransformer: ((rows: DataTableRow[]) => DataTableRow[]) | undefined
tagOverrides: Record<string, string[]>
tagsFilter: string[]
viewUrlState: AccountsViewUrlState
@@ -254,6 +185,13 @@ export interface accountsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsLogicActions {
+ loadCustomPropertyDefinitionsSuccess: (
+ customPropertyDefinitions: CustomPropertyDefinitionApi[],
+ payload?: any
+ ) => {
+ customPropertyDefinitions: CustomPropertyDefinitionApi[]
+ payload?: any
+ } // accountsColumnConfigLogic
moveColumn: (
oldIndex: number,
newIndex: number
@@ -457,9 +395,8 @@ export interface accountsLogicMeta {
sortedRowsTransformer: (
canSortClientSide: boolean,
sortOrder: AccountSortOrder,
- visibleColumnNames: string[]
+ accountsTableQueryPlan: AccountsTableQueryPlan
) => ((rows: DataTableRow[]) => DataTableRow[]) | undefined
- postgresAccountsEnabled: (featureFlags: FeatureFlagsSet) => boolean
accountsTableQueryPlanInput: (
querySelectColumns: string[],
visibleColumnNames: string[],
@@ -477,54 +414,20 @@ export interface accountsLogicMeta {
) => BuildAccountsTableQueryPlanInput
accountsTableQueryPlan: (
accountsTableQueryPlanInput: BuildAccountsTableQueryPlanInput
- ) => AccountsTableQueryPlan | null
- accountsTableResponsePlan: (
- accountsTableQueryPlanInput: BuildAccountsTableQueryPlanInput
- ) => AccountsTableQueryPlan | null
- hogqlQuery: (
- searchQuery: string,
- tagsFilter: string[],
- allRolesUnassigned: boolean,
- assignedToFilter: RoleFilterValue,
- accountIdFilter: string | null,
- tileFilter: TileFilter | null,
- sortOrder: AccountSortOrder,
- canSortClientSide: boolean,
- querySelectColumns: string[],
- visibleColumnNames: string[],
- customPropertyFilters: AccountCustomPropertyFilter[],
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,
- aliasToDefinition: Record<string, CustomPropertyDefinitionApi>
- ) => DataTableNode
+ ) => AccountsTableQueryPlan
accountsQuerySource: (
- hogqlQuery: DataTableNode,
- accountsTableQueryPlan: AccountsTableQueryPlan | null,
- postgresAccountsEnabled: boolean,
+ accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean
- ) => AccountsQuery | AccountsTableQuery | null
+ ) => AccountsTableQuery | null
accountsDataTableQuery: (
- hogqlQuery: DataTableNode,
- accountsQuerySource: AccountsQuery | AccountsTableQuery | null,
- visibleColumnNames: string[]
+ accountsTableQueryPlan: AccountsTableQueryPlan,
+ accountsQuerySource: AccountsTableQuery | null
) => DataTableNode
- tableRowsTransformer: (
- accountsTableResponsePlan: AccountsTableQueryPlan | null,
- sortedRowsTransformer: ((rows: DataTableRow[]) => DataTableRow[]) | undefined
- ) => ((rows: DataTableRow[]) => DataTableRow[]) | undefined
metricsQuery: (
- overviewMetrics: string[],
- overviewPostgresMetrics: AccountsTableMetric[],
- accountsTableQueryPlanInput: BuildAccountsTableQueryPlanInput,
- searchQuery: string,
- tagsFilter: string[],
- allRolesUnassigned: boolean,
- assignedToFilter: RoleFilterValue,
- accountIdFilter: string | null,
- tileFilter: TileFilter | null,
- customPropertyFilters: AccountCustomPropertyFilter[],
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,
+ overviewMetrics: AccountsTableMetric[],
+ accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean
- ) => AccountsQuery | AccountsTableQuery | null
+ ) => AccountsTableQuery | null
}
}
@@ -543,8 +446,6 @@ export const accountsLogic = kea<accountsLogicType>([
['currentTeamId'],
userLogic,
['user'],
- featureFlagLogic,
- ['featureFlags'],
accountsColumnConfigLogic,
[
'selectColumns',
@@ -558,15 +459,16 @@ export const accountsLogic = kea<accountsLogicType>([
'columnDisplay',
],
accountsOverviewTilesLogic,
- ['metrics as overviewMetrics', 'postgresMetrics as overviewPostgresMetrics', 'tileFilter'],
+ ['metrics as overviewMetrics', 'tileFilter'],
customerAnalyticsSceneLogic,
['mineOnly'],
- dataNodeLogic({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY } as DataNodeLogicProps),
+ dataNodeLogic({ key: ACCOUNTS_TABLE_DATA_NODE_KEY } as DataNodeLogicProps),
['hasMoreData as listHasMoreData'],
],
actions: [
accountsColumnConfigLogic,
[
+ 'loadCustomPropertyDefinitionsSuccess',
'setSelectColumns',
'selectColumn',
'unselectColumn',
@@ -585,7 +487,7 @@ export const accountsLogic = kea<accountsLogicType>([
['loadUserSuccess'],
membersLogic,
['ensureAllMembersLoaded'],
- dataNodeLogic({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY } as DataNodeLogicProps),
+ dataNodeLogic({ key: ACCOUNTS_TABLE_DATA_NODE_KEY } as DataNodeLogicProps),
['loadData as listLoadData', 'loadNextData as listLoadNextData'],
],
})),
@@ -712,7 +614,7 @@ export const accountsLogic = kea<accountsLogicType>([
},
],
// Assignments written from the list, keyed `${accountId}:${column}` — masks the
- // stale HogQL cell until the async refetch lands.
+ // stale fetched cell until the async refetch lands.
relationshipOverrides: [
{} as Record<string, number[]>,
{
@@ -733,7 +635,7 @@ export const accountsLogic = kea<accountsLogicType>([
},
},
],
- // Tags written from the list, keyed by account id — masks the stale HogQL
+ // Tags written from the list, keyed by account id, mask the stale fetched
// cell until the async refetch lands.
tagOverrides: [
{} as Record<string, string[]>,
@@ -851,21 +753,19 @@ export const accountsLogic = kea<accountsLogicType>([
(listHasMoreData: boolean, listPaginated: boolean): boolean => !listHasMoreData && !listPaginated,
],
sortedRowsTransformer: [
- (s) => [s.canSortClientSide, s.sortOrder, s.visibleColumnNames],
+ (s) => [s.canSortClientSide, s.sortOrder, s.accountsTableQueryPlan],
(
canSortClientSide: boolean,
sortOrder: AccountSortOrder,
- visibleColumnNames: string[]
+ plan: AccountsTableQueryPlan
): ((rows: DataTableRow[]) => DataTableRow[]) | undefined =>
canSortClientSide && sortOrder
- ? (rows: DataTableRow[]): DataTableRow[] => sortAccountRows(rows, sortOrder, visibleColumnNames)
+ ? (rows: DataTableRow[]): DataTableRow[] =>
+ sortAccountRows(rows, sortOrder, (record, column) =>
+ isAccountsTableRow(record) ? accountsTableCell(record, column, plan) : undefined
+ )
: undefined,
],
- postgresAccountsEnabled: [
- (s) => [s.featureFlags],
- (featureFlags: FeatureFlagsSet): boolean =>
- !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES],
- ],
accountsTableQueryPlanInput: [
(s) => [
s.querySelectColumns,
@@ -914,206 +814,68 @@ export const accountsLogic = kea<accountsLogicType>([
],
accountsTableQueryPlan: [
(s) => [s.accountsTableQueryPlanInput],
- (input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan | null =>
- buildAccountsTableQueryPlan(input),
- ],
- accountsTableResponsePlan: [
- (s) => [s.accountsTableQueryPlanInput],
- (input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan | null =>
- buildAccountsTableQueryPlan({ ...input, tileFilter: null }),
+ (input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan => buildAccountsTableQueryPlan(input),
],
- hogqlQuery: [
- (s) => [
- s.searchQuery,
- s.tagsFilter,
- s.allRolesUnassigned,
- s.assignedToFilter,
- s.accountIdFilter,
- s.tileFilter,
- s.sortOrder,
- s.canSortClientSide,
- s.querySelectColumns,
- s.visibleColumnNames,
- s.customPropertyFilters,
- s.customPropertyDefinitionsById,
- s.aliasToDefinition,
- ],
- (
- searchQuery: string,
- tagsFilter: string[],
- allRolesUnassigned: boolean,
- assignedToFilter: RoleFilterValue,
- accountIdFilter: string | null,
- tileFilter: TileFilter | null,
- sortOrder: AccountSortOrder,
- canSortClientSide: boolean,
- querySelectColumns: string[],
- visibleColumnNames: string[],
- customPropertyFilters: AccountCustomPropertyFilter[],
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,
- aliasToDefinition: Record<string, CustomPropertyDefinitionApi>
- ): DataTableNode => {
- const source: AccountsQuery = {
- kind: NodeKind.AccountsQuery,
- select: querySelectColumns,
- tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_list' },
- }
- applyAccountFilters(source, {
- searchQuery,
- tagsFilter,
- allRolesUnassigned,
- 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
- // (a legacy role with no matching definition) — the alias wouldn't resolve.
- if (sortOrder && !canSortClientSide && visibleColumnNames.includes(sortOrder.column)) {
- const expr = orderByExpression(sortOrder.column, aliasToDefinition)
- source.orderBy = [sortOrder.direction === 'asc' ? expr : `${expr} DESC`]
- }
- return {
- kind: NodeKind.DataTableNode,
- source,
- full: true,
- // Suppress DataTable's built-in sort indicator on column
- // headers — our `SortableColumnHeader` renders its own.
- allowSorting: true,
- }
- },
- ],
- // What the list data node actually runs: null until the relationship
- // definitions settle, so the list fetches once with its final columns
- // instead of fetching base columns and refetching after the upgrade.
accountsQuerySource: [
- (s) => [s.hogqlQuery, s.accountsTableQueryPlan, s.postgresAccountsEnabled, s.relationshipDefinitionsLoaded],
+ (s) => [s.accountsTableQueryPlan, s.relationshipDefinitionsLoaded],
(
- hogqlQuery: DataTableNode,
- accountsTableQueryPlan: AccountsTableQueryPlan | null,
- postgresAccountsEnabled: boolean,
+ accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean
- ): AccountsQuery | AccountsTableQuery | null => {
- if (!relationshipDefinitionsLoaded) {
- return null
- }
- return postgresAccountsEnabled && accountsTableQueryPlan
- ? accountsTableQueryPlan.query
- : (hogqlQuery.source as AccountsQuery)
- },
+ ): AccountsTableQuery | null => (relationshipDefinitionsLoaded ? accountsTableQueryPlan.query : null),
],
accountsDataTableQuery: [
- (s) => [s.hogqlQuery, s.accountsQuerySource, s.visibleColumnNames],
+ (s) => [s.accountsTableQueryPlan, s.accountsQuerySource],
(
- hogqlQuery: DataTableNode,
- accountsQuerySource: AccountsQuery | AccountsTableQuery | null,
- visibleColumnNames: string[]
+ accountsTableQueryPlan: AccountsTableQueryPlan,
+ accountsQuerySource: AccountsTableQuery | null
): DataTableNode => ({
- ...hogqlQuery,
- columns: visibleColumnNames,
- source: accountsQuerySource ?? hogqlQuery.source,
+ kind: NodeKind.DataTableNode,
+ columns: accountsTableQueryPlan.columns.map((column) => column.visibleName),
+ source: accountsQuerySource ?? accountsTableQueryPlan.query,
+ full: true,
+ allowSorting: true,
}),
],
- tableRowsTransformer: [
- (s) => [s.accountsTableResponsePlan, s.sortedRowsTransformer],
- (
- accountsTableResponsePlan: AccountsTableQueryPlan | null,
- sortedRowsTransformer: ((rows: DataTableRow[]) => DataTableRow[]) | undefined
- ): ((rows: DataTableRow[]) => DataTableRow[]) | undefined =>
- (rows: DataTableRow[]): DataTableRow[] => {
- const rowResults = rows.map((row) => row.result)
- if (!rowResults.some(isAccountsTableRow)) {
- return sortedRowsTransformer ? sortedRowsTransformer(rows) : rows
- }
- if (!accountsTableResponsePlan || !rowResults.every(isAccountsTableRow)) {
- return []
- }
- const translatedResults = accountsTableRowsToLegacyRows(rowResults, accountsTableResponsePlan)
- const translatedRows = rows.map((row, index) => ({
- ...row,
- result: translatedResults[index],
- }))
- return sortedRowsTransformer ? sortedRowsTransformer(translatedRows) : translatedRows
- },
- ],
- // The overview-tile aggregations run as their own metrics-only query (no
- // `select`), keyed to ACCOUNTS_METRICS_DATA_NODE_KEY, so they load
- // independently of the list rows. Null when there are no tiles — the
- // data node then stays idle. Shares the list's filters so tiles
- // aggregate over the same set the table shows.
metricsQuery: [
- (s) => [
- s.overviewMetrics,
- s.overviewPostgresMetrics,
- s.accountsTableQueryPlanInput,
- s.searchQuery,
- s.tagsFilter,
- s.allRolesUnassigned,
- s.assignedToFilter,
- s.accountIdFilter,
- s.tileFilter,
- s.customPropertyFilters,
- s.customPropertyDefinitionsById,
- s.relationshipDefinitionsLoaded,
- ],
+ (s) => [s.overviewMetrics, s.accountsTableQueryPlan, s.relationshipDefinitionsLoaded],
(
- overviewMetrics: string[],
- overviewPostgresMetrics: AccountsTableMetric[],
- accountsTableQueryPlanInput: BuildAccountsTableQueryPlanInput,
- searchQuery: string,
- tagsFilter: string[],
- allRolesUnassigned: boolean,
- assignedToFilter: RoleFilterValue,
- accountIdFilter: string | null,
- tileFilter: TileFilter | null,
- customPropertyFilters: AccountCustomPropertyFilter[],
- customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,
+ overviewMetrics: AccountsTableMetric[],
+ accountsTableQueryPlan: AccountsTableQueryPlan,
relationshipDefinitionsLoaded: boolean
- ): AccountsQuery | AccountsTableQuery | null => {
+ ): AccountsTableQuery | null => {
if (overviewMetrics.length === 0 || !relationshipDefinitionsLoaded) {
return null
}
- const postgresPlan = buildAccountsTableQueryPlan({
- ...accountsTableQueryPlanInput,
- querySelectColumns: [],
- visibleColumnNames: [],
- sortOrder: null,
- canSortClientSide: true,
- })
- if (postgresPlan && overviewPostgresMetrics.length === overviewMetrics.length) {
- return {
- ...postgresPlan.query,
- columns: [],
- metrics: overviewPostgresMetrics,
- sort: undefined,
- tags: {
- ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
- name: 'customer_analytics_accounts_overview',
- },
- }
- }
- const source: AccountsQuery = {
- kind: NodeKind.AccountsQuery,
+ return {
+ ...accountsTableQueryPlan.query,
+ columns: [],
metrics: overviewMetrics,
+ sort: undefined,
tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_overview' },
}
- applyAccountFilters(source, {
- searchQuery,
- tagsFilter,
- allRolesUnassigned,
- assignedToFilter,
- accountIdFilter,
- tileFilter,
- customPropertyFilters,
- customPropertyDefinitionsById,
- })
- return source
},
],
}),
listeners(({ actions, values, cache }) => ({
+ loadCustomPropertyDefinitionsSuccess: ({ customPropertyDefinitions }) => {
+ cache.customPropertyDefinitionsLoaded = true
+ const definitionsById = Object.fromEntries(
+ customPropertyDefinitions.map((definition) => [definition.id, definition])
+ )
+ const supportedFilters = supportedCustomPropertyFilters(values.customPropertyFilters, definitionsById)
+ if (!objectsEqual(supportedFilters, values.customPropertyFilters)) {
+ actions.setCustomPropertyFilters(supportedFilters)
+ }
+ },
+ setCustomPropertyFilters: ({ filters }) => {
+ if (!cache.customPropertyDefinitionsLoaded) {
+ return
+ }
+ const supportedFilters = supportedCustomPropertyFilters(filters, values.customPropertyDefinitionsById)
+ if (!objectsEqual(supportedFilters, filters)) {
+ actions.setCustomPropertyFilters(supportedFilters)
+ }
+ },
setSearchInput: async ({ query }, breakpoint) => {
await breakpoint(SEARCH_DEBOUNCE_MS)
actions.setSearchQuery(query)
@@ -1224,7 +986,7 @@ export const accountsLogic = kea<accountsLogicType>([
active_filter_count: values.activeFilterCount,
sort_column: values.sortOrder?.column ?? null,
})
- dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')
+ dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
},
updateAccountRole: async ({ accountId, column, user }) => {
@@ -1261,7 +1023,7 @@ export const accountsLogic = kea<accountsLogicType>([
assigned_user_id: user?.id ?? null,
source: 'list_row',
})
- dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')
+ dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
} catch (error) {
posthog.captureException(error as Error, { scope: 'accountsLogic.updateAccountRole' })
@@ -1292,7 +1054,7 @@ export const accountsLogic = kea<accountsLogicType>([
posthog.capture(AccountsEvents.TagsUpdated, { tag_count: tags.length })
// A newly created tag should show up in the available-tags pickers right away.
tagsModel.findMounted()?.actions.loadTags()
- dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')
+ dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
} catch (error) {
actions.setTagsOverride(accountId, previous)
@@ -1303,19 +1065,13 @@ export const accountsLogic = kea<accountsLogicType>([
}
},
openAccount: ({ accountId, externalId, name, tab }) => {
- const dataNode = dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })
+ const dataNode = dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })
const results = (dataNode?.values.response as { results?: unknown[] } | undefined)?.results
const rows = Array.isArray(results) ? results : []
- const nameIndex = values.visibleColumnNames.indexOf(ACCOUNTS_NAME_COLUMN)
- const isVisible =
- nameIndex >= 0 &&
- rows.some((row) => {
- if (row && typeof row === 'object' && !Array.isArray(row)) {
- return (row as { id?: string }).id === accountId
- }
- const cell = Array.isArray(row) ? (row as unknown[])[nameIndex] : undefined
- return !!cell && typeof cell === 'object' && (cell as { id?: string }).id === accountId
- })
+ const isVisible = rows.some(
+ (row) =>
+ row && typeof row === 'object' && !Array.isArray(row) && (row as { id?: string }).id === accountId
+ )
// Reveal the account if it isn't currently shown, so the expanded row actually renders.
if (!isVisible) {
if (values.tagsFilter.length > 0) {
@@ -1398,7 +1154,7 @@ export const accountsLogic = kea<accountsLogicType>([
// The URL stays on the path — neither setter is wired into actionToUrl, and the setters that
// are keep the current path (see `accountsPathToWriteBackTo`).
const openAccountByPath = (accountId: string | undefined, rawTab?: string): void => {
- // Guard the path param before it's interpolated into the HogQL id filter.
+ // Invalid path ids must not reach the typed account filter.
if (!accountId || !isUUIDLike(accountId)) {
return
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
index 37c35c9eab13..a8e57c0b3edb 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
@@ -241,7 +241,6 @@ describe('tileFilterFor', () => {
})
).toEqual({
tileId: 'b',
- expression: 'toFloatOrNull(accounts.custom_properties.values.`11111111-2222-3333-4444-555555555555`) < 6',
filter: {
kind: 'custom_property',
definitionId: '11111111-2222-3333-4444-555555555555',
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
index dc610221d518..eafe5134b871 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
@@ -12,7 +12,6 @@ import {
AccountsTableCustomPropertyOperator,
AccountsTableMetric,
AccountsTableQueryResponse,
- AccountsQueryResponse,
AccountsTableThresholdOperator,
DataNode,
} from '~/queries/schema/schema-general'
@@ -88,8 +87,7 @@ export interface AccountsOverviewTile {
export interface TileFilter {
tileId: string
- expression: string
- filter?: AccountsTableCustomPropertyFilter
+ filter: AccountsTableCustomPropertyFilter
}
// Saved column expressions include an alias for table rendering, while saved
@@ -121,25 +119,6 @@ export function numericColumnOptions(groups: AccountColumnGroup[]): AccountColum
)
}
-export function applyScale(expression: string, scale: number | undefined): string {
- if (scale === undefined || !Number.isFinite(scale) || scale === 1) {
- return expression
- }
- return `${expression} * ${scale}`
-}
-
-export function tileMetricExpression(tile: AccountsOverviewTile): string {
- const { metric } = tile
- switch (metric.type) {
- case 'count':
- return 'count()'
- case 'count_threshold':
- return `countIf(${metric.columnExpression} ${metric.operator} ${metric.value})`
- default:
- return applyScale(`${metric.type}(${metric.columnExpression})`, metric.scale)
- }
-}
-
export function scaleSuffix(scale: number | undefined): string {
return scale === undefined || !Number.isFinite(scale) || scale === 1 ? '' : ` × ${scale}`
}
@@ -233,14 +212,8 @@ export function isTileClickable(tile: AccountsOverviewTile): boolean {
}
export function tileFilterFor(tile: AccountsOverviewTile): TileFilter | null {
- if (tile.metric.type !== 'count_threshold') {
- return null
- }
- return {
- tileId: tile.id,
- expression: `${tile.metric.columnExpression} ${tile.metric.operator} ${tile.metric.value}`,
- filter: tileToRowFilter(tile) ?? undefined,
- }
+ const filter = tileToRowFilter(tile)
+ return filter ? { tileId: tile.id, filter } : null
}
function readNumeric(raw: unknown): number | null {
@@ -252,7 +225,7 @@ function readNumeric(raw: unknown): number | null {
}
export function parseTileValues(
- response: AccountsQueryResponse | AccountsTableQueryResponse | null,
+ response: AccountsTableQueryResponse | null,
tiles: AccountsOverviewTile[]
): Record<string, number | null> {
const values: Record<string, number | null> = {}
@@ -272,7 +245,7 @@ function reconcileTilesAgainstSchema(
if (tile.metric.type === 'count') {
return true
}
- return numericExpressions.has(tile.metric.columnExpression)
+ return numericExpressions.has(tile.metric.columnExpression) && tileQueryMetric(tile) !== null
})
}
@@ -336,10 +309,9 @@ export interface accountsOverviewTilesLogicValues {
| null // dataNodeLogic
accountsResponseLoading: boolean // dataNodeLogic
editorVisible: boolean
- metrics: string[]
+ metrics: AccountsTableMetric[]
numericColumnExpressions: Set<string>
numericColumns: AccountColumnOption[]
- postgresMetrics: AccountsTableMetric[]
reconciledTiles: AccountsOverviewTile[]
selectedTileId: string | null
tileFilter: TileFilter | null
@@ -405,8 +377,7 @@ export interface accountsOverviewTilesLogicMeta {
tiles: AccountsOverviewTile[],
numericColumnExpressions: Set<string>
) => AccountsOverviewTile[]
- metrics: (reconciledTiles: AccountsOverviewTile[]) => string[]
- postgresMetrics: (reconciledTiles: AccountsOverviewTile[]) => AccountsTableMetric[]
+ metrics: (reconciledTiles: AccountsOverviewTile[]) => AccountsTableMetric[]
tileValues: (
accountsResponse:
| ErrorTrackingQueryResponse
@@ -520,10 +491,6 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
reconcileTilesAgainstSchema(tiles, expressions),
],
metrics: [
- (s) => [s.reconciledTiles],
- (tiles: AccountsOverviewTile[]): string[] => tiles.map(tileMetricExpression),
- ],
- postgresMetrics: [
(s) => [s.reconciledTiles],
(tiles: AccountsOverviewTile[]): AccountsTableMetric[] =>
tiles.map(tileQueryMetric).filter((metric): metric is AccountsTableMetric => metric !== null),
@@ -531,7 +498,7 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
tileValues: [
(s) => [s.accountsResponse, s.reconciledTiles],
(
- response: AccountsQueryResponse | AccountsTableQueryResponse | null,
+ response: AccountsTableQueryResponse | null,
tiles: AccountsOverviewTile[]
): Record<string, number | null> => parseTileValues(response, tiles),
],
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts
index 5fc64b32e5ac..51f451028577 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts
@@ -18,26 +18,25 @@ const buildRow = ({
})
const cellAt = (row: DataTableRow, index: number): unknown => (row.result as unknown[])[index]
+const getCell = (record: unknown, column: string): unknown =>
+ Array.isArray(record) ? record[COLUMNS.indexOf(column)] : undefined
const names = (rows: DataTableRow[]): string[] => rows.map((r) => (cellAt(r, 0) as { name: string }).name)
const counts = (rows: DataTableRow[]): unknown[] => rows.map((r) => cellAt(r, 1))
describe('sortAccountRows', () => {
- it.each([
- ['there is no active sort', null as AccountSortOrder],
- ['the sorted column is not visible', { column: 'missing', direction: 'asc' } as AccountSortOrder],
- ])('returns the same rows untouched when %s', (_label, sortOrder) => {
+ it('returns the same rows untouched when there is no active sort', () => {
const rows = [buildRow({ name: 'B' }), buildRow({ name: 'A' })]
- expect(sortAccountRows(rows, sortOrder, COLUMNS)).toBe(rows)
+ expect(sortAccountRows(rows, null as AccountSortOrder, getCell)).toBe(rows)
})
it('sorts the name tuple column by its name, case-insensitively, in both directions', () => {
const rows = [buildRow({ name: 'Charlie' }), buildRow({ name: 'alpha' }), buildRow({ name: 'Bravo' })]
- expect(names(sortAccountRows(rows, { column: 'name', direction: 'asc' }, COLUMNS))).toEqual([
+ expect(names(sortAccountRows(rows, { column: 'name', direction: 'asc' }, getCell))).toEqual([
'alpha',
'Bravo',
'Charlie',
])
- expect(names(sortAccountRows(rows, { column: 'name', direction: 'desc' }, COLUMNS))).toEqual([
+ expect(names(sortAccountRows(rows, { column: 'name', direction: 'desc' }, getCell))).toEqual([
'Charlie',
'Bravo',
'alpha',
@@ -50,7 +49,7 @@ describe('sortAccountRows', () => {
buildRow({ name: 'b', count: 10 }),
buildRow({ name: 'c', count: 1 }),
]
- expect(counts(sortAccountRows(rows, { column: 'notebook_count', direction: 'asc' }, COLUMNS))).toEqual([
+ expect(counts(sortAccountRows(rows, { column: 'notebook_count', direction: 'asc' }, getCell))).toEqual([
1, 2, 10,
])
})
@@ -61,12 +60,12 @@ describe('sortAccountRows', () => {
buildRow({ name: 'b', count: 5 }),
buildRow({ name: 'c', count: null }),
]
- expect(counts(sortAccountRows(rows, { column: 'notebook_count', direction }, COLUMNS))).toEqual([5, null, null])
+ expect(counts(sortAccountRows(rows, { column: 'notebook_count', direction }, getCell))).toEqual([5, null, null])
})
it('treats an empty relationship array as an empty cell (sorts last)', () => {
const rows = [buildRow({ name: 'unassigned', csm: [] }), buildRow({ name: 'assigned', csm: [42] })]
- expect(names(sortAccountRows(rows, { column: 'csm', direction: 'asc' }, COLUMNS))).toEqual([
+ expect(names(sortAccountRows(rows, { column: 'csm', direction: 'asc' }, getCell))).toEqual([
'assigned',
'unassigned',
])
@@ -78,7 +77,7 @@ describe('sortAccountRows', () => {
buildRow({ name: 'second', count: 5 }),
buildRow({ name: 'third', count: 5 }),
]
- expect(names(sortAccountRows(rows, { column: 'notebook_count', direction: 'asc' }, COLUMNS))).toEqual([
+ expect(names(sortAccountRows(rows, { column: 'notebook_count', direction: 'asc' }, getCell))).toEqual([
'first',
'second',
'third',
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsSort.ts b/products/customer_analytics/frontend/components/Accounts/accountsSort.ts
index ff55f6456700..5ee01548c459 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsSort.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsSort.ts
@@ -35,26 +35,18 @@ function compareNonEmpty(a: unknown, b: unknown): number {
return String(ka).localeCompare(String(kb), undefined, { numeric: true, sensitivity: 'base' })
}
-function getCellAt(row: DataTableRow, index: number): unknown {
- return Array.isArray(row.result) ? row.result[index] : undefined
-}
-
export function sortAccountRows(
rows: DataTableRow[],
sortOrder: AccountSortOrder,
- visibleColumnNames: string[]
+ getCell: (record: unknown, column: string) => unknown
): DataTableRow[] {
if (!sortOrder) {
return rows
}
- const index = visibleColumnNames.indexOf(sortOrder.column)
- if (index < 0) {
- return rows
- }
const direction = sortOrder.direction === 'desc' ? -1 : 1
return [...rows].sort((a, b) => {
- const av = getCellAt(a, index)
- const bv = getCellAt(b, index)
+ const av = getCell(a.result, sortOrder.column)
+ const bv = getCell(b.result, sortOrder.column)
const aEmpty = isEmptyCell(av)
const bEmpty = isEmptyCell(bv)
if (aEmpty || bEmpty) {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
index 4dadb0dae5e1..6436dbeb7eaa 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
@@ -11,7 +11,7 @@ import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/fr
import {
AccountsTableQueryPlan,
BuildAccountsTableQueryPlanInput,
- accountsTableRowsToLegacyRows,
+ accountsTableCell,
buildAccountsTableQueryPlan,
} from './accountsTableQuery'
@@ -135,12 +135,23 @@ describe('accountsTableQuery', () => {
expect(plan?.query.filters).toEqual([{ kind: 'account_id', accountId: RELATIONSHIP_ID }])
})
+ it('drops unsupported columns instead of changing runners', () => {
+ const plan = buildAccountsTableQueryPlan(
+ queryInput({
+ querySelectColumns: ['name', 'arbitrary_hogql()'],
+ visibleColumnNames: ['name', 'unsupported'],
+ })
+ )
+
+ expect(plan.query.columns).toEqual([{ kind: 'account_field', field: 'name' }])
+ expect(plan.columns.map((column) => column.visibleName)).toEqual(['name'])
+ })
+
it('translates a threshold tile into a typed list filter', () => {
const plan = buildAccountsTableQueryPlan(
queryInput({
tileFilter: {
tileId: 'tile',
- expression: `toFloatOrNull(accounts.custom_properties.values.\`${CUSTOM_PROPERTY_ID}\`) > 1`,
filter: {
kind: 'custom_property',
definitionId: CUSTOM_PROPERTY_ID,
@@ -151,7 +162,7 @@ describe('accountsTableQuery', () => {
})
)
- expect(plan?.query.filters).toEqual([
+ expect(plan.query.filters).toEqual([
{
kind: 'custom_property',
definitionId: CUSTOM_PROPERTY_ID,
@@ -166,7 +177,6 @@ describe('accountsTableQuery', () => {
queryInput({
tileFilter: {
tileId: 'tile',
- expression: `toFloatOrNull(accounts.custom_properties.values.\`${CUSTOM_PROPERTY_ID}\`) != 1`,
filter: {
kind: 'custom_property',
definitionId: CUSTOM_PROPERTY_ID,
@@ -177,7 +187,7 @@ describe('accountsTableQuery', () => {
})
)
- expect(plan?.query.filters).toEqual([
+ expect(plan.query.filters).toEqual([
{
kind: 'custom_property',
definitionId: CUSTOM_PROPERTY_ID,
@@ -193,85 +203,42 @@ describe('accountsTableQuery', () => {
])
})
- it.each([
- [
- 'unsupported column',
- { querySelectColumns: ['name', 'arbitrary_hogql()'], visibleColumnNames: ['name', 'x'] },
- ],
- ['misaligned columns', { querySelectColumns: ['name'], visibleColumnNames: ['name', 'extra'] }],
- ])('falls back to HogQL for %s', (_, overrides) => {
- expect(buildAccountsTableQueryPlan(queryInput(overrides))).toBeNull()
- })
-
it.each([
['regex', 'currency', PropertyOperator.Regex],
['contains on a number', 'currency', PropertyOperator.IContains],
['comparison on text', 'text', PropertyOperator.GreaterThan],
['date comparison on boolean', 'boolean', PropertyOperator.IsDateBefore],
- ])('falls back to HogQL for %s custom property filters', (_, displayType, operator) => {
+ ])('omits unsupported %s custom property filters', (_, displayType, operator) => {
const incompatibleDefinition = { ...definition, display_type: displayType } as CustomPropertyDefinitionApi
-
- expect(
- buildAccountsTableQueryPlan(
- queryInput({
- customPropertyDefinitionsById: { [CUSTOM_PROPERTY_ID]: incompatibleDefinition },
- customPropertyFilters: [customFilter({ operator })],
- })
- )
- ).toBeNull()
- })
-
- it('translates custom property values and history into positional cells', () => {
const plan = buildAccountsTableQueryPlan(
queryInput({
- querySelectColumns: [
- 'name',
- `accounts.custom_properties.values.\`${CUSTOM_PROPERTY_ID}\` AS cp_value`,
- `accounts.custom_properties_history.values.\`${CUSTOM_PROPERTY_ID}\` AS cp_history`,
- ],
- visibleColumnNames: ['name', 'cp_value', 'cp_history'],
- columnDisplay: { [CUSTOM_PROPERTY_ID]: { mode: 'trend', window_days: 30 } },
+ customPropertyDefinitionsById: { [CUSTOM_PROPERTY_ID]: incompatibleDefinition },
+ customPropertyFilters: [customFilter({ operator })],
})
- ) as AccountsTableQueryPlan
-
- const rows = accountsTableRowsToLegacyRows(
- [
- {
- id: 'account-id',
- name: 'Acme',
- accountFields: { name: 'Acme' },
- relationships: {},
- customProperties: { [CUSTOM_PROPERTY_ID]: 42 },
- customPropertyHistory: {
- [CUSTOM_PROPERTY_ID]: [{ timestamp: '2026-01-01T00:00:00Z', value: 40 }],
- },
- },
- ],
- plan
)
- expect(rows).toEqual([[{ id: 'account-id', name: 'Acme', external_id: null }, 42, [[1767225600, 40]]]])
+ expect(plan.query.filters).toEqual([])
})
- it('translates keyed Postgres rows into the positional table response', () => {
+ it('reads cells directly from keyed rows', () => {
const plan = buildAccountsTableQueryPlan(queryInput()) as AccountsTableQueryPlan
- const rows = accountsTableRowsToLegacyRows(
- [
- {
- id: 'account-id',
- name: 'Acme',
- externalId: 'acme-1',
- accountFields: { name: 'Acme' },
- tags: ['enterprise'],
- noteCount: 2,
- relationships: { [RELATIONSHIP_ID]: [42] },
- customProperties: {},
- customPropertyHistory: {},
- },
- ],
- plan
- )
-
- expect(rows).toEqual([[{ id: 'account-id', name: 'Acme', external_id: 'acme-1' }, ['enterprise'], 2, [42]]])
+ const row = {
+ id: 'account-id',
+ name: 'Acme',
+ externalId: 'acme-1',
+ accountFields: { name: 'Acme' },
+ tags: ['enterprise'],
+ noteCount: 2,
+ relationships: { [RELATIONSHIP_ID]: [42] },
+ customProperties: {},
+ customPropertyHistory: {},
+ }
+
+ expect(plan.columns.map((column) => accountsTableCell(row, column.visibleName, plan))).toEqual([
+ { id: 'account-id', name: 'Acme', external_id: 'acme-1' },
+ ['enterprise'],
+ 2,
+ [42],
+ ])
})
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
index 780ace6a8330..5dc661b4a096 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
@@ -178,7 +178,14 @@ function customPropertyFilter(
}
}
-function queryFilters(input: BuildAccountsTableQueryPlanInput): AccountsTableFilter[] | null {
+export function supportedCustomPropertyFilters(
+ filters: AccountCustomPropertyFilter[],
+ definitionsById: Record<string, CustomPropertyDefinitionApi>
+): AccountCustomPropertyFilter[] {
+ return filters.filter((filter) => customPropertyFilter(filter, definitionsById) !== null)
+}
+
+function queryFilters(input: BuildAccountsTableQueryPlanInput): AccountsTableFilter[] {
if (input.accountIdFilter) {
return [{ kind: 'account_id', accountId: input.accountIdFilter } satisfies AccountsTableAccountIdFilter]
}
@@ -199,29 +206,24 @@ function queryFilters(input: BuildAccountsTableQueryPlanInput): AccountsTableFil
}
for (const filter of input.customPropertyFilters) {
const translatedFilter = customPropertyFilter(filter, input.customPropertyDefinitionsById)
- if (!translatedFilter) {
- return null
+ if (translatedFilter) {
+ filters.push(translatedFilter)
}
- filters.push(translatedFilter)
}
- if (input.tileFilter) {
+ if (input.tileFilter?.filter) {
const filter = input.tileFilter.filter
- if (!filter) {
- return null
- }
const definition = input.customPropertyDefinitionsById[filter.definitionId]
- if (!isUUIDLike(filter.definitionId) || !definition || !isNumericDisplayType(definition.display_type)) {
- return null
- }
- if (filter.operator === AccountsTableCustomPropertyOperator.IsNot) {
- filters.push({
- kind: 'custom_property',
- definitionId: filter.definitionId,
- operator: AccountsTableCustomPropertyOperator.IsSet,
- values: [],
- })
+ if (isUUIDLike(filter.definitionId) && definition && isNumericDisplayType(definition.display_type)) {
+ if (filter.operator === AccountsTableCustomPropertyOperator.IsNot) {
+ filters.push({
+ kind: 'custom_property',
+ definitionId: filter.definitionId,
+ operator: AccountsTableCustomPropertyOperator.IsSet,
+ values: [],
+ })
+ }
+ filters.push(filter)
}
- filters.push(filter)
}
return filters
}
@@ -233,18 +235,14 @@ function sortableColumn(column: AccountsTableColumn): AccountsTableSortableColum
return column
}
-export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan | null {
- if (input.querySelectColumns.length !== input.visibleColumnNames.length) {
- return null
- }
-
+export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan {
const columns: AccountsTablePlannedColumn[] = []
- for (let index = 0; index < input.querySelectColumns.length; index++) {
+ const columnCount = Math.min(input.querySelectColumns.length, input.visibleColumnNames.length)
+ for (let index = 0; index < columnCount; index++) {
const column = columnFromExpression(input.querySelectColumns[index], input.columnDisplay)
- if (!column) {
- return null
+ if (column) {
+ columns.push({ visibleName: input.visibleColumnNames[index], column })
}
- columns.push({ visibleName: input.visibleColumnNames[index], column })
}
let sort: AccountsTableSort | undefined
@@ -262,9 +260,6 @@ export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanIn
}
const filters = queryFilters(input)
- if (!filters) {
- return null
- }
return {
query: {
@@ -272,7 +267,7 @@ export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanIn
columns: columns.map(({ column }) => column),
filters,
sort,
- tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_postgres_list' },
+ tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_list' },
},
columns,
}
@@ -288,7 +283,11 @@ function accountFieldValue(row: AccountsTableRow, field: AccountsTableAccountFie
return row.accountFields[field] ?? null
}
-function legacyCellValue(row: AccountsTableRow, column: AccountsTableColumn): unknown {
+export function accountsTableCell(row: AccountsTableRow, visibleName: string, plan: AccountsTableQueryPlan): unknown {
+ const column = plan.columns.find((candidate) => candidate.visibleName === visibleName)?.column
+ if (!column) {
+ return undefined
+ }
switch (column.kind) {
case 'account_field':
return accountFieldValue(row, column.field)
@@ -301,10 +300,7 @@ function legacyCellValue(row: AccountsTableRow, column: AccountsTableColumn): un
case 'custom_property':
return row.customProperties[column.definitionId] ?? null
case 'custom_property_history':
- return (row.customPropertyHistory[column.definitionId] ?? []).map((point): [number, number] => [
- Math.floor(Date.parse(point.timestamp) / 1000),
- point.value,
- ])
+ return row.customPropertyHistory[column.definitionId] ?? []
}
}
@@ -322,7 +318,3 @@ export function isAccountsTableRow(value: unknown): value is AccountsTableRow {
!!row.customPropertyHistory
)
}
-
-export function accountsTableRowsToLegacyRows(rows: AccountsTableRow[], plan: AccountsTableQueryPlan): unknown[][] {
- return rows.map((row) => plan.columns.map(({ column }) => legacyCellValue(row, column)))
-}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
index 2620a1e7ccb1..4d410250301e 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
@@ -1,7 +1,7 @@
import { AccountsTableCustomPropertyOperator } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
-import { ACCOUNTS_HOGQL_DEFAULT_SELECT } from './accountsColumnConfigLogic'
+import { ACCOUNTS_DEFAULT_COLUMNS } from './accountsColumnConfigLogic'
import {
AccountsViewState,
deserializeAccountsView,
@@ -61,7 +61,6 @@ describe('serializeAccountsView / deserializeAccountsView', () => {
assignedTo: [1, 2, 3],
tileFilter: {
tileId: 't1',
- expression: 'mrr > 100',
filter: {
kind: 'custom_property',
definitionId: '11111111-2222-3333-4444-555555555555',
@@ -93,7 +92,7 @@ describe('serializeAccountsView / deserializeAccountsView', () => {
it('omits empty filters and serializes no sort', () => {
const payload = serializeAccountsView({
- columns: [...ACCOUNTS_HOGQL_DEFAULT_SELECT],
+ columns: [...ACCOUNTS_DEFAULT_COLUMNS],
sortOrder: null,
filters: {
search: '',
@@ -128,6 +127,6 @@ describe('serializeAccountsView / deserializeAccountsView', () => {
it('falls back to default columns when a row has none', () => {
const state = deserializeAccountsView({ columns: [], order_by: [], filters: {}, properties: {} })
- expect(state.columns).toEqual(ACCOUNTS_HOGQL_DEFAULT_SELECT)
+ expect(state.columns).toEqual(ACCOUNTS_DEFAULT_COLUMNS)
})
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
index 66b7bee1fe5e..c72bf5f2383b 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
@@ -2,7 +2,7 @@ import type { AccountCustomPropertyFilter } from '~/types'
import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'
-import { ACCOUNTS_HOGQL_DEFAULT_SELECT, AccountColumnDisplayState } from './accountsColumnConfigLogic'
+import { ACCOUNTS_DEFAULT_COLUMNS, AccountColumnDisplayState } from './accountsColumnConfigLogic'
import type { AccountSortOrder, RoleFilterValue } from './accountsLogic'
import type { AccountsOverviewTile, TileFilter } from './accountsOverviewTilesLogic'
import { DEFAULT_TILES } from './constants'
@@ -44,9 +44,8 @@ export function normalizeRoleFilter(value: unknown): RoleFilterValue {
return typeof value === 'number' ? [value] : []
}
-// Sort persists as a single `["<column> <ASC|DESC>"]` entry using the LOGICAL
-// column name (e.g. `csm`) — HogQL resolves it against the SELECT alias at
-// query-build time.
+// Sort persists under the logical column name so saved views do not depend on
+// the typed query's relationship or custom-property references.
export function sortOrderToOrderBy(sortOrder: AccountSortOrder): string[] {
if (!sortOrder) {
return []
@@ -108,7 +107,7 @@ export function deserializeAccountsView(view: Partial<ColumnConfigurationApi>):
) as AccountsViewProperties
return {
- columns: view.columns && view.columns.length > 0 ? view.columns : [...ACCOUNTS_HOGQL_DEFAULT_SELECT],
+ columns: view.columns && view.columns.length > 0 ? view.columns : [...ACCOUNTS_DEFAULT_COLUMNS],
sortOrder: orderByToSortOrder(view.order_by),
filters: {
search: rawFilters.search ?? '',
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
index 72e0ae35655d..0d4e1bf52d3d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
@@ -5,7 +5,7 @@ import { expectLogic } from 'kea-test-utils'
import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
-import { AccountsTableCustomPropertyOperator } from '~/queries/schema/schema-general'
+import type { AccountsTableQuery } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'
@@ -82,11 +82,10 @@ describe('accountsViewsLogic', () => {
assignedTo: [1, 2, 3],
tileFilter: {
tileId: 't1',
- expression: 'mrr > 100',
filter: {
kind: 'custom_property',
definitionId: '11111111-2222-3333-4444-555555555555',
- operator: AccountsTableCustomPropertyOperator.GreaterThan,
+ operator: 'gt',
values: [100],
},
},
@@ -105,17 +104,39 @@ describe('accountsViewsLogic', () => {
])
expect(accountsOverviewTilesLogic.values.tileFilter).toEqual({
tileId: 't1',
- expression: 'mrr > 100',
filter: {
kind: 'custom_property',
definitionId: '11111111-2222-3333-4444-555555555555',
- operator: AccountsTableCustomPropertyOperator.GreaterThan,
+ operator: 'gt',
values: [100],
},
})
expect(logic.values.currentViewId).toEqual('view-1')
})
+ it('translates an applied saved view into the Postgres query', async () => {
+ useMocks({ get: { '/api/environments/:team_id/column_configurations/': { count: 0, results: [] } } })
+ mountAll()
+ await expectLogic(logic, () =>
+ logic.actions.applyView(
+ buildView({
+ columns: ['name'],
+ filters: { search: 'acme', tags: ['enterprise'], assignedTo: [1, 2] },
+ order_by: ['name DESC'],
+ })
+ )
+ ).toFinishAllListeners()
+
+ const source = accountsLogic.values.accountsQuerySource as AccountsTableQuery
+ expect(source.kind).toBe('AccountsTableQuery')
+ expect(source.columns).toEqual([{ kind: 'account_field', field: 'name' }])
+ expect(source.filters).toEqual([
+ { kind: 'search', query: 'acme' },
+ { kind: 'tags', tagNames: ['enterprise'] },
+ { kind: 'assigned_to', userIds: [1, 2] },
+ ])
+ })
+
it('isDirty flips when live state diverges from the applied view and clears on re-apply', async () => {
useMocks({
get: {
diff --git a/products/customer_analytics/frontend/constants.ts b/products/customer_analytics/frontend/constants.ts
index c43034889524..38347fdbab08 100644
--- a/products/customer_analytics/frontend/constants.ts
+++ b/products/customer_analytics/frontend/constants.ts
@@ -2,7 +2,7 @@ import { ProductKey, QueryLogTags } from '~/queries/schema/schema-general'
export const CUSTOMER_ANALYTICS_DATA_COLLECTION_NODE_ID = 'customer-analytics'
-export const ACCOUNTS_HOGQL_DATA_NODE_KEY = 'customer-analytics-accounts-hogql'
+export const ACCOUNTS_TABLE_DATA_NODE_KEY = 'customer-analytics-accounts-table'
// Overview-tile metrics load through their own data node so their (slower)
// aggregations never block the list rows from rendering.