: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(sql insights): extract pie slice/format helpers into an adapter (#65025)
Sam Penningtoncc02dbb05be5
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsxindex 911b6b8b8743..a8bbbbb69f33 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx@@ -4,15 +4,15 @@ import { useMemo } from 'react'import { LemonColorGlyph } from '@posthog/lemon-ui'-import { getSeriesColor } from 'lib/colors'import { insightLogic } from 'scenes/insights/insightLogic'import { PieChart as InsightPieChart } from 'scenes/insights/views/LineGraph/PieChart'import { ChartSettings } from '~/queries/schema/schema-general'-import { InsightLogicProps, GraphType } from '~/types'+import { GraphType, InsightLogicProps } from '~/types'-import { AxisSeries, AxisSeriesSettings, formatDataWithSettings } from '../../dataVisualizationLogic'+import { AxisSeries, formatDataWithSettings } from '../../dataVisualizationLogic'import { AxisBreakdownSeries } from '../seriesBreakdownLogic'+import { buildPieSlices, formatPieSliceCount } from './sqlPieGraphAdapter'export interface PieChartProps {xData: AxisSeries<string> | null@@ -23,96 +23,6 @@ export interface PieChartProps {uniqueKey: string}-export interface PieSlice {- label: string- value: number- color: string-}--const isBreakdownSeries = (- series: AxisSeries<number | null> | AxisBreakdownSeries<number | null>-): series is AxisBreakdownSeries<number | null> => {- return !('column' in series)-}--const toSliceLabel = (value: unknown): string => {- if (value === null || value === undefined || value === '') {- return '[No value]'- }-- return String(value)-}--const sumValues = (values: (number | null)[]): number => {- return values.reduce<number>((sum, value) => sum + (value ?? 0), 0)-}--const getSeriesLabel = (- series: AxisSeries<number | null> | AxisBreakdownSeries<number | null>,- index: number-): string => {- if (isBreakdownSeries(series)) {- return series.name || `[Series ${index + 1}]`- }-- return series.settings?.display?.label || series.column.name-}--export const buildPieSlices = (- xData: AxisSeries<string> | null,- yData: AxisSeries<number | null>[] | AxisBreakdownSeries<number | null>[]-): PieSlice[] => {- if (!yData.length) {- return []- }-- if (yData.some(isBreakdownSeries)) {- return yData- .map((series, index) => ({- label: getSeriesLabel(series, index),- value: sumValues(series.data),- color: series.settings?.display?.color ?? getSeriesColor(index),- }))- .filter((slice) => slice.value > 0)- }-- if (yData.length === 1 && xData && xData.column.name !== 'None') {- const totalsByLabel = new Map<string, number>()-- xData.data.forEach((rawLabel, index) => {- const label = toSliceLabel(rawLabel)- const value = yData[0].data[index] ?? 0- totalsByLabel.set(label, (totalsByLabel.get(label) ?? 0) + value)- })-- return Array.from(totalsByLabel.entries())- .map(([label, value], index) => ({- label,- value,- color: getSeriesColor(index),- }))- .filter((slice) => slice.value > 0)- }-- return yData- .map((series, index) => ({- label: getSeriesLabel(series, index),- value: sumValues(series.data),- color: series.settings?.display?.color ?? getSeriesColor(index),- }))- .filter((slice) => slice.value > 0)-}--export const formatPieSliceCount = (value: number, total: number, settings?: AxisSeriesSettings): string => {- const formatted = String(formatDataWithSettings(value, settings) ?? value)- // Percent-styled values are already a share, so a share-of-total suffix would be confusing- if (!total || settings?.formatting?.style === 'percent') {- return formatted- }- const shareOfTotal = parseFloat(((value / total) * 100).toFixed(1))- return `${formatted} (${shareOfTotal}%)`-}-export function PieChart({xData,yData,diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.test.tssimilarity index 74%rename from frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.tsrename to frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.test.tsindex 3820616251e3..5213cccbaef0 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.test.ts@@ -1,10 +1,20 @@import { getSeriesColor } from 'lib/colors'+import { ChartDisplayType } from '~/types'+import { AxisSeries } from '../../dataVisualizationLogic'import { AxisBreakdownSeries } from '../seriesBreakdownLogic'-import { buildPieSlices, formatPieSliceCount } from './PieChart'+import { LineGraphProps } from './LineGraph'+import { buildPieSeries, buildPieSlices, canRenderSqlPieGraph, formatPieSliceCount } from './sqlPieGraphAdapter'++const baseProps = (visualizationType: ChartDisplayType): LineGraphProps => ({+ xData: null,+ yData: [],+ visualizationType,+ chartSettings: {},+})-describe('PieChart', () => {+describe('sqlPieGraphAdapter', () => {describe('formatPieSliceCount', () => {it.each([['appends share of total', 25, 100, undefined, '25 (25%)'],@@ -131,4 +141,34 @@ describe('PieChart', () => {])})})++ describe('buildPieSeries', () => {+ it('maps each slice to a single-value quill series, pinning the slice color', () => {+ expect(+ buildPieSeries([+ { label: 'alpha', value: 7, color: '#111111' },+ { label: 'beta', value: 3, color: '#222222' },+ ])+ ).toEqual([+ { key: 'alpha-0', label: 'alpha', color: '#111111', data: [7] },+ { key: 'beta-1', label: 'beta', color: '#222222', data: [3] },+ ])+ })++ it('returns an empty array when there are no slices', () => {+ expect(buildPieSeries([])).toEqual([])+ })+ })++ describe('canRenderSqlPieGraph', () => {+ it.each([+ [ChartDisplayType.ActionsPie, true],+ [ChartDisplayType.ActionsLineGraph, false],+ [ChartDisplayType.ActionsBar, false],+ [ChartDisplayType.ActionsStackedBar, false],+ [ChartDisplayType.ActionsAreaGraph, false],+ ])('returns %s -> %s', (visualizationType, expected) => {+ expect(canRenderSqlPieGraph(baseProps(visualizationType))).toBe(expected)+ })+ })})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.tsnew file mode 100644index 000000000000..f97580990ee9--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts@@ -0,0 +1,109 @@+import { type Series } from '@posthog/quill-charts'++import { getSeriesColor } from 'lib/colors'++import { ChartDisplayType } from '~/types'++import { AxisSeries, AxisSeriesSettings, formatDataWithSettings } from '../../dataVisualizationLogic'+import { AxisBreakdownSeries } from '../seriesBreakdownLogic'+import { LineGraphProps } from './LineGraph'++export interface PieSlice {+ label: string+ value: number+ color: string+}++export type SqlPieYSeries = AxisSeries<number | null> | AxisBreakdownSeries<number | null>++const isBreakdownSeries = (series: SqlPieYSeries): series is AxisBreakdownSeries<number | null> => {+ return !('column' in series)+}++const toSliceLabel = (value: unknown): string => {+ if (value === null || value === undefined || value === '') {+ return '[No value]'+ }++ return String(value)+}++const sumValues = (values: (number | null)[]): number => {+ return values.reduce<number>((sum, value) => sum + (value ?? 0), 0)+}++const getSeriesLabel = (series: SqlPieYSeries, index: number): string => {+ if (isBreakdownSeries(series)) {+ return series.name || `[Series ${index + 1}]`+ }++ return series.settings?.display?.label || series.column.name+}++/** One slice per y-series — the breakdown and no-categorical-x-axis cases share this shaping. */+const seriesToSlices = (yData: SqlPieYSeries[]): PieSlice[] =>+ yData+ .map((series, index) => ({+ label: getSeriesLabel(series, index),+ value: sumValues(series.data),+ color: series.settings?.display?.color ?? getSeriesColor(index),+ }))+ .filter((slice) => slice.value > 0)++export const buildPieSlices = (+ xData: AxisSeries<string> | null,+ yData: AxisSeries<number | null>[] | AxisBreakdownSeries<number | null>[]+): PieSlice[] => {+ if (!yData.length) {+ return []+ }++ if (yData.some(isBreakdownSeries)) {+ return seriesToSlices(yData)+ }++ if (yData.length === 1 && xData && xData.column.name !== 'None') {+ const totalsByLabel = new Map<string, number>()++ xData.data.forEach((rawLabel, index) => {+ const label = toSliceLabel(rawLabel)+ const value = yData[0].data[index] ?? 0+ totalsByLabel.set(label, (totalsByLabel.get(label) ?? 0) + value)+ })++ return Array.from(totalsByLabel.entries())+ .map(([label, value], index) => ({+ label,+ value,+ color: getSeriesColor(index),+ }))+ .filter((slice) => slice.value > 0)+ }++ return seriesToSlices(yData)+}++/** One quill `Series` per slice, with the slice's resolved color pinned so per-breakdown+ * `resultCustomizations` survive the move off chart.js. */+export const buildPieSeries = (slices: PieSlice[]): Series[] => {+ return slices.map((slice, index) => ({+ key: `${slice.label}-${index}`,+ label: slice.label,+ color: slice.color,+ data: [slice.value],+ }))+}++export const formatPieSliceCount = (value: number, total: number, settings?: AxisSeriesSettings): string => {+ const formatted = String(formatDataWithSettings(value, settings) ?? value)+ // Percent-styled values are already a share, so a share-of-total suffix would be confusing+ if (!total || settings?.formatting?.style === 'percent') {+ return formatted+ }+ const shareOfTotal = parseFloat(((value / total) * 100).toFixed(1))+ return `${formatted} (${shareOfTotal}%)`+}++export function canRenderSqlPieGraph(props: LineGraphProps): boolean {+ return props.visualizationType === ChartDisplayType.ActionsPie+}