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): add configurable accounts overview tiles (#60997)

Arthur Moreira de Deusb19bc183b2ea
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f921ace96146..e0a9de19493d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4191,25 +4191,25 @@ snapshots:
scenes-app-batchexports--runs-with-data--light:
hash: v1.k794b7964.f4a8d5cc4f5447f093d5ddbbcd8572e13f7297a7db8a89504f9290226e60a2bc._CkUe6i49hMMGaDUNDHeNZDgaVp5DJQCay44V8WqfR4
scenes-app-customer-analytics-accounts--default--dark:
- hash: v1.k794b7964.364fd66cbc1f8550023f9b319456628c98d18ffb0eebf19997e7ea3a6132d203.hiid2MP7Dz7Lz8JT0Whv3SDhpzbJbb5hDldnVXU4dcU
+ hash: v1.k794b7964.2cfaa8253c84fdcf8c83cc7ba5a19ad9e23c94d53e22f56e283b70fdfaeba7ec.X3Et3UqSsRTSoIs_gmsFbWBV4l6eneKs60wf-rTmcTM
scenes-app-customer-analytics-accounts--default--light:
- hash: v1.k794b7964.fef53cd15f11d0150aba8d57f105c07447e331ed3fcdb0a2b835a05d3ddb78b2.J1w5KgXTLTr_2dgiMGEcaXFS4z0640fuis4GUV-55sM
+ hash: v1.k794b7964.fc3d8055ff98049e433f274d3349666d00ecc4614fb75251f607fdcb4ce77909.j110JmmyfW52OY83n8BUvVElUT_CRdVQTz6VQNg99Ho
scenes-app-customer-analytics-accounts--empty--dark:
- hash: v1.k794b7964.7f912a40a190873db50f699033fb6a8d012e443e16b4a88402d8feea2537799b.6Uwpljl7-tHmUfhDuxbBI327ghQYyWR6Tly30zwS0Og
+ hash: v1.k794b7964.73491757bada1620aa713372c9e8d46abc53a2af573d0268705bb5b1cbe74c53.2YMX56dsIKrVY1sCeeqQ48PwemBOqeMDhE3Etu75OHo
scenes-app-customer-analytics-accounts--empty--light:
- hash: v1.k794b7964.ff4a55634887ae1e9623859ec7cd51a73385eae41c1958e4cd6147e8160e8527.bmq9aOg_FellQivzjF2qf73EDiPBs1-9wp63N6hf-AU
+ hash: v1.k794b7964.68c2dcb3162cb3778596874e67fec954404912ce39785ad745e4c374b973d7a4.U0ZTB2P50b7MO9p9sY_-wpJPizpxMBjNAq7CCh43Jxs
scenes-app-customer-analytics-accounts--feature-gate-off--dark:
hash: v1.k794b7964.7750bce37ad591ab773135ad1a9b8738ac790727774c03d3aa7b5abbfc42fab0.KbXf74dR5pSVh6Wc8mSjrNGqL8LbTcsMl78W7WVvTXU
scenes-app-customer-analytics-accounts--feature-gate-off--light:
hash: v1.k794b7964.102431e5d999bc15bb9589ef2eccc8d0e44a779b9c820279aa1637d293edf403.AxkbpynMmXkyb0voFylEK03iBfJO43IXPpsGqxgzTkE
scenes-app-customer-analytics-accounts--row-expanded-empty--dark:
- hash: v1.k794b7964.bb77d9f11fba85dbcefb46f2221ad55d8da8b31e6e61bd0b8b53d6ea1cea4810.ZTgUhLKoP86MuHer-MHhS027QmFgMtkdp24XxXu6ycY
+ hash: v1.k794b7964.b13cbe3831d8061ef40152025cdd3d6760f914417355679d0f22581de83de586.W8vrcREpOiVfHeVafSDXEU3Iyom5qvydZLiA0lgnvaU
scenes-app-customer-analytics-accounts--row-expanded-empty--light:
- hash: v1.k794b7964.021a1c353b9538e92b53522c2f9f0ce54edfe2128a8d73d2db5a1c18300fd521.ue3Cheto6fAr6I55Hn41DRJ8Ki0uSQydijiiDYjJpJY
+ hash: v1.k794b7964.904bd5b939f99d43408ae3a8a814a3c299bd57bf13a0fd1d98ff6033fd66e343.K1Z16ICEF6-O9kIej8kGnYyarloq2oZH5rdtmx-8Hu0
scenes-app-customer-analytics-accounts--row-expanded-with-note--dark:
- hash: v1.k794b7964.5766de93c835a93b824169b0d68674fdda0f2370094692ddcf7c7b182a3cfe89.wVjuimww9AOH7VBoaI7Ji07pOrxrW6PmWexYN23lRQc
+ hash: v1.k794b7964.3c9ce002ecb9931c56ef82618cc1625ee847a7f8df2a35c490006e4b356e6fb5.bK3yVZfb-U4TUMJHKvLemkMdqx6YNKdkFC2lnrWBgYg
scenes-app-customer-analytics-accounts--row-expanded-with-note--light:
- hash: v1.k794b7964.ddac5516ff9df120ea18a456cf3a3a648dc5b32cb6672a962c73273f384e4ded.J7Gn0iZoA4IIpF7iidcgsnhSuGPe7YssglzpxegJQl0
+ hash: v1.k794b7964.452b394edba2503e01cded37a8013ba927cbec10f6982ff95452d116a414e76f.QEGOESUmS51vqV3H72T6h8pP4_BPOtai3nUsv91coRU
scenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--dark:
hash: v1.k794b7964.b1e7b3b4db44122983952ce49cdcb2721216d6e09cdda2e03d88250a66f9531d.XEmKGVDBb7ph1xN1zMKNGWDQAkJPR509WPM2orhsrZo
scenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--light:
@@ -4911,7 +4911,7 @@ snapshots:
scenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--light:
hash: v1.k794b7964.414326f685dca45885b93d728ae8a75c7d8b600af35d76c9512a74a27e453006.IyZ8qHUwOv6qsBYvdUR1ZsK1Md_GNFCftDGvNZj78BQ
scenes-app-insights-funnels--funnel-left-to-right-edit--dark:
- hash: v1.k794b7964.c47bdb853ef9b6becfb675e2ca0bdbdb0c1b4385cf2442d50dd92752d90f7906.gaL7vRk-pWoOUkiPi-NGCd1W72x-M5l9jk5Qu-UcjwI
+ hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.xupnP9sdcp25xPBOMzrhSHwtRpKPLKHaqLDBncapvQA
scenes-app-insights-funnels--funnel-left-to-right-edit--light:
hash: v1.k794b7964.c63132bb5b13cbe97938ebdb2e59e320ebc338bd12b2d3bfd6af81e56270650a.3gc3UBg-8GVo4HkNBH7UrogK2q1uh9pXPDjTdYGT8nc
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--medium--dark:
@@ -4923,7 +4923,7 @@ snapshots:
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--superwide--light:
hash: v1.k794b7964.c95c5a49f7a20b7fcb1041dd26c73ee87c9a906cb229247a44fd4633bbdc9173.StrJ2VBA5acLqvnsiO2CS_o6qadxeaeO6ST8lxf5UdI
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--dark:
- hash: v1.k794b7964.c47bdb853ef9b6becfb675e2ca0bdbdb0c1b4385cf2442d50dd92752d90f7906.URrKOLP9uUjbKWcui2yOA7hm_JsXsbkAlOcWJshoQrI
+ hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.O7SwG4Drfr3z02hcLNC1LsLsGWddouhybBp4xZaUE-A
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--light:
hash: v1.k794b7964.c63132bb5b13cbe97938ebdb2e59e320ebc338bd12b2d3bfd6af81e56270650a.KSiw8WpvjWXIDh87ExL4cPnopVJlTXvzU8N8ruh6Hi8
scenes-app-insights-funnels--funnel-time-to-convert--dark:
diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
index 62efab4d66d5..4246a74e7920 100644
--- a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
@@ -1,5 +1,6 @@
import clsx from 'clsx'
import { useValues } from 'kea'
+import type React from 'react'
import { IconTrending, IconWarning } from '@posthog/icons'
import { LemonBanner, LemonSkeleton, Link } from '@posthog/lemon-ui'
@@ -33,6 +34,12 @@ export interface OverviewItem {
isIncreaseBad?: boolean
warning?: string
warningLink?: string
+ /** Optional human-readable description rendered under the value. Only shown when no trend is present. */
+ caption?: string
+ /** Click handler. When set, the cell renders as a button and shows a pointer cursor. */
+ onClick?: () => void
+ /** Render with the highlighted/active appearance — e.g. when this tile drives an active filter. */
+ selected?: boolean
}
export interface SamplingRate {
@@ -183,12 +190,35 @@ const OverviewItemCell = ({
? `${label}: ${formatItem(item.value, item.kind, { precise: true, currency: baseCurrency })}`
: 'No data'
+ const clickable = !!item.onClick
+ const handleClick = clickable
+ ? (event: React.MouseEvent) => {
+ event.stopPropagation()
+ item.onClick?.()
+ }
+ : undefined
+ const handleKeyDown = clickable
+ ? (event: React.KeyboardEvent) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault()
+ item.onClick?.()
+ }
+ }
+ : undefined
+
return (
<div
className={clsx(
- 'flex-1 border bg-surface-primary rounded relative',
- compact ? 'min-w-[6rem] h-24' : 'min-w-[10rem] h-30'
+ 'flex-1 border bg-surface-primary rounded relative transition-colors',
+ compact ? 'min-w-[6rem] h-24' : 'min-w-[10rem] h-30',
+ item.selected && 'border-accent ring-1 ring-accent',
+ clickable && 'cursor-pointer hover:border-accent'
)}
+ onClick={handleClick}
+ onKeyDown={handleKeyDown}
+ role={clickable ? 'button' : undefined}
+ tabIndex={clickable ? 0 : undefined}
+ aria-pressed={clickable ? !!item.selected : undefined}
>
{/* Rendered as a sibling of the Tooltip trigger so hovering the badge
does not also surface the cell's metric tooltip. */}
@@ -242,6 +272,13 @@ const OverviewItemCell = ({
</div>
) : isNotNil(item.changeFromPreviousPct) && Math.abs(item.changeFromPreviousPct) >= 999999 ? (
<div className="text-muted">-</div>
+ ) : item.caption ? (
+ <div
+ className={clsx('text-secondary truncate max-w-full', compact ? 'text-[10px]' : 'text-xs')}
+ title={item.caption}
+ >
+ {item.caption}
+ </div>
) : (
<div />
)}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 9e118b307a66..6362d5d768d5 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -33,6 +33,10 @@
"csm": {
"$ref": "#/definitions/AccountsRoleAssignmentFilter"
},
+ "filterExpression": {
+ "$ref": "#/definitions/HogQLExpression",
+ "description": "Optional HogQL boolean expression AND-ed into the WHERE clause. Used by the overview tile click-to-filter affordance."
+ },
"kind": {
"const": "AccountsQuery",
"type": "string"
@@ -40,6 +44,13 @@
"limit": {
"$ref": "#/definitions/integer"
},
+ "metrics": {
+ "description": "Aggregation expressions evaluated against the filtered account set; one value per metric is returned in `metricsResults`. When `metrics` is set without a `select`, the runner skips the regular row fetch and returns only the aggregated values.",
+ "items": {
+ "$ref": "#/definitions/HogQLExpression"
+ },
+ "type": "array"
+ },
"modifiers": {
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
@@ -107,6 +118,13 @@
"limit": {
"$ref": "#/definitions/integer"
},
+ "metricsResults": {
+ "description": "When `metrics` is set on the query, the aggregated values in the same order.",
+ "items": {
+ "type": ["number", "null"]
+ },
+ "type": "array"
+ },
"modifiers": {
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
@@ -4888,6 +4906,13 @@
"limit": {
"$ref": "#/definitions/integer"
},
+ "metricsResults": {
+ "description": "When `metrics` is set on the query, the aggregated values in the same order.",
+ "items": {
+ "type": ["number", "null"]
+ },
+ "type": "array"
+ },
"modifiers": {
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
@@ -14124,6 +14149,13 @@
"limit": {
"$ref": "#/definitions/integer"
},
+ "metricsResults": {
+ "description": "When `metrics` is set on the query, the aggregated values in the same order.",
+ "items": {
+ "type": ["number", "null"]
+ },
+ "type": "array"
+ },
"modifiers": {
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
@@ -33415,6 +33447,13 @@
"limit": {
"$ref": "#/definitions/integer"
},
+ "metricsResults": {
+ "description": "When `metrics` is set on the query, the aggregated values in the same order.",
+ "items": {
+ "type": ["number", "null"]
+ },
+ "type": "array"
+ },
"modifiers": {
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
@@ -34660,6 +34699,13 @@
"limit": {
"$ref": "#/definitions/integer"
},
+ "metricsResults": {
+ "description": "When `metrics` is set on the query, the aggregated values in the same order.",
+ "items": {
+ "type": ["number", "null"]
+ },
+ "type": "array"
+ },
"modifiers": {
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 639f63ecab58..2c809a1ef0a9 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2281,6 +2281,8 @@ export interface AccountsQueryResponse extends AnalyticsQueryResponseBase {
hasMore?: boolean
limit: integer
offset: integer
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[]
}
export type AccountsRoleAssignmentFilter = integer | 'unassigned'
@@ -2288,12 +2290,16 @@ export type AccountsRoleAssignmentFilter = integer | 'unassigned'
export interface AccountsQuery extends DataNode<AccountsQueryResponse> {
kind: NodeKind.AccountsQuery
select?: HogQLExpression[]
+ /** Aggregation expressions evaluated against the filtered account set; one value per metric is returned in `metricsResults`. When `metrics` is set without a `select`, the runner skips the regular row fetch and returns only the aggregated values. */
+ metrics?: HogQLExpression[]
search?: string
tagNames?: string[]
csm?: AccountsRoleAssignmentFilter
accountExecutive?: AccountsRoleAssignmentFilter
accountOwner?: AccountsRoleAssignmentFilter
allRolesUnassigned?: boolean
+ /** Optional HogQL boolean expression AND-ed into the WHERE clause. Used by the overview tile click-to-filter affordance. */
+ filterExpression?: HogQLExpression
orderBy?: string[]
limit?: integer
offset?: integer
diff --git a/posthog/schema.py b/posthog/schema.py
index 7fc33f91e8dd..b9f7d3227935 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -10065,6 +10065,10 @@ class AccountsQueryResponse(BaseModel):
hogql: str = Field(..., description="Generated HogQL query.")
kind: Literal["AccountsQuery"] = "AccountsQuery"
limit: int
+ metricsResults: list[float | None] | None = Field(
+ default=None,
+ description=("When `metrics` is set on the query, the aggregated values in the same order."),
+ )
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int
query_status: QueryStatus | None = Field(
@@ -11465,6 +11469,10 @@ class CachedAccountsQueryResponse(BaseModel):
kind: Literal["AccountsQuery"] = "AccountsQuery"
last_refresh: AwareDatetime
limit: int
+ metricsResults: list[float | None] | None = Field(
+ default=None,
+ description=("When `metrics` is set on the query, the aggregated values in the same order."),
+ )
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
next_allowed_client_refresh: AwareDatetime
offset: int
@@ -15467,6 +15475,10 @@ class Response27(BaseModel):
hogql: str = Field(..., description="Generated HogQL query.")
kind: Literal["AccountsQuery"] = "AccountsQuery"
limit: int
+ metricsResults: list[float | None] | None = Field(
+ default=None,
+ description=("When `metrics` is set on the query, the aggregated values in the same order."),
+ )
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int
query_status: QueryStatus | None = Field(
@@ -19834,6 +19846,10 @@ class QueryResponseAlternative66(BaseModel):
hogql: str = Field(..., description="Generated HogQL query.")
kind: Literal["AccountsQuery"] = "AccountsQuery"
limit: int
+ metricsResults: list[float | None] | None = Field(
+ default=None,
+ description=("When `metrics` is set on the query, the aggregated values in the same order."),
+ )
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int
query_status: QueryStatus | None = Field(
@@ -20620,6 +20636,10 @@ class QueryResponseAlternative91(BaseModel):
hogql: str = Field(..., description="Generated HogQL query.")
kind: Literal["AccountsQuery"] = "AccountsQuery"
limit: int
+ metricsResults: list[float | None] | None = Field(
+ default=None,
+ description=("When `metrics` is set on the query, the aggregated values in the same order."),
+ )
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int
query_status: QueryStatus | None = Field(
@@ -21910,8 +21930,24 @@ class AccountsQuery(BaseModel):
accountOwner: str | int | None = None
allRolesUnassigned: bool | None = None
csm: str | int | None = None
+ filterExpression: str | None = Field(
+ default=None,
+ description=(
+ "Optional HogQL boolean expression AND-ed into the WHERE clause. Used by"
+ " the overview tile click-to-filter affordance."
+ ),
+ )
kind: Literal["AccountsQuery"] = "AccountsQuery"
limit: int | None = None
+ metrics: list[str] | None = Field(
+ default=None,
+ description=(
+ "Aggregation expressions evaluated against the filtered account set; one"
+ " value per metric is returned in `metricsResults`. When `metrics` is set"
+ " without a `select`, the runner skips the regular row fetch and returns"
+ " only the aggregated values."
+ ),
+ )
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
orderBy: list[str] | None = None
diff --git a/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
index fcc8e7cf17d8..6d4b4052fc1b 100644
--- a/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
@@ -1,8 +1,11 @@
from posthog.schema import AccountsQuery, AccountsQueryResponse, CachedAccountsQueryResponse
from posthog.hogql import ast
+from posthog.hogql.errors import BaseHogQLError, ExposedHogQLError
from posthog.hogql.parser import parse_expr, parse_order_expr, parse_select
+from posthog.hogql.query import execute_hogql_query
+from posthog.errors import ExposedCHQueryError, InternalCHQueryError
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.models import User
@@ -37,21 +40,25 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- raw_selects = list(self.query.select) if self.query.select else list(DEFAULT_COLUMNS)
+ # Metrics-only callers (just aggregations, no `select`) skip column
+ # resolution. A combined query carries both `select` and `metrics`.
+ self._metrics_only = bool(self.query.metrics) and not self.query.select
- seen: set[str] = set()
self.columns: list[str] = []
self._select_exprs: list[ast.Expr] = []
- for raw in raw_selects:
- column_name, expr = self._resolve_column(raw)
- if column_name in seen:
- continue
- seen.add(column_name)
- self.columns.append(column_name)
- self._select_exprs.append(expr)
- if NAME_COLUMN not in seen:
- self.columns.insert(0, NAME_COLUMN)
- self._select_exprs.insert(0, self._name_tuple_expr())
+ if not self._metrics_only:
+ raw_selects = list(self.query.select) if self.query.select else list(DEFAULT_COLUMNS)
+ seen: set[str] = set()
+ for raw in raw_selects:
+ column_name, expr = self._resolve_column(raw)
+ if column_name in seen:
+ continue
+ seen.add(column_name)
+ self.columns.append(column_name)
+ self._select_exprs.append(expr)
+ if NAME_COLUMN not in seen:
+ self.columns.insert(0, NAME_COLUMN)
+ self._select_exprs.insert(0, self._name_tuple_expr())
self.paginator = HogQLHasMorePaginator.from_limit_context(
limit_context=self.limit_context,
@@ -88,7 +95,7 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
),
)
- def to_query(self) -> ast.SelectQuery:
+ def _build_where_exprs(self) -> list[ast.Expr]:
where_exprs: list[ast.Expr] = []
if self.query.search and self.query.search.strip():
@@ -113,6 +120,13 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
for json_key in ROLE_FIELDS.values():
where_exprs.append(self._role_id_isnull(json_key))
+ if self.query.filterExpression and self.query.filterExpression.strip():
+ where_exprs.append(parse_expr(self.query.filterExpression))
+
+ return where_exprs
+
+ def to_query(self) -> ast.SelectQuery:
+ where_exprs = self._build_where_exprs()
order_clauses = self.query.orderBy or [DEFAULT_ORDER_BY]
return ast.SelectQuery(
@@ -125,6 +139,18 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
order_by=[parse_order_expr(_normalize_order_clause(c), timings=self.timings) for c in order_clauses],
)
+ def _to_metrics_query(self, metrics: list[str]) -> ast.SelectQuery:
+ where_exprs = self._build_where_exprs()
+ select_exprs = [parse_expr(expr) for expr in metrics]
+ return ast.SelectQuery(
+ select=select_exprs,
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=["system", "accounts"]),
+ alias="accounts",
+ ),
+ where=ast.And(exprs=where_exprs) if where_exprs else None,
+ )
+
def _tag_filter_expr(self, tag_names: list[str]) -> ast.Expr:
subquery = parse_select(
"""
@@ -161,6 +187,21 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
)
def _calculate(self) -> AccountsQueryResponse:
+ metrics_results = self._compute_metrics_results(self.query.metrics) if self.query.metrics else None
+
+ if self._metrics_only:
+ return AccountsQueryResponse(
+ kind="AccountsQuery",
+ columns=[],
+ results=[],
+ types=[],
+ metricsResults=metrics_results,
+ hogql="",
+ modifiers=self.modifiers,
+ limit=self.query.limit or 0,
+ offset=self.query.offset or 0,
+ )
+
response = self.paginator.execute_hogql_query(
query_type="AccountsQuery",
query=self.to_query(),
@@ -184,8 +225,56 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
columns=list(self.columns),
results=results,
types=[t for _, t in response.types] if response.types else [],
+ metricsResults=metrics_results,
hogql=response.hogql or "",
timings=response.timings,
modifiers=self.modifiers,
**self.paginator.response_params(),
)
+
+ def _compute_metrics_results(self, metrics: list[str]) -> list[float | int | None]:
+ try:
+ response = self._execute_metrics_query(metrics)
+ except (InternalCHQueryError, BaseHogQLError) as error:
+ raise self._metric_evaluation_error(metrics, error) from error
+
+ row = response.results[0] if response.results else []
+ metrics_results: list[float | int | None] = [
+ (value if isinstance(value, (int, float)) else None) for value in row
+ ]
+ while len(metrics_results) < len(metrics):
+ metrics_results.append(None)
+ return metrics_results
+
+ def _execute_metrics_query(self, metrics: list[str]):
+ return execute_hogql_query(
+ query_type="AccountsMetricsQuery",
+ query=self._to_metrics_query(metrics),
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ )
+
+ def _metric_evaluation_error(self, metrics: list[str], error: Exception) -> ExposedHogQLError:
+ culprits = self._isolate_failing_metrics(metrics) if len(metrics) > 1 else list(metrics)
+ listed = ", ".join(f"`{expr}`" for expr in (culprits or metrics))
+ plural = "s" if len(culprits or metrics) > 1 else ""
+ detail = (
+ f"Could not evaluate overview tile metric{plural}: {listed}. "
+ "Check that any referenced column exists and is numeric "
+ "(data warehouse columns must be synced)."
+ )
+ if isinstance(error, (ExposedHogQLError, ExposedCHQueryError)):
+ detail = f"{detail} {error}"
+ return ExposedHogQLError(detail)
+
+ def _isolate_failing_metrics(self, metrics: list[str]) -> list[str]:
+ """Re-run each metric on its own (error path only) to name the offenders."""
+ failing: list[str] = []
+ for expr in metrics:
+ try:
+ self._execute_metrics_query([expr])
+ except Exception:
+ failing.append(expr)
+ return failing
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 55a395801b37..41fa66e7f086 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
@@ -7,6 +7,8 @@ from parameterized import parameterized
from posthog.schema import AccountsQuery, AccountsQueryResponse
+from posthog.hogql.errors import ExposedHogQLError
+
from posthog.api.tagged_item import set_tags_on_object
from posthog.constants import AvailableFeature
from posthog.models import Tag
@@ -377,6 +379,64 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
runner = AccountsQueryRunner(query=AccountsQuery(select=["id", "name", "id"]), team=self.team)
self.assertEqual(runner.columns, ["id", "name"])
+ def test_metrics_mode_returns_aggregations_and_no_rows(self):
+ create_account(team_id=self.team.id, name="A")
+ create_account(team_id=self.team.id, name="B")
+ create_account(team_id=self.team.id, name="C")
+ _, response = self._run_query(metrics=["count()"], select=[])
+ self.assertEqual(response.results, [])
+ self.assertEqual(response.columns, [])
+ self.assertEqual(response.metricsResults, [3])
+
+ def test_combined_mode_returns_rows_and_metrics_in_one_response(self):
+ create_account(team_id=self.team.id, name="A")
+ create_account(team_id=self.team.id, name="B")
+ create_account(team_id=self.team.id, name="C")
+ runner, response = self._run_query(select=["name"], metrics=["count()"])
+ name_idx = runner.columns.index("name")
+ self.assertEqual(len(response.results), 3)
+ self.assertTrue(all(row[name_idx]["name"] for row in response.results))
+ self.assertEqual(response.metricsResults, [3])
+
+ def test_metrics_mode_reuses_table_where_clause(self):
+ create_account(team_id=self.team.id, name="Acme")
+ create_account(team_id=self.team.id, name="Other")
+ _, response = self._run_query(metrics=["count()"], select=[], search="acme")
+ self.assertEqual(response.metricsResults, [1])
+
+ def test_metrics_mode_respects_team_isolation(self):
+ create_account(team_id=self.team.id, name="Mine")
+ other_team = Team.objects.create(organization=self.organization)
+ create_account(team_id=other_team.id, name="Theirs")
+ _, response = self._run_query(metrics=["count()"], select=[])
+ self.assertEqual(response.metricsResults, [1])
+
+ def test_bad_metric_raises_an_error_naming_the_offending_expression(self):
+ create_account(team_id=self.team.id, name="A")
+ with self.assertRaises(ExposedHogQLError) as ctx:
+ self._run_query(select=["name"], metrics=["count()", "sum(does_not_exist)"])
+ message = str(ctx.exception)
+ self.assertIn("sum(does_not_exist)", message)
+ # The healthy metric should not be blamed.
+ self.assertNotIn("`count()`", message)
+
+ def test_filter_expression_narrows_the_row_set(self):
+ create_account(team_id=self.team.id, name="A", _properties={"score": 80})
+ create_account(team_id=self.team.id, name="B", _properties={"score": 20})
+ create_account(team_id=self.team.id, name="C", _properties={"score": 10})
+ ids = self._ids(filterExpression="JSONExtract(properties, 'score', 'Nullable(Int64)') < 50")
+ self.assertEqual(len(ids), 2)
+
+ def test_filter_expression_combines_with_search(self):
+ create_account(team_id=self.team.id, name="Match", _properties={"score": 5})
+ create_account(team_id=self.team.id, name="WrongScore", _properties={"score": 99})
+ create_account(team_id=self.team.id, name="WrongName", _properties={"score": 5})
+ names = self._names(
+ search="match",
+ filterExpression="JSONExtract(properties, 'score', 'Nullable(Int64)') < 50",
+ )
+ self.assertEqual(names, ["Match"])
+
def test_validate_query_runner_access_default(self):
runner = AccountsQueryRunner(query=AccountsQuery(), team=self.team)
self.assertTrue(runner.validate_query_runner_access(self.user))
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
index 821a9480b0ad..a491cd6f3300 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
@@ -14,10 +14,10 @@ import { DataTable } from '~/queries/nodes/DataTable/DataTable'
import { DataTableNode } from '~/queries/schema/schema-general'
import { QueryContext, QueryContextColumn, QueryContextColumnComponent } from '~/queries/types'
+import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'
import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'
import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
-import { AccountsColumnConfigurator } from './AccountsColumnConfigurator'
-import { ACCOUNTS_HOGQL_DATA_NODE_KEY, AccountRoleKey, accountsLogic } from './accountsLogic'
+import { AccountRoleKey, accountsLogic } from './accountsLogic'
type AccountAssignment = { id: number; email: string } | null
@@ -310,7 +310,8 @@ function AccountsHogQLSkeleton(): JSX.Element {
)
}
-function AccountsHogQLDataTable({ query }: { query: DataTableNode }): JSX.Element {
+export function AccountsHogQLTable(): JSX.Element {
+ const { hogqlQuery } = useValues(accountsLogic)
const { responseLoading, response } = useValues(dataNodeLogic)
const contextColumns = useContextColumns()
const expandable = useExpandable()
@@ -320,7 +321,7 @@ function AccountsHogQLDataTable({ query }: { query: DataTableNode }): JSX.Elemen
return (
<DataTable
uniqueKey="customer-analytics-accounts-hogql"
- query={query}
+ query={hogqlQuery}
setQuery={() => {
// Filters are owned by accountsLogic; column/sort changes from the DataTable are ignored on purpose.
}}
@@ -335,16 +336,3 @@ function AccountsHogQLDataTable({ query }: { query: DataTableNode }): JSX.Elemen
/>
)
}
-
-export function AccountsHogQLTable(): JSX.Element {
- const { hogqlQuery } = useValues(accountsLogic)
-
- return (
- <div className="flex flex-col gap-2">
- <div className="flex justify-end">
- <AccountsColumnConfigurator />
- </div>
- <AccountsHogQLDataTable query={hogqlQuery} />
- </div>
- )
-}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTiles.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTiles.tsx
new file mode 100644
index 000000000000..66b5a362f2b7
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTiles.tsx
@@ -0,0 +1,65 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { OverviewGrid, OverviewItem } from '~/queries/nodes/OverviewGrid/OverviewGrid'
+
+import { accountsOverviewTilesLogic, AccountsOverviewTile, isTileClickable } from './accountsOverviewTilesLogic'
+
+function tileCaption(tile: AccountsOverviewTile): string | undefined {
+ const { metric } = tile
+ switch (metric.type) {
+ case 'count':
+ return undefined
+ case 'sum':
+ return `sum of ${metric.columnLabel}`
+ case 'avg':
+ return `avg of ${metric.columnLabel}`
+ case 'count_threshold':
+ return `${metric.columnLabel} ${metric.operator} ${metric.value}`
+ }
+}
+
+function tileLabelByKey(tiles: AccountsOverviewTile[]): (key: string) => string {
+ const labelsById = new Map(tiles.map((tile) => [tile.id, tile.label]))
+ return (key) => labelsById.get(key) ?? key
+}
+
+export function AccountsOverviewTiles(): JSX.Element {
+ const { reconciledTiles, tileValues, tilesLoading, selectedTileId } = useValues(accountsOverviewTilesLogic)
+ const { showEditor, toggleTileSelection } = useActions(accountsOverviewTilesLogic)
+
+ const overviewItems: OverviewItem[] = reconciledTiles.map((tile) => ({
+ key: tile.id,
+ value: tileValues[tile.id] ?? undefined,
+ kind: 'unit',
+ caption: tileCaption(tile),
+ selected: selectedTileId === tile.id,
+ onClick: isTileClickable(tile) ? () => toggleTileSelection(tile) : undefined,
+ }))
+
+ if (reconciledTiles.length === 0) {
+ return (
+ <div
+ className="border rounded p-6 flex flex-col items-center justify-center gap-2 text-secondary bg-surface-primary"
+ data-attr="accounts-overview-tiles"
+ >
+ <span>No overview tiles configured.</span>
+ <LemonButton type="primary" size="small" onClick={showEditor}>
+ Add tile
+ </LemonButton>
+ </div>
+ )
+ }
+
+ return (
+ <div data-attr="accounts-overview-tiles">
+ <OverviewGrid
+ items={overviewItems}
+ loading={tilesLoading}
+ numSkeletons={Math.max(reconciledTiles.length, 1)}
+ labelFromKey={tileLabelByKey(reconciledTiles)}
+ />
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesButton.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesButton.tsx
new file mode 100644
index 000000000000..5ad0ed1c2aa6
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesButton.tsx
@@ -0,0 +1,27 @@
+import { useActions, useValues } from 'kea'
+
+import { IconGear } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { AccountsOverviewTilesEditor } from './AccountsOverviewTilesEditor'
+import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'
+
+export function AccountsOverviewTilesButton(): JSX.Element {
+ const { editorVisible } = useValues(accountsOverviewTilesLogic)
+ const { showEditor, hideEditor } = useActions(accountsOverviewTilesLogic)
+
+ return (
+ <>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconGear />}
+ onClick={showEditor}
+ data-attr="accounts-overview-tiles-edit"
+ >
+ Edit overview tiles
+ </LemonButton>
+ <AccountsOverviewTilesEditor isOpen={editorVisible} onClose={hideEditor} />
+ </>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
new file mode 100644
index 000000000000..ef785bdf6d91
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
@@ -0,0 +1,307 @@
+import { DndContext } from '@dnd-kit/core'
+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'
+import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { IconPlus, IconX } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonModal, LemonSelect } from '@posthog/lemon-ui'
+
+import { SortableDragIcon } from 'lib/lemon-ui/icons'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+import { AccountColumnOption } from './accountsColumnConfigLogic'
+import {
+ ACCOUNTS_OVERVIEW_THRESHOLD_OPERATORS,
+ AccountsOverviewThresholdOperator,
+ accountsOverviewTilesLogic,
+ AccountsOverviewTile,
+ AccountsOverviewTileMetric,
+ AccountsOverviewTileMetricType,
+} from './accountsOverviewTilesLogic'
+
+const METRIC_TYPE_LABELS: Record<AccountsOverviewTileMetricType, string> = {
+ count: 'Count of accounts',
+ sum: 'Sum of column',
+ avg: 'Average of column',
+ count_threshold: 'Count above/below threshold',
+}
+
+function fallbackColumn(options: AccountColumnOption[]): AccountColumnOption | null {
+ return options[0] ?? null
+}
+
+function defaultLabelForMetric(metric: AccountsOverviewTileMetric): string {
+ switch (metric.type) {
+ case 'count':
+ return 'Accounts'
+ case 'sum':
+ return `Total ${metric.columnLabel}`
+ case 'avg':
+ return `Average ${metric.columnLabel}`
+ case 'count_threshold':
+ return `Accounts ${metric.operator} ${metric.value}`
+ }
+}
+
+function metricOfType(
+ type: AccountsOverviewTileMetricType,
+ options: AccountColumnOption[],
+ previous: AccountsOverviewTileMetric
+): AccountsOverviewTileMetric | null {
+ if (type === 'count') {
+ return { type: 'count' }
+ }
+ let columnExpression: string
+ let columnLabel: string
+ if (previous.type !== 'count') {
+ columnExpression = previous.columnExpression
+ columnLabel = previous.columnLabel
+ } else {
+ const fallback = fallbackColumn(options)
+ if (!fallback) {
+ return null
+ }
+ columnExpression = fallback.expression
+ columnLabel = fallback.name
+ }
+ if (type === 'count_threshold') {
+ return {
+ type,
+ columnExpression,
+ columnLabel,
+ operator: previous.type === 'count_threshold' ? previous.operator : '>',
+ value: previous.type === 'count_threshold' ? previous.value : 0,
+ }
+ }
+ return { type, columnExpression, columnLabel }
+}
+
+export function AccountsOverviewTilesEditor({
+ isOpen,
+ onClose,
+}: {
+ isOpen: boolean
+ onClose: () => void
+}): JSX.Element {
+ const { tiles, numericColumns } = useValues(accountsOverviewTilesLogic)
+ const { addTile, updateTile, removeTile, moveTile, resetTiles } = useActions(accountsOverviewTilesLogic)
+
+ const handleAddTile = (): void => {
+ addTile({ label: 'Accounts', metric: { type: 'count' } })
+ }
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ title="Edit overview tiles"
+ onClose={onClose}
+ className="w-full max-w-248"
+ footer={
+ <>
+ <div className="flex-1 flex items-center gap-2">
+ <LemonButton type="secondary" onClick={resetTiles}>
+ Reset to defaults
+ </LemonButton>
+ </div>
+ <LemonButton type="secondary" onClick={onClose} data-attr="accounts-overview-tiles-close">
+ Close
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-3">
+ {tiles.length === 0 ? (
+ <div className="text-secondary text-sm">No tiles configured yet — add one to get started.</div>
+ ) : (
+ <DndContext
+ onDragEnd={({ active, over }) => {
+ if (!over || active.id === over.id) {
+ return
+ }
+ const oldIndex = tiles.findIndex((t) => t.id === active.id)
+ const newIndex = tiles.findIndex((t) => t.id === over.id)
+ if (oldIndex >= 0 && newIndex >= 0) {
+ moveTile(oldIndex, newIndex)
+ }
+ }}
+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}
+ >
+ <SortableContext items={tiles.map((t) => t.id)} strategy={verticalListSortingStrategy}>
+ <div className="flex flex-col gap-2">
+ {tiles.map((tile) => (
+ <TileEditorRow
+ key={tile.id}
+ tile={tile}
+ numericColumns={numericColumns}
+ onChange={(next) => updateTile(tile.id, next)}
+ onRemove={() => removeTile(tile.id)}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ )}
+ <LemonButton
+ type="secondary"
+ icon={<IconPlus />}
+ onClick={handleAddTile}
+ data-attr="accounts-overview-tiles-add"
+ >
+ Add tile
+ </LemonButton>
+ </div>
+ </LemonModal>
+ )
+}
+
+interface TileEditorRowProps {
+ tile: AccountsOverviewTile
+ numericColumns: AccountColumnOption[]
+ onChange: (next: Omit<AccountsOverviewTile, 'id'>) => void
+ onRemove: () => void
+}
+
+function TileEditorRow({ tile, numericColumns, onChange, onRemove }: TileEditorRowProps): JSX.Element {
+ const { setNodeRef, attributes, transform, transition, listeners } = useSortable({ id: tile.id })
+ const needsColumn = tile.metric.type !== 'count'
+ const noNumericColumns = numericColumns.length === 0
+
+ const columnOptions = useMemo(
+ () => numericColumns.map((column) => ({ value: column.expression, label: column.name })),
+ [numericColumns]
+ )
+
+ const onMetricTypeChange = (next: AccountsOverviewTileMetricType): void => {
+ const nextMetric = metricOfType(next, numericColumns, tile.metric)
+ if (!nextMetric) {
+ return
+ }
+ onChange({ label: tile.label, metric: nextMetric })
+ }
+
+ const onColumnChange = (expression: string): void => {
+ if (tile.metric.type === 'count') {
+ return
+ }
+ const column = numericColumns.find((c) => c.expression === expression)
+ if (!column) {
+ return
+ }
+ const previousLabelLooksAuto = tile.label === defaultLabelForMetric(tile.metric)
+ const nextMetric: AccountsOverviewTileMetric = {
+ ...tile.metric,
+ columnExpression: column.expression,
+ columnLabel: column.name,
+ }
+ onChange({
+ label: previousLabelLooksAuto ? defaultLabelForMetric(nextMetric) : tile.label,
+ metric: nextMetric,
+ })
+ }
+
+ const onOperatorChange = (operator: AccountsOverviewThresholdOperator): void => {
+ if (tile.metric.type !== 'count_threshold') {
+ return
+ }
+ const previousLabelLooksAuto = tile.label === defaultLabelForMetric(tile.metric)
+ const nextMetric: AccountsOverviewTileMetric = { ...tile.metric, operator }
+ onChange({
+ label: previousLabelLooksAuto ? defaultLabelForMetric(nextMetric) : tile.label,
+ metric: nextMetric,
+ })
+ }
+
+ const onThresholdValueChange = (value: number): void => {
+ if (tile.metric.type !== 'count_threshold') {
+ return
+ }
+ const previousLabelLooksAuto = tile.label === defaultLabelForMetric(tile.metric)
+ const nextMetric: AccountsOverviewTileMetric = { ...tile.metric, value }
+ onChange({
+ label: previousLabelLooksAuto ? defaultLabelForMetric(nextMetric) : tile.label,
+ metric: nextMetric,
+ })
+ }
+
+ return (
+ <div
+ ref={setNodeRef}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ transform: CSS.Transform.toString(transform), transition }}
+ {...attributes}
+ >
+ <div className="border border-border rounded p-3 flex flex-col gap-2 bg-surface-primary">
+ <div className="flex items-center gap-2">
+ <span {...listeners} className="cursor-grab text-secondary">
+ <SortableDragIcon />
+ </span>
+ <LemonInput
+ value={tile.label}
+ onChange={(label) => onChange({ label, metric: tile.metric })}
+ placeholder="Tile label"
+ fullWidth
+ data-attr={`accounts-overview-tile-label-${tile.id}`}
+ />
+ <Tooltip title="Remove tile">
+ <LemonButton
+ onClick={onRemove}
+ status="danger"
+ size="small"
+ icon={<IconX />}
+ data-attr={`accounts-overview-tile-remove-${tile.id}`}
+ />
+ </Tooltip>
+ </div>
+ <div className="flex flex-wrap items-center gap-2 pl-6">
+ <LemonSelect
+ size="small"
+ value={tile.metric.type}
+ onChange={(value) => value && onMetricTypeChange(value)}
+ options={(Object.keys(METRIC_TYPE_LABELS) as AccountsOverviewTileMetricType[]).map((type) => ({
+ value: type,
+ label: METRIC_TYPE_LABELS[type],
+ disabledReason:
+ type !== 'count' && noNumericColumns ? 'No numeric columns available' : undefined,
+ }))}
+ data-attr={`accounts-overview-tile-metric-type-${tile.id}`}
+ />
+ {needsColumn ? (
+ <LemonSelect
+ size="small"
+ value={tile.metric.type === 'count' ? undefined : tile.metric.columnExpression}
+ onChange={(value) => value && onColumnChange(value)}
+ options={columnOptions}
+ disabledReason={noNumericColumns ? 'No numeric columns available' : undefined}
+ placeholder="Pick a column"
+ data-attr={`accounts-overview-tile-column-${tile.id}`}
+ />
+ ) : null}
+ {tile.metric.type === 'count_threshold' ? (
+ <>
+ <LemonSelect
+ size="small"
+ value={tile.metric.operator}
+ onChange={(value) => value && onOperatorChange(value)}
+ options={ACCOUNTS_OVERVIEW_THRESHOLD_OPERATORS.map((op) => ({
+ value: op,
+ label: op,
+ }))}
+ data-attr={`accounts-overview-tile-operator-${tile.id}`}
+ />
+ <LemonInput
+ type="number"
+ value={tile.metric.value}
+ onChange={(value) =>
+ onThresholdValueChange(typeof value === 'number' ? value : Number(value) || 0)
+ }
+ data-attr={`accounts-overview-tile-threshold-${tile.id}`}
+ />
+ </>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx
index 20a7d224bc7c..4637e76c311b 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx
@@ -2,8 +2,12 @@ import { BindLogic, useValues } from 'kea'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'
+import { AccountsColumnConfigurator } from './AccountsColumnConfigurator'
import { AccountsHogQLTable } from './AccountsHogQLTable'
-import { ACCOUNTS_HOGQL_DATA_NODE_KEY, accountsLogic } from './accountsLogic'
+import { accountsLogic } from './accountsLogic'
+import { AccountsOverviewTiles } from './AccountsOverviewTiles'
+import { AccountsOverviewTilesButton } from './AccountsOverviewTilesButton'
import { AccountsTabFilters } from './AccountsTabFilters'
export function AccountsTabContent(): JSX.Element {
@@ -19,6 +23,11 @@ export function AccountsTabContent(): JSX.Element {
>
<div className="flex flex-col gap-3">
<AccountsTabFilters />
+ <div className="flex justify-end gap-2">
+ <AccountsOverviewTilesButton />
+ <AccountsColumnConfigurator />
+ </div>
+ <AccountsOverviewTiles />
<AccountsHogQLTable />
</div>
</BindLogic>
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx
index f7a393401f6f..1add3ae97ddc 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx
@@ -11,11 +11,11 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { accountsLogic, RoleFilterValue } from './accountsLogic'
export function AccountsTabFilters(): JSX.Element {
- const { searchQuery, tagsFilter, allRolesUnassigned, csmFilter, accountExecutiveFilter, accountOwnerFilter } =
+ const { searchInput, tagsFilter, allRolesUnassigned, csmFilter, accountExecutiveFilter, accountOwnerFilter } =
useValues(accountsLogic)
const { responseLoading: accountsLoading } = useValues(dataNodeLogic)
const {
- setSearchQuery,
+ setSearchInput,
setTagsFilter,
setAllRolesUnassigned,
setCsmFilter,
@@ -33,8 +33,8 @@ export function AccountsTabFilters(): JSX.Element {
<LemonInput
type="search"
placeholder="Search by name or ID..."
- value={searchQuery}
- onChange={setSearchQuery}
+ value={searchInput}
+ onChange={setSearchInput}
size="small"
className="min-w-64"
data-attr="accounts-search"
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 8750dd319d73..d0b06c6c8cc6 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -87,6 +87,18 @@ describe('accountsLogic', () => {
expect(logic.values.searchQuery).toBe('acme')
})
+ it('setSearchInput updates the input immediately but defers the committed searchQuery', () => {
+ logic.actions.setSearchInput('acme')
+ expect(logic.values.searchInput).toBe('acme')
+ // Debounced: the query-driving value is not committed synchronously.
+ expect(logic.values.searchQuery).toBe('')
+ })
+
+ it('carries the overview tile metrics on the same AccountsQuery', () => {
+ const source = logic.values.hogqlQuery.source as AccountsQuery
+ expect(source.metrics).toEqual(['count()'])
+ })
+
it('setAllRolesUnassigned toggles the flag', () => {
logic.actions.setAllRolesUnassigned(true)
expect(logic.values.allRolesUnassigned).toBe(true)
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 8398d2234197..af9298a65c04 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -14,11 +14,12 @@ import type {
PatchedAccountApiProperties,
} from 'products/customer_analytics/frontend/generated/api.schemas'
-import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
+import { ACCOUNTS_HOGQL_DATA_NODE_KEY, CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
import { accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import type { accountsLogicType } from './accountsLogicType'
+import { accountsOverviewTilesLogic, TileFilter } from './accountsOverviewTilesLogic'
-export const ACCOUNTS_HOGQL_DATA_NODE_KEY = 'customer-analytics-accounts-hogql'
+export const SEARCH_DEBOUNCE_MS = 300
interface SortLikeValues {
sortOrder: AccountSortOrder
@@ -81,10 +82,18 @@ export const savingRoleKey = (accountId: string, role: AccountRoleKey): string =
export const accountsLogic = kea<accountsLogicType>([
path(['scenes', 'customerAnalytics', 'accounts', 'accountsLogic']),
connect(() => ({
- values: [teamLogic, ['currentTeamId'], accountsColumnConfigLogic, ['selectColumns', 'visibleColumnNames']],
+ values: [
+ teamLogic,
+ ['currentTeamId'],
+ accountsColumnConfigLogic,
+ ['selectColumns', 'visibleColumnNames'],
+ accountsOverviewTilesLogic,
+ ['metrics as overviewMetrics', 'tileFilter'],
+ ],
actions: [accountsColumnConfigLogic, ['setSelectColumns', 'unselectColumn', 'resetColumns']],
})),
actions({
+ setSearchInput: (query: string) => ({ query }),
setSearchQuery: (query: string) => ({ query }),
setTagsFilter: (tags: string[]) => ({ tags }),
setAllRolesUnassigned: (value: boolean) => ({ value }),
@@ -104,6 +113,13 @@ export const accountsLogic = kea<accountsLogicType>([
replaceAccount: (account: AccountApi) => ({ account }),
}),
reducers({
+ searchInput: [
+ '',
+ {
+ setSearchInput: (_, { query }) => query,
+ setSearchQuery: (_, { query }) => query,
+ },
+ ],
searchQuery: [
'',
{
@@ -182,6 +198,8 @@ export const accountsLogic = kea<accountsLogicType>([
s.csmFilter,
s.accountExecutiveFilter,
s.accountOwnerFilter,
+ s.tileFilter,
+ s.overviewMetrics,
s.sortOrder,
s.selectColumns,
],
@@ -192,6 +210,8 @@ export const accountsLogic = kea<accountsLogicType>([
csmFilter: RoleFilterValue,
accountExecutiveFilter: RoleFilterValue,
accountOwnerFilter: RoleFilterValue,
+ tileFilter: TileFilter | null,
+ overviewMetrics: string[],
sortOrder: AccountSortOrder,
selectColumns: string[]
): DataTableNode => {
@@ -200,6 +220,9 @@ export const accountsLogic = kea<accountsLogicType>([
select: selectColumns,
tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_list' },
}
+ if (overviewMetrics.length > 0) {
+ source.metrics = overviewMetrics
+ }
const trimmed = searchQuery.trim()
if (trimmed) {
source.search = trimmed
@@ -219,6 +242,9 @@ export const accountsLogic = kea<accountsLogicType>([
if (accountOwnerFilter !== null) {
source.accountOwner = accountOwnerFilter
}
+ if (tileFilter) {
+ source.filterExpression = tileFilter.expression
+ }
if (sortOrder) {
const expr = deriveAccountsOrderByExpr(sortOrder.column)
source.orderBy = [sortOrder.direction === 'asc' ? expr : `${expr} DESC`]
@@ -237,6 +263,10 @@ export const accountsLogic = kea<accountsLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ setSearchInput: async ({ query }, breakpoint) => {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ actions.setSearchQuery(query)
+ },
setAllRolesUnassigned: ({ value }) => {
if (value) {
if (values.csmFilter !== null) {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
new file mode 100644
index 000000000000..5c99145ccf29
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
@@ -0,0 +1,182 @@
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import {
+ AccountsOverviewTile,
+ isNumericColumnType,
+ isTileClickable,
+ numericColumnOptions,
+ parseTileValues,
+ stripHogqlAlias,
+ tileFilterFor,
+ tileMetricExpression,
+ tileToRowFilter,
+} from './accountsOverviewTilesLogic'
+
+describe('stripHogqlAlias', () => {
+ it('strips a trailing AS alias', () => {
+ expect(stripHogqlAlias('accounts.health.score AS score')).toBe('accounts.health.score')
+ })
+
+ it('leaves a plain expression untouched', () => {
+ expect(stripHogqlAlias('health_score')).toBe('health_score')
+ })
+
+ it('does not strip AS in the middle', () => {
+ expect(stripHogqlAlias("toString(JSONExtract(properties, 'score', 'Nullable(Int64)'))")).toBe(
+ "toString(JSONExtract(properties, 'score', 'Nullable(Int64)'))"
+ )
+ })
+})
+
+describe('isNumericColumnType', () => {
+ it('accepts numeric types', () => {
+ expect(isNumericColumnType('integer')).toBe(true)
+ expect(isNumericColumnType('float')).toBe(true)
+ expect(isNumericColumnType('decimal')).toBe(true)
+ })
+
+ it('rejects non-numeric types', () => {
+ expect(isNumericColumnType('string')).toBe(false)
+ expect(isNumericColumnType('boolean')).toBe(false)
+ expect(isNumericColumnType(undefined)).toBe(false)
+ })
+})
+
+describe('numericColumnOptions', () => {
+ it('keeps numeric direct columns and strips aliases on join columns', () => {
+ const options = numericColumnOptions([
+ {
+ key: 'account_properties',
+ label: 'Account properties',
+ options: [
+ { name: 'name', expression: 'name', type: 'string' },
+ { name: 'health_score', expression: 'health_score', type: 'integer' },
+ ],
+ },
+ {
+ key: 'accounts.health',
+ label: 'health',
+ options: [{ name: 'score', expression: 'accounts.health.score AS score', type: 'float' }],
+ },
+ { key: 'sql_expression', label: 'SQL expression', options: [], isFreeform: true },
+ ])
+ expect(options).toEqual([
+ { name: 'health_score', expression: 'health_score', type: 'integer' },
+ { name: 'score', expression: 'accounts.health.score', type: 'float' },
+ ])
+ })
+})
+
+describe('tileMetricExpression', () => {
+ it('produces the right HogQL fragment per metric type', () => {
+ expect(tileMetricExpression({ id: 'x', label: 'l', metric: { type: 'count' } })).toBe('count()')
+ expect(
+ tileMetricExpression({
+ id: 'x',
+ label: 'l',
+ metric: { type: 'sum', columnExpression: 'health_score', columnLabel: 'Health score' },
+ })
+ ).toBe('sum(health_score)')
+ expect(
+ tileMetricExpression({
+ id: 'x',
+ label: 'l',
+ metric: { type: 'avg', columnExpression: 'health_score', columnLabel: 'Health score' },
+ })
+ ).toBe('avg(health_score)')
+ expect(
+ tileMetricExpression({
+ id: 'x',
+ label: 'l',
+ metric: {
+ type: 'count_threshold',
+ columnExpression: 'health_score',
+ columnLabel: 'Health score',
+ operator: '<',
+ value: 6,
+ },
+ })
+ ).toBe('countIf(health_score < 6)')
+ })
+})
+
+describe('tileToRowFilter / isTileClickable', () => {
+ const thresholdTile: AccountsOverviewTile = {
+ id: 'b',
+ label: 'At risk',
+ metric: {
+ type: 'count_threshold',
+ columnExpression: 'health_score',
+ columnLabel: 'Health score',
+ operator: '<',
+ value: 6,
+ },
+ }
+
+ it('maps a threshold tile to its row predicate', () => {
+ expect(tileToRowFilter(thresholdTile)).toBe('health_score < 6')
+ expect(isTileClickable(thresholdTile)).toBe(true)
+ })
+
+ it('returns null for non-threshold tiles', () => {
+ const countTile: AccountsOverviewTile = { id: 'a', label: 'Accounts', metric: { type: 'count' } }
+ expect(tileToRowFilter(countTile)).toBeNull()
+ expect(isTileClickable(countTile)).toBe(false)
+ })
+})
+
+describe('tileFilterFor', () => {
+ it('maps a threshold tile to its active filter descriptor', () => {
+ expect(
+ tileFilterFor({
+ id: 'b',
+ label: 'At risk',
+ metric: {
+ type: 'count_threshold',
+ columnExpression: 'health_score',
+ columnLabel: 'Health score',
+ operator: '<',
+ value: 6,
+ },
+ })
+ ).toEqual({ tileId: 'b', expression: 'health_score < 6' })
+ })
+
+ it('returns null when the tile is not a row-level predicate', () => {
+ expect(tileFilterFor({ id: 'a', label: 'Accounts', metric: { type: 'count' } })).toBeNull()
+ })
+})
+
+describe('parseTileValues', () => {
+ const tiles: AccountsOverviewTile[] = [
+ { id: 'a', label: 'Accounts', metric: { type: 'count' } },
+ {
+ id: 'b',
+ label: 'Sum',
+ metric: { type: 'sum', columnExpression: 'health_score', columnLabel: 'Health score' },
+ },
+ ]
+
+ function responseWith(metricsResults: (number | null)[] | undefined): any {
+ return {
+ kind: NodeKind.AccountsQuery,
+ results: [],
+ columns: [],
+ types: [],
+ hogql: '',
+ limit: 0,
+ offset: 0,
+ metricsResults,
+ }
+ }
+
+ it('reads metric values in tile order', () => {
+ expect(parseTileValues(responseWith([42, 7.5]), tiles)).toEqual({ a: 42, b: 7.5 })
+ })
+
+ it('returns null when metricsResults is missing or malformed', () => {
+ expect(parseTileValues(null, tiles)).toEqual({ a: null, b: null })
+ expect(parseTileValues(responseWith(undefined), tiles)).toEqual({ a: null, b: null })
+ expect(parseTileValues(responseWith([null, null]), tiles)).toEqual({ a: null, b: null })
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
new file mode 100644
index 000000000000..841eb9aa141b
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
@@ -0,0 +1,256 @@
+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { v4 as uuidv4 } from 'uuid'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { AccountsQueryResponse, DataNode } from '~/queries/schema/schema-general'
+
+import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'
+import { AccountColumnGroup, AccountColumnOption, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
+import type { accountsOverviewTilesLogicType } from './accountsOverviewTilesLogicType'
+
+export const ACCOUNTS_OVERVIEW_THRESHOLD_OPERATORS = ['>', '>=', '<', '<=', '=', '!='] as const
+export type AccountsOverviewThresholdOperator = (typeof ACCOUNTS_OVERVIEW_THRESHOLD_OPERATORS)[number]
+
+export type AccountsOverviewTileMetric =
+ | { type: 'count' }
+ | { type: 'sum'; columnExpression: string; columnLabel: string }
+ | { type: 'avg'; columnExpression: string; columnLabel: string }
+ | {
+ type: 'count_threshold'
+ columnExpression: string
+ columnLabel: string
+ operator: AccountsOverviewThresholdOperator
+ value: number
+ }
+
+export type AccountsOverviewTileMetricType = AccountsOverviewTileMetric['type']
+
+export interface AccountsOverviewTile {
+ id: string
+ label: string
+ metric: AccountsOverviewTileMetric
+}
+
+export interface TileFilter {
+ tileId: string
+ expression: string
+}
+
+const NUMERIC_FIELD_TYPES = new Set(['integer', 'float', 'decimal'])
+
+const DEFAULT_TILES: AccountsOverviewTile[] = [{ id: 'default-accounts', label: 'Accounts', metric: { type: 'count' } }]
+
+const teamIdForPersistence = window.POSTHOG_APP_CONTEXT?.current_team?.id
+const persistConfig = {
+ persist: true,
+ prefix: `${teamIdForPersistence}_customer_analytics_accounts_overview__`,
+}
+
+// Strip a trailing `AS alias` from a HogQL fragment — column entries in the
+// account column groups carry aliases (e.g. `accounts.health.score AS score`)
+// so the data table can address them by name, but aggregation expressions
+// must reference the bare column.
+export function stripHogqlAlias(expression: string): string {
+ return expression.replace(/\s+AS\s+[A-Za-z_][\w]*\s*$/i, '').trim()
+}
+
+export function isNumericColumnType(type: string | undefined): boolean {
+ return !!type && NUMERIC_FIELD_TYPES.has(type)
+}
+
+export function numericColumnOptions(groups: AccountColumnGroup[]): AccountColumnOption[] {
+ return groups
+ .filter((group) => !group.isFreeform)
+ .flatMap((group) =>
+ group.options
+ .filter((option) => isNumericColumnType(option.type))
+ .map((option) => ({
+ ...option,
+ expression: stripHogqlAlias(option.expression),
+ }))
+ )
+}
+
+export function tileMetricExpression(tile: AccountsOverviewTile): string {
+ const { metric } = tile
+ switch (metric.type) {
+ case 'count':
+ return 'count()'
+ case 'sum':
+ return `sum(${metric.columnExpression})`
+ case 'avg':
+ return `avg(${metric.columnExpression})`
+ case 'count_threshold':
+ return `countIf(${metric.columnExpression} ${metric.operator} ${metric.value})`
+ }
+}
+
+// A tile only acts as a row-level predicate when it represents an
+// inherently row-level condition. `count_threshold` does; `count`/`sum`/`avg`
+// describe the whole set, not a subset.
+export function tileToRowFilter(tile: AccountsOverviewTile): string | null {
+ if (tile.metric.type !== 'count_threshold') {
+ return null
+ }
+ const { columnExpression, operator, value } = tile.metric
+ return `${columnExpression} ${operator} ${value}`
+}
+
+export function isTileClickable(tile: AccountsOverviewTile): boolean {
+ return tileToRowFilter(tile) !== null
+}
+
+export function tileFilterFor(tile: AccountsOverviewTile): TileFilter | null {
+ const expression = tileToRowFilter(tile)
+ return expression ? { tileId: tile.id, expression } : null
+}
+
+function readNumeric(raw: unknown): number | null {
+ if (raw === null || raw === undefined) {
+ return null
+ }
+ const numeric = typeof raw === 'number' ? raw : Number(raw)
+ return Number.isFinite(numeric) ? numeric : null
+}
+
+export function parseTileValues(
+ response: AccountsQueryResponse | null,
+ tiles: AccountsOverviewTile[]
+): Record<string, number | null> {
+ const values: Record<string, number | null> = {}
+ const metricsResults = response?.metricsResults
+ tiles.forEach((tile, index) => {
+ const raw = Array.isArray(metricsResults) ? metricsResults[index] : null
+ values[tile.id] = readNumeric(raw)
+ })
+ return values
+}
+
+function reconcileTilesAgainstSchema(
+ tiles: AccountsOverviewTile[],
+ numericExpressions: Set<string>
+): AccountsOverviewTile[] {
+ return tiles.filter((tile) => {
+ if (tile.metric.type === 'count') {
+ return true
+ }
+ return numericExpressions.has(tile.metric.columnExpression)
+ })
+}
+
+export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
+ path(['scenes', 'customerAnalytics', 'accounts', 'accountsOverviewTilesLogic']),
+ connect(() => ({
+ values: [
+ accountsColumnConfigLogic,
+ ['accountsColumnGroups'],
+ dataNodeLogic({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY, query: {} as DataNode }),
+ ['response as accountsResponse', 'responseLoading as accountsResponseLoading'],
+ ],
+ })),
+ actions({
+ addTile: (tile: Omit<AccountsOverviewTile, 'id'> & { id?: string }) => ({ tile }),
+ updateTile: (id: string, tile: Omit<AccountsOverviewTile, 'id'>) => ({ id, tile }),
+ removeTile: (id: string) => ({ id }),
+ moveTile: (oldIndex: number, newIndex: number) => ({ oldIndex, newIndex }),
+ toggleTileSelection: (tile: AccountsOverviewTile) => ({ tile }),
+ setTileFilter: (filter: TileFilter | null) => ({ filter }),
+ resetTiles: true,
+ showEditor: true,
+ hideEditor: true,
+ }),
+ reducers(() => ({
+ tiles: [
+ DEFAULT_TILES,
+ persistConfig,
+ {
+ addTile: (
+ state: AccountsOverviewTile[],
+ { tile }: { tile: Omit<AccountsOverviewTile, 'id'> & { id?: string } }
+ ) => [...state, { ...tile, id: tile.id || uuidv4() }],
+ updateTile: (
+ state: AccountsOverviewTile[],
+ { id, tile }: { id: string; tile: Omit<AccountsOverviewTile, 'id'> }
+ ) => state.map((t) => (t.id === id ? { ...tile, id } : t)),
+ removeTile: (state: AccountsOverviewTile[], { id }: { id: string }) => state.filter((t) => t.id !== id),
+ moveTile: (
+ state: AccountsOverviewTile[],
+ { oldIndex, newIndex }: { oldIndex: number; newIndex: number }
+ ) => {
+ if (oldIndex === newIndex || oldIndex < 0 || oldIndex >= state.length) {
+ return state
+ }
+ const next = [...state]
+ const [removed] = next.splice(oldIndex, 1)
+ next.splice(newIndex, 0, removed)
+ return next
+ },
+ resetTiles: () => [...DEFAULT_TILES],
+ },
+ ],
+ tileFilter: [
+ null as TileFilter | null,
+ {
+ setTileFilter: (_, { filter }) => filter,
+ },
+ ],
+ editorVisible: [
+ false,
+ {
+ showEditor: () => true,
+ hideEditor: () => false,
+ },
+ ],
+ })),
+ selectors({
+ numericColumns: [
+ (s) => [s.accountsColumnGroups],
+ (groups: AccountColumnGroup[]): AccountColumnOption[] => numericColumnOptions(groups),
+ ],
+ numericColumnExpressions: [
+ (s) => [s.numericColumns],
+ (options: AccountColumnOption[]): Set<string> => new Set(options.map((o) => o.expression)),
+ ],
+ reconciledTiles: [
+ (s) => [s.tiles, s.numericColumnExpressions],
+ (tiles: AccountsOverviewTile[], expressions: Set<string>): AccountsOverviewTile[] =>
+ reconcileTilesAgainstSchema(tiles, expressions),
+ ],
+ metrics: [
+ (s) => [s.reconciledTiles],
+ (tiles: AccountsOverviewTile[]): string[] => tiles.map(tileMetricExpression),
+ ],
+ tileValues: [
+ (s) => [s.accountsResponse, s.reconciledTiles],
+ (response: AccountsQueryResponse | null, tiles: AccountsOverviewTile[]): Record<string, number | null> =>
+ parseTileValues(response, tiles),
+ ],
+ tilesLoading: [(s) => [s.accountsResponseLoading], (loading: boolean): boolean => loading],
+ selectedTileId: [(s) => [s.tileFilter], (filter: TileFilter | null): string | null => filter?.tileId ?? null],
+ }),
+ listeners(({ actions, values }) => ({
+ removeTile: ({ id }) => {
+ if (values.tileFilter?.tileId === id) {
+ actions.setTileFilter(null)
+ }
+ },
+ resetTiles: () => {
+ if (values.tileFilter) {
+ actions.setTileFilter(null)
+ }
+ },
+ updateTile: ({ id, tile }) => {
+ if (values.tileFilter?.tileId !== id) {
+ return
+ }
+ actions.setTileFilter(tileFilterFor({ ...tile, id }))
+ },
+ toggleTileSelection: ({ tile }) => {
+ const next = tileFilterFor(tile)
+ if (!next) {
+ return
+ }
+ actions.setTileFilter(values.tileFilter?.tileId === tile.id ? null : next)
+ },
+ })),
+])
diff --git a/products/customer_analytics/frontend/constants.ts b/products/customer_analytics/frontend/constants.ts
index 251f803f9f8c..191004e3d417 100644
--- a/products/customer_analytics/frontend/constants.ts
+++ b/products/customer_analytics/frontend/constants.ts
@@ -2,6 +2,8 @@ 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 CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS: QueryLogTags = {
productKey: ProductKey.CUSTOMER_ANALYTICS,
}
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 42366d7f08da..1dd9d08de005 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -4189,6 +4189,8 @@ export interface Response27Api {
hogql: string
kind?: 'AccountsQuery'
limit: number
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset: number
@@ -6875,6 +6877,8 @@ export interface AccountsQueryResponseApi {
hogql: string
kind?: 'AccountsQuery'
limit: number
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset: number
@@ -6895,8 +6899,12 @@ export interface AccountsQueryApi {
accountOwner?: string | number | null
allRolesUnassigned?: boolean | null
csm?: string | number | null
+ /** Optional HogQL boolean expression AND-ed into the WHERE clause. Used by the overview tile click-to-filter affordance. */
+ filterExpression?: string | null
kind?: 'AccountsQuery'
limit?: number | null
+ /** Aggregation expressions evaluated against the filtered account set; one value per metric is returned in `metricsResults`. When `metrics` is set without a `select`, the runner skips the regular row fetch and returns only the aggregated values. */
+ metrics?: string[] | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index b99737ecb4fa..82665a6a7726 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -3882,6 +3882,8 @@ export interface Response27Api {
hogql: string
kind?: 'AccountsQuery'
limit: number
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset: number
@@ -6568,6 +6570,8 @@ export interface AccountsQueryResponseApi {
hogql: string
kind?: 'AccountsQuery'
limit: number
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset: number
@@ -6588,8 +6592,12 @@ export interface AccountsQueryApi {
accountOwner?: string | number | null
allRolesUnassigned?: boolean | null
csm?: string | number | null
+ /** Optional HogQL boolean expression AND-ed into the WHERE clause. Used by the overview tile click-to-filter affordance. */
+ filterExpression?: string | null
kind?: 'AccountsQuery'
limit?: number | null
+ /** Aggregation expressions evaluated against the filtered account set; one value per metric is returned in `metricsResults`. When `metrics` is set without a `select`, the runner skips the regular row fetch and returns only the aggregated values. */
+ metrics?: string[] | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 10b7c164cd66..9c4d7de23fca 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -475,6 +475,8 @@ export namespace Schemas {
hogql: string;
kind?: 'AccountsQuery';
limit: number;
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset: number;
@@ -504,8 +506,12 @@ export namespace Schemas {
accountOwner?: string | number | null;
allRolesUnassigned?: boolean | null;
csm?: string | number | null;
+ /** Optional HogQL boolean expression AND-ed into the WHERE clause. Used by the overview tile click-to-filter affordance. */
+ filterExpression?: string | null;
kind?: 'AccountsQuery';
limit?: number | null;
+ /** Aggregation expressions evaluated against the filtered account set; one value per metric is returned in `metricsResults`. When `metrics` is set without a `select`, the runner skips the regular row fetch and returns only the aggregated values. */
+ metrics?: string[] | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
@@ -4823,6 +4829,8 @@ export namespace Schemas {
hogql: string;
kind?: 'AccountsQuery';
limit: number;
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset: number;
@@ -35633,6 +35641,8 @@ export namespace Schemas {
hogql: string;
kind?: 'AccountsQuery';
limit: number;
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset: number;
@@ -36068,6 +36078,8 @@ export namespace Schemas {
hogql: string;
kind?: 'AccountsQuery';
limit: number;
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset: number;