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.

chore(customer-analytics): render billing charts via quill-charts directly (#74136)

Sam Penningtonf746ade4c50d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 23196498c5af..6f170e9dc211 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5573,7 +5573,7 @@ snapshots:
scenes-app-dashboards--show-across-viewports--medium--dark:
hash: v1.k794b7964.700cde8e1a4cc8c902b217300de8c5bbca2c3d1d4c727f0533fc664679bc22d3.bd-grjT3BisGzyb6iVrYefXx4uBqpaFrcjl3ZM-eEII
scenes-app-dashboards--show-across-viewports--medium--light:
- hash: v1.k794b7964.a234c28bcd64c498f325a8d7afbb3e5733e43aab3b07a7cae6b98af69603d1e6.xUojuNjkLX7GERozP3JglULFZ8NLXOqQ0ZPKmRBMaZQ
+ hash: v1.k794b7964.2e865350cfdb9ec6f0ac5387df2f4b0fb67d3a7605b7bf7dd4ddae901f510128.A-k_xdWvVTsFK3zbzXsYP-TjPTPx4Peb8QW2oBUXdTk
scenes-app-dashboards--show-across-viewports--narrow--dark:
hash: v1.k794b7964.e919c4955d7113170ab00269c5f628c318afe14f26dc8aafb046b172e17f362e.YDXD84rrb2KR1I36pHMxEsGZ0sN0os_cBBdNIf89Pu8
scenes-app-dashboards--show-across-viewports--narrow--light:
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index f8f22b267034..84d739d79d9c 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -89,7 +89,7 @@ The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so
The Usage and Spend tabs render existing saved billing insights — **point users to them, don't rebuild billing as new insights.**
-**Customer analytics owns the billing chart render.** Each billing chart is multi-series on one shared axis, so a small-magnitude series (e.g. feature flag requests) is a flat sliver against large ones (events/enhanced persons) and can't be read. To offer per-series show/hide **without touching shared data-viz code**, `AccountBillingChart` renders the saved insight's SQL chart directly via `@posthog/quill-charts` instead of an embedded `<Query>`/DataVisualization. It reuses the shared pipeline read-only — `dataVisualizationLogic` for fetch + SQL-results→series parsing, and the exported `useSqlChartModel`/`build*ChartConfig` builders so the chart matches what the insight renders elsewhere — and injects the hidden series into quill's controlled `legend.hiddenKeys` (excluded from drawing and scales; the rest rescale into the freed space). `AccountBillingSeriesToggle` is the control: a compact chip row under each chart, one chip per series colored to match its line/bar (items come from `legendItemsFromSeries` over the same `buildSeries` output the chart draws, so keys and colors can't drift). The hidden-keys state lives in `accountBillingLogic` (`ephemeralHiddenSeriesKeysByShortId`, keyed per insight because the spend tab renders two) — per-view only: never written to the saved insight, reset on date change, gone on row collapse. Queries whose shape `AccountBillingChart` can't render (non-DataViz, table/number/pie displays, series breakdowns — see `canRenderBillingChart`) fall back to the embedded `<Query>` with no chips.
+**Customer analytics owns the billing chart render.** Each billing chart is multi-series on one shared axis, so a small-magnitude series (e.g. feature flag requests) is a flat sliver against large ones (events/enhanced persons) and can't be read. To offer per-series show/hide **without touching shared data-viz code**, `AccountBillingChart` renders the saved insight's SQL chart directly via `@posthog/quill-charts` instead of an embedded `<Query>`/DataVisualization. It reuses `dataVisualizationLogic` read-only for fetch + SQL-results→series parsing, and renders via `sqlLineGraphAdapter.ts`'s pure builders — the same series building, render dispatch, and line/bar/combo config building (per-column formatting, area fills, right-axis routing, goal and trend lines, percent stacks, plus the 200-series render cap applied locally) the SQL insight chart uses — while staying off that chart's React layer (`LineGraph`/`useSqlChartModel`). Chart-semantics changes belong in the adapter (covered by `sqlLineGraphAdapter.test.ts`), not here. Hidden series are injected into quill's controlled `legend.hiddenKeys` (excluded from drawing and scales; the rest rescale into the freed space). `AccountBillingSeriesToggle` is the control: a compact chip row under each chart, one chip per series colored to match its line/bar (items come from `legendItemsFromSeries` over the same `buildSeries` output the chart draws, so keys and colors can't drift). The hidden-keys state lives in `accountBillingLogic` (`ephemeralHiddenSeriesKeysByShortId`, keyed per insight because the spend tab renders two) — per-view only: never written to the saved insight, reset on date change, gone on row collapse. Queries whose shape `AccountBillingChart` can't render (non-DataViz, table/number/pie displays, series breakdowns — see `canRenderBillingChart`) fall back to the embedded `<Query>` with no chips.
The Opportunities tab lists the account's Salesforce opportunities from the data-warehouse `salesforce.opportunity` table (joined by the account's `sfdc_id`). The query runs in `accountOpportunitiesLogic` rather than via a bare `<Query>` so the tab owns every state: a missing `sfdc_id` shows a "not linked to Salesforce" empty state, and because `salesforce.opportunity` is **access-gated and production-only**, a failed query degrades to a pretty hog empty state instead of a red error box. The expected denied/absent-table `QueryError` (`You don't have access to table …` / `Unknown table …`) is **not** captured to PostHog — it's the normal empty state, not a bug — while genuine, unexpected query failures are still reported (`isExpectedMissingTableError` in `accountOpportunitiesLogic`). Each opportunity name links to its Salesforce record (`SALESFORCE_ORIGIN/<id>` in `constants.ts`, the same origin the Useful links sidebar uses).
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx
index 8f1362789ff6..2021006b192c 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx
@@ -1,34 +1,42 @@
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
+import { useMemo } from 'react'
import { LemonSkeleton } from '@posthog/lemon-ui'
import {
type ChartTheme,
type LegendItem,
+ type Series,
TimeSeriesBarChart,
TimeSeriesComboChart,
TimeSeriesLineChart,
legendItemsFromSeries,
} from '@posthog/quill-charts'
-import { useChartTheme } from 'lib/charts/hooks'
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { InsightErrorState } from 'scenes/insights/EmptyStates'
+import { teamLogic } from 'scenes/teamLogic'
-import { LineGraphProps } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'
import {
- SqlLineSeriesMeta,
+ type BuildBarConfigArgs,
+ MAX_SERIES,
+ type SqlLineSeriesMeta,
buildBarChartConfig,
buildComboChartConfig,
buildLineChartConfig,
buildSeries,
canRenderSqlBarGraph,
canRenderSqlComboGraph,
- capYSeriesData,
} from '~/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter'
-import { useSqlChartModel } from '~/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel'
-import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
-import { DataVisualizationNode, HogQLVariable, NodeKind } from '~/queries/schema/schema-general'
+import { AxisSeries, dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
+import {
+ ChartSettings,
+ DataVisualizationNode,
+ GoalLine,
+ HogQLVariable,
+ NodeKind,
+} from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
import { AccountBillingLogicProps, accountBillingLogic } from './accountBillingLogic'
@@ -56,20 +64,60 @@ const handleChartError = (error: Error): void => {
posthog.captureException(error, { scope: 'AccountBillingChart' })
}
+/** The slice of a saved insight's chart definition the billing tabs render. Series breakdowns are
+ * excluded upstream (`canRenderBillingChart`), so the y series are always plain axis columns. */
+interface BillingChartProps {
+ xData: AxisSeries<string> | null
+ yData: AxisSeries<number | null>[]
+ visualizationType: ChartDisplayType
+ chartSettings: ChartSettings
+ goalLines?: GoalLine[]
+}
+
function chipItemsFromChartOwnSeries(
- yData: LineGraphProps['yData'],
+ yData: BillingChartProps['yData'],
visualizationType: ChartDisplayType,
theme: ChartTheme
): LegendItem[] {
- const ySeriesData = capYSeriesData(yData)
- return ySeriesData?.length ? legendItemsFromSeries(buildSeries(ySeriesData, visualizationType), theme) : []
+ return yData?.length ? legendItemsFromSeries(buildSeries(yData, visualizationType), theme) : []
+}
+
+interface BillingChartModel<TConfig> {
+ series: Series<SqlLineSeriesMeta>[]
+ labels: string[]
+ theme: ChartTheme
+ config: TConfig
+}
+
+/** Builds the quill series + config for one billing chart. Returns null until there's something to
+ * draw, so each renderer can bail without branching on half-built state. */
+function useBillingChartModel<TConfig extends object>(
+ { xData, yData, visualizationType, chartSettings, goalLines }: BillingChartProps,
+ buildConfig: (args: BuildBarConfigArgs) => TConfig
+): BillingChartModel<TConfig> | null {
+ const { timezone } = useValues(teamLogic)
+ const theme = useChartTheme()
+
+ const series = useMemo(() => buildSeries(yData, visualizationType), [yData, visualizationType])
+ const config = useChartConfig(
+ () =>
+ xData
+ ? buildConfig({ xData, ySeriesData: yData, visualizationType, chartSettings, timezone, goalLines })
+ : undefined,
+ [xData, yData, visualizationType, chartSettings, timezone, goalLines, buildConfig]
+ )
+
+ if (!xData || series.length === 0 || !config) {
+ return null
+ }
+ return { series, labels: xData.data, theme, config }
}
function BillingChartByKind({
chartProps,
hiddenKeys,
}: {
- chartProps: LineGraphProps
+ chartProps: BillingChartProps
hiddenKeys: string[]
}): JSX.Element | null {
if (canRenderSqlComboGraph(chartProps)) {
@@ -81,15 +129,15 @@ function BillingChartByKind({
return <BillingLineChart chartProps={chartProps} hiddenKeys={hiddenKeys} />
}
-// One subcomponent per chart kind because useSqlChartModel's config type follows the builder it's given.
+// One subcomponent per chart kind because useBillingChartModel's config type follows the builder it's given.
function BillingLineChart({
chartProps,
hiddenKeys,
}: {
- chartProps: LineGraphProps
+ chartProps: BillingChartProps
hiddenKeys: string[]
}): JSX.Element | null {
- const model = useSqlChartModel(chartProps, buildLineChartConfig)
+ const model = useBillingChartModel(chartProps, buildLineChartConfig)
if (!model) {
return null
}
@@ -108,10 +156,10 @@ function BillingBarChart({
chartProps,
hiddenKeys,
}: {
- chartProps: LineGraphProps
+ chartProps: BillingChartProps
hiddenKeys: string[]
}): JSX.Element | null {
- const model = useSqlChartModel(chartProps, buildBarChartConfig)
+ const model = useBillingChartModel(chartProps, buildBarChartConfig)
if (!model) {
return null
}
@@ -130,10 +178,10 @@ function BillingComboChart({
chartProps,
hiddenKeys,
}: {
- chartProps: LineGraphProps
+ chartProps: BillingChartProps
hiddenKeys: string[]
}): JSX.Element | null {
- const model = useSqlChartModel(chartProps, buildComboChartConfig)
+ const model = useBillingChartModel(chartProps, buildComboChartConfig)
if (!model) {
return null
}
@@ -149,13 +197,13 @@ function BillingComboChart({
}
/**
- * Renders a saved billing insight's SQL chart directly via @posthog/quill-charts instead of the
+ * Renders a saved billing insight's chart directly via @posthog/quill-charts instead of the
* embedded DataVisualization, so Customer analytics owns the per-series show/hide chips without
- * touching shared data-viz code. The shared pipeline is reused read-only — `dataVisualizationLogic`
- * for fetch + SQL-results→series parsing, the exported `useSqlChartModel`/config builders for the
- * render — so the chart matches what the insight renders elsewhere. Hidden series go into quill's
- * controlled `legend.hiddenKeys`: excluded from drawing and scales, the rest rescale into the
- * freed space.
+ * touching shared data-viz code. `dataVisualizationLogic` is still reused read-only for fetch +
+ * SQL-results→series parsing, and the series/config builders come from `sqlLineGraphAdapter`'s
+ * pure functions — but not the SQL chart's React layer (`LineGraph`, `useSqlChartModel`), so this
+ * stays clear of the legacy paths being cleaned up there. Hidden series go into quill's controlled
+ * `legend.hiddenKeys`: excluded from drawing and scales, the rest rescale into the freed space.
*/
export function AccountBillingChart({
logicProps,
@@ -187,14 +235,17 @@ export function AccountBillingChart({
const theme = useChartTheme()
const hiddenKeys = ephemeralHiddenSeriesKeysByShortId[shortId] ?? []
- const chartProps: LineGraphProps = {
+ // Capped here, once, so renderer dispatch, chart config, and legend chips all see the same series.
+ // (The SQL path caps inside useSqlChartModel; this path builds its model itself, so cap at the source.)
+ const cappedYData = useMemo(() => (yData.length > MAX_SERIES ? yData.slice(0, MAX_SERIES) : yData), [yData])
+ const chartProps: BillingChartProps = {
xData,
- yData,
+ yData: cappedYData,
visualizationType: effectiveVisualizationType,
chartSettings,
goalLines: chartSettings.goalLines,
}
- const chipItems = chipItemsFromChartOwnSeries(yData, effectiveVisualizationType, theme)
+ const chipItems = chipItemsFromChartOwnSeries(cappedYData, effectiveVisualizationType, theme)
let content: JSX.Element | null
if (responseError) {