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): expand overview tile math and display (#70467)

jake sciottod02801d87d6a
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index ee6bf19ea5a8..fb503f7a68fa 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -64,7 +64,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc
Default columns: `name`, `tag_names`, `notebook_count`, plus one relationship column per team definition. `ACCOUNTS_HOGQL_DEFAULT_SELECT` (base columns only) is just the pre-load seed; once `loadRelationshipDefinitionsSuccess` fires, still-default columns are upgraded to the `defaultSelectColumns` selector (seeded definitions keep their legacy bare names, others get `rel_<id>` expressions) — anything already customized by the user, a saved view, or a shared URL is left alone, and the URL hash serializes columns only when they differ from `defaultSelectColumns`. The name column is force-kept (`ensureNameColumn`) — removing it breaks identity, scroll, and role edits. Extra columns come from account properties, lazy/virtual-table joins under `system.accounts`, data-warehouse joins, freeform SQL, or **custom properties** — all assembled by `buildAccountColumnGroups`.
-**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 columns** surface the team's `CustomPropertyDefinition`s (loaded in `accountsColumnConfigLogic` via the generated `customPropertyDefinitionsList`) as a "Custom properties" picker group. Each is selected as ``accounts.custom_properties.values.`<definition-id>` AS cp_<id>`` — a JSON dot-access through the `custom_properties` lazy join on `system.accounts` (backed by the `customer_analytics_custompropertyvalue` EAV table; one JOIN regardless of column count). Because the alias is an opaque `cp_<id>`, every label-bearing surface must resolve it back via the `aliasToDefinition` selector: the table header (`useContextColumns` in `AccountsHogQLTable`) and the configurator's "Visible columns" list (`SelectedAccountColumn`). Cells render by display type (`CustomPropertyCell`: date→`TZLabel`, boolean→icon, select→`LemonColorGlyph` + label, numeric→`formatCustomPropertyValue`). Sorting a numeric custom property (display type `number`/`currency`/`percent`) casts the (string) JSON value with `toFloatOrNull(...)` in the `orderBy` — see `orderByExpression` in `accountsLogic`, driven by `aliasToDefinition` — so numbers sort by magnitude rather than lexically; non-numeric types sort by the alias directly. The stored sort state (URL hash, saved views) keeps the clean column name; the cast is applied only at query-build time. Numeric custom properties are also selectable in the **overview tiles** sum/avg/min/max/median/threshold pickers — `numericColumnOptions` recognizes the display type and wraps the value in `toFloatOrNull(...)` the same way so aggregation is numeric.
**Custom property 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`).
@@ -81,6 +81,10 @@ Negative operators (is not / doesn't contain / doesn't match regex) are wrapped
Filters for deleted definitions or with incomplete values compile to nothing rather than breaking the query, and only validated UUID keys are ever interpolated (quoted via the shared `escapePropertyAsHogQLIdentifier`).
Value suggestions load from`GET /api/projects/:team_id/custom_property_definitions/values/?key=<definition-id>&value=<search>`(the group's`valuesEndpoint`): select → option labels, boolean → true/false, text/numeric → distinct active values; date pickers need no suggestions.
+**Overview tile math** (`accountsOverviewTilesLogic` / `AccountsOverviewTilesEditor`). A tile's metric is a discriminated union: `count` (`count()`), the column aggregations `sum`/`avg`/`min`/`max`/`median` (the metric-type name _is_ the HogQL aggregate fn, so `tileMetricExpression`'s one `default` branch emits `${type}(col)`), and `count_threshold` (`countIf(col op val)`, the only row-level-clickable tile). The column aggregations carry an optional `scale` multiplier (`applyScale`) rendered as `agg(col) * n`, e.g. `sum(mrr) * 12` to annualize; a `scale` of 1/undefined/non-finite is a no-op. `scaleSuffix` mirrors that guard for the `× n` label/caption suffix. Add a new aggregation by extending `COLUMN_AGGREGATE_TYPES` (must be a valid HogQL aggregate fn) plus the editor's `METRIC_TYPE_LABELS` / `COLUMN_AGGREGATE_LABEL_PREFIX`. No backend change: `accounts_query_runner` `parse_expr`s each metric string with no fn whitelist.
+
+**Tile display** (title / subtitle / value format). A tile also carries two optional presentation fields, independent of the metric: `caption` (custom subtitle) and `format` (`TileValueFormat` = `unit`/`currency`/`percentage`, a subset of `OverviewGrid`'s `WebAnalyticsItemKind` so `format ?? 'unit'` maps 1:1 to the render `kind`). `tileCaption(tile)` resolves the subtitle: the trimmed custom `caption` when set, else `autoCaption(tile)` (the derived `agg of col × n` / `col op val` text; `count` has no derived caption, so a custom one is the only subtitle it can show). The editor edits `caption` (empty → `undefined`) and `format` (`unit` → `undefined`); both flow through the row's `emit(patch)` merge so a metric edit never drops them. Render formatting lives in `OverviewGrid.formatItem`: `currency` uses the team `baseCurrency`, `percentage` treats the value as already in percent units (`85` → "85%", combine with `scale × 100` for a 0-1 fraction). Both fields ride along in `properties.tiles` (no backend/schema/migration) and default cleanly for older saved/legacy tiles.
+
Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`), else the backend gets an `orderBy` referencing a missing alias.
## The expanded row
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTiles.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTiles.tsx
index 66b5a362f2b7..2584c3b82220 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTiles.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTiles.tsx
@@ -4,21 +4,12 @@ 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}`
- }
-}
+import {
+ accountsOverviewTilesLogic,
+ AccountsOverviewTile,
+ isTileClickable,
+ tileCaption,
+} from './accountsOverviewTilesLogic'
function tileLabelByKey(tiles: AccountsOverviewTile[]): (key: string) => string {
const labelsById = new Map(tiles.map((tile) => [tile.id, tile.label]))
@@ -32,7 +23,7 @@ export function AccountsOverviewTiles(): JSX.Element {
const overviewItems: OverviewItem[] = reconciledTiles.map((tile) => ({
key: tile.id,
value: tileValues[tile.id] ?? undefined,
- kind: 'unit',
+ kind: tile.format ?? 'unit',
caption: tileCaption(tile),
selected: selectedTileId === tile.id,
onClick: isTileClickable(tile) ? () => toggleTileSelection(tile) : undefined,
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
index d5946db3fb25..5918b4516d27 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsOverviewTilesEditor.tsx
@@ -17,6 +17,11 @@ import {
AccountsOverviewTile,
AccountsOverviewTileMetric,
AccountsOverviewTileMetricType,
+ autoCaption,
+ isColumnAggregateMetric,
+ scaleSuffix,
+ TILE_VALUE_FORMATS,
+ TileValueFormat,
} from './accountsOverviewTilesLogic'
import {
ACCOUNTS_OVERVIEW_THRESHOLD_OPERATORS,
@@ -28,6 +33,9 @@ const METRIC_TYPE_LABELS: Record<AccountsOverviewTileMetricType, string> = {
count: 'Count of accounts',
sum: 'Sum of column',
avg: 'Average of column',
+ min: 'Minimum of column',
+ max: 'Maximum of column',
+ median: 'Median of column',
count_threshold: 'Count above/below threshold',
}
@@ -35,16 +43,28 @@ function fallbackColumn(options: AccountColumnOption[]): AccountColumnOption | n
return options[0] ?? null
}
+const FORMAT_LABELS: Record<TileValueFormat, string> = {
+ unit: 'Number',
+ currency: 'Currency',
+ percentage: 'Percentage',
+}
+
+const COLUMN_AGGREGATE_LABEL_PREFIX: Record<'sum' | 'avg' | 'min' | 'max' | 'median', string> = {
+ sum: 'Total',
+ avg: 'Average',
+ min: 'Min',
+ max: 'Max',
+ median: 'Median',
+}
+
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}`
+ default:
+ return `${COLUMN_AGGREGATE_LABEL_PREFIX[metric.type]} ${metric.columnLabel}${scaleSuffix(metric.scale)}`
}
}
@@ -78,7 +98,9 @@ function metricOfType(
value: previous.type === 'count_threshold' ? previous.value : 0,
}
}
- return { type, columnExpression, columnLabel }
+ // Preserve the scale multiplier when switching between column aggregations.
+ const scale = isColumnAggregateMetric(previous) ? previous.scale : undefined
+ return { type, columnExpression, columnLabel, scale }
}
export function AccountsOverviewTilesEditor({
@@ -181,12 +203,22 @@ function TileEditorRow({ tile, numericColumns, onChange, onRemove }: TileEditorR
[numericColumns]
)
+ // Merge a partial update onto the current tile so caption/format (and any other
+ // field the handler doesn't touch) survive; updateTile replaces the whole tile.
+ const emit = (patch: Partial<Omit<AccountsOverviewTile, 'id'>>): void =>
+ onChange({ label: tile.label, metric: tile.metric, caption: tile.caption, format: tile.format, ...patch })
+
+ // The label auto-refreshes only while it still matches the derived default; once
+ // the user types their own it sticks. Metric edits recompute the default the same way.
+ const labelAfterMetricChange = (nextMetric: AccountsOverviewTileMetric): string =>
+ tile.label === defaultLabelForMetric(tile.metric) ? defaultLabelForMetric(nextMetric) : tile.label
+
const onMetricTypeChange = (next: AccountsOverviewTileMetricType): void => {
const nextMetric = metricOfType(next, numericColumns, tile.metric)
if (!nextMetric) {
return
}
- onChange({ label: tile.label, metric: nextMetric })
+ emit({ metric: nextMetric })
}
const onColumnChange = (expression: string): void => {
@@ -197,40 +229,46 @@ function TileEditorRow({ tile, numericColumns, onChange, onRemove }: TileEditorR
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,
- })
+ emit({ label: labelAfterMetricChange(nextMetric), 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,
- })
+ emit({ label: labelAfterMetricChange(nextMetric), 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,
- })
+ emit({ label: labelAfterMetricChange(nextMetric), metric: nextMetric })
+ }
+
+ // Clearing the input (valueAsNumber → NaN) drops the multiplier back to a no-op.
+ const onScaleChange = (value: number | undefined): void => {
+ if (!isColumnAggregateMetric(tile.metric)) {
+ return
+ }
+ const scale = value === undefined || !Number.isFinite(value) ? undefined : value
+ const nextMetric: AccountsOverviewTileMetric = { ...tile.metric, scale }
+ emit({ label: labelAfterMetricChange(nextMetric), metric: nextMetric })
+ }
+
+ const onCaptionChange = (value: string): void => {
+ emit({ caption: value.trim() ? value : undefined })
+ }
+
+ const onFormatChange = (format: TileValueFormat): void => {
+ emit({ format: format === 'unit' ? undefined : format })
}
return (
@@ -247,7 +285,7 @@ function TileEditorRow({ tile, numericColumns, onChange, onRemove }: TileEditorR
</span>
<LemonInput
value={tile.label}
- onChange={(label) => onChange({ label, metric: tile.metric })}
+ onChange={(label) => emit({ label })}
placeholder="Tile label"
fullWidth
data-attr={`accounts-overview-tile-label-${tile.id}`}
@@ -262,6 +300,16 @@ function TileEditorRow({ tile, numericColumns, onChange, onRemove }: TileEditorR
/>
</Tooltip>
</div>
+ <div className="pl-6">
+ <LemonInput
+ value={tile.caption ?? ''}
+ onChange={onCaptionChange}
+ placeholder={autoCaption(tile) ?? 'Subtitle (optional)'}
+ size="small"
+ fullWidth
+ data-attr={`accounts-overview-tile-caption-${tile.id}`}
+ />
+ </div>
<div className="flex flex-wrap items-center gap-2 pl-6">
<LemonSelect
size="small"
@@ -308,6 +356,36 @@ function TileEditorRow({ tile, numericColumns, onChange, onRemove }: TileEditorR
/>
</>
) : null}
+ {isColumnAggregateMetric(tile.metric) ? (
+ <Tooltip title="Multiply the result, e.g. × 12 to annualize a monthly value">
+ <div className="flex items-center gap-1">
+ <span className="text-secondary text-sm">×</span>
+ <LemonInput
+ type="number"
+ size="small"
+ className="w-20"
+ value={tile.metric.scale}
+ onChange={onScaleChange}
+ placeholder="1"
+ data-attr={`accounts-overview-tile-scale-${tile.id}`}
+ />
+ </div>
+ </Tooltip>
+ ) : null}
+ <LemonSelect
+ size="small"
+ value={tile.format ?? 'unit'}
+ onChange={(value) => value && onFormatChange(value)}
+ options={TILE_VALUE_FORMATS.map((format) => ({
+ value: format,
+ label: FORMAT_LABELS[format],
+ tooltip:
+ format === 'percentage'
+ ? 'Value is treated as already a percentage (85 → 85%)'
+ : undefined,
+ }))}
+ data-attr={`accounts-overview-tile-format-${tile.id}`}
+ />
</div>
</div>
</div>
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
index 77718df90fec..d2deaabf0173 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts
@@ -12,6 +12,7 @@ import {
numericColumnOptions,
parseTileValues,
stripHogqlAlias,
+ tileCaption,
tileFilterFor,
tileMetricExpression,
tileToRowFilter,
@@ -107,26 +108,80 @@ describe('numericColumnOptions', () => {
})
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)')
+ // Each column-aggregation metric type must emit its own HogQL aggregate function
+ // (the type name is the function name); a regression collapsing them to one fn
+ // would silently query the wrong statistic.
+ it.each([
+ [{ type: 'count' as const }, 'count()'],
+ [{ type: 'sum' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'sum(health_score)'],
+ [{ type: 'avg' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'avg(health_score)'],
+ [{ type: 'min' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'min(health_score)'],
+ [{ type: 'max' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'max(health_score)'],
+ [
+ { type: 'median' as const, columnExpression: 'health_score', columnLabel: 'Health score' },
+ 'median(health_score)',
+ ],
+ [
+ {
+ type: 'count_threshold' as const,
+ columnExpression: 'health_score',
+ columnLabel: 'Health score',
+ operator: '<' as const,
+ value: 6,
+ },
+ 'countIf(health_score < 6)',
+ ],
+ ])('produces the right HogQL fragment for %o', (metric, expected) => {
+ expect(tileMetricExpression({ id: 'x', label: 'l', metric })).toBe(expected)
+ })
+
+ // The optional scale multiplier wraps the aggregation; no-op values (1, missing,
+ // non-finite) must not append a stray `* n` that would change or break the query.
+ it.each([
+ [12, 'sum(mrr) * 12'],
+ [0.5, 'sum(mrr) * 0.5'],
+ [1, 'sum(mrr)'],
+ [undefined, 'sum(mrr)'],
+ [NaN, 'sum(mrr)'],
+ ])('applies scale %p to a column aggregation', (scale, expected) => {
expect(
tileMetricExpression({
id: 'x',
label: 'l',
- metric: { type: 'avg', columnExpression: 'health_score', columnLabel: 'Health score' },
+ metric: { type: 'sum', columnExpression: 'mrr', columnLabel: 'MRR', scale },
})
- ).toBe('avg(health_score)')
- expect(
- tileMetricExpression({
- id: 'x',
- label: 'l',
+ ).toBe(expected)
+ })
+})
+
+describe('tileCaption', () => {
+ const sum: AccountsOverviewTile = {
+ id: 's',
+ label: 'MRR',
+ metric: { type: 'sum', columnExpression: 'mrr', columnLabel: 'MRR' },
+ }
+ const count: AccountsOverviewTile = { id: 'c', label: 'Accounts', metric: { type: 'count' } }
+
+ // A custom caption must win over the derived one, an empty/whitespace caption must fall
+ // back to it, and, since count tiles have no derived caption, a custom caption is the
+ // only way they get a subtitle at all. A regression in the precedence silently either
+ // drops the user's subtitle or blanks the auto one.
+ it.each<[string, AccountsOverviewTile, string | undefined]>([
+ ['custom overrides derived', { ...sum, caption: 'Monthly recurring' }, 'Monthly recurring'],
+ ['whitespace-only caption falls back to derived', { ...sum, caption: ' ' }, 'sum of MRR'],
+ ['undefined caption uses derived', sum, 'sum of MRR'],
+ [
+ 'derived caption keeps the scale suffix',
+ { ...sum, metric: { ...sum.metric, scale: 12 } } as AccountsOverviewTile,
+ 'sum of MRR × 12',
+ ],
+ ['count tile has no derived caption', count, undefined],
+ ['count tile shows a custom caption', { ...count, caption: 'Book size' }, 'Book size'],
+ [
+ 'threshold tile derives from its predicate',
+ {
+ id: 't',
+ label: 'At risk',
metric: {
type: 'count_threshold',
columnExpression: 'health_score',
@@ -134,8 +189,11 @@ describe('tileMetricExpression', () => {
operator: '<',
value: 6,
},
- })
- ).toBe('countIf(health_score < 6)')
+ },
+ 'Health score < 6',
+ ],
+ ])('%s', (_name, tile, expected) => {
+ expect(tileCaption(tile)).toBe(expected)
})
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
index 4369ca9495b8..6f84ee7c8a9c 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
@@ -35,10 +35,15 @@ import {
NUMERIC_FIELD_TYPES,
} from './constants'
+// Single-column scalar aggregations whose metric-type name is also the HogQL
+// aggregate function name (see tileMetricExpression). They share one shape and
+// support an optional `scale` multiplier, e.g. sum(mrr) * 12 to annualize.
+export const COLUMN_AGGREGATE_TYPES = ['sum', 'avg', 'min', 'max', 'median'] as const
+export type ColumnAggregateType = (typeof COLUMN_AGGREGATE_TYPES)[number]
+
export type AccountsOverviewTileMetric =
| { type: 'count' }
- | { type: 'sum'; columnExpression: string; columnLabel: string }
- | { type: 'avg'; columnExpression: string; columnLabel: string }
+ | { type: ColumnAggregateType; columnExpression: string; columnLabel: string; scale?: number }
| {
type: 'count_threshold'
columnExpression: string
@@ -49,10 +54,27 @@ export type AccountsOverviewTileMetric =
export type AccountsOverviewTileMetricType = AccountsOverviewTileMetric['type']
+// Per-tile value display format. A subset of OverviewGrid's WebAnalyticsItemKind
+// (we omit `duration_s`, no account metric is a duration), so `format` maps 1:1
+// to the render `kind`. `currency` uses the team's base currency; `percentage`
+// treats the value as already in percent units (85 → "85%").
+export const TILE_VALUE_FORMATS = ['unit', 'currency', 'percentage'] as const
+export type TileValueFormat = (typeof TILE_VALUE_FORMATS)[number]
+
+export function isColumnAggregateMetric(
+ metric: AccountsOverviewTileMetric
+): metric is Extract<AccountsOverviewTileMetric, { type: ColumnAggregateType }> {
+ return (COLUMN_AGGREGATE_TYPES as readonly string[]).includes(metric.type)
+}
+
export interface AccountsOverviewTile {
id: string
label: string
metric: AccountsOverviewTileMetric
+ // Custom subtitle; empty/whitespace/undefined falls back to the auto-derived caption.
+ caption?: string
+ // Value display format; undefined renders as a plain unit.
+ format?: TileValueFormat
}
export interface TileFilter {
@@ -93,23 +115,59 @@ export function numericColumnOptions(groups: AccountColumnGroup[]): AccountColum
)
}
+// A `scale` of undefined/1 (or anything non-finite) is a no-op; otherwise the
+// aggregation is multiplied by the literal. `scale` is always a finite number
+// from the editor's numeric input, so it is safe to inline into the HogQL.
+export function applyScale(expression: string, scale: number | undefined): string {
+ if (scale === undefined || !Number.isFinite(scale) || scale === 1) {
+ return expression
+ }
+ return `${expression} * ${scale}`
+}
+
+// Human-readable multiplier suffix for tile labels/captions (e.g. " × 12").
+// Empty when the scale is a no-op, mirroring applyScale's guard.
+export function scaleSuffix(scale: number | undefined): string {
+ return scale === undefined || !Number.isFinite(scale) || scale === 1 ? '' : ` × ${scale}`
+}
+
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})`
+ default:
+ // sum | avg | min | max | median: the metric type is the HogQL aggregate fn name.
+ return applyScale(`${metric.type}(${metric.columnExpression})`, metric.scale)
}
}
+// The auto-derived subtitle for a tile, from its metric. `count` has none.
+export function autoCaption(tile: AccountsOverviewTile): string | undefined {
+ const { metric } = tile
+ switch (metric.type) {
+ case 'count':
+ return undefined
+ case 'count_threshold':
+ return `${metric.columnLabel} ${metric.operator} ${metric.value}`
+ default:
+ // sum | avg | min | max | median: the metric type reads as the aggregation verb.
+ return `${metric.type} of ${metric.columnLabel}${scaleSuffix(metric.scale)}`
+ }
+}
+
+// The subtitle shown on a tile: the user's custom caption when set, else the
+// auto-derived one. A whitespace-only caption is treated as unset.
+export function tileCaption(tile: AccountsOverviewTile): string | undefined {
+ const custom = tile.caption?.trim()
+ return custom ? custom : autoCaption(tile)
+}
+
// 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.
+// inherently row-level condition. `count_threshold` does; `count` and the
+// column aggregations describe the whole set, not a subset.
export function tileToRowFilter(tile: AccountsOverviewTile): string | null {
if (tile.metric.type !== 'count_threshold') {
return null