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): sparkline and trend display for custom property columns (#73599)

Arthur Moreira de Deusec1d1a2eb6a4
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.py
index deb6a5d7e336..1202335bcf51 100644
--- a/posthog/hogql/database/lazy_join_registry.py
+++ b/posthog/hogql/database/lazy_join_registry.py
@@ -32,6 +32,7 @@ from posthog.hogql.database.warehouse_join_resolvers import (
)
from products.customer_analytics.backend.facade.hogql import (
+ account_custom_properties_history_join,
account_custom_properties_join,
account_notebooks_join,
account_relationships_join,
@@ -78,6 +79,7 @@ RESOLVERS: dict[str, LazyJoinResolver] = {
tags.ACCOUNT_TAGS: account_tags_join,
tags.ACCOUNT_NOTEBOOKS: account_notebooks_join,
tags.ACCOUNT_CUSTOM_PROPERTIES: account_custom_properties_join,
+ tags.ACCOUNT_CUSTOM_PROPERTIES_HISTORY: account_custom_properties_history_join,
tags.ACCOUNT_RELATIONSHIPS: account_relationships_join,
}
diff --git a/posthog/hogql/database/lazy_join_tags.py b/posthog/hogql/database/lazy_join_tags.py
index a82d88ba47fb..8b1b5db67e5a 100644
--- a/posthog/hogql/database/lazy_join_tags.py
+++ b/posthog/hogql/database/lazy_join_tags.py
@@ -26,4 +26,5 @@ ERROR_TRACKING_FINGERPRINT_ISSUE_STATE = "error_tracking_fingerprint_issue_state
ACCOUNT_TAGS = "account_tags"
ACCOUNT_NOTEBOOKS = "account_notebooks"
ACCOUNT_CUSTOM_PROPERTIES = "account_custom_properties"
+ACCOUNT_CUSTOM_PROPERTIES_HISTORY = "account_custom_properties_history"
ACCOUNT_RELATIONSHIPS = "account_relationships"
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 5d76dff62b62..561c112b009c 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -24,6 +24,7 @@ from posthog.scopes import APIScopeObject
from products.customer_analytics.backend.facade.hogql import (
account_custom_property_values,
+ account_custom_property_values_history,
account_relationship_definitions,
account_relationships,
account_resource_notebooks,
@@ -2024,6 +2025,9 @@ class SystemTables(TableNode):
"_account_custom_property_values": TableNode(
name="_account_custom_property_values", table=account_custom_property_values, hidden=True
),
+ "_account_custom_property_values_history": TableNode(
+ name="_account_custom_property_values_history", table=account_custom_property_values_history, hidden=True
+ ),
"account_relationship_definitions": TableNode(
name="account_relationship_definitions", table=account_relationship_definitions
),
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 50bec114ad39..cfc6d1d60ce5 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -102,6 +102,7 @@ TEAM_ID_FILTER_PATTERNS = {
"_account_resource_notebooks": "system__accounts.team_id",
"_account_tagged_items": "system__accounts.team_id",
"_account_custom_property_values": "system__accounts.team_id",
+ "_account_custom_property_values_history": "system__accounts.team_id",
}
@@ -135,6 +136,7 @@ class TestSystemTablesTeamScoping(BaseTest):
"_account_resource_notebooks",
"_account_tagged_items",
"_account_custom_property_values",
+ "_account_custom_property_values_history",
# information_schema is a namespace of virtual catalog tables (tables/columns/
# relationships/data_types) computed per-query from the caller's own Database object,
# so it has no team_id column to isolate; behaviour is covered by TestInformationSchema.
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index cb717f98d0c0..33d34fb4e5a2 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -2768,6 +2768,19 @@
"table": "account_custom_properties",
"type": "lazy_table"
},
+ "custom_properties_history": {
+ "chain": null,
+ "fields": [
+ "account_id",
+ "values"
+ ],
+ "hogql_value": "custom_properties_history",
+ "id": "custom_properties_history",
+ "name": "custom_properties_history",
+ "schema_valid": true,
+ "table": "account_custom_properties_history",
+ "type": "lazy_table"
+ },
"relationships": {
"chain": null,
"fields": [
@@ -11543,6 +11556,19 @@
"table": "account_custom_properties",
"type": "lazy_table"
},
+ "custom_properties_history": {
+ "chain": null,
+ "fields": [
+ "account_id",
+ "values"
+ ],
+ "hogql_value": "custom_properties_history",
+ "id": "custom_properties_history",
+ "name": "custom_properties_history",
+ "schema_valid": true,
+ "table": "account_custom_properties_history",
+ "type": "lazy_table"
+ },
"relationships": {
"chain": null,
"fields": [
diff --git a/posthog/hogql/database/test/test_lazy_join_resolvers.py b/posthog/hogql/database/test/test_lazy_join_resolvers.py
index 4361afaa1026..6c3678d1a3aa 100644
--- a/posthog/hogql/database/test/test_lazy_join_resolvers.py
+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py
@@ -183,6 +183,7 @@ class TestLazyJoinManifest(SimpleTestCase):
list changes what consumers of a serialized schema must implement — update deliberately."""
assert sorted(RESOLVERS) == [
"account_custom_properties",
+ "account_custom_properties_history",
"account_notebooks",
"account_relationships",
"account_tags",
diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.py
index acfad18b5178..87fceb1ab2c5 100644
--- a/products/customer_analytics/backend/facade/hogql.py
+++ b/products/customer_analytics/backend/facade/hogql.py
@@ -9,9 +9,9 @@ product's Postgres tables is import-visible (tach) and facade-gated (CI): core
hardcoding the product's table and column names.
The raw federated junction tables (`_account_tagged_items`, `_account_resource_notebooks`,
-`_account_custom_property_values`) have no `team_id` column and should not be reachable
-directly from the SQL editor — they exist only so the lazy join subqueries below can be
-resolved by the planner.
+`_account_custom_property_values`, `_account_custom_property_values_history`) have no
+`team_id` column and should not be reachable directly from the SQL editor — they exist only
+so the lazy join subqueries below can be resolved by the planner.
"""
from posthog.hogql import ast
@@ -19,6 +19,7 @@ from posthog.hogql.base import Expr
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.lazy_join_tags import (
ACCOUNT_CUSTOM_PROPERTIES,
+ ACCOUNT_CUSTOM_PROPERTIES_HISTORY,
ACCOUNT_NOTEBOOKS,
ACCOUNT_RELATIONSHIPS,
ACCOUNT_TAGS,
@@ -127,6 +128,29 @@ account_custom_property_values: _AccountScopedPostgresTable = _AccountScopedPost
)
+account_custom_property_values_history: _AccountScopedPostgresTable = _AccountScopedPostgresTable(
+ name="_account_custom_property_values_history",
+ postgres_table_name="customer_analytics_custompropertyvalue",
+ description="Internal federated table (PostgreSQL `customer_analytics_custompropertyvalue`) of every custom property value write per account, superseded rows included; not for direct querying — use `system.accounts.custom_properties_history`.",
+ fields={
+ "id": UUIDDatabaseField(name="id", description="Primary key of the custom property value row."),
+ "definition_id": UUIDDatabaseField(
+ name="definition_id", description="Custom property definition this value is for."
+ ),
+ "account_id": UUIDDatabaseField(
+ name="account_id", nullable=True, description="Account the value belongs to; join to `system.accounts.id`."
+ ),
+ "created_at": DateTimeDatabaseField(name="created_at", description="When the value was written."),
+ "is_deleted": BooleanDatabaseField(
+ name="is_deleted", description="Whether this value has been superseded (soft-deleted)."
+ ),
+ "value_num": FloatDatabaseField(
+ name="value_num", nullable=True, description="Numeric value, if a numeric type."
+ ),
+ },
+)
+
+
def _account_tags_select() -> ast.SelectQuery | ast.SelectSetQuery:
return parse_select(
"""
@@ -202,6 +226,55 @@ def _account_custom_properties_select(fields_accessed: dict[str, list[str | int]
)
+def _account_custom_properties_history_select(fields_accessed: dict[str, list[str | int]]) -> ast.SelectQuery:
+ r"""Aggregate each account's numeric custom property value writes into ordered histories.
+
+ Inner select: one row per (account, definition) with the sorted array of
+ (unix timestamp, value) points — active and superseded rows alike, since every write is
+ a data point. Outer select: each requested key
+ (`accounts.custom_properties_history.values.\`<id>\``, arriving as `values___<id>`) is
+ materialized as its own column via `anyIf` — a lazy-join subquery can't JSON-extract
+ after the fact.
+ """
+ inner = parse_select(
+ # The 180-day horizon caps the federated scan; UI look-back presets top out at 90 days.
+ # The active (non-deleted) row is always included — at most one per (account, definition) —
+ # so a value last written before the horizon still reaches the cell as the current value.
+ """
+ SELECT
+ cpv.account_id AS account_id,
+ toString(cpv.definition_id) AS definition_key,
+ arraySort(groupArray(tuple(toUnixTimestamp(cpv.created_at), cpv.value_num))) AS points
+ FROM system._account_custom_property_values_history AS cpv
+ WHERE isNotNull(cpv.value_num) AND (cpv.created_at >= now() - INTERVAL 180 DAY OR NOT cpv.is_deleted)
+ GROUP BY cpv.account_id, cpv.definition_id
+ """
+ )
+ select: list[ast.Expr] = [parse_expr("account_id AS account_id")]
+ for name, chain in fields_accessed.items():
+ if chain == ["account_id"]:
+ continue
+ if len(chain) >= 2 and chain[0] == "values":
+ select.append(
+ ast.Alias(
+ alias=name,
+ expr=parse_expr(
+ "anyIf(points, definition_key = {key})",
+ placeholders={"key": ast.Constant(value=str(chain[1]))},
+ ),
+ )
+ )
+ elif chain == ["values"]:
+ select.append(
+ parse_expr("toJSONString(mapFromArrays(groupArray(definition_key), groupArray(points))) AS values")
+ )
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=inner),
+ group_by=[ast.Field(chain=["account_id"])],
+ )
+
+
def _account_relationships_select(fields_accessed: dict[str, list[str | int]]) -> ast.SelectQuery:
r"""Aggregate each account's ACTIVE relationship assignments.
@@ -326,6 +399,40 @@ class _AccountCustomPropertiesTable(LazyTable):
return "account_custom_properties"
+class _AccountCustomPropertiesHistoryTable(LazyTable):
+ description: str = (
+ "Internal aggregating table backing `system.accounts.custom_properties_history`: each "
+ "account's numeric custom property write history, keyed by definition id."
+ )
+ fields: dict[str, FieldOrTable] = {
+ "account_id": UUIDDatabaseField(
+ name="account_id", description="Account this history belongs to; join to `system.accounts.id`."
+ ),
+ "values": StringJSONDatabaseField(
+ name="values",
+ description=(
+ "JSON object keyed by custom property definition id; each value is the property's "
+ "write history over the last 180 days (plus the current value, however old) as "
+ "[unix timestamp, value] pairs sorted ascending — numeric properties only. Read one "
+ "property with accounts.custom_properties_history.values.`<definition_id>` "
+ "(backtick-quote the id). Get definition ids and names from "
+ "system.custom_property_definitions."
+ ),
+ ),
+ }
+
+ def lazy_select(
+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery
+ ) -> ast.SelectQuery | ast.SelectSetQuery:
+ return _account_custom_properties_history_select(table_to_add.fields_accessed)
+
+ def to_printed_clickhouse(self, context: HogQLContext) -> str:
+ return "account_custom_properties_history"
+
+ def to_printed_hogql(self) -> str:
+ return "account_custom_properties_history"
+
+
class _AccountRelationshipsTable(LazyTable):
description: str = (
"Internal aggregating table backing `system.accounts.relationships`: a JSON object of each "
@@ -394,6 +501,14 @@ def account_custom_properties_join(
return _join_on_account_id(_account_custom_properties_select(join_to_add.fields_accessed), join_to_add)
+def account_custom_properties_history_join(
+ join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery
+) -> ast.JoinExpr:
+ if not join_to_add.fields_accessed:
+ raise ResolutionError("No fields requested from `accounts.custom_properties_history`")
+ return _join_on_account_id(_account_custom_properties_history_select(join_to_add.fields_accessed), join_to_add)
+
+
def account_relationships_join(
join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery
) -> ast.JoinExpr:
@@ -420,6 +535,12 @@ account_custom_properties_lazy_join: LazyJoin = LazyJoin(
resolver=ACCOUNT_CUSTOM_PROPERTIES,
)
+account_custom_properties_history_lazy_join: LazyJoin = LazyJoin(
+ from_field=["id"],
+ join_table=_AccountCustomPropertiesHistoryTable(),
+ resolver=ACCOUNT_CUSTOM_PROPERTIES_HISTORY,
+)
+
account_relationships_lazy_join: LazyJoin = LazyJoin(
from_field=["id"],
@@ -541,6 +662,7 @@ accounts: PostgresTable = PostgresTable(
"tags": account_tags_lazy_join,
"notebooks": account_notebooks_lazy_join,
"custom_properties": account_custom_properties_lazy_join,
+ "custom_properties_history": account_custom_properties_history_lazy_join,
"relationships": account_relationships_lazy_join,
},
)
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
index 45343de2ca9b..c35ad91a25a9 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
@@ -1,4 +1,4 @@
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest
@@ -544,6 +544,55 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
# An account with no value for the definition aggregates to NULL/empty.
self.assertFalse(values_by_id[str(other.id)])
+ def test_custom_property_history_returns_ordered_writes_within_horizon(self):
+ account = create_account(team_id=self.team.id, name="A")
+ stale_account = create_account(team_id=self.team.id, name="Stale")
+ definition = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type="number")
+ text_definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ CustomPropertyValue.objects.unscoped().create(
+ team_id=self.team.id, account=account, definition=text_definition, value_str="enterprise"
+ )
+ now = timezone.now()
+ for target, value, is_deleted, written_at in [
+ (account, 99.0, True, now - timedelta(days=200)),
+ (account, 10.0, True, now - timedelta(days=10)),
+ (account, 33.0, False, now - timedelta(days=5)),
+ # An active value last written before the horizon must still surface as the
+ # current value — only superseded rows age out.
+ (stale_account, 77.0, False, now - timedelta(days=200)),
+ ]:
+ row = CustomPropertyValue.objects.unscoped().create(
+ team_id=self.team.id, account=target, definition=definition, value_num=value, is_deleted=is_deleted
+ )
+ CustomPropertyValue.objects.unscoped().filter(id=row.id).update(created_at=written_at)
+
+ runner = AccountsQueryRunner(
+ query=AccountsQuery(
+ select=[
+ "id",
+ f"accounts.custom_properties_history.values.`{definition.id}` AS numeric_history",
+ f"accounts.custom_properties_history.values.`{text_definition.id}` AS text_history",
+ ]
+ ),
+ team=self.team,
+ user=self.user,
+ )
+ response = runner.calculate()
+ self.assertEqual(len(response.results), 2)
+ id_idx = runner.columns.index("id")
+ rows_by_id = {str(row[id_idx]): row for row in response.results}
+
+ numeric_history = rows_by_id[str(account.id)][runner.columns.index("numeric_history")]
+ # The 200-day-old superseded write falls outside the fetch horizon; the two in-horizon
+ # writes come back oldest first, superseded row included.
+ self.assertEqual([point[1] for point in numeric_history], [10.0, 33.0])
+ timestamps = [point[0] for point in numeric_history]
+ self.assertEqual(timestamps, sorted(timestamps))
+ self.assertFalse(rows_by_id[str(account.id)][runner.columns.index("text_history")])
+
+ stale_history = rows_by_id[str(stale_account.id)][runner.columns.index("numeric_history")]
+ self.assertEqual([point[1] for point in stale_history], [77.0])
+
def test_numeric_custom_property_aggregates_in_metrics_mode(self):
# Overview tiles sum/avg a numeric custom property by casting its (string) value to a float.
definition = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type="number")
diff --git a/products/customer_analytics/backend/test/test_facade_hogql.py b/products/customer_analytics/backend/test/test_facade_hogql.py
index 4179ba7415a7..6e23e275fe8d 100644
--- a/products/customer_analytics/backend/test/test_facade_hogql.py
+++ b/products/customer_analytics/backend/test/test_facade_hogql.py
@@ -15,6 +15,7 @@ from posthog.models import TaggedItem
from products.customer_analytics.backend.facade.hogql import (
account_custom_property_values,
+ account_custom_property_values_history,
account_resource_notebooks,
account_tagged_items,
accounts,
@@ -30,6 +31,7 @@ class TestFacadeHogqlSystemTables(SimpleTestCase):
("accounts", accounts, Account),
("custom_property_definitions", custom_property_definitions, CustomPropertyDefinition),
("account_custom_property_values", account_custom_property_values, CustomPropertyValue),
+ ("account_custom_property_values_history", account_custom_property_values_history, CustomPropertyValue),
("account_tagged_items", account_tagged_items, TaggedItem),
("account_resource_notebooks", account_resource_notebooks, ResourceNotebook),
]
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 62df1e7e4b88..f8f22b267034 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -62,6 +62,13 @@ Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship co
**Custom property columns** surface the team's `CustomPropertyDefinition`s (loaded in `accountsColumnConfigLogic` via the generated `customPropertyDefinitionsList`) as a "Custom properties" picker group. Each is selected as ``accounts.custom_properties.values.`<definition-id>` AS cp_<id>`` — a JSON dot-access through the `custom_properties` lazy join on `system.accounts` (backed by the `customer_analytics_custompropertyvalue` EAV table; one JOIN regardless of column count). Because the alias is an opaque `cp_<id>`, every label-bearing surface must resolve it back via the `aliasToDefinition` selector: the table header (`useContextColumns` in `AccountsHogQLTable`) and the configurator's "Visible columns" list (`SelectedAccountColumn`). Cells render by display type (`CustomPropertyCell`: date→`TZLabel`, boolean→icon, select→`LemonColorGlyph` + label, numeric→`formatCustomPropertyValue`). Sorting a numeric custom property (display type `number`/`currency`/`percent`) casts the (string) JSON value with `toFloatOrNull(...)` in the `orderBy` — see `orderByExpression` in `accountsLogic`, driven by `aliasToDefinition` — so numbers sort by magnitude rather than lexically; non-numeric types sort by the alias directly. The stored sort state (URL hash, saved views) keeps the clean column name; the cast is applied only at query-build time. Numeric custom properties are also selectable in the **overview tiles** sum/avg/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the value in `toFloatOrNull(...)` the same way so aggregation is numeric.
+**Custom property 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`).
+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.
+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).
+
**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.
@@ -130,8 +137,9 @@ A shared link's `#view=` URL hash always wins over the saved `currentViewId`.
**One-time tiles migration:** on first load, if the signed-in user is the creator of the existing default `ColumnConfiguration` row and its `properties.tiles` is empty while their localStorage tiles differ from `DEFAULT_TILES`, `accountsViewsLogic` patches the localStorage tiles into that row.
The operation is idempotent and skips non-creators.
-**Column configurator:** `AccountsColumnConfigurator.tsx` no longer persists columns itself — its footer button is "Done" (closes only).
+**Column configurator:** `AccountsColumnConfigurator.tsx` no longer persists columns itself — "Done" closes only.
Column changes are saved as part of a view via `AccountsViewSelector.tsx` (the view dropdown in `AccountsTabFilters`), which offers "Save current view" (creates) and "Update '<name>'" (patches the selected view).
+The configurator's footer also surfaces that path (`SaveViewButton`): "Update "<name>"" when the current view is editable (disabled until dirty), otherwise "Save as new view" — both delegate to `accountsViewsLogic` (`updateView` / `setIsCreating`), the latter opening the create-view modal that `AccountsViewSelector` renders.
## Max / agent integration
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
index 8e4880c4f65d..4edb8cc7643f 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsColumnConfigurator.tsx
@@ -8,19 +8,35 @@ import { useActions, useValues } from 'kea'
import { useMemo, useState } from 'react'
import { IconPencil, IconX } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonModal, LemonSearchableSelect, LemonTextArea, Link } from '@posthog/lemon-ui'
+import {
+ LemonButton,
+ LemonInput,
+ LemonModal,
+ LemonSearchableSelect,
+ LemonSegmentedButton,
+ LemonSelect,
+ LemonTextArea,
+ Link,
+} from '@posthog/lemon-ui'
import { IconOpenInNew, IconTuning, SortableDragIcon } from 'lib/lemon-ui/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { extractDisplayLabel } from '~/queries/nodes/DataTable/utils'
+import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { isNumericDisplayType } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'
import {
ACCOUNTS_NAME_COLUMN,
+ AccountColumnDisplayMode,
AccountColumnGroup,
AccountColumnGroupKey,
+ COLUMN_DISPLAY_WINDOW_OPTIONS,
+ DEFAULT_COLUMN_DISPLAY_WINDOW_DAYS,
accountsColumnConfigLogic,
} from './accountsColumnConfigLogic'
+import { accountsViewsLogic } from './accountsViewsLogic'
const HOGQL_DOCS_URL = 'https://posthog.com/docs/hogql'
@@ -45,15 +61,9 @@ export function AccountsColumnConfigurator(): JSX.Element {
}
function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }): JSX.Element {
- const { selectColumns, accountsColumnGroups, databaseLoading } = useValues(accountsColumnConfigLogic)
- const { moveColumn, resetColumns, setSelectColumns, unselectColumn } = useActions(accountsColumnConfigLogic)
-
- const onEditColumn = (column: string, index: number): void => {
- const next = window.prompt('Edit column', column)
- if (next !== null && next !== '') {
- setSelectColumns(selectColumns.map((c, i) => (i === index ? next : c)))
- }
- }
+ const { selectColumns, accountsColumnGroups, databaseLoading, editingColumn, editingColumnIndex } =
+ useValues(accountsColumnConfigLogic)
+ const { moveColumn, resetColumns, unselectColumn, setEditingColumnIndex } = useActions(accountsColumnConfigLogic)
return (
<LemonModal
@@ -68,6 +78,7 @@ function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean;
Reset to defaults
</LemonButton>
</div>
+ <SaveViewButton />
<LemonButton type="primary" onClick={onClose} data-attr="accounts-columns-done">
Done
</LemonButton>
@@ -98,7 +109,8 @@ function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean;
key={column}
column={column}
dataIndex={index}
- onEdit={onEditColumn}
+ isEditing={index === editingColumnIndex}
+ onEdit={setEditingColumnIndex}
onRemove={unselectColumn}
/>
))}
@@ -106,25 +118,199 @@ function AccountsColumnConfiguratorModal({ isOpen, onClose }: { isOpen: boolean;
</DndContext>
</div>
</div>
- <div className="w-full">
- <h4 className="secondary uppercase text-secondary">Available columns</h4>
- <AvailableColumnsPicker groups={accountsColumnGroups} loading={databaseLoading} />
- </div>
+ {editingColumn !== null && editingColumnIndex !== null ? (
+ <ColumnEditSection
+ key={editingColumnIndex}
+ column={editingColumn}
+ columnIndex={editingColumnIndex}
+ onClose={() => setEditingColumnIndex(null)}
+ />
+ ) : (
+ <div className="w-full">
+ <h4 className="secondary uppercase text-secondary">Available columns</h4>
+ <AvailableColumnsPicker groups={accountsColumnGroups} loading={databaseLoading} />
+ </div>
+ )}
</div>
</div>
</LemonModal>
)
}
+// Column and display changes only persist when saved to a view; surface that path here
+// so users don't have to find the view selector after configuring.
+function SaveViewButton(): JSX.Element {
+ const { currentView, canEditCurrentView, isDirty, viewsLoading } = useValues(accountsViewsLogic)
+ const { updateView, setIsCreating } = useActions(accountsViewsLogic)
+ const { hideColumnConfigurator } = useActions(accountsColumnConfigLogic)
+
+ if (currentView && canEditCurrentView) {
+ return (
+ <LemonButton
+ type="secondary"
+ loading={viewsLoading}
+ disabledReason={isDirty ? undefined : 'No changes to save'}
+ onClick={() => updateView({ id: currentView.id, updates: {} })}
+ data-attr="accounts-columns-update-view"
+ >
+ Update "{currentView.name}"
+ </LemonButton>
+ )
+ }
+ return (
+ <LemonButton
+ type="secondary"
+ // The create-view modal is rendered by AccountsViewSelector and would stack
+ // behind this one — close the configurator first so it's reachable.
+ onClick={() => {
+ hideColumnConfigurator()
+ setIsCreating(true)
+ }}
+ data-attr="accounts-columns-save-view"
+ >
+ Save as new view
+ </LemonButton>
+ )
+}
+
+function ColumnEditSection({
+ column,
+ columnIndex,
+ onClose,
+}: {
+ column: string
+ columnIndex: number
+ onClose: () => void
+}): JSX.Element {
+ const { aliasToDefinition } = useValues(accountsColumnConfigLogic)
+ const definition = aliasToDefinition[extractDisplayLabel(column)]
+
+ return (
+ <div className="w-full flex flex-col gap-2 p-3 border border-border rounded" data-attr="accounts-column-edit">
+ <div className="flex items-center justify-between">
+ <h4 className="secondary uppercase text-secondary mb-0">
+ Edit column{definition ? `: ${definition.name}` : ''}
+ </h4>
+ <LemonButton size="small" onClick={onClose} data-attr="accounts-column-edit-close">
+ Back to available columns
+ </LemonButton>
+ </div>
+ {definition ? (
+ <CustomPropertyDisplayEditor definition={definition} />
+ ) : (
+ <ExpressionEditor column={column} columnIndex={columnIndex} />
+ )}
+ </div>
+ )
+}
+
+function CustomPropertyDisplayEditor({ definition }: { definition: CustomPropertyDefinitionApi }): JSX.Element {
+ const { columnDisplay } = useValues(accountsColumnConfigLogic)
+ const { setColumnDisplay } = useActions(accountsColumnConfigLogic)
+ const definitionId = definition.id
+ const config = columnDisplay[definitionId] ?? null
+ const isNumeric = isNumericDisplayType(definition.display_type)
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-4">
+ <span className="text-sm font-medium">Display as</span>
+ <LemonSegmentedButton
+ size="small"
+ value={config?.mode ?? 'value'}
+ onChange={(mode) =>
+ setColumnDisplay(
+ definitionId,
+ mode === 'value'
+ ? null
+ : {
+ mode: mode as AccountColumnDisplayMode,
+ window_days: config?.window_days ?? DEFAULT_COLUMN_DISPLAY_WINDOW_DAYS,
+ }
+ )
+ }
+ options={[
+ { value: 'value', label: 'Plain value' },
+ {
+ value: 'sparkline',
+ label: 'Sparkline',
+ disabledReason: isNumeric ? undefined : 'Only available for numeric properties',
+ },
+ {
+ value: 'trend',
+ label: 'Trend',
+ disabledReason: isNumeric ? undefined : 'Only available for numeric properties',
+ },
+ ]}
+ data-attr="accounts-column-display-mode"
+ />
+ </div>
+ {config ? (
+ <div className="flex items-center gap-4">
+ <span className="text-sm font-medium">Look-back window</span>
+ <LemonSelect
+ size="small"
+ value={config.window_days}
+ onChange={(window_days) =>
+ window_days != null && setColumnDisplay(definitionId, { ...config, window_days })
+ }
+ options={COLUMN_DISPLAY_WINDOW_OPTIONS.map((days) => ({
+ value: days,
+ label: `${days} days`,
+ }))}
+ data-attr="accounts-column-display-window"
+ />
+ </div>
+ ) : null}
+ <div className="text-xs text-secondary">
+ {config?.mode === 'sparkline'
+ ? 'Shows how the value changed over the look-back window.'
+ : config?.mode === 'trend'
+ ? 'Shows the current value and how much it changed over the look-back window.'
+ : 'Shows the current value.'}
+ </div>
+ </div>
+ )
+}
+
+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,
+ isEditing,
onEdit,
onRemove,
}: {
column: string
dataIndex: number
- onEdit: (column: string, index: number) => void
+ isEditing: boolean
+ onEdit: (index: number) => void
onRemove: (column: string) => void
}): JSX.Element {
const { aliasToDefinition, aliasToRelationshipDefinition } = useValues(accountsColumnConfigLogic)
@@ -154,7 +340,7 @@ function SelectedAccountColumn({
<div className="flex-1" />
{isMandatory ? null : (
<Tooltip title="Edit">
- <LemonButton onClick={() => onEdit(column, dataIndex)} size="small">
+ <LemonButton onClick={() => onEdit(dataIndex)} size="small" active={isEditing}>
<IconPencil data-attr="column-display-item-edit-icon" />
</LemonButton>
</Tooltip>
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts
new file mode 100644
index 000000000000..807ceb5507d8
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts
@@ -0,0 +1,44 @@
+import { buildHistoryDisplay } from './AccountsHogQLTable'
+
+const DAY = 24 * 60 * 60
+const NOW_MS = 1_800_000_000_000
+const NOW_S = NOW_MS / 1000
+
+const daysAgo = (days: number): number => Math.floor(NOW_S - days * DAY)
+
+describe('buildHistoryDisplay', () => {
+ it('carries the last pre-window write forward so sparse histories still chart', () => {
+ const points: [number, number][] = [
+ [daysAgo(45), 100],
+ [daysAgo(3), 120],
+ ]
+ const { latest, baseline, chartPoints } = buildHistoryDisplay(points, 7, NOW_MS)
+ expect(latest).toEqual([daysAgo(3), 120])
+ expect(baseline).toEqual([daysAgo(7), 100])
+ expect(chartPoints).toEqual([
+ [daysAgo(7), 100],
+ [daysAgo(3), 120],
+ ])
+ })
+
+ it('uses only in-window points when nothing precedes the window', () => {
+ const points: [number, number][] = [
+ [daysAgo(5), 10],
+ [daysAgo(1), 30],
+ ]
+ const { baseline, chartPoints } = buildHistoryDisplay(points, 7, NOW_MS)
+ expect(baseline).toEqual([daysAgo(5), 10])
+ expect(chartPoints).toHaveLength(2)
+ })
+
+ it('falls back to a single carried point for a property with one write ever', () => {
+ const points: [number, number][] = [[daysAgo(60), 500]]
+ const { latest, chartPoints } = buildHistoryDisplay(points, 7, NOW_MS)
+ expect(latest).toEqual([daysAgo(60), 500])
+ expect(chartPoints).toHaveLength(1)
+ })
+
+ it('returns empty state for no history', () => {
+ expect(buildHistoryDisplay([], 7, NOW_MS)).toEqual({ latest: null, baseline: null, chartPoints: [] })
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
index 772578a5bd20..64487f466cc4 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
@@ -9,10 +9,14 @@ import type { DataColorToken } from 'lib/colors'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { MemberSelect } from 'lib/components/MemberSelect'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
+import { Sparkline } from 'lib/components/Sparkline'
import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'
import { Link } from 'lib/lemon-ui/Link'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { percentage } from 'lib/utils/numbers'
import { membersLogic } from 'scenes/organization/membersLogic'
import { urls } from 'scenes/urls'
@@ -29,7 +33,12 @@ import type {
import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'
import { formatCustomPropertyValue } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'
import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'
-import { ACCOUNTS_NAME_COLUMN, LEGACY_ROLE_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import {
+ ACCOUNTS_NAME_COLUMN,
+ AccountColumnDisplayConfig,
+ LEGACY_ROLE_COLUMNS,
+ accountsColumnConfigLogic,
+} from './accountsColumnConfigLogic'
import { accountsExpansionLogic } from './accountsExpansionLogic'
import { accountsLogic, savingRoleKey } from './accountsLogic'
import { AccountsEvents } from './constants'
@@ -204,17 +213,127 @@ function RelationshipCell({
)
}
+// History cells arrive as [unix timestamp, value] pairs sorted ascending from the
+// `accounts.custom_properties_history.values` lazy join.
+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) {
+ continue
+ }
+ const timestamp = Number(entry[0])
+ const value = Number(entry[1])
+ if (Number.isFinite(timestamp) && Number.isFinite(value)) {
+ points.push([timestamp, value])
+ }
+ }
+ return points
+}
+
+export interface HistoryDisplay {
+ latest: [number, number] | null
+ /** The value in effect at the window start: the last write before the cutoff,
+ * carried forward, so sparsely-written properties still chart at any window. */
+ baseline: [number, number] | null
+ chartPoints: [number, number][]
+}
+
+export function buildHistoryDisplay(allPoints: [number, number][], windowDays: number, nowMs: number): HistoryDisplay {
+ const cutoff = Math.floor(nowMs / 1000) - windowDays * 24 * 60 * 60
+ const inWindow = allPoints.filter(([timestamp]) => timestamp >= cutoff)
+ const lastBefore = allPoints.filter(([timestamp]) => timestamp < cutoff).at(-1) ?? null
+ const carriedForward: [number, number] | null = lastBefore ? [cutoff, lastBefore[1]] : null
+ const latest = inWindow.at(-1) ?? lastBefore
+ return {
+ latest,
+ baseline: carriedForward ?? inWindow[0] ?? null,
+ chartPoints: carriedForward ? [carriedForward, ...inWindow] : inWindow,
+ }
+}
+
+function CustomPropertyHistoryCell({
+ raw,
+ definition,
+ display,
+}: {
+ raw: unknown
+ definition: CustomPropertyDefinitionApi
+ display: AccountColumnDisplayConfig
+}): JSX.Element {
+ const { latest, baseline, chartPoints } = buildHistoryDisplay(
+ parseHistoryPoints(raw),
+ display.window_days,
+ dayjs().valueOf()
+ )
+
+ if (!latest) {
+ return <span className="text-muted">—</span>
+ }
+ const formatValue = (value: number): string => formatCustomPropertyValue(String(value), definition)
+ if (chartPoints.length < 2) {
+ return (
+ <Tooltip title="Not enough history to chart yet — showing the current value.">
+ <span>{formatValue(latest[1])}</span>
+ </Tooltip>
+ )
+ }
+
+ if (display.mode === 'sparkline') {
+ return (
+ <div className="w-32">
+ <Sparkline
+ type="line"
+ className="h-8"
+ data={chartPoints.map(([, value]) => value)}
+ labels={chartPoints.map(([timestamp]) => dayjs.unix(timestamp).format('MMM D, YYYY HH:mm'))}
+ renderTooltipValue={formatValue}
+ maximumIndicator={false}
+ />
+ </div>
+ )
+ }
+
+ const delta = latest[1] - baseline![1]
+ const deltaClass = delta > 0 ? 'text-success' : delta < 0 ? 'text-danger' : 'text-muted'
+ // Percentage change against the window-start value; a zero baseline has no
+ // meaningful ratio, so fall back to the absolute delta.
+ const deltaText =
+ delta === 0
+ ? 'No change'
+ : baseline![1] === 0
+ ? `${delta > 0 ? '+' : '-'}${formatValue(Math.abs(delta))}`
+ : `${delta > 0 ? '+' : '-'}${percentage(Math.abs(delta / baseline![1]), 1)}`
+ return (
+ <Tooltip
+ title={`${formatValue(latest[1])} now, compared to ${formatValue(baseline![1])} ${display.window_days} days ago`}
+ >
+ <span className="inline-flex items-baseline gap-1.5">
+ <span>{formatValue(latest[1])}</span>
+ <span className={`text-xs ${deltaClass}`}>{deltaText}</span>
+ </span>
+ </Tooltip>
+ )
+}
+
function CustomPropertyCell({
record,
column,
definition,
+ display,
}: {
record: unknown
column: string
definition: CustomPropertyDefinitionApi
+ display?: AccountColumnDisplayConfig
}): JSX.Element {
const getCell = useGetCell()
const raw = getCell(record, column)
+ if (display) {
+ return <CustomPropertyHistoryCell raw={raw} definition={definition} display={display} />
+ }
const value = raw === null || raw === undefined ? '' : String(raw)
if (!value) {
@@ -292,16 +411,19 @@ const KNOWN_COLUMN_TEMPLATES: Record<string, KnownColumnTemplate> = {
}
function useContextColumns(): Record<string, QueryContextColumn> {
- const { visibleColumnNames, aliasToDefinition, aliasToRelationshipDefinition } =
+ const { visibleColumnNames, aliasToDefinition, aliasToRelationshipDefinition, displayByAlias } =
useValues(accountsColumnConfigLogic)
return useMemo(() => {
const columns: Record<string, QueryContextColumn> = {}
for (const key of visibleColumnNames) {
const definition = aliasToDefinition[key]
if (definition) {
+ const display = displayByAlias[key]
columns[key] = {
renderTitle: () => <SortableColumnHeader column={key} label={definition.name} />,
- render: ({ record }) => <CustomPropertyCell record={record} column={key} definition={definition} />,
+ render: ({ record }) => (
+ <CustomPropertyCell record={record} column={key} definition={definition} display={display} />
+ ),
}
continue
}
@@ -325,7 +447,7 @@ function useContextColumns(): Record<string, QueryContextColumn> {
}
}
return columns
- }, [visibleColumnNames, aliasToDefinition, aliasToRelationshipDefinition])
+ }, [visibleColumnNames, aliasToDefinition, aliasToRelationshipDefinition, displayByAlias])
}
function useExpandable(): QueryContext<DataTableNode>['expandable'] {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
index 1bf01c82d2b6..04bb5429ad33 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
@@ -6,6 +6,7 @@ import type {
} from 'products/customer_analytics/frontend/generated/api.schemas'
import {
+ applyColumnDisplayToSelect,
buildAccountColumnGroups,
customPropertyAlias,
relationshipAlias,
@@ -120,4 +121,21 @@ describe('accountsColumnConfigLogic column groups and translation', () => {
`accounts.relationships.values.\`${csm.id}\` AS csm`,
])
})
+
+ it('applyColumnDisplayToSelect swaps only configured custom property columns to the history join', () => {
+ const id = '11111111-2222-3333-4444-555555555555'
+ const scalar = `accounts.custom_properties.values.\`${id}\` AS ${customPropertyAlias(id)}`
+ const other = 'accounts.tags.names AS tag_names'
+
+ expect(applyColumnDisplayToSelect([scalar, other], {})).toEqual([scalar, other])
+ expect(applyColumnDisplayToSelect([scalar, other], { [id]: { mode: 'sparkline', window_days: 7 } })).toEqual([
+ `accounts.custom_properties_history.values.\`${id}\` AS ${customPropertyAlias(id)}`,
+ other,
+ ])
+ expect(
+ applyColumnDisplayToSelect([scalar], {
+ '99999999-0000-1111-2222-333333333333': { mode: 'trend', window_days: 30 },
+ })
+ ).toEqual([scalar])
+ })
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index 93a7cbbf9180..e0df5e53f7cd 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -102,6 +102,38 @@ export function relationshipAlias(id: string): string {
return `rel_${id.replace(/-/g, '')}`
}
+export type AccountColumnDisplayMode = 'sparkline' | 'trend'
+
+export interface AccountColumnDisplayConfig {
+ mode: AccountColumnDisplayMode
+ window_days: number
+}
+
+// Keyed by custom property definition id (not alias) so the config survives column
+// removal/re-add and matches how saved views key custom-property filters.
+export type AccountColumnDisplayState = Record<string, AccountColumnDisplayConfig>
+
+export const COLUMN_DISPLAY_WINDOW_OPTIONS = [7, 14, 30, 90] as const
+export const DEFAULT_COLUMN_DISPLAY_WINDOW_DAYS = 7
+
+const CUSTOM_PROPERTY_COLUMN_REGEX = /^accounts\.custom_properties\.values\.`([0-9a-fA-F-]+)` AS (cp_[0-9a-fA-F]+)$/
+
+// Sparkline/trend columns select the write history instead of the current value. The swap
+// happens at query-build time so the stored column string (saved views, shared URLs) stays
+// in the stable scalar form.
+export function applyColumnDisplayToSelect(columns: string[], columnDisplay: AccountColumnDisplayState): string[] {
+ if (Object.keys(columnDisplay).length === 0) {
+ return columns
+ }
+ return columns.map((column) => {
+ const match = column.match(CUSTOM_PROPERTY_COLUMN_REGEX)
+ if (!match || !columnDisplay[match[1]]) {
+ return column
+ }
+ return `accounts.custom_properties_history.values.\`${match[1]}\` AS ${match[2]}`
+ })
+}
+
function relationshipExpression(definition: AccountRelationshipDefinitionApi, alias: string): string {
return `accounts.relationships.values.\`${definition.id}\` AS ${alias}`
}
@@ -321,6 +353,7 @@ export interface accountsColumnConfigLogicValues {
aliasToDefinition: Record<string, CustomPropertyDefinitionApi>
aliasToRelationshipDefinition: Record<string, AccountRelationshipDefinitionApi>
columnConfiguratorVisible: boolean
+ columnDisplay: AccountColumnDisplayState
customPropertyDefinitions: CustomPropertyDefinitionApi[]
customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
customPropertyDefinitionsLoading: boolean
@@ -329,6 +362,9 @@ export interface accountsColumnConfigLogicValues {
property_type: PropertyType
})[]
defaultSelectColumns: string[]
+ displayByAlias: AccountColumnDisplayState
+ editingColumn: string | null
+ editingColumnIndex: number | null
querySelectColumns: string[]
relationshipDefinitions: AccountRelationshipDefinitionApi[]
relationshipDefinitionsLoaded: boolean
@@ -396,6 +432,19 @@ export interface accountsColumnConfigLogicActions {
selectColumn: (column: string) => {
column: string
}
+ setColumnDisplay: (
+ definitionId: string,
+ config: AccountColumnDisplayConfig | null
+ ) => {
+ config: AccountColumnDisplayConfig | null
+ definitionId: string
+ }
+ setColumnDisplayConfig: (config: AccountColumnDisplayState) => {
+ config: AccountColumnDisplayState
+ }
+ setEditingColumnIndex: (index: number | null) => {
+ index: number | null
+ }
setSelectColumns: (columns: string[]) => {
columns: string[]
}
@@ -405,6 +454,13 @@ 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.
@@ -418,7 +474,8 @@ export interface accountsColumnConfigLogicMeta {
selectColumns: string[],
roleKeyToDefinition: Partial<
Record<'account_executive' | 'account_owner' | 'csm', AccountRelationshipDefinitionApi>
- >
+ >,
+ columnDisplay: AccountColumnDisplayState
) => string[]
visibleColumnNames: (querySelectColumns: string[]) => string[]
accountsColumnGroups: (
@@ -430,6 +487,8 @@ export interface accountsColumnConfigLogicMeta {
customPropertyDefinitionsById: (
customPropertyDefinitions: CustomPropertyDefinitionApi[]
) => Record<string, CustomPropertyDefinitionApi>
+ editingColumn: (selectColumns: string[], editingColumnIndex: number | null) => string | null
+ displayByAlias: (columnDisplay: AccountColumnDisplayState) => AccountColumnDisplayState
aliasToDefinition: (
customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>
) => Record<string, CustomPropertyDefinitionApi>
@@ -479,6 +538,13 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
resetColumns: true,
showColumnConfigurator: true,
hideColumnConfigurator: true,
+ setColumnDisplay: (definitionId: string, config: AccountColumnDisplayConfig | null) => ({
+ definitionId,
+ config,
+ }),
+ setColumnDisplayConfig: (config: AccountColumnDisplayState) => ({ config }),
+ setEditingColumnIndex: (index: number | null) => ({ index }),
+ updateColumnExpression: (index: number, expression: string) => ({ index, expression }),
}),
reducers({
selectColumns: [
@@ -498,6 +564,27 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
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))
+ },
+ },
+ ],
+ // Which visible-column row the configurator's edit section targets. Any action that
+ // reshuffles or replaces the column list closes the editor so the index can't go stale.
+ editingColumnIndex: [
+ null as number | null,
+ {
+ setEditingColumnIndex: (_, { index }) => index,
+ updateColumnExpression: () => null,
+ setSelectColumns: () => null,
+ unselectColumn: () => null,
+ moveColumn: () => null,
+ resetColumns: () => null,
+ hideColumnConfigurator: () => null,
},
],
columnConfiguratorVisible: [
@@ -507,6 +594,19 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
hideColumnConfigurator: () => false,
},
],
+ columnDisplay: [
+ {} as AccountColumnDisplayState,
+ {
+ setColumnDisplay: (state, { definitionId, config }) => {
+ if (!config) {
+ const { [definitionId]: _removed, ...rest } = state
+ return rest
+ }
+ return { ...state, [definitionId]: config }
+ },
+ setColumnDisplayConfig: (_, { config }) => config,
+ },
+ ],
// Queries wait for this so the list fetches once with its final columns,
// instead of fetching with the base columns and refetching after the
// definitions land (a wasted query and a visible column pop).
@@ -563,11 +663,13 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
// names resolved through the relationships lazy join (or dropped when the
// matching definition doesn't exist). Row cells align to THIS list.
querySelectColumns: [
- (s) => [s.selectColumns, s.roleKeyToDefinition],
+ (s) => [s.selectColumns, s.roleKeyToDefinition, s.columnDisplay],
(
selectColumns: string[],
- roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>
- ): string[] => translateSelectColumns(selectColumns, roleKeyToDefinition),
+ roleKeyToDefinition: Partial<Record<AccountRoleKey, AccountRelationshipDefinitionApi>>,
+ columnDisplay: AccountColumnDisplayState
+ ): string[] =>
+ applyColumnDisplayToSelect(translateSelectColumns(selectColumns, roleKeyToDefinition), columnDisplay),
],
visibleColumnNames: [
(s) => [s.querySelectColumns],
@@ -593,6 +695,23 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
(customPropertyDefinitions: CustomPropertyDefinitionApi[]): Record<string, CustomPropertyDefinitionApi> =>
Object.fromEntries(customPropertyDefinitions.map((definition) => [definition.id, definition])),
],
+ editingColumn: [
+ (s) => [s.selectColumns, s.editingColumnIndex],
+ (selectColumns: string[], editingColumnIndex: number | null): string | null =>
+ editingColumnIndex !== null ? (selectColumns[editingColumnIndex] ?? null) : null,
+ ],
+ // Re-keyed by the cp_<id> column alias so cell renderers can look up their
+ // display mode by visible column name.
+ displayByAlias: [
+ (s) => [s.columnDisplay],
+ (columnDisplay: AccountColumnDisplayState): AccountColumnDisplayState =>
+ Object.fromEntries(
+ Object.entries(columnDisplay).map(([definitionId, config]) => [
+ customPropertyAlias(definitionId),
+ config,
+ ])
+ ),
+ ],
// The same map re-keyed by the cp_<id> column alias — resolves visible column
// names back to their definition (table header, configurator labels).
aliasToDefinition: [
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 95f3a3f21781..3d52ef382727 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -30,6 +30,7 @@ import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'
import type { AccountRelationshipDefinitionApi, CustomPropertyDefinitionApi } from '../../generated/api.schemas'
import { isNumericDisplayType } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'
import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic, isLegacyRoleColumn } from './accountsColumnConfigLogic'
+import type { AccountColumnDisplayState } from './accountsColumnConfigLogic'
import { customPropertyFiltersToExpressions } from './accountsCustomPropertyFilters'
import {
ACCOUNT_EXPANSION_TABS,
@@ -155,6 +156,7 @@ export interface AccountsViewUrlState {
mine?: boolean
sort?: NonNullable<AccountSortOrder>
columns?: string[]
+ columnDisplay?: AccountColumnDisplayState
tileFilter?: TileFilter
customProperties?: AccountCustomPropertyFilter[]
}
@@ -163,6 +165,7 @@ export interface AccountsViewUrlState {
export interface accountsLogicValues {
aliasToDefinition: Record<string, CustomPropertyDefinitionApi> // accountsColumnConfigLogic
aliasToRelationshipDefinition: Record<string, AccountRelationshipDefinitionApi> // accountsColumnConfigLogic
+ columnDisplay: AccountColumnDisplayState // accountsColumnConfigLogic
customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi> // accountsColumnConfigLogic
defaultSelectColumns: string[] // accountsColumnConfigLogic
querySelectColumns: string[] // accountsColumnConfigLogic
@@ -209,6 +212,16 @@ export interface accountsLogicActions {
selectColumn: (column: string) => {
column: string
} // accountsColumnConfigLogic
+ setColumnDisplay: (
+ definitionId: string,
+ config: null | import('./accountsColumnConfigLogic').AccountColumnDisplayConfig
+ ) => {
+ config: null | import('./accountsColumnConfigLogic').AccountColumnDisplayConfig
+ definitionId: string
+ } // accountsColumnConfigLogic
+ setColumnDisplayConfig: (config: AccountColumnDisplayState) => {
+ config: AccountColumnDisplayState
+ } // accountsColumnConfigLogic
setSelectColumns: (columns: string[]) => {
columns: string[]
} // accountsColumnConfigLogic
@@ -347,7 +360,8 @@ export interface accountsLogicMeta {
selectColumns: string[],
defaultSelectColumns: string[],
tileFilter: TileFilter | null,
- customPropertyFilters: AccountCustomPropertyFilter[]
+ customPropertyFilters: AccountCustomPropertyFilter[],
+ columnDisplay: AccountColumnDisplayState
) => AccountsViewUrlState
hogqlQuery: (
searchQuery: string,
@@ -404,6 +418,7 @@ export const accountsLogic = kea<accountsLogicType>([
'aliasToDefinition',
'relationshipDefinitionsLoaded',
'customPropertyDefinitionsById',
+ 'columnDisplay',
],
accountsOverviewTilesLogic,
['metrics as overviewMetrics', 'tileFilter'],
@@ -412,7 +427,15 @@ export const accountsLogic = kea<accountsLogicType>([
],
actions: [
accountsColumnConfigLogic,
- ['setSelectColumns', 'selectColumn', 'unselectColumn', 'moveColumn', 'resetColumns'],
+ [
+ 'setSelectColumns',
+ 'selectColumn',
+ 'unselectColumn',
+ 'moveColumn',
+ 'resetColumns',
+ 'setColumnDisplay',
+ 'setColumnDisplayConfig',
+ ],
accountsOverviewTilesLogic,
['setTileFilter'],
accountsExpansionLogic,
@@ -584,6 +607,7 @@ export const accountsLogic = kea<accountsLogicType>([
s.defaultSelectColumns,
s.tileFilter,
s.customPropertyFilters,
+ s.columnDisplay,
],
(
searchQuery: string,
@@ -594,7 +618,8 @@ export const accountsLogic = kea<accountsLogicType>([
selectColumns: string[],
defaultSelectColumns: string[],
tileFilter: TileFilter | null,
- customPropertyFilters: AccountCustomPropertyFilter[]
+ customPropertyFilters: AccountCustomPropertyFilter[],
+ columnDisplay: AccountColumnDisplayState
): AccountsViewUrlState => {
const state: AccountsViewUrlState = {}
const trimmedSearch = searchQuery.trim()
@@ -616,6 +641,9 @@ export const accountsLogic = kea<accountsLogicType>([
if (!objectsEqual(selectColumns, defaultSelectColumns)) {
state.columns = selectColumns
}
+ if (Object.keys(columnDisplay).length > 0) {
+ state.columnDisplay = columnDisplay
+ }
if (tileFilter) {
state.tileFilter = tileFilter
}
@@ -986,6 +1014,8 @@ export const accountsLogic = kea<accountsLogicType>([
unselectColumn: toUrl,
moveColumn: toUrl,
resetColumns: toUrl,
+ setColumnDisplay: toUrl,
+ setColumnDisplayConfig: toUrl,
setTileFilter: toUrl,
}
}),
@@ -1066,6 +1096,12 @@ export const accountsLogic = kea<accountsLogicType>([
actions.setSelectColumns(view.columns)
}
+ const columnDisplay =
+ view.columnDisplay && typeof view.columnDisplay === 'object' ? view.columnDisplay : {}
+ if (!objectsEqual(columnDisplay, values.columnDisplay)) {
+ actions.setColumnDisplayConfig(columnDisplay)
+ }
+
const tileFilter = view.tileFilter ?? null
if (!objectsEqual(tileFilter, values.tileFilter)) {
actions.setTileFilter(tileFilter)
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
index 12bc1c1102b7..b68efb69ce6e 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts
@@ -69,11 +69,14 @@ describe('serializeAccountsView / deserializeAccountsView', () => {
],
},
tiles: [{ id: 't1', label: 'Accounts', metric: { type: 'count' as const } }],
+ columnDisplay: {
+ '11111111-2222-3333-4444-555555555555': { mode: 'sparkline' as const, window_days: 30 },
+ },
}
const payload = serializeAccountsView(state)
expect(payload.order_by).toEqual(['csm DESC'])
expect(payload.columns).toEqual(['name', 'csm'])
- expect(payload.properties).toEqual({ tiles: state.tiles })
+ expect(payload.properties).toEqual({ tiles: state.tiles, column_display: state.columnDisplay })
expect(deserializeAccountsView(payload)).toEqual(state)
})
@@ -90,9 +93,11 @@ describe('serializeAccountsView / deserializeAccountsView', () => {
customProperties: [],
},
tiles: [...DEFAULT_TILES],
+ columnDisplay: {},
})
expect(payload.filters).toEqual({})
expect(payload.order_by).toEqual([])
+ expect(payload.properties).toEqual({ tiles: DEFAULT_TILES })
})
it('treats a legacy columns-only row (filters [], no properties) as defaults', () => {
@@ -107,6 +112,7 @@ describe('serializeAccountsView / deserializeAccountsView', () => {
})
expect(state.tiles).toEqual(DEFAULT_TILES)
expect(state.sortOrder).toBeNull()
+ expect(state.columnDisplay).toEqual({})
})
it('falls back to default columns when a row has none', () => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.ts
index 6d8a2567bc1f..66b7bee1fe5e 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 } from './accountsColumnConfigLogic'
+import { ACCOUNTS_HOGQL_DEFAULT_SELECT, AccountColumnDisplayState } from './accountsColumnConfigLogic'
import type { AccountSortOrder, RoleFilterValue } from './accountsLogic'
import type { AccountsOverviewTile, TileFilter } from './accountsOverviewTilesLogic'
import { DEFAULT_TILES } from './constants'
@@ -18,6 +18,7 @@ export interface AccountsViewFilters {
export interface AccountsViewProperties {
tiles?: AccountsOverviewTile[]
+ column_display?: AccountColumnDisplayState
}
export interface AccountsViewState {
@@ -25,6 +26,7 @@ export interface AccountsViewState {
sortOrder: AccountSortOrder
filters: AccountsViewFilters
tiles: AccountsOverviewTile[]
+ columnDisplay: AccountColumnDisplayState
}
type AccountsViewPayload = Pick<ColumnConfigurationApi, 'columns' | 'order_by'> & {
@@ -84,11 +86,15 @@ export function serializeAccountsView(state: AccountsViewState): AccountsViewPay
if (state.filters.customProperties.length > 0) {
filters.customProperties = state.filters.customProperties
}
+ const properties: AccountsViewProperties = { tiles: state.tiles }
+ if (Object.keys(state.columnDisplay).length > 0) {
+ properties.column_display = state.columnDisplay
+ }
return {
columns: state.columns,
order_by: sortOrderToOrderBy(state.sortOrder),
filters,
- properties: { tiles: state.tiles },
+ properties,
}
}
@@ -113,5 +119,9 @@ export function deserializeAccountsView(view: Partial<ColumnConfigurationApi>):
customProperties: Array.isArray(rawFilters.customProperties) ? rawFilters.customProperties : [],
},
tiles: rawProperties.tiles && rawProperties.tiles.length > 0 ? rawProperties.tiles : [...DEFAULT_TILES],
+ columnDisplay:
+ rawProperties.column_display && typeof rawProperties.column_display === 'object'
+ ? rawProperties.column_display
+ : {},
}
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
index fe768b56d7ce..85f5147dc52b 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.ts
@@ -17,6 +17,7 @@ import { ColumnConfigurationApi } from 'products/product_analytics/frontend/gene
import type { UserType } from '../../../../../frontend/src/types'
import type { AccountCustomPropertyFilter } from '../../../../../frontend/src/types'
import { ACCOUNTS_COLUMN_CONFIG_KEY, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import type { AccountColumnDisplayState } from './accountsColumnConfigLogic'
import { accountsLogic } from './accountsLogic'
import type { AccountSortOrder, RoleFilterValue } from './accountsLogic'
import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'
@@ -33,6 +34,7 @@ export type ViewVisibility = 'private' | 'shared'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsViewsLogicValues {
+ columnDisplay: AccountColumnDisplayState // accountsColumnConfigLogic
selectColumns: string[] // accountsColumnConfigLogic
allRolesUnassigned: boolean // accountsLogic
assignedToFilter: RoleFilterValue // accountsLogic
@@ -109,6 +111,9 @@ export interface accountsViewsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsViewsLogicActions {
+ setColumnDisplayConfig: (config: AccountColumnDisplayState) => {
+ config: AccountColumnDisplayState
+ } // accountsColumnConfigLogic
setSelectColumns: (columns: string[]) => {
columns: string[]
} // accountsColumnConfigLogic
@@ -351,7 +356,8 @@ export interface accountsViewsLogicMeta {
sortOrder: AccountSortOrder,
tileFilter: TileFilter | null,
tiles: AccountsOverviewTile[],
- customPropertyFilters: AccountCustomPropertyFilter[]
+ customPropertyFilters: AccountCustomPropertyFilter[],
+ columnDisplay: AccountColumnDisplayState
) => AccountsViewState
currentView: (views: ColumnConfigurationApi[], currentViewId: string | null) => ColumnConfigurationApi | null
isDirty: (currentView: ColumnConfigurationApi | null, liveViewState: AccountsViewState) => boolean
@@ -375,7 +381,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
userLogic,
['user'],
accountsColumnConfigLogic,
- ['selectColumns'],
+ ['selectColumns', 'columnDisplay'],
accountsLogic,
[
'searchQuery',
@@ -390,7 +396,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
],
actions: [
accountsColumnConfigLogic,
- ['setSelectColumns'],
+ ['setSelectColumns', 'setColumnDisplayConfig'],
accountsLogic,
[
'setSearchQuery',
@@ -494,6 +500,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
s.tileFilter,
s.tiles,
s.customPropertyFilters,
+ s.columnDisplay,
],
(
selectColumns: string[],
@@ -504,7 +511,8 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
sortOrder: import('./accountsLogic').AccountSortOrder,
tileFilter: null | import('./accountsOverviewTilesLogic').TileFilter,
tiles: import('./accountsOverviewTilesLogic').AccountsOverviewTile[],
- customPropertyFilters: import('~/types').AccountCustomPropertyFilter[]
+ customPropertyFilters: import('~/types').AccountCustomPropertyFilter[],
+ columnDisplay: import('./accountsColumnConfigLogic').AccountColumnDisplayState
): AccountsViewState => ({
columns: selectColumns,
sortOrder,
@@ -517,6 +525,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
customProperties: customPropertyFilters,
},
tiles,
+ columnDisplay,
}),
],
currentView: [
@@ -579,6 +588,7 @@ export const accountsViewsLogic = kea<accountsViewsLogicType>([
applyView: ({ view }) => {
const state = deserializeAccountsView(view)
actions.setSelectColumns(state.columns)
+ actions.setColumnDisplayConfig(state.columnDisplay)
actions.setSearchQuery(state.filters.search)
actions.setTagsFilter(state.filters.tags)
// accountsLogic cross-clears the assigned-to filter vs "unassigned only", so set the