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(revenue-analytics): migrate charts to quill (#61840)

Sam Penningtoncec23a23c519
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 18c6fa8db76a..3b3df6c44c05 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5907,17 +5907,25 @@ snapshots:
scenes-app-replay-vision--scanners-list--light:
hash: v1.k794b7964.498983062797fa546436034f824fbae467678dc342e693c140389b615804679f.YxqzOmHvrqE9h81CC2VMBT_NHuwvvdyMqMdO1BUVR-k
scenes-app-revenue-analytics--revenue-analytics-dashboard--dark:
- hash: v1.k794b7964.7c2a90fe3c3a969c054186bb666664efa891d65d411a546539a968518938ea71.OoOKh-Mc_IiPWTgIV4QNPtACZXPPktfU7bjGk-q-uLE
+ hash: v1.k794b7964.3b4f6a185d0332a9ac4871791ad9cbd8c5153062e35b02463cf264ff78d929ae.yxixzefaqbohT5c-mkkDGFkQ5jFbxFZTJNQMfwOnapI
scenes-app-revenue-analytics--revenue-analytics-dashboard--light:
- hash: v1.k794b7964.e28fe6f60136f350f5339146d7246f21e78586a948bfa29edb6c01926e993a1d.WX2NwRYvLh0q8A6QKLBseHRJ6XKWU76Ak-QfwsPt7c8
+ hash: v1.k794b7964.e377f74a29ac2e0276263d416ee1262c2b12400e927871c06be52e314ca2da09.V-mkg8TbXd_z-6ovJ9BoMzCV_sJ2GQ2o9WcSLdvlX8g
+ scenes-app-revenue-analytics--revenue-analytics-dashboard-area-mode--dark:
+ hash: v1.k794b7964.e809b6057b3726a9a3bbfabe8b641164c53a113637d0371fdc75e57f59e9e6e1.t7Yi7gvwTUxhm_cxJoLCKJdAYKcvedk85pqf6Mkhm20
+ scenes-app-revenue-analytics--revenue-analytics-dashboard-area-mode--light:
+ hash: v1.k794b7964.ae4bd815a206bdbad9c1bd5e909fd51cb281f87e8eea7ad336135707984ca53a.Yj1cH-7VAUDQsMn-09ppYCfTyEjAuhIL17YZhh6X31Q
+ scenes-app-revenue-analytics--revenue-analytics-dashboard-bar-mode--dark:
+ hash: v1.k794b7964.127eeedd4aac02b5c07d856a6fb7726f284597153b4373fbabf1465d3d540373.rTYvcngE7KxbqbxYHSCsamc8HclEe8gmbMxRwSCIgy8
+ scenes-app-revenue-analytics--revenue-analytics-dashboard-bar-mode--light:
+ hash: v1.k794b7964.a39ee336074c150d47b1b780c8dfa70cca4812b88b9a0a5b1aea6e320b027584.XLkzmwlIVkavbv1ZQNqV0zld9_fCnTYvBI3Nlqj_0_E
scenes-app-revenue-analytics--revenue-analytics-dashboard-sync-in-progress--dark:
- hash: v1.k794b7964.9a09c8b3c4e5162b63d6c9d66d035faad157215ba81ecb5edbaf9dd9920782f5.1ZertlNKsZ0uWQ0FvBTnbSyJrW__9KzCKcIWFTRzQ4E
+ hash: v1.k794b7964.64238c158c8ad819ac47e780646c8beb7b36cc3e3d32e551340457426260f10d.xTB8G4yV7ZG6lbxWcmxkrS8zRGniCGHl5Jd_QDax8og
scenes-app-revenue-analytics--revenue-analytics-dashboard-sync-in-progress--light:
- hash: v1.k794b7964.a25e103bc9538a4d856cf368325539c281fcd48f305a74bf7a2b39afdbb482db.PySARFNnAAu2DdxhKRpLDbKxr456rHxKuAn8tru68YE
+ hash: v1.k794b7964.b5a85ba3d84b972ded4435b99744319a10ae1e8e991fbdb42dc8f73765ad011f.XRLpdbBkMVEhv75hgHMpSpQbw9YHH5L941DaqOYQsvI
scenes-app-revenue-analytics-mrr-breakdown-modal--mrr-breakdown-modal--dark:
- hash: v1.k794b7964.6834f94d3e762233c3f65284296bc844f2a2feecdb181b121ce10144a26a82c7.L7tkJ6-p1ThrdFpU5RMpeNXMg5f5hUB2Q8ZVVadfIK8
+ hash: v1.k794b7964.938ab51f3ea5a625ceb998fec10ef2a20f0a83858d872d2f79d7d7ccb54cc708.1hsX-zh8Cg_rIt1a86SahGk6XjfkO60W_XEDOCYvl0s
scenes-app-revenue-analytics-mrr-breakdown-modal--mrr-breakdown-modal--light:
- hash: v1.k794b7964.2322ff2e937e8b0a7a92ce0c92cd2de5db06c224b4e6a13c63bfc5b0a6490952.BkAbf4RC1PnA4aY4J8nrxipdeR2kCG8Hh-ZPvRDOKcc
+ hash: v1.k794b7964.85ec1f8829adf2c2b8a3f747e90dfd5e3a2575d225d336363154cc7783b81d1f.Y3xHKwFKq4P2Nz4WmkWtt7coOcw7u0CI4ssfbHm-9y4
scenes-app-revenue-analytics-onboarding--onboarding--dark:
hash: v1.k794b7964.68602963ca1e1c8570bd35c00a7b42d8805016ca3412f3b638ba1600f728a13e.4Ylomq8HoVkFyNnSBGKbNRNsvKMHuU8nzkTqxvs6F1Y
scenes-app-revenue-analytics-onboarding--onboarding--light:
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b78a82af07a3..79eeaf5c9b0d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3471,6 +3471,9 @@ importers:
'@posthog/icons':
specifier: '*'
+ '@posthog/quill-charts':
+ specifier: workspace:*
+ version: link:../../packages/quill/packages/charts
'@storybook/react':
specifier: 'catalog:'
diff --git a/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx b/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx
index 791b31eba2b3..8f54c15c4aef 100644
--- a/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx
+++ b/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx
@@ -103,6 +103,28 @@ export function RevenueAnalyticsDashboard(): JSX.Element {
return <App />
}
+export function RevenueAnalyticsDashboardAreaMode(): JSX.Element {
+ const { setInsightsDisplayMode, addBreakdown } = useActions(revenueAnalyticsLogic)
+
+ useEffect(() => {
+ setInsightsDisplayMode('area')
+ addBreakdown(PRODUCT_A_BREAKDOWN)
+ }, [setInsightsDisplayMode, addBreakdown])
+
+ return <App />
+}
+
+export function RevenueAnalyticsDashboardBarMode(): JSX.Element {
+ const { setInsightsDisplayMode, addBreakdown } = useActions(revenueAnalyticsLogic)
+
+ useEffect(() => {
+ setInsightsDisplayMode('bar')
+ addBreakdown(PRODUCT_A_BREAKDOWN)
+ }, [setInsightsDisplayMode, addBreakdown])
+
+ return <App />
+}
+
export function RevenueAnalyticsDashboardSyncInProgress(): JSX.Element {
const { setTopCustomersDisplayMode, addBreakdown, setRevenueAnalyticsFilters } = useActions(revenueAnalyticsLogic)
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsChart.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsChart.tsx
new file mode 100644
index 000000000000..c4bc42898ba6
--- /dev/null
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsChart.tsx
@@ -0,0 +1,166 @@
+import { useValues } from 'kea'
+import { useCallback, useMemo } from 'react'
+
+import { ChartLegend, TimeSeriesBarChart, TimeSeriesLineChart, legendItemsFromSeries } from '@posthog/quill-charts'
+import type {
+ GoalLineConfig,
+ TimeSeriesBarChartConfig,
+ TimeSeriesLineChartConfig,
+ TooltipConfig,
+ TooltipContext,
+ YAxisConfig,
+} from '@posthog/quill-charts'
+
+import { buildTheme } from 'lib/charts/utils/theme'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+import type { TrendsFilter } from '~/queries/schema/schema-general'
+import type { GraphDataset } from '~/types'
+
+import { trendsFilterToYFormatterConfig } from 'products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat'
+import type { TrendsSeriesMeta } from 'products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta'
+import { TrendsTooltip } from 'products/product_analytics/frontend/insights/trends/shared/TrendsTooltip'
+
+import { revenueAnalyticsLogic } from '../revenueAnalyticsLogic'
+import {
+ buildRevenueAnalyticsSeries,
+ orderLegendItems,
+ type RevenueAnalyticsChartKind,
+} from './revenueAnalyticsChartTransforms'
+
+export type { RevenueAnalyticsChartKind }
+
+const TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'top' }
+
+export interface RevenueAnalyticsChartLegendProps {
+ show: boolean
+ position?: 'top' | 'bottom' | 'left' | 'right'
+ // See orderLegendItems: reverse keeps the legend order matching a stack's visual order.
+ reverse?: boolean
+}
+
+export interface RevenueAnalyticsChartProps {
+ dataAttr: string
+ datasets: GraphDataset[]
+ labels: string[]
+ kind: RevenueAnalyticsChartKind
+ trendsFilter?: TrendsFilter | null
+ goalLines?: GoalLineConfig[]
+ legend?: RevenueAnalyticsChartLegendProps
+ // Stacked bars only — stack negative segments (e.g. churn/contraction) below the zero baseline.
+ divergingStack?: boolean
+ // Dash the final segment to mark the still-incomplete current period (line/area only).
+ isInProgress?: boolean
+ // Override the per-series color (e.g. MRR breakdown maps status → fixed color). When omitted,
+ // the chart falls back to the theme palette by series index, matching the legacy chart.
+ getColor?: (dataset: GraphDataset, index: number) => string | undefined
+}
+
+export function RevenueAnalyticsChart({
+ dataAttr,
+ datasets,
+ labels,
+ kind,
+ trendsFilter,
+ goalLines,
+ legend,
+ divergingStack,
+ isInProgress = false,
+ getColor,
+}: RevenueAnalyticsChartProps): JSX.Element {
+ const { timezone, baseCurrency } = useValues(teamLogic)
+ const { dateFilter } = useValues(revenueAnalyticsLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+
+ // isDarkModeOn is a dep (not an arg): getColor can resolve theme-dependent CSS colors into
+ // concrete values, so the series must rebuild on a light/dark toggle.
+ const series = useMemo(
+ () => buildRevenueAnalyticsSeries(datasets, { kind, isInProgress, getColor }),
+ [datasets, kind, isInProgress, getColor, isDarkModeOn]
+ )
+
+ const yAxis = useMemo<YAxisConfig>(
+ () => ({ ...trendsFilterToYFormatterConfig(trendsFilter, false, baseCurrency), showGrid: true }),
+ [trendsFilter, baseCurrency]
+ )
+
+ const legendItems = useMemo(
+ () => orderLegendItems(legendItemsFromSeries(series, theme), legend?.reverse),
+ [series, theme, legend?.reverse]
+ )
+
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext<TrendsSeriesMeta>) => (
+ <TrendsTooltip
+ context={ctx}
+ timezone={timezone}
+ interval={dateFilter.interval}
+ trendsFilter={trendsFilter}
+ baseCurrency={baseCurrency}
+ groupTypeLabel=""
+ />
+ ),
+ [timezone, dateFilter.interval, trendsFilter, baseCurrency]
+ )
+
+ const legendPosition = legend?.position ?? 'right'
+ const showLegend = !!legend?.show
+
+ // No xAxis config: the backend ships pre-formatted period labels, so the time-axis date
+ // formatter is intentionally left inert (it would otherwise re-format the labels itself).
+ if (kind === 'bar') {
+ const config: TimeSeriesBarChartConfig = {
+ yAxis,
+ goalLines,
+ barLayout: 'stacked',
+ divergingStack,
+ tooltip: TOOLTIP_CONFIG,
+ }
+ return (
+ <ChartLegend
+ show={showLegend}
+ items={legendItems}
+ position={legendPosition}
+ legendDataAttr={`${dataAttr}-legend`}
+ >
+ <TimeSeriesBarChart<TrendsSeriesMeta>
+ series={series}
+ labels={labels}
+ theme={theme}
+ config={config}
+ tooltip={renderTooltip}
+ className="BarGraph"
+ dataAttr={dataAttr}
+ />
+ </ChartLegend>
+ )
+ }
+
+ const config: TimeSeriesLineChartConfig = {
+ yAxis,
+ goalLines,
+ showCrosshair: true,
+ tooltip: TOOLTIP_CONFIG,
+ }
+ return (
+ <ChartLegend
+ show={showLegend}
+ items={legendItems}
+ position={legendPosition}
+ legendDataAttr={`${dataAttr}-legend`}
+ >
+ <TimeSeriesLineChart<TrendsSeriesMeta>
+ series={series}
+ labels={labels}
+ theme={theme}
+ config={config}
+ tooltip={renderTooltip}
+ className="LineGraph"
+ dataAttr={dataAttr}
+ />
+ </ChartLegend>
+ )
+}
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx
index 8f7f4fa92684..90693d50d779 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsGrossRevenueNode.tsx
@@ -89,8 +89,6 @@ const Tile = ({ context }: TileProps): JSX.Element => {
labels={labels}
legend={{
display: breakdownProperties.length > 0 && datasets.length > 1,
- position: 'right',
- // By default chart.js renders first item at the bottom of stack, but legend goes at the top, let's reverse the legend instead
reverse: true,
}}
trendsFilter={{
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx
index 53980ca42468..aaf444139099 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsMRRNode.tsx
@@ -138,8 +138,6 @@ const Tile = ({ context }: TileProps): JSX.Element => {
labels={labels}
legend={{
display: breakdownProperties.length > 0 && mappedDatasets.length > 1,
- position: 'right',
- // By default chart.js renders first item at the bottom of stack, but legend goes at the top, let's reverse the legend instead
reverse: true,
}}
trendsFilter={{
diff --git a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx
index 2c8899f9b1b0..0ed2fd649e7c 100644
--- a/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx
+++ b/products/revenue_analytics/frontend/nodes/RevenueAnalyticsTopCustomersNode.tsx
@@ -1,5 +1,5 @@
import { BindLogic, BuiltLogic, LogicWrapper, useValues } from 'kea'
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { getCurrencySymbol } from 'lib/utils/geography/currency'
@@ -7,7 +7,6 @@ import { InsightLoadingState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
import { InsightsWrapper } from 'scenes/insights/InsightsWrapper'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
-import { LineGraph } from 'scenes/insights/views/LineGraph/LineGraph'
import { teamLogic } from 'scenes/teamLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
@@ -17,9 +16,10 @@ import {
RevenueAnalyticsTopCustomersQueryResponse,
} from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
-import { GraphDataset, GraphType } from '~/types'
+import { GraphDataset } from '~/types'
import { revenueAnalyticsLogic } from '../revenueAnalyticsLogic'
+import { RevenueAnalyticsChart } from './RevenueAnalyticsChart'
let uniqueNode = 0
export function RevenueAnalyticsTopCustomersNode(props: {
@@ -45,6 +45,41 @@ export function RevenueAnalyticsTopCustomersNode(props: {
const { baseCurrency } = useValues(teamLogic)
const { response, responseLoading, queryId } = useValues(logic)
+ // `results` is an array of array in order [customer_name, customer_id, revenue, month]
+ const { labels, datasets } = useMemo(() => {
+ const queryResponse = response as RevenueAnalyticsTopCustomersQueryResponse | undefined
+ const results = (queryResponse?.results ?? []) as any[][]
+
+ const resultsGroupedByCustomer: Record<string, Record<string, any>> = {}
+ for (const result of results) {
+ const [, id, , month] = result
+ resultsGroupedByCustomer[id] ||= {}
+ resultsGroupedByCustomer[id][month] = result
+ }
+
+ const labels: string[] = Array.from(new Set(results.map((result) => result[3]))).sort() as string[]
+ const datasets: GraphDataset[] = Object.entries(resultsGroupedByCustomer).map(([_, results], idx) => {
+ const key = Object.keys(results)[0]
+
+ return {
+ id: idx + 1, // Make them start at 1, for good measure
+
+ // Name is in the second column, grab from any result
+ // Fallback to first column if second is undefined, that's the customer_id
+ label: results[key][1] ?? results[key][0],
+
+ // In the same order as the labels get the revenue
+ // assuming it was 0 if not present in the dataset
+ data: labels.map((label) => results[label]?.[2] ?? 0),
+
+ // Color stuff, make it look pretty
+ colorIndex: idx,
+ }
+ })
+
+ return { labels, datasets }
+ }, [response])
+
if (responseLoading) {
return (
<InsightsWrapper>
@@ -53,39 +88,16 @@ export function RevenueAnalyticsTopCustomersNode(props: {
)
}
- // `results` is an array of array in order [customer_name, customer_id, revenue, month]
- const queryResponse = response as RevenueAnalyticsTopCustomersQueryResponse | undefined
- const results = (queryResponse?.results ?? []) as any[][]
-
- const resultsGroupedByCustomer: Record<string, Record<string, any>> = {}
- for (const result of results) {
- const [, id, , month] = result
- resultsGroupedByCustomer[id] ||= {}
- resultsGroupedByCustomer[id][month] = result
- }
-
- const labels: string[] = Array.from(new Set(results.map((result) => result[3]))).sort() as string[]
- const datasets: GraphDataset[] = Object.entries(resultsGroupedByCustomer).map(([_, results], idx) => {
- const key = Object.keys(results)[0]
-
- return {
- id: idx + 1, // Make them start at 1, for good measure
-
- // Name is in the second column, grab from any result
- // Fallback to first column if second is undefined, that's the customer_id
- label: results[key][1] ?? results[key][0],
-
- // In the same order as the labels get the revenue
- // assuming it was 0 if not present in the dataset
- data: labels.map((label) => results[label]?.[2] ?? 0),
-
- // Color stuff, make it look pretty
- colorIndex: idx,
- }
- })
-
const { isPrefix, symbol: currencySymbol } = getCurrencySymbol(baseCurrency)
+ const trendsFilter = {
+ aggregationAxisFormat: 'numeric' as const,
+ decimalPlaces: 2,
+ minDecimalPlaces: 2,
+ aggregationAxisPrefix: isPrefix ? currencySymbol : undefined,
+ aggregationAxisPostfix: isPrefix ? undefined : currencySymbol,
+ }
+
// These classes are all pretty weird but they're here because we want to maintain consistency
// between the trends and top customers views
return (
@@ -93,21 +105,13 @@ export function RevenueAnalyticsTopCustomersNode(props: {
<div className="TrendsInsight TrendsInsight--ActionsLineGraph">
<BindLogic logic={insightLogic} props={props.context.insightProps ?? {}}>
<BindLogic logic={insightVizDataLogic} props={props.context.insightProps ?? {}}>
- <LineGraph
- data-attr="revenue-analytics-top-customers-node-graph"
- type={GraphType.Line}
+ <RevenueAnalyticsChart
+ dataAttr="revenue-analytics-top-customers-node-graph"
+ kind="line"
datasets={datasets}
labels={labels}
isInProgress={!dateFilter.dateTo}
- trendsFilter={{
- aggregationAxisFormat: 'numeric',
- decimalPlaces: 2,
- minDecimalPlaces: 2,
- aggregationAxisPrefix: isPrefix ? currencySymbol : undefined,
- aggregationAxisPostfix: isPrefix ? undefined : currencySymbol,
- }}
- incompletenessOffsetFromEnd={1}
- labelGroupType="none"
+ trendsFilter={trendsFilter}
/>
</BindLogic>
</BindLogic>
diff --git a/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx b/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx
index beebaf58317e..a631e58d2491 100644
--- a/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx
+++ b/products/revenue_analytics/frontend/nodes/modals/MRRBreakdownChart.tsx
@@ -1,23 +1,31 @@
import { useValues } from 'kea'
+import { useCallback } from 'react'
+import { getBarColorFromStatus } from 'lib/colors'
import { getCurrencySymbol } from 'lib/utils/geography/currency'
import { InsightsWrapper } from 'scenes/insights/InsightsWrapper'
-import { LineGraph } from 'scenes/insights/views/LineGraph/LineGraph'
import { teamLogic } from 'scenes/teamLogic'
-import { GraphDataset, GraphType } from '~/types'
+import type { RevenueAnalyticsMRRQueryResultItem } from '~/queries/schema/schema-general'
+import { GraphDataset } from '~/types'
-import { revenueAnalyticsLogic } from '../../revenueAnalyticsLogic'
+import { RevenueAnalyticsChart } from '../RevenueAnalyticsChart'
import { extractLabelAndDatasets } from '../shared'
import { mrrBreakdownModalLogic } from './mrrBreakdownModalLogic'
+type RevenueAnalyticsStatus = `revenue-analytics-${keyof RevenueAnalyticsMRRQueryResultItem}`
+
export function MRRBreakdownChart(): JSX.Element {
const { baseCurrency } = useValues(teamLogic)
- const { dateFilter } = useValues(revenueAnalyticsLogic)
const { data, newDatasets, expansionDatasets, contractionDatasets, churnDatasets } =
useValues(mrrBreakdownModalLogic)
const { isPrefix, symbol: currencySymbol } = getCurrencySymbol(baseCurrency)
+ const getColor = useCallback(
+ (dataset: GraphDataset) => getBarColorFromStatus(dataset.status as RevenueAnalyticsStatus),
+ []
+ )
+
if (!data || data.length === 0) {
return <div>No data available</div>
}
@@ -39,27 +47,26 @@ export function MRRBreakdownChart(): JSX.Element {
}) as GraphDataset
)
+ const trendsFilter = {
+ aggregationAxisFormat: 'numeric' as const,
+ aggregationAxisPrefix: isPrefix ? currencySymbol : undefined,
+ aggregationAxisPostfix: isPrefix ? undefined : currencySymbol,
+ }
+
return (
<div className="w-full">
<InsightsWrapper>
<div className="TrendsInsight TrendsInsight--ActionsLineGraph">
- <LineGraph
+ <RevenueAnalyticsChart
+ dataAttr="mrr-breakdown-chart"
datasets={datasetsWithIds}
labels={labels}
- type={GraphType.Bar}
- data-attr="mrr-breakdown-chart"
- labelGroupType="none"
- isStacked={true}
- isInProgress={!dateFilter.dateTo}
- legend={{
- display: true,
- position: 'right',
- }}
- trendsFilter={{
- aggregationAxisFormat: 'numeric',
- aggregationAxisPrefix: isPrefix ? currencySymbol : undefined,
- aggregationAxisPostfix: isPrefix ? undefined : currencySymbol,
- }}
+ kind="bar"
+ divergingStack
+ getColor={getColor}
+ // No `legend` prop: the modal renders its own descriptive MRRLegend above the
+ // chart, so the chart's built-in legend would duplicate it.
+ trendsFilter={trendsFilter}
/>
</div>
</InsightsWrapper>
diff --git a/products/revenue_analytics/frontend/nodes/revenueAnalyticsChartTransforms.test.ts b/products/revenue_analytics/frontend/nodes/revenueAnalyticsChartTransforms.test.ts
new file mode 100644
index 000000000000..0eb32f096009
--- /dev/null
+++ b/products/revenue_analytics/frontend/nodes/revenueAnalyticsChartTransforms.test.ts
@@ -0,0 +1,154 @@
+import type { LegendItem } from '@posthog/quill-charts'
+
+import type { GraphDataset } from '~/types'
+
+import {
+ buildRevenueAnalyticsSeries,
+ orderLegendItems,
+ type RevenueAnalyticsChartKind,
+} from './revenueAnalyticsChartTransforms'
+
+const dataset = (overrides: Partial<GraphDataset> = {}): GraphDataset =>
+ ({ id: 0, label: 'stripe.saas', data: [1, 2, 3], ...overrides }) as GraphDataset
+
+describe('buildRevenueAnalyticsSeries', () => {
+ it('maps a dataset onto a series with key, label, data and meta', () => {
+ const [series] = buildRevenueAnalyticsSeries(
+ [dataset({ id: 7, label: 'stripe.merch', data: [10, 20], days: ['2025-01-01', '2025-02-01'] })],
+ { kind: 'line' }
+ )
+
+ expect(series).toMatchObject({
+ key: '7',
+ label: 'stripe.merch',
+ data: [10, 20],
+ meta: { days: ['2025-01-01', '2025-02-01'] },
+ })
+ })
+
+ it('falls back to the array index for key and order when id/action are missing', () => {
+ const series = buildRevenueAnalyticsSeries([dataset({ id: undefined }), dataset({ id: undefined })], {
+ kind: 'line',
+ })
+
+ expect(series.map((s) => s.key)).toEqual(['0', '1'])
+ expect(series.map((s) => s.meta?.order)).toEqual([0, 1])
+ })
+
+ it('prefers action.order over the array index', () => {
+ const [series] = buildRevenueAnalyticsSeries([dataset({ action: { order: 5 } as GraphDataset['action'] })], {
+ kind: 'bar',
+ })
+
+ expect(series.meta?.order).toBe(5)
+ })
+
+ it.each<{ kind: RevenueAnalyticsChartKind; expectedFill: Record<string, never> | undefined }>([
+ { kind: 'area', expectedFill: {} },
+ { kind: 'line', expectedFill: undefined },
+ { kind: 'bar', expectedFill: undefined },
+ ])('adds an area fill only for the area kind (kind=$kind)', ({ kind, expectedFill }) => {
+ expect(buildRevenueAnalyticsSeries([dataset()], { kind })[0].fill).toEqual(expectedFill)
+ })
+
+ it.each<{
+ name: string
+ kind: RevenueAnalyticsChartKind
+ data: number[]
+ isInProgress: boolean
+ expectedStroke: { partial: { fromIndex: number } } | undefined
+ }>([
+ {
+ name: 'line in-progress dashes the final segment',
+ kind: 'line',
+ data: [1, 2, 3],
+ isInProgress: true,
+ expectedStroke: { partial: { fromIndex: 2 } },
+ },
+ {
+ name: 'area in-progress dashes the final segment',
+ kind: 'area',
+ data: [1, 2, 3],
+ isInProgress: true,
+ expectedStroke: { partial: { fromIndex: 2 } },
+ },
+ {
+ name: 'bars never dash',
+ kind: 'bar',
+ data: [1, 2, 3],
+ isInProgress: true,
+ expectedStroke: undefined,
+ },
+ {
+ name: 'complete (not in-progress) charts do not dash',
+ kind: 'line',
+ data: [1, 2, 3],
+ isInProgress: false,
+ expectedStroke: undefined,
+ },
+ {
+ name: 'single-point series do not dash',
+ kind: 'line',
+ data: [1],
+ isInProgress: true,
+ expectedStroke: undefined,
+ },
+ ])('$name', ({ kind, data, isInProgress, expectedStroke }) => {
+ expect(buildRevenueAnalyticsSeries([dataset({ data })], { kind, isInProgress })[0].stroke).toEqual(
+ expectedStroke
+ )
+ })
+
+ it('applies the color override when provided and leaves color unset otherwise', () => {
+ const colorByIndex: (string | undefined)[] = ['#abcdef', undefined]
+ const withColor = buildRevenueAnalyticsSeries([dataset(), dataset({ id: 1 })], {
+ kind: 'bar',
+ getColor: (_, index) => colorByIndex[index],
+ })
+ expect(withColor[0].color).toBe('#abcdef')
+ expect(withColor[1].color).toBeUndefined()
+
+ expect(buildRevenueAnalyticsSeries([dataset()], { kind: 'line' })[0].color).toBeUndefined()
+ })
+
+ it('forwards action and breakdown_value onto series meta', () => {
+ const action = { order: 2, id: 42 } as GraphDataset['action']
+ const [series] = buildRevenueAnalyticsSeries([dataset({ action, breakdown_value: 'stripe.saas' })], {
+ kind: 'line',
+ })
+
+ expect(series.meta?.action).toBe(action)
+ expect(series.meta?.breakdown_value).toBe('stripe.saas')
+ })
+
+ it('keeps a falsy-but-valid id as the key rather than the index', () => {
+ const series = buildRevenueAnalyticsSeries([dataset({ id: 0 }), dataset({ id: 0 })], { kind: 'line' })
+ expect(series.map((s) => s.key)).toEqual(['0', '0'])
+ })
+
+ it('tolerates a missing data array', () => {
+ const [series] = buildRevenueAnalyticsSeries([dataset({ data: undefined })], { kind: 'line' })
+ expect(series.data).toEqual([])
+ })
+})
+
+describe('orderLegendItems', () => {
+ const items = [{ label: 'a' }, { label: 'b' }, { label: 'c' }] as LegendItem[]
+
+ it('reverses the items when reverse is true', () => {
+ expect(orderLegendItems(items, true).map((i) => i.label)).toEqual(['c', 'b', 'a'])
+ })
+
+ it.each([{ reverse: false }, { reverse: undefined }])(
+ 'keeps the original order when reverse=$reverse',
+ ({ reverse }) => {
+ expect(orderLegendItems(items, reverse).map((i) => i.label)).toEqual(['a', 'b', 'c'])
+ }
+ )
+
+ it('does not mutate the input array', () => {
+ const input = [{ label: 'a' }, { label: 'b' }] as LegendItem[]
+ orderLegendItems(input, true)
+ expect(input.map((i) => i.label)).toEqual(['a', 'b'])
+ })
+})
diff --git a/products/revenue_analytics/frontend/nodes/revenueAnalyticsChartTransforms.ts b/products/revenue_analytics/frontend/nodes/revenueAnalyticsChartTransforms.ts
new file mode 100644
index 000000000000..eddc0961a5f8
--- /dev/null
+++ b/products/revenue_analytics/frontend/nodes/revenueAnalyticsChartTransforms.ts
@@ -0,0 +1,44 @@
+import type { LegendItem, Series } from '@posthog/quill-charts'
+
+import type { GraphDataset } from '~/types'
+
+import type { TrendsSeriesMeta } from 'products/product_analytics/frontend/insights/trends/shared/trendsSeriesMeta'
+
+export type RevenueAnalyticsChartKind = 'line' | 'area' | 'bar'
+
+export interface BuildRevenueAnalyticsSeriesOpts {
+ kind: RevenueAnalyticsChartKind
+ isInProgress?: boolean
+ getColor?: (dataset: GraphDataset, index: number) => string | undefined
+}
+
+export function buildRevenueAnalyticsSeries(
+ datasets: GraphDataset[],
+ opts: BuildRevenueAnalyticsSeriesOpts
+): Series<TrendsSeriesMeta>[] {
+ const { kind, isInProgress = false, getColor } = opts
+ return datasets.map((dataset, index) => {
+ const data = (dataset.data ?? []) as number[]
+ const dashFromIndex = isInProgress && kind !== 'bar' && data.length > 1 ? data.length - 1 : undefined
+ return {
+ key: String(dataset.id ?? index),
+ label: dataset.label ?? '',
+ data,
+ color: getColor?.(dataset, index),
+ fill: kind === 'area' ? {} : undefined,
+ stroke: dashFromIndex !== undefined ? { partial: { fromIndex: dashFromIndex } } : undefined,
+ meta: {
+ action: dataset.action,
+ breakdown_value: dataset.breakdown_value,
+ days: dataset.days,
+ order: dataset.action?.order ?? index,
+ },
+ }
+ })
+}
+
+// Stacked charts draw the first series at the bottom but list it at the top of the legend;
+// reversing keeps the legend reading top-down in the same visual order as the stack.
+export function orderLegendItems(items: LegendItem[], reverse?: boolean): LegendItem[] {
+ return reverse ? [...items].reverse() : items
+}
diff --git a/products/revenue_analytics/frontend/nodes/shared.tsx b/products/revenue_analytics/frontend/nodes/shared.tsx
index 5ea2429645b5..92e0802c5f88 100644
--- a/products/revenue_analytics/frontend/nodes/shared.tsx
+++ b/products/revenue_analytics/frontend/nodes/shared.tsx
@@ -12,15 +12,17 @@ import {
InsightValidationError,
} from 'scenes/insights/EmptyStates'
import { InsightsWrapper } from 'scenes/insights/InsightsWrapper'
-import { LineGraph, LineGraphProps } from 'scenes/insights/views/LineGraph/LineGraph'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { extractValidationError, isTimeoutError } from '~/queries/nodes/InsightViz/utils'
-import { AnyResponseType, GoalLine, RevenueAnalyticsGoal } from '~/queries/schema/schema-general'
+import { AnyResponseType, GoalLine, RevenueAnalyticsGoal, TrendsFilter } from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
-import { GraphDataset, GraphType } from '~/types'
+import { GraphDataset } from '~/types'
+
+import { schemaGoalLinesToConfigs } from 'products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter'
import { DisplayMode, revenueAnalyticsLogic } from '../revenueAnalyticsLogic'
+import { RevenueAnalyticsChart, RevenueAnalyticsChartKind } from './RevenueAnalyticsChart'
// Simple interface for the tile props, letting us create tiles with a consistent interface
export interface TileProps {
@@ -129,31 +131,38 @@ export const TileWrapper = ({ title, tooltip, extra, children, context }: TileWr
)
}
-const DISPLAY_MODE_TO_GRAPH_TYPE: Record<DisplayMode, GraphType> = {
- line: GraphType.Line,
- area: GraphType.Line,
- bar: GraphType.Bar,
+const DISPLAY_MODE_TO_CHART_KIND: Record<DisplayMode, RevenueAnalyticsChartKind> = {
+ line: 'line',
+ area: 'area',
+ bar: 'bar',
// not really supported, but here to satisfy the type checker
- table: GraphType.Line,
+ table: 'line',
+}
+
+export interface RevenueAnalyticsLineGraphProps {
+ 'data-attr': string
+ datasets: GraphDataset[]
+ labels: string[]
+ trendsFilter?: TrendsFilter | null
+ legend?: { display: boolean; reverse?: boolean }
}
-// Simple wrapper around the LineGraph component, adding consistent display mode and date filter
-export const RevenueAnalyticsLineGraph = (
- props: Omit<LineGraphProps, 'type' | 'isArea' | 'isInProgress' | 'labelGroupType'>
-): JSX.Element => {
+export const RevenueAnalyticsLineGraph = (props: RevenueAnalyticsLineGraphProps): JSX.Element => {
const { insightsDisplayMode, dateFilter } = useValues(revenueAnalyticsLogic)
+ const legend = props.legend ?? { display: props.datasets.length > 1 }
+
return (
- <LineGraph
- type={DISPLAY_MODE_TO_GRAPH_TYPE[insightsDisplayMode]}
- isArea={insightsDisplayMode !== 'line'}
+ <RevenueAnalyticsChart
+ dataAttr={props['data-attr']}
+ datasets={props.datasets}
+ labels={props.labels}
+ kind={DISPLAY_MODE_TO_CHART_KIND[insightsDisplayMode]}
+ trendsFilter={props.trendsFilter}
+ goalLines={schemaGoalLinesToConfigs(props.trendsFilter?.goalLines)}
isInProgress={!dateFilter.dateTo}
- legend={{ display: props.datasets.length > 1, position: 'right' }}
- trendsFilter={{ aggregationAxisFormat: 'numeric' }}
- labelGroupType="none"
- goalLines={props.goalLines || props.trendsFilter?.goalLines}
- {...props}
+ legend={{ show: legend.display, position: 'right', reverse: legend.reverse }}
/>
)
}
diff --git a/products/revenue_analytics/package.json b/products/revenue_analytics/package.json
index a01722158942..f30f4c7c2ea8 100644
--- a/products/revenue_analytics/package.json
+++ b/products/revenue_analytics/package.json
@@ -4,6 +4,7 @@
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
},
"dependencies": {
+ "@posthog/quill-charts": "workspace:*",
"kea": "catalog:",
"kea-forms": "catalog:",
"kea-loaders": "catalog:",