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.

fix(bi): clarify measure expressions and expose table formatting (#121241)

Marius Andra099abd1666f9
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 1e602676b729..a609d411226f 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -92,6 +92,10 @@ Direct connections group tables by schema. Search matches table and folder names
## Calculated measures in BI mode
+Choose **Edit measure expression** from a measure pill to edit its SQL and aggregation together. The editor shows the aggregation applied to each group. Choose **Custom SQL · no extra aggregation** when the expression already contains aggregate functions, such as `sum(revenue) / nullIf(count(), 0)`. This uses the expression directly without wrapping it in Count or Sum. Changes apply together when you select **Update SQL expression**; closing the editor discards the draft.
+
+Worksheet tables offer **Conditional formatting** beside the visualization settings button. It opens the same rule editor used by SQL insights. Rules apply to the table and persist with the worksheet, so copying its query into another insight is unnecessary. This control applies to tables, not pivot tables or charts.
+
Chart settings offer **Reference lines** for BI line and bar charts. Add a constant target, or choose **Mean**, **Median**, **Minimum**, or **Maximum** across returned marks on the left axis. **Per series** calculates a separate reference for each color group or measure and includes its name in the label. Calculated lines update with the results, after aggregation and table calculations; they exclude missing values and respect result limits. They do not re-aggregate the underlying source rows or apply to the right axis. Calculated lines are hidden on 100% stacked charts, where constant percentage targets remain available.
The **Marks** card offers table calculations per measure: percent of total, running total, difference or percent change from the preceding point, trailing moving average, and rank. **Compute using** selects the dimension to traverse, with the date dimension chosen by default; other dimensions partition the calculation. Moving averages use a trailing window including the current point, in ascending order. Partial windows average available non-null values; **Require a full window** leaves the result empty until every point in the window has a value. Calculations run before the result limit, and zero denominators produce empty cells.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ac3ffec36540..5abc309df5d4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6866,6 +6866,10 @@ snapshots:
hash: v1.k794b7964.1d80c6db4f1f88a1db7ef2cd87c7078817324cb960257d8bc4fc5685876ccac6.ff6KqB1lZjhdbYfDeeK4vL9Y55rFaVr7WhBdiFp_Zno
products-business-intelligence-worksheet-exploration--sql-preview--light:
hash: v1.k794b7964.a694a2e34e9c18f6c4c50e3b930558dfd97dd59874df8e104fff77957a14fa06.WiYn-ILI2MLWRei6QPwwv-a_mBBFKFQpDdtAwCBcHaE
+ products-business-intelligence-worksheet-exploration--table-conditional-formatting--dark:
+ hash: v1.k794b7964.2285dff4633e5992bd7d1552cdef4c94f51b055a968f7be591ccee170dd95a90.9L0cgGYF5UAinLuhlN-XVXbarxapwHorTB93Dgkf40U
+ products-business-intelligence-worksheet-exploration--table-conditional-formatting--light:
+ hash: v1.k794b7964.351c0fda7bf0696591ba8fae59fee71acf2a28865cfc5ce637468823c8303fdd.h8tIQMd2l9RRcDLLWKJ9e7fOe_vtc4lvbO0Ak93-5WI
products-business-intelligence-worksheets--worksheets--dark:
hash: v1.k794b7964.838bf04ffdacba54c2f70f91dbc672e423e58a4ca8755f797d231d994dce8405.ZSy44AUoYYG-8us1HscrH2qR_SbXbBOzizBhHLB2Kak
products-business-intelligence-worksheets--worksheets--light:
@@ -10359,9 +10363,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
hash: v1.k794b7964.a28fe74151fe162afed2aef0cc3e08361f697caecea4bad6840cf1202dcc4445.RGSfrPhsnDlNzudY_9ruoEm8qErJKrmNlHW3B6w-h48
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.22a20d17eab279b832fc6b2f6ee0f4b3172941d930da08db6a8e119f262c7357.stu7E8T6rt7DD7Z6Te_UyF3lH3Z8cknHBcr-wQ_aGjs
+ hash: v1.k794b7964.b4ce9e84f0f8d6fd98e0d44d9b1457e6939682ff10968d1742ef3ac626d7a679.oQxm5UEKsWwqTIOq3Bj_OCeP-srCGqHqxaZWa-p2dGk
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.b9e4f271b838f88b67d553599338bc9219805d444b324c3340a7de6d4b7a233f.UP-LInLaWrxPn5wtKirfGZem-aa1fVCQLLXCM3K5nLk
+ hash: v1.k794b7964.aba1a2003e94bb3b7260a06ba6f089965fef45f44a2eceaf3b85beccdbe73e35.Y7EU5lpu3LvR5kiaY9mG1YOILQhmUCRF6QO__tWpCj4
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
hash: v1.k794b7964.0420942940ebe86d82b461ba813e00bc9985c9373f93333ae0873135286b9a85.Ya5LBQvbsZd_Oe3qrpE1D1O_i91yHF1350PNQocsCo8
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
@@ -10407,9 +10411,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
hash: v1.k794b7964.946ee03244d1551a8a10651bd5b9056e21d775b95b705bac58d154f547f46a62.88TBl5h3uvG7yS9W6BXwnV9-1zEo_XifVGV6AUhwF68
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.74a1daf65ba33fe931c0a94c8af6639dec1aa7ab34bce84f15c7cc2592505c16.s0DXmHm2ZTQBYSCBuP16YZO-_KE6s3vE31tdJD-folY
+ hash: v1.k794b7964.2cac7f0aa71a9a992cbe6f8197b95ce45c4e612025b88157ce2868278f76ea5e.A83E66s_OVMQmI7vWizl0jHLo4cObkWH0jt9oiWnx7U
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.3ed48924bc253517bb87335f23ada51112d858e15a6089afbb1946d992c91c5d.R_CTb0YRRMWizALWLWFEya0tczznLB0ay6V1J7tW0a8
+ hash: v1.k794b7964.d1949187804261259f00f6ac8b4cd6aa4b98df861f32c988c23fc37afb1946b6.mYHscbLc8Nga36gpCDkp1JfXh-67WRSng9Z2rBfLzOI
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.06df092616d217a4ebdaf0f5f35015c05fe63f5bc1e9b9c39dcdf6594293c0e3.D8zEjaefT5868HRYC8F6GkfsuMMlcxSxekM5z-VoXyM
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
@@ -10419,9 +10423,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-source-preview-large-sample--light:
hash: v1.k794b7964.f9bdafe72c33b8454fe4d48e70433457801d2d198e398a25d58ff3926f4f29ab.VcdI3e-Cydfw21sTHkEAiZdXPeRVvBT6TBGUZbP5lTc
scenes-app-data-warehouse-sql-editor--bi-table-analysis--dark:
- hash: v1.k794b7964.74e9fbf12a84be1c6be726c55f970616d5cb28efb3abbc0a57ef9ac7da1b8861.ONSBDimZYZjRS0Y5C5ldETWfuJiUhgMzJ799ZczUci4
+ hash: v1.k794b7964.13e469538d6b0f6d5fb6f5a1d3b0f7c93a08282d843f28e1b54670cc234f1ef3.0LLI_p2z10NDsCrEq3dnR0bM-utFqudI3A5jwdkcARI
scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
- hash: v1.k794b7964.e861b368d3503bf7c5a027336409e6193af633a03d3a643bea869d586cbd60a5.r1gDj9lKngDStrL1zlONSoXAyrULGZjvGRbexR2xsmM
+ hash: v1.k794b7964.44d69a1bbaccaf0b36c54de60fe8da960486b037d9c463ebd792babe5c06e5e9.fxjYqqNq6B7MDjD9WUXXn2D6PCVSTqWdPMbdlAo44NA
scenes-app-data-warehouse-sql-editor--bi-wide-transposed-results--dark:
hash: v1.k794b7964.149351e0c2ce9de8ced8adf4a1c2a990069579b37d826dd4a745d630ef2395e5.wA9l58Kdj1OH6f_5SRT-_guSbpryqUVzCZWDhaFNulw
scenes-app-data-warehouse-sql-editor--bi-wide-transposed-results--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index f9f58b97a176..e79f6b2a5045 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -68,7 +68,7 @@ import { AddVariableButton } from './Components/Variables/AddVariableButton'
import { variableModalLogic } from './Components/Variables/variableModalLogic'
import { VariablesForInsight } from './Components/Variables/Variables'
import { VariablesLogicProps, variablesLogic } from './Components/Variables/variablesLogic'
-import { DataVisualizationLogicProps, dataVisualizationLogic } from './dataVisualizationLogic'
+import { DataVisualizationLogicProps, SideBarTab, dataVisualizationLogic } from './dataVisualizationLogic'
import { displayLogic } from './displayLogic'
import { applyDataVisualizationQueryUpdate } from './queryUpdateUtils'
@@ -267,7 +267,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
[biConfig, effectiveVisualizationType]
)
- const { toggleChartSettingsPanel } = useActions(dataVisualizationLogic)
+ const { toggleChartSettingsPanel, setSideBarTab } = useActions(dataVisualizationLogic)
const { queryId, pollResponse } = useValues(dataNodeLogic)
@@ -702,6 +702,27 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
aria-label="Visualization settings"
/>
+ {query.kind === NodeKind.BIVisualizationNode &&
+ effectiveVisualizationType === ChartDisplayType.ActionsTable && (
+ <LemonButton
+ size={controlSize}
+ type="secondary"
+ data-attr="bi-conditional-formatting"
+ onClick={() => {
+ setSideBarTab(SideBarTab.ConditionalFormatting)
+ if (settingsPanel) {
+ if (!settingsPanel.isOpen) {
+ settingsPanel.onToggle()
+ }
+ } else {
+ toggleChartSettingsPanel(true)
+ }
+ }}
+ >
+ Conditional formatting
+ </LemonButton>
+ )}
+
{props.exportContext && (
<ExportButton
size={controlSize}
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
index a618db7cd61c..b0e6d4bc4768 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
@@ -1993,6 +1993,12 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
const rules = values.conditionalFormattingRules
const saveableRules = rules.filter((n) => n.columnName && n.input && n.templateId && n.bytecode.length)
+ if (values.query.kind === NodeKind.BIVisualizationNode) {
+ captureBIWorksheetAction('conditional_formatting_updated', values.query.config, {
+ rule_count: saveableRules.length,
+ })
+ }
+
actions.setQuery((query) => ({
...query,
tableSettings: {
@@ -2012,6 +2018,11 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
},
})),
listeners(({ props, values, actions, sharedListeners }) => ({
+ setSideBarTab: ({ tab }) => {
+ if (tab === SideBarTab.ConditionalFormatting && values.query.kind === NodeKind.BIVisualizationNode) {
+ captureBIWorksheetAction('conditional_formatting_opened', values.query.config)
+ }
+ },
loadHogVm: async () => {
try {
actions.setHogVm(await retryImport(() => import('lib/hog')))
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
index 4768924afcf3..3dba228db958 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.stories.tsx
@@ -7,10 +7,10 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { mswDecorator } from '~/mocks/browser'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
-import { ChartSettings, NodeKind } from '~/queries/schema/schema-general'
+import { ChartSettings, NodeKind, TableSettings } from '~/queries/schema/schema-general'
import { ChartDisplayType, AccessControlResourceType, AccessControlLevel } from '~/types'
-import { expect } from 'storybook/test'
+import { expect, userEvent } from 'storybook/test'
import { buildBIQuery, getBIResultDimensions, getBIResultMeasureColumns } from './biEditorTypes'
import { biSceneLogic } from './biSceneLogic'
@@ -46,11 +46,13 @@ function WorksheetStage({
width = 1200,
sqlPreview = false,
chartSettings,
+ tableSettings,
}: {
config: BIConfig
width?: number
sqlPreview?: boolean
chartSettings?: ChartSettings
+ tableSettings?: TableSettings
}): JSX.Element {
useEffect(() => {
const logic = biSceneLogic({ tabId })
@@ -60,6 +62,7 @@ function WorksheetStage({
kind: NodeKind.BIVisualizationNode,
config,
chartSettings: { ...buildBIQuery(config)!.node.chartSettings, ...chartSettings },
+ tableSettings: { ...buildBIQuery(config)!.node.tableSettings, ...tableSettings },
}
logic.actions.restoreWorksheet(node)
logic.actions.recordWorksheet(true)
@@ -67,7 +70,7 @@ function WorksheetStage({
logic.actions.setSqlPreviewOpen(true)
}
return unmount
- }, [config, sqlPreview, chartSettings])
+ }, [config, sqlPreview, chartSettings, tableSettings])
return (
<div className="h-[850px] max-w-full" style={{ width }}>
<BusinessIntelligenceScene tabId={tabId} />
@@ -124,6 +127,9 @@ const meta: Meta = {
const { query } = (await request.json()) as {
query: { kind: string; query?: string; limit?: number }
}
+ if (query.kind === NodeKind.HogQLAutocomplete) {
+ return [200, { suggestions: [] }]
+ }
if (query.kind === NodeKind.HogQLMetadata) {
return [
200,
@@ -261,6 +267,31 @@ export default meta
export const FiltersAndHierarchy: StoryObj = { render: () => <WorksheetStage config={config} /> }
export const Narrow: StoryObj = { render: () => <WorksheetStage config={config} width={520} /> }
export const SQLPreview: StoryObj = { render: () => <WorksheetStage config={config} sqlPreview /> }
+const tableConfig: BIConfig = { ...config, chartType: ChartDisplayType.ActionsTable }
+const tableSettings: TableSettings = {
+ conditionalFormatting: [
+ {
+ id: 'revenue-highlight',
+ templateId: 'equals',
+ columnName: getBIResultMeasureColumns(tableConfig)[0].column,
+ input: '27',
+ color: '#FFADAD',
+ colorMode: 'light',
+ bytecode: ['_H', 1, 32, 'input', 1, 1, 32, 'value', 1, 1, 11, 38],
+ },
+ ],
+}
+export const TableConditionalFormatting: StoryObj = {
+ render: () => <WorksheetStage config={tableConfig} tableSettings={tableSettings} />,
+ play: async (context) => {
+ await meta.play?.(context)
+ const button = context.canvasElement.querySelector('[data-attr="bi-conditional-formatting"]')
+ expect(button).toBeTruthy()
+ await userEvent.click(button!)
+ await waitFor(() => expect(context.canvasElement.querySelector('.ConditionalFormattingTab')).toBeTruthy())
+ await waitFor(() => expect(context.canvasElement.querySelector('td[style*="background-color"]')).toBeTruthy())
+ },
+}
const dailyConfig: BIConfig = {
...config,
chartType: ChartDisplayType.ActionsLineGraph,
diff --git a/products/business_intelligence/frontend/biEditorAnalytics.ts b/products/business_intelligence/frontend/biEditorAnalytics.ts
index 1759e9d16720..e8e7c13f0b3e 100644
--- a/products/business_intelligence/frontend/biEditorAnalytics.ts
+++ b/products/business_intelligence/frontend/biEditorAnalytics.ts
@@ -97,6 +97,9 @@ export type BIWorksheetAction =
| 'local_field_saved'
| 'calculated_field_saved'
| 'chart_settings_changed'
+ | 'conditional_formatting_opened'
+ | 'conditional_formatting_updated'
+ | 'measure_expression_updated'
| 'undo'
| 'redo'
| 'copied'
@@ -127,6 +130,7 @@ export function captureBIWorksheetAction(
starter_kind?: 'metric' | 'certified_source' | 'events'
source_certification?: 'certified' | 'deprecated' | 'unmarked'
setting_keys?: string[]
+ rule_count?: number
} = {}
): void {
posthog.capture(BI_EDITOR_EVENTS.WORKSHEET_ACTION, {
diff --git a/products/business_intelligence/frontend/biEditorLogic.test.ts b/products/business_intelligence/frontend/biEditorLogic.test.ts
index 3d655a4ccf93..d0e5d781e6b7 100644
--- a/products/business_intelligence/frontend/biEditorLogic.test.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.test.ts
@@ -62,6 +62,35 @@ describe('biEditorLogic', () => {
limit: 1000,
sort: null,
}
+ it.each(['sum(properties.amount)', 'sum(properties.amount) / nullIf(count(), 0)'])(
+ 'saves a custom measure expression without the previous count wrapper: %s',
+ (expression) => {
+ const logic = biEditorLogic({ tabId: TAB_ID })
+ logic.mount()
+ logic.actions.setAutoUpdate(false)
+ const measure = { field: eventField, aggregation: 'count' as const, formatting: { decimalPlaces: 2 } }
+ logic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: { ...config, values: [measure, measure] },
+ })
+
+ logic.actions.setMeasureExpression(0, expression, 'custom')
+
+ expect(logic.values.config.values[0]).toEqual({
+ ...measure,
+ aggregation: 'custom',
+ customExpression: expression,
+ })
+ expect(logic.values.config.values[1]).toEqual(measure)
+ expect(buildBIQuery(logic.values.config)!.query).toContain(`${expression} AS`)
+ expect(buildBIQuery(logic.values.config)!.query).not.toContain(`count(${expression})`)
+
+ logic.actions.setMeasureExpression(0, 'properties.amount', 'sum')
+ expect(buildBIQuery(logic.values.config)!.query).toContain('sum(properties.amount) AS')
+ expect(logic.values.config.values[0].formatting).toEqual(measure.formatting)
+ logic.unmount()
+ }
+ )
it.each(['rows', 'columns'] as const)('only adds a calculated field to %s after confirmation', async (shelf) => {
const logic = biEditorLogic({ tabId: TAB_ID })
logic.mount()
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index d008f62de3b9..0988111af2af 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -672,6 +672,15 @@ export interface biEditorLogicActions {
setLocalFieldDraft: (field: BIField | null) => {
field: BIField | null
}
+ setMeasureExpression: (
+ index: number,
+ expression: string,
+ aggregation: BIAggregation
+ ) => {
+ aggregation: BIAggregation
+ expression: string
+ index: number
+ }
setMeasureShelf: (
index: number,
shelf: 'columns' | 'rows'
@@ -923,6 +932,11 @@ export const biEditorLogic = kea<biEditorLogicType>([
dateBucket,
}),
setValueCustomExpression: (index: number, customExpression: string) => ({ index, customExpression }),
+ setMeasureExpression: (index: number, expression: string, aggregation: BIAggregation) => ({
+ index,
+ expression,
+ aggregation,
+ }),
setFilterCustomExpression: (index: number, customExpression: string) => ({ index, customExpression }),
resetConfig: true,
}),
@@ -1343,6 +1357,21 @@ export const biEditorLogic = kea<biEditorLogicType>([
valueIndex === index ? { ...value, customExpression } : value
),
}),
+ setMeasureExpression: (config, { index, expression, aggregation }) => ({
+ ...config,
+ values: config.values.map((value, valueIndex) =>
+ valueIndex === index
+ ? {
+ ...value,
+ aggregation,
+ ...(aggregation === 'custom'
+ ? { customExpression: expression }
+ : { field: { ...value.field, expression, name: expression.trim() } }),
+ }
+ : value
+ ),
+ topN: config.topN?.measureIndex === index ? undefined : config.topN,
+ }),
setFilterCustomExpression: (config, { index, customExpression }) => ({
...config,
filters: config.filters.map((filter, filterIndex) =>
@@ -1714,6 +1743,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
setFieldDatePart: () => actions.runAfterChange(),
duplicateField: () => actions.runAfterChange(),
setValueCustomExpression: () => actions.runAfterChange(),
+ setMeasureExpression: () => {
+ captureBIWorksheetAction('measure_expression_updated', values.config)
+ actions.runAfterChange()
+ },
setFilterCustomExpression: () => actions.runAfterChange(),
})),
subscriptions(({ actions, values }) => ({
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index 9468fed82894..7bae8e9c6c1e 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -947,6 +947,7 @@ describe('biSceneLogic', () => {
() => editor.actions.addFieldToShelf(eventField, 'filters'),
() => editor.actions.setFilterValue(0, '$pageview'),
() => editor.actions.addFieldToShelf(eventField, 'values'),
+ () => editor.actions.setMeasureExpression(0, 'count(DISTINCT distinct_id)', 'custom'),
() => editor.actions.setTableCalculation(0, { type: 'running_total' }),
() => editor.actions.updateMeasureSettings(0, { formatting: { prefix: '€' } }),
() => editor.actions.addResultFilter(),
@@ -1069,16 +1070,30 @@ describe('biSceneLogic', () => {
expect(logic.values.insight?.name).toBe('Saved worksheet (copy)')
})
- it('preserves an unfinished calculated measure when chart settings update', () => {
- logic.actions.restoreWorksheet(worksheet())
+ it('saves and reloads conditional formatting without discarding an unfinished calculated measure', async () => {
+ await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
editor.actions.setCalculatedMeasureDraft({
index: null,
name: 'Revenue per user',
expression: 'sum(revenue) /',
})
const draft = editor.values.calculatedMeasureDraft
- logic.actions.setVisualization({ ...logic.values.worksheet, tableSettings: { conditionalFormatting: [] } })
+ const conditionalFormatting = [
+ {
+ id: 'count-threshold',
+ templateId: 'equals',
+ columnName: 'count',
+ input: '10',
+ color: '#FFADAD',
+ bytecode: ['_H', 1, 32, 'input', 1, 1, 32, 'value', 1, 1, 11, 38],
+ },
+ ]
+ logic.actions.setVisualization({ ...logic.values.worksheet, tableSettings: { conditionalFormatting } })
expect(editor.values.calculatedMeasureDraft).toEqual(draft)
+ await expectLogic(logic, () => logic.actions.saveInsight()).toFinishAllListeners()
+ expect(stored.query.tableSettings?.conditionalFormatting).toEqual(conditionalFormatting)
+ await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
+ expect(logic.values.worksheet.tableSettings?.conditionalFormatting).toEqual(conditionalFormatting)
})
it('reruns unchanged SQL for a date change while preserving dashboard properties', async () => {
diff --git a/products/business_intelligence/frontend/components/BIExpressionPopover.tsx b/products/business_intelligence/frontend/components/BIExpressionPopover.tsx
index 46671a0fcb64..597e668e935d 100644
--- a/products/business_intelligence/frontend/components/BIExpressionPopover.tsx
+++ b/products/business_intelligence/frontend/components/BIExpressionPopover.tsx
@@ -1,17 +1,22 @@
+import { useEffect, useState } from 'react'
+
import { IconX } from '@posthog/icons'
-import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'
+import { LemonButton, LemonDropdown, LemonSelect } from '@posthog/lemon-ui'
import { HogQLEditor } from 'lib/components/HogQLEditor/HogQLEditor'
-import { BIDataSource } from '~/queries/schema/schema-business-intelligence'
+import { BIAggregation, BIDataSource } from '~/queries/schema/schema-business-intelligence'
import { NodeKind } from '~/queries/schema/schema-general'
import { escapeDottedHogQLIdentifier } from '~/queries/utils'
+import { AGGREGATION_OPTIONS } from '../biEditorOptions'
+
export function BIExpressionPopover({
visible,
value,
source,
placeholder,
+ aggregation,
onChange,
onClose,
children,
@@ -20,10 +25,14 @@ export function BIExpressionPopover({
value: string
source: BIDataSource
placeholder?: string
- onChange: (value: string) => void
+ aggregation?: BIAggregation
+ onChange: (value: string, aggregation?: BIAggregation) => void
onClose: () => void
children: React.ReactElement
}): JSX.Element {
+ const [draftAggregation, setDraftAggregation] = useState(aggregation)
+ useEffect(() => setDraftAggregation(aggregation), [aggregation, visible])
+
return (
<LemonDropdown
visible={visible}
@@ -34,7 +43,9 @@ export function BIExpressionPopover({
overlay={
<div className="w-120 max-w-[max(60vw,20rem)]">
<div className="flex items-center justify-between border-b px-2 py-1">
- <span className="font-semibold">Edit expression</span>
+ <span className="font-semibold">
+ {aggregation ? 'Edit measure expression' : 'Edit expression'}
+ </span>
<LemonButton
icon={<IconX />}
size="xsmall"
@@ -43,23 +54,49 @@ export function BIExpressionPopover({
onClick={onClose}
/>
</div>
+ {aggregation && (
+ <div className="flex flex-col gap-2 p-2">
+ <LemonSelect
+ aria-label="Expression aggregation"
+ value={draftAggregation}
+ onChange={setDraftAggregation}
+ options={AGGREGATION_OPTIONS.map((option) => ({
+ ...option,
+ label:
+ option.value === 'custom' ? 'Custom SQL · no extra aggregation' : option.label,
+ }))}
+ data-attr="bi-expression-aggregation"
+ />
+ <p className="m-0 text-xs text-secondary">
+ {draftAggregation === 'custom'
+ ? 'This expression calculates each group directly. No extra aggregation is added. Use aggregate functions such as sum, count, or avg.'
+ : `${AGGREGATION_OPTIONS.find((option) => option.value === draftAggregation)?.label} is applied to this expression for each group. If your expression already includes aggregate functions, select Custom SQL.`}
+ </p>
+ </div>
+ )}
<HogQLEditor
value={value}
- placeholder={placeholder}
+ placeholder={
+ aggregation
+ ? draftAggregation === 'custom'
+ ? 'For example: sum(amount) / nullIf(count(), 0)'
+ : 'Enter a row expression using fields from the selected table.'
+ : placeholder
+ }
metadataSource={{
kind: NodeKind.HogQLQuery,
query: `SELECT * FROM ${escapeDottedHogQLIdentifier(source.table)}`,
connectionId: source.connectionId,
}}
onChange={(nextValue) => {
- onChange(nextValue)
+ onChange(nextValue, draftAggregation)
onClose()
}}
/>
</div>
}
>
- {children}
+ <span className="inline-flex min-w-0 max-w-full">{children}</span>
</LemonDropdown>
)
}
diff --git a/products/business_intelligence/frontend/components/BIFieldPill.tsx b/products/business_intelligence/frontend/components/BIFieldPill.tsx
index 493b9491db8f..f91001c079cd 100644
--- a/products/business_intelligence/frontend/components/BIFieldPill.tsx
+++ b/products/business_intelligence/frontend/components/BIFieldPill.tsx
@@ -48,9 +48,9 @@ export function BIFieldPill({
setFieldDateBucket,
setFieldDatePart,
setFieldExpression,
+ setMeasureExpression,
setSort,
setValueAggregation,
- setValueCustomExpression,
renameField,
} = useActions(biEditorLogic)
@@ -86,9 +86,10 @@ export function BIFieldPill({
? 'This calculation needs a numeric field'
: undefined,
onClick: () => {
- setValueAggregation(index, option.value)
- if (option.value === 'custom' && !value.customExpression) {
+ if (option.value === 'custom') {
setEditing('aggregation')
+ } else {
+ setValueAggregation(index, option.value)
}
},
})),
@@ -137,7 +138,10 @@ export function BIFieldPill({
onClick: () => editCalculatedField({ ...field, id: field.localFieldId ?? field.id }),
}
: !isCalculatedMeasure
- ? { label: 'Edit field expression', onClick: () => setEditing('field') }
+ ? {
+ label: isMeasure ? 'Edit measure expression' : 'Edit field expression',
+ onClick: () => setEditing('field'),
+ }
: null,
value?.aggregation === 'custom' && field.localDefinition?.kind !== 'expression'
? { label: 'Edit calculated measure', onClick: () => editCalculatedMeasure(index) }
@@ -196,12 +200,17 @@ export function BIFieldPill({
)}
<BIExpressionPopover
visible={expressionTarget !== null}
- value={expressionTarget === 'aggregation' ? (value?.customExpression ?? '') : field.expression}
+ value={
+ expressionTarget === 'aggregation' || value?.aggregation === 'custom'
+ ? (value?.customExpression ?? field.expression)
+ : field.expression
+ }
source={field.source}
+ aggregation={expressionTarget === 'aggregation' ? 'custom' : value?.aggregation}
placeholder={expressionTarget === 'aggregation' ? 'For example: sum(amount) / count()' : undefined}
- onChange={(nextExpression) =>
- expressionTarget === 'aggregation'
- ? setValueCustomExpression(index, nextExpression)
+ onChange={(nextExpression, aggregation) =>
+ aggregation
+ ? setMeasureExpression(index, nextExpression, aggregation)
: setFieldExpression(shelf, index, nextExpression)
}
onClose={() => {