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): polish field defaults and chart editing (#116885)

Marius Andra15f71d6a5bcb
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 480a7aafc25b..084b0a78b55c 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -36,12 +36,18 @@ Choose a connection in the **Data** panel, then select a table below it. **Run**
**Charts** opens chart types and series controls in the right panel. **Analysis** and the visualization settings button replace that panel with their own controls. The panel starts closed. Close it after editing to return to the chart. The Series/Display settings use the same panel and scroll independently. Row filters appear once above the chart; click a filter to edit it. **AND / OR groups** opens the grouping dialog, and **Result filters** opens a popover. The left pane contains the selected source and its dimensions and measures; **Fields** hides or restores it. The toolbar wraps as the worksheet narrows, and the right panel overlays the chart when there is not enough space to dock it. These layout changes apply only to BI worksheets; SQL and other insights retain their existing settings layout.
+Single-value filters distinguish selecting **(empty string)** from clearing the input: the former matches an empty value, while the latter removes the condition.
+
Date dimensions sort oldest first by default, including in tables; explicit sorts still take precedence. Time charts show years centered below their date ticks. Clicking a bar opens the drill-down options for that result.
-**Auto update** is off by default and remembers your choice. Selecting a table leaves a blank worksheet, even with auto-update enabled. Add a field to rows or columns before running. A worksheet with dimensions and no selected measure shows **Count of rows** on its shelf and value axis. Turning auto-update off keeps the current result; **Run** applies pending changes.
+**Auto update** is off by default and remembers your choice. Selecting a table leaves a blank worksheet, even with auto-update enabled. The blank worksheet offers **Start with daily row count** when a date field is available, or **Start with row count** otherwise. The suggestion adds fields only when clicked and respects auto-update. Identifier fields such as `person_id`, `distinct_id`, and `user_id` appear as measures and default to Count; their shelf menu can convert them to dimensions or change the aggregation. A worksheet with dimensions and no selected measure shows **Count of rows** on its shelf and value axis. Turning auto-update off keeps the current result; **Run** applies pending changes.
+
+Choose **Rename** from a shelf field's menu to change its worksheet label without changing the source expression. Labels persist in saved charts and tables without changing dashboard filter bindings or custom axis titles. Click an axis on a line, area, or bar chart to edit its label and tick visibility directly; value axes also offer scale and zero-baseline controls. **Save axis** applies chart settings to the displayed result without running pending shelf or filter changes. Cancel or the close button discards the draft. The same labels remain editable in visualization settings.
**Clear sheet** clears shelves, filters, chart settings, and results while retaining the selected table, connection, date scope, and worksheet-local field definitions. Drag pills onto another pill to reorder them. **Swap rows and columns** exchanges dimensions and measure placement, preserving calculations and sort choices; bar charts switch between vertical and horizontal orientation. The **Charts** picker offers chart types suited to the selected fields.
+The **Charts** picker also includes proportion bars, scatter plots, and box plots. Scatter plots initialize numeric axes and need at least two numeric columns; box plots need six numeric summary columns.
+
Drag the right edge of the fields pane to resize it. Docked panes each take at most a quarter of a wide worksheet, leaving at least half the width for the chart. Less frequent worksheet actions, including **Save a copy**, **Save as SQL view**, and **Discard changes**, are in the worksheet actions menu beside **Share**.
BI usage keeps the existing `sql-editor-bi-mode-selected`, `sql-editor-bi-query-run`, and `sql-editor-bi-query-saved` events. Their properties describe table calculations, Top N, comparisons, formatting, axes, totals, and related/property field counts. The `bi-worksheet-action` event's `action` property defines the funnel: `opened`, `source_selected`, `first_chart`, `saved`, `added_to_dashboard`. The first chart is the first nonempty successful result per editor visit; reruns and failures do not count again. Saved and dashboard steps include `insight_id`. Additional actions record drill-down choices, related-table expansion, and property browsing/search. These events exclude SQL, source names, field names, formulas, search text, filter values, and result contents.
@@ -84,32 +90,29 @@ Pivot tables display every measure beneath nested column headers. Expand or coll
The **Analysis** card ranks **Top N** categories by a selected measure across the full current date range. **Include "Other"** combines the remaining source rows and re-aggregates them, including averages and distinct counts. Removing the ranking measure turns Top N off. Previous-period comparisons use the current period's category selection. Tables offer a grand total; pivot tables offer row and column grand totals. Both support hierarchy subtotals when an axis has multiple dimensions. Totals re-aggregate source rows; table-calculation cells remain blank on total rows. Summary rows can occupy at most half the result limit, reserving room for detail cells. The BI visualization requests an extra row to determine whether more results exist, then removes it before building tables and charts. Saved SQL and exports retain the worksheet's configured limit. A notice appears only when the response confirms more results beyond that limit, which also applies across comparison periods. Cached results and execution caps may prevent the extra row from being returned.
-Each measure's **Format and display** dialog sets its label, currency, decimal precision, abbreviation, percentage format, and suffix. Percentage formatting expects fractional values (0.25 displays as 25%); percent-of-total and percent-change calculations produce that scale automatically. Formats persist in saved insights and apply to charts, tables, and pivot cells. Bar, line, and area charts support a separate series style and left/right axis for each measure. **Combine line + bar** assigns two measures to separate axes with bar and line styles.
+Each measure's **Format and display** dialog sets its label, currency, decimal precision, abbreviation, percentage format, and suffix. Percentage formatting expects fractional values (0.25 displays as 25%); percent-of-total and percent-change calculations produce that scale automatically. Formats persist in saved insights and apply to charts, tables, and pivot cells. The **Charts** panel exposes series style and left/right axis selectors for each measure. Bar, line, and area charts support these mixed styles and axes. **Combine line + bar** assigns two measures to separate axes with bar and line styles.
Click a bar, line point, table cell, or pivot cell to explore its source rows. **Filter in new worksheet** preserves the original insight and adds the selected dimensions to a new worksheet. **View underlying rows** loads up to 1,000 matching source rows before aggregation; **Open in SQL editor** carries the same conditions, connection, and effective dashboard filters. When adding a drill-down condition would exceed the filter-group nesting limit, use **View underlying rows** or **Open in SQL editor**. Total cells omit rolled-up dimensions, and **Other** selects the categories outside the current Top N. Comparison-period points open rows from their original dates; their filtered-worksheet action is disabled to avoid combining current dates with prior-period conditions. These actions are unavailable on public shared insights.
**Compare previous period** turns date comparison on or off in one click. The adjacent comparison picker still supports custom offsets. Select a bounded date range before enabling comparison.
-With `SQL_EDITOR_BI_MODE` enabled, choose **Add calculated field** in the data pane. Select a row-level dimension or an aggregate measure, then enter a name and a plain HogQL expression using fields from the selected table. Dimensions can use expressions such as `coalesce(properties.plan, 'Unknown')`; measures can use `sum(revenue) / nullIf(count(DISTINCT user_id), 0)`.
+With `SQL_EDITOR_BI_MODE` enabled, choose **Add calculated field** in the data pane or the plus button on Rows or Columns. Nothing is added until **Add field** is clicked; Cancel or the close button discards the draft. A shelf's plus button places the saved field on that shelf. Select a row-level dimension or an aggregate measure, then enter a name and a plain HogQL expression using fields from the selected table. Dimensions can use expressions such as `coalesce(properties.plan, 'Unknown')`; measures can use `sum(revenue) / nullIf(count(DISTINCT user_id), 0)`.
Calculated fields appear in Dimensions or Measures with a ƒ indicator. Drag or double-click them to reuse the definition. Editing a definition updates its name and expression on every shelf, including duplicated uses; date granularities and measure display settings remain independent. A field's role cannot change after creation. **Delete field and all uses** removes the local definition and its shelf/filter uses; Undo restores them. Clear sheet retains the definitions. Save, reload, and Save a copy preserve them inside the worksheet, without creating source-table or project-wide fields.
-The result footer reports distinct dimension groups and non-empty measure values (marks), rather than source-row counts. It excludes total rows and marks truncated results as limited. The grouping labels describe the executed query while edits await Run.
+The result footer reports distinct dimension groups and non-empty measure values, rather than source-row counts. It excludes total rows and marks truncated results as limited. The grouping labels describe the executed query while edits await Run.
Date and timestamp drops start with daily buckets. A date pill offers **Timeline (keeps the year)** buckets and **Date part (combines years)** choices: month of year, quarter of year, and day of week. **Duplicate** creates an independently configurable shelf field, so the same date can appear at two granularities. Hold **Alt** (**Option** on Mac) while dragging a dimension or measure to copy it to another shelf or position. Copies retain calculations and settings; dropping with the modifier outside a shelf leaves the original in place.
-**Marks → Color** separates series coloring from shelf grouping. **Single color** preserves every group and series while using one color; switching back restores automatic or customized colors. With two categorical dimensions, select either field to define the colored series and use the other on the axis. Date dimensions remain on the timeline. Automatic uses lines for dates, grouped bars for one or two categorical dimensions, and a number for a single total. Explicit chart choices remain selected. **New worksheet** is available directly in the worksheet header.
+**Charts → Series → Color** separates series coloring from shelf grouping. **Single color** preserves every group and series while using one color; switching back restores automatic or customized colors. With two categorical dimensions, select either field to define the colored series and use the other on the axis. Date dimensions remain on the timeline. Automatic uses lines for dates, grouped bars for one or two categorical dimensions, and a number for a single total. Explicit chart choices remain selected. **New worksheet** is available directly in the worksheet header.
## Filters in BI mode
-Drop a field onto the compact Filters shelf beside or below the data pane. Quick filters on the right
-show the current selection; click a value to edit it, or use the checkbox beside its name to toggle it.
-Wider worksheets show quick filters in two columns. In tight scenes, click a filter pill on the left
-to edit its values and settings. String fields start with
+Drop a field onto **Row filters** above the chart. Click its pill to edit values and settings. String fields start with
**Is any of**: select several values, or type a value and press Enter. **Is none of** excludes the
selected values. An empty selection leaves all values included. Suggestions load when the picker
opens, respect the other applied filters, and show up to 100 distinct values; additional values can
-always be entered manually.
+always be entered manually. Single-value conditions, including **Equals**, offer the same searchable suggestions for text and numeric fields. Date conditions retain their calendar picker, and ranges retain separate bounds.
Use **Between** for numeric or date fields. Both bounds are inclusive, and either can be left empty
for an open-ended range. Date-time fields include the time. Uncheck **Apply filter** in the editor to temporarily
@@ -311,6 +314,8 @@ You'll need to install MS SQL drivers for the PostHog app to connect to a MS SQL
symbol not found in flat namespace '_bcp_batch'
```
+BI chart settings preserve custom scatter axes and implicit count formatting. Numeric date parts can be used as scatter axes. Switching to a box plot initializes statistic mappings from matching result column names. Generated axis labels follow field renames, while custom axis labels remain unchanged.
+
## Connected fields in BI mode
Below Dimensions and Measures, **Connections** lists the selected table's linked tables and views.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f36bec87e75a..f3ef72b40449 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10011,33 +10011,33 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-category-groups--light:
hash: v1.k794b7964.d5e34769fc378768fcf98225dd001e2cf04a6f426e626fe6556bb81397c2b170.Y6etSZ8dq76cbaCMpsCN0b0HSONai8UbCpAsOy-7rpk
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
- hash: v1.k794b7964.f1c6c92784061618b6c7232c162cc3b1678c9731089de48f9734d73bd7ddc8f1.uY9ysCPQw7b7gTBpCSfrHv4Don_2GmrtQY1k_ZM_KMM
+ hash: v1.k794b7964.865d4eb990b497a14f9acf245b156d6c91d564e82254d8a6ec946256a76e8057.Z5aPGxdlS-bBgCuzisWwUW1oeTf7ew3Mluhn7J4hp7s
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
- hash: v1.k794b7964.253c420433f95e920e441e7a88464d7c2df1c621e34d92794d4fc3b12f3c0020.O55jRGWBSaPRUUR2AXDNDRWlVutGnZ_s2EZ3iyO8qLk
+ hash: v1.k794b7964.1f903572d448a00bb796711413024469b62c9530a627cdd9cb0dbfd3072e322a.iDIDaX-GAUVQH6UH8CLQR-BJC3Ticdx689vUCM6w-BY
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
hash: v1.k794b7964.5ead38bdfedf6a867cccf730ce512bfd81a1207816be9f43b2ff459e1f53f66a.9zBHu_GwPR2mpGP7kurhvZDOBlVzluxXwDloisx_9EA
scenes-app-data-warehouse-sql-editor--bi-connections--light:
hash: v1.k794b7964.4349a11054a4e939a512d687e6e79fe9506d06cb7fcfc6ceda1ea08a08cd8b63.CKdN-OxYRnBEd4HPoyStmcVHSgy1ap3TlfzUtSXJPG8
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.f04cf1b1590d1eb3ada6a352fe768afc4be283abc92e289b5aeab961cd27f04d.XzgKF1gpUvLVekmsi5Fc2jQzpAg5S_fTPy3dO6bYXjk
+ hash: v1.k794b7964.35cc2cbd62f70064133e54283675857679876c1e7a3a13d70943739cccee8d9e.P15jZlT3qKinaLh4iLp3LzXYM31LAgP_5qVI5wn3g9I
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.56e2c6244631e945e8141a5f83d91c27813c3001b823c995e7423ecc1c2f1ae0.1dEbTL3adPyPaL6ggKJr6H9zsdp9qOwspqT1L1B57yM
+ hash: v1.k794b7964.ce25f62f39a6e1f6c1483b8a4433bad7566425a9f1b478166ee7db2fdc51cc2e.Oy2e9QpVx03iVGhUevNI_OVQda3QFFh4FtQdo5uXH4k
scenes-app-data-warehouse-sql-editor--bi-drilldown--dark:
hash: v1.k794b7964.ba29aa7ee46e9d36abf42e48a05532f7a1c29e136dcd0d23e8ada1dfcdb0a309.LrxMD2ghnFj_2mufzrOvzUAeCNtrHtmygqLvHrmflY8
scenes-app-data-warehouse-sql-editor--bi-drilldown--light:
hash: v1.k794b7964.e43a77554e3256a78ae51ef7a04756b1178498ffe1eb66a79c5ec816af394eb7.NHelBdO8fSVLsIQQy_P8BkM9M4fccNiHOVZ-mF1UiVg
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.8abbc2cad888ce12240e05435b5624c80b511018a5c131f781f32d3e2d2e3559.f6Nzg1-bQqOnCxbokz26r4F2i5NgH-tTrYrZiZuRjTk
+ hash: v1.k794b7964.431ec5d6290cebddae2e6501a2791f97ffb0a278546ea8c9099997e449da7fba.DjG78Z7wuA122QOFn6ZYgEV5dSHlDrsft9h5rU0_v7E
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.6915d9dfa8cc8e5b05edb458c20c41f2f3af7a8805579b2cee31a4bd9153ea2f.KAH_Jlm9DnTsHrOnEVrfnERpYcDN8ySDJYm0nCHw4GI
+ hash: v1.k794b7964.2e753a0347047d535a10a282550f93677cd32a6cf65fc04e573e44177bb70924.uL57udzKGUS_3pi_TbsrusvGgLUEgL9NJBp1hkmPUto
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
hash: v1.k794b7964.cda73be4adaa1a9fe5d2b3467a11e119e43f0539e25093f778e2f8dfff397d63.SC23lgvHPbwqALOLh7NBSVUAPwYOH148bvzy3RXnhLM
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
hash: v1.k794b7964.078f2e9f2eb8f5bab2ae1f560f3c5025c542fe523c51de8523034414daee979b.XKwLbrExUxHw1neScPMF-2MTUaTxopzeW1dXgjD8OFM
scenes-app-data-warehouse-sql-editor--bi-measure-display--dark:
- hash: v1.k794b7964.2828dfa1d443110392f59b3da593a4601b875f8bbf62ca8527ddc1d4ef418475.9bwvrKVklCFhbCG1Z5GHw2-0Ar2gH8fMKOV9kFHyHhQ
+ hash: v1.k794b7964.d6f28f89e3e2b5f8b69ea0da60c5e30a933c89aeaf562d7c29002c62bd7492aa.3d9FIlgXOHIH-FDFCi0T0gzNy8NKXGa7k2QZeojDluA
scenes-app-data-warehouse-sql-editor--bi-measure-display--light:
- hash: v1.k794b7964.4faecd765886170a0583387013faf029eb7f71deb0f6859b528cc066654d6656.yzzqbwLLtDiTdbJNL8Gqm_2ZNFQR39BI4m1Yh416uEc
+ hash: v1.k794b7964.21c1c02eef2de163f6f736cc24bcb6f12455d10a5dbf8afab34420d8e92b5073.qeaVWvqkqfMK1LehuauOSWguNb-vpgEMXavUidF7VPs
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
hash: v1.k794b7964.6309ca3f3ecb88032969e856079e14cda460aa306a5172863693ff8a95ea011c.dIXWRHfmipDgezW97RK0MYne72aosXhe0o1S_uXrt_w
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
@@ -10051,29 +10051,29 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--light:
hash: v1.k794b7964.120de8b3789e5492ac3109cdc6eaf76114df2156b2486bff88236a060d9bece9.ZHUJRbOG3tikk_4SFDkft_ftpPa-eo4SCuqElDiDH3A
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
- hash: v1.k794b7964.5fb032db5e0ff22ff76520b490b9092f042486b78430a790a8142d2ff6d88e5c.PvhceGy_sR_NpCeWfDb-UIyH_l-x6uoL__Xjwl57gOM
+ hash: v1.k794b7964.0a3c311af93ed7d316d6e2cb90402144cdadedce0079f947eaab4247357eb9b2.t98p7S9808hEhTgDBv6qvnLeNFr2Pn3exbudMpmSdLI
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
- hash: v1.k794b7964.b6aa7dff9cddfde3d5da97dbcfdec0d305f6d8fbc94a5027d74cbaad24f116bd.6QCvuv8yYGKcomriiZ2pYrlx-dTxuG_bbC3BfDRcGmg
+ hash: v1.k794b7964.2a0b04c89ee252ec2e4f69a56fe32db2c3f4d3b9de0f9b2d4bd53e0546f4bbe6.7ebhKqs7LBZ7gy5XaehWQgzUHsixe7d8HQz_cbCudJk
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--dark:
- hash: v1.k794b7964.2b51225b78e1abec3c05b28ddca656ef67a2856ef5fd8ceb6391ebed9559c51b.1mRcmUto0Hg-Dj_i4IGGpSknJu9cKF7j5hjRWGyhfqw
+ hash: v1.k794b7964.a3ca1e94c408158f4ca9bedbd3d4830da8a0e574b6ae6a4275e013d2c39ceecc.9WjwLwhLcyKvBqn5-tqvl54jXwmXS5BgNIiJvSdHAaQ
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--light:
- hash: v1.k794b7964.18d24a183a1017fa8d139d31de32b68e86e1049ab1f318b46ae2edbd490c70c4.HzZB0G1OCyUgklNlWpVBdqUjYkby8tPdJCHEbt2bIsU
+ hash: v1.k794b7964.f492de26751475f72e7b7db5c3d006552f01c821f8967aaeaa109b66757a79af.yFAwJ56fVIb8EmApSxMqpT1I7LOXmD4Gjmj4rPq5lyA
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.d4a5dd843d4a01f363e8ca6fc3d4a5c94ebc81f7b7f361e9924cd90f1262de29.BNYObyAQ1MQS0qImL0gZzpxnF5yYlpMA-3DpvK7GQeQ
+ hash: v1.k794b7964.b3a6ec3c1df46bbf4c92dd8d1219b12c3be1cfbcfacaeff6d552046773865fbe.2daze0fR0GNxqefe-kLOx7Wo1rheaS0kGKs8pa_xRRU
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.533ade7775abc3ddb5ac6e6922dad0d92dbdf50275a1e829bf372355efa0e49a.2Kd_ZwP2ZvRUfHxOrw_-IbAmNX-fJMDLQsK4Fn-402g
+ hash: v1.k794b7964.c59e2f8083c699411a9ddca1c78f872bf071f7ea9e81005936beef83e005fc63.ny9HfCoW6AkHqk4CcT35GUtfygnnMfERhtKz0PtLPk8
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.40ad630f2ee7b3b295d3564765fe358c9002712a2ef27c4060f8e184f4edd280.ESDabwhM4aDhpUOjc7dIClU0gUbKa-FKaIRogX-XMXI
+ hash: v1.k794b7964.ec5c878ebbcf2f811f27bc50775ae9f32937b7d628222e91c5ad56133a44f0b6.8QcK6drEtU4qu-RrnjPCzMConqoVnD1YbRLBSJEm_q0
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.e7db08ce2d5e580cde7a678f00d7783262cbbc9f687624db8e1d1ec06438b643.OpUSKOi-ss50LirtJ06s3OJBw2vnoFnkpAgKOecVdjc
+ hash: v1.k794b7964.4ab4e8c5bf12a2de383d658471dbc9528f697d463b58c9afe8117c1fbd0d21a4.weR6LsySZOU14958G8EIyrrH9wHrpO4LCoA5GAAabN0
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:
hash: v1.k794b7964.2c5f15b06d4347f767fc34bf934ea1bd53e988c443d528edb457795e778cc556.FcMHWv530RuOEcqg3G_bnos4zzZ4mku3Q9pdsK-VCXU
scenes-app-data-warehouse-sql-editor--bi-table-analysis--dark:
- hash: v1.k794b7964.b0a74ae541fa14e1207ffb16f01757428f1aa32b10fb81265be0412710529412.2FIYisR4fLPZgvBRa3irQQryPcxs9mPxkxzgSvqGj40
+ hash: v1.k794b7964.9d9020314462a44cf7a9beab2a16c7011c9467ef55d8941b6a68385e194a405c.LJFs5OpOCqFp3RtfM0l4PU70-T0fdO3WB3WPJQa4bD4
scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
- hash: v1.k794b7964.ef22f781ac458c833ee217db23e43b8bb55f771236e499705d68e5ebcd41cb5e.LrtZ0JhrOemD838Zh0O5A0Y4fTu2z6ICzWliCf_Kp0Q
+ hash: v1.k794b7964.c3e796908cc19da75b2caa858ac3173fc0706626e69330a538c054382d62f0fb.59AQepvbMBwKgcqbCwaBNSZhT4kzuGviJDIv9FdyhCU
scenes-app-data-warehouse-sql-editor--edited-insight--dark:
hash: v1.k794b7964.334b216a8359c768613cdec5b99a8a8ee26b6b5fac76397eaed8d6d1401a23c0.0pI7NMTufzUIfDel9Ngmhv3P3sdBu6IgpSj5xYNmYrY
scenes-app-data-warehouse-sql-editor--edited-insight--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
index 510de810b78b..4e5184e035c8 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
@@ -84,6 +84,7 @@ export const SqlBarGraph = (props: SqlChartProps): JSX.Element => {
onError={handleChartError}
>
<ReferenceLines lines={model.config.referenceLines ?? []} />
+ {props.children}
{props.chartSettings.showValuesOnSeries && <ValueLabels valueFormatter={valueLabelFormatter} />}
</BarChart>
) : (
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index b56f3bf6b28d..c8471650bbbf 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -31,6 +31,7 @@ import { shouldQueryBeAsync } from '~/queries/utils'
import { ChartDisplayType, ExportContext, ExporterFormat, InsightLogicProps } from '~/types'
import { alertsToThresholdGoalLines, insightAlertsLogic } from 'products/alerts/frontend/logic/insightAlertsLogic'
+import { BIChartAxisControls } from 'products/business_intelligence/frontend/BIChartAxisControls'
import { getBIChartDateAxis } from 'products/business_intelligence/frontend/biChartDateAxis'
import { BIChartYearLabels } from 'products/business_intelligence/frontend/BIChartYearLabels'
import { BIComparisonSummary } from 'products/business_intelligence/frontend/BIComparisonSummary'
@@ -384,6 +385,9 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
pointClickHint={canDrill ? 'Click to explore this result' : undefined}
>
{showYearLabels && <BIChartYearLabels timezone={timezone} />}
+ {query.kind === NodeKind.BIVisualizationNode && props.editMode && props.context?.onEditBIAxis && (
+ <BIChartAxisControls onEdit={props.context.onEditBIAxis} />
+ )}
</SqlChart>
</BindLogic>
)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 7617b9f5ce4f..2a7f88cee929 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6295,6 +6295,9 @@
"id": {
"type": "string"
},
+ "label": {
+ "type": "string"
+ },
"localDefinition": {
"$ref": "#/definitions/BILocalFieldDefinition"
},
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index 2c3a2d3d2845..e8feb86e8a83 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -58,6 +58,7 @@ export interface BIDataSource {
export interface BIField {
id: string
name: string
+ label?: string
expression: string
type: DatabaseSerializedFieldType
source: BIDataSource
diff --git a/frontend/src/queries/types.ts b/frontend/src/queries/types.ts
index 407f865b3b99..475f79b3e6dc 100644
--- a/frontend/src/queries/types.ts
+++ b/frontend/src/queries/types.ts
@@ -107,6 +107,7 @@ export interface QueryContext<Q extends QuerySchema = QuerySchema> {
hideAxes?: boolean
/** Hide or resize the visualization selector when the host provides its own chart picker. */
chartTypeSelectorClassName?: string
+ onEditBIAxis?: (axis: 'x' | 'left' | 'right') => void
/** Hosts visualization settings in the scene's own panel instead of opening another sidebar. */
visualizationSettingsPanel?: {
isOpen: boolean
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7217a9fe571b..28e2b9ddfabc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2736,6 +2736,12 @@ importers:
specifier: 18.3.1
version: 18.3.1
devDependencies:
+ '@testing-library/react':
+ specifier: ^14.3.1
+ '@testing-library/user-event':
+ specifier: ^14.6.1
+ version: 14.6.1(@testing-library/[email protected])
kea-test-utils:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
diff --git a/posthog/schema.py b/posthog/schema.py
index 8a828089eb4f..aefb4b6b8bb3 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5147,6 +5147,7 @@ class BIField(BaseModel):
datePart: DatePart | None = None
expression: str
id: str
+ label: str | None = None
localDefinition: BILocalFieldDefinition1 | BILocalFieldDefinition2 | BILocalFieldDefinition3 | None = None
localFieldId: str | None = None
name: str
diff --git a/products/business_intelligence/frontend/BIChartAxisControls.tsx b/products/business_intelligence/frontend/BIChartAxisControls.tsx
new file mode 100644
index 000000000000..2f98bf11955f
--- /dev/null
+++ b/products/business_intelligence/frontend/BIChartAxisControls.tsx
@@ -0,0 +1,59 @@
+import { CSSProperties } from 'react'
+
+import { useChartLayout } from '@posthog/quill-charts'
+
+export type BIChartAxis = 'x' | 'left' | 'right'
+
+export function BIChartAxisControls({ onEdit }: { onEdit: (axis: BIChartAxis) => void }): JSX.Element {
+ const { dimensions, axis, yGutters } = useChartLayout()
+ const { plotLeft, plotTop, plotWidth, plotHeight, width, height } = dimensions
+ const horizontal = axis.orientation === 'horizontal'
+ const targets: { axis: BIChartAxis; label: string; style: CSSProperties }[] = [
+ {
+ axis: horizontal ? 'left' : 'x',
+ label: 'Edit bottom axis',
+ style: {
+ left: plotLeft,
+ top: plotTop + plotHeight,
+ width: plotWidth,
+ height: height - plotTop - plotHeight,
+ },
+ },
+ {
+ axis: horizontal ? 'x' : 'left',
+ label: 'Edit left axis',
+ style: { left: 0, top: plotTop, width: plotLeft, height: plotHeight },
+ },
+ ...(!horizontal && yGutters.some((gutter) => gutter.side === 'right')
+ ? [
+ {
+ axis: 'right' as const,
+ label: 'Edit right axis',
+ style: {
+ left: plotLeft + plotWidth,
+ top: plotTop,
+ width: width - plotLeft - plotWidth,
+ height: plotHeight,
+ },
+ },
+ ]
+ : []),
+ ]
+ return (
+ <>
+ {targets.map((target) => (
+ <button
+ key={target.axis}
+ type="button"
+ className="pointer-events-auto absolute cursor-pointer rounded border border-transparent bg-transparent hover:border-primary focus-visible:border-primary focus-visible:outline-none"
+ // Axis hit areas follow the chart's measured gutters, including horizontal bars.
+ // eslint-disable-next-line react/forbid-dom-props
+ style={target.style}
+ aria-label={target.label}
+ title={target.label}
+ onClick={() => onEdit(target.axis)}
+ />
+ ))}
+ </>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIChartAxisModal.tsx b/products/business_intelligence/frontend/BIChartAxisModal.tsx
new file mode 100644
index 000000000000..0268adc7cbe4
--- /dev/null
+++ b/products/business_intelligence/frontend/BIChartAxisModal.tsx
@@ -0,0 +1,79 @@
+import { useState } from 'react'
+
+import { LemonButton, LemonInput, LemonLabel, LemonModal, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
+
+import { ChartSettings, YAxisSettings } from '~/queries/schema/schema-general'
+
+import { BIChartAxis } from './BIChartAxisControls'
+
+export function BIChartAxisModal({
+ axis,
+ settings,
+ onSave,
+ onClose,
+}: {
+ axis: BIChartAxis
+ settings: ChartSettings
+ onSave: (settings: ChartSettings) => void
+ onClose: () => void
+}): JSX.Element {
+ const key = axis === 'right' ? 'rightYAxisSettings' : 'leftYAxisSettings'
+ const [label, setLabel] = useState(axis === 'x' ? (settings.xAxisLabel ?? '') : (settings[key]?.label ?? ''))
+ const [draft, setDraft] = useState<YAxisSettings>(settings[key] ?? {})
+ const [showTicks, setShowTicks] = useState(
+ axis === 'x' ? (settings.showXAxisTicks ?? true) : (settings[key]?.showTicks ?? true)
+ )
+ return (
+ <LemonModal
+ isOpen
+ title="Edit axis"
+ onClose={onClose}
+ width="28rem"
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={onClose}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={() => {
+ onSave(
+ axis === 'x'
+ ? { ...settings, xAxisLabel: label, showXAxisTicks: showTicks }
+ : { ...settings, [key]: { ...draft, label, showTicks } }
+ )
+ onClose()
+ }}
+ >
+ Save axis
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-3">
+ <LemonLabel htmlFor="bi-axis-label">Axis label</LemonLabel>
+ <LemonInput id="bi-axis-label" value={label} onChange={setLabel} autoFocus />
+ {axis !== 'x' && (
+ <>
+ <LemonLabel>Scale</LemonLabel>
+ <LemonSelect
+ aria-label="Axis scale"
+ value={draft.scale ?? 'linear'}
+ options={[
+ { value: 'linear', label: 'Linear' },
+ { value: 'logarithmic', label: 'Logarithmic' },
+ ]}
+ onChange={(scale) => setDraft({ ...draft, scale })}
+ />
+ <LemonSwitch
+ label="Begin at zero"
+ checked={draft.startAtZero ?? true}
+ onChange={(startAtZero) => setDraft({ ...draft, startAtZero })}
+ />
+ </>
+ )}
+ <LemonSwitch label="Show tick labels" checked={showTicks} onChange={setShowTicks} />
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIComparisonSummary.tsx b/products/business_intelligence/frontend/BIComparisonSummary.tsx
index c759fb730111..21fa5fcb3577 100644
--- a/products/business_intelligence/frontend/BIComparisonSummary.tsx
+++ b/products/business_intelligence/frontend/BIComparisonSummary.tsx
@@ -4,6 +4,7 @@ import { BIConfig } from '~/queries/schema/schema-business-intelligence'
import { ChartSettings } from '~/queries/schema/schema-general'
import { BIComparisonRow, buildBIComparisonRows, getBIComparisonValues } from './biComparisonResults'
+import { getBIFieldPillLabel } from './biEditorTypes'
import { formatBIMeasure, getBIResultMeasures } from './biResultPresentation'
export function BIComparisonSummary({
@@ -114,7 +115,7 @@ export function BIComparisonSummary({
{
children: dimensions.map((field, index) => ({
key: field.id,
- title: field.name,
+ title: getBIFieldPillLabel(field),
render: (_: unknown, row: BIComparisonRow) =>
String(row.dimensions[index] ?? '(empty)'),
})),
diff --git a/products/business_intelligence/frontend/BIFilterValueInput.test.tsx b/products/business_intelligence/frontend/BIFilterValueInput.test.tsx
new file mode 100644
index 000000000000..c133d939418b
--- /dev/null
+++ b/products/business_intelligence/frontend/BIFilterValueInput.test.tsx
@@ -0,0 +1,78 @@
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { BindLogic } from 'kea'
+
+import * as queryRunner from '~/queries/query'
+import { initKeaTests } from '~/test/init'
+
+import { biEditorLogic } from './biEditorLogic'
+import { BIEditorView, DEFAULT_BI_CONFIG, buildBIQuery, getBIFilterSummary } from './biEditorTypes'
+import { BIFilterValueInput } from './BIFilterValueInput'
+
+describe('BI filter value input', () => {
+ beforeEach(() => initKeaTests())
+ afterEach(() => {
+ cleanup()
+ jest.restoreAllMocks()
+ })
+
+ it.each(['equals', 'not_equals', 'in'] as const)('offers searchable suggestions for %s', async (operator) => {
+ jest.spyOn(queryRunner, 'performQuery').mockResolvedValue({ results: [['pending'], ['paid'], ['']] } as never)
+ const props = { tabId: 'filter-input-test' }
+ const logic = biEditorLogic(props)
+ logic.mount()
+ logic.actions.setAutoUpdate(false)
+ logic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'orders' },
+ filters: [
+ {
+ field: {
+ id: 'status',
+ name: 'status',
+ expression: 'status',
+ type: 'string',
+ source: { table: 'orders' },
+ },
+ operator,
+ value: '',
+ },
+ ],
+ },
+ })
+ render(
+ <BindLogic logic={biEditorLogic} props={props}>
+ <BIFilterValueInput index={0} />
+ </BindLogic>
+ )
+ await userEvent.click(screen.getByTestId('bi-filter-values'))
+ await userEvent.click(await screen.findByText('pending'))
+ await waitFor(() =>
+ expect(
+ operator === 'in' ? logic.values.config.filters[0].values : logic.values.config.filters[0].value
+ ).toEqual(operator === 'in' ? ['pending'] : 'pending')
+ )
+ if (operator !== 'in') {
+ const input = screen.getByRole('textbox')
+ await userEvent.click(input)
+ await userEvent.clear(input)
+ await userEvent.tab()
+ expect(logic.values.config.filters[0].value).toBe('')
+ expect(buildBIQuery(logic.values.config)!.query).not.toContain('AND (status')
+ await userEvent.click(input)
+ await userEvent.click(await screen.findByText('(empty string)'))
+ expect(logic.values.config.filters[0].values).toEqual([''])
+ expect(getBIFilterSummary(logic.values.config.filters[0])).toContain('(empty string)')
+ expect(buildBIQuery(logic.values.config)!.query).toContain(
+ `AND (status ${operator === 'equals' ? '=' : '!='} '')`
+ )
+ await userEvent.click(input)
+ await userEvent.tab()
+ expect(logic.values.config.filters[0].values).toEqual([''])
+ }
+ cleanup()
+ logic.unmount()
+ })
+})
diff --git a/products/business_intelligence/frontend/BIFilterValueInput.tsx b/products/business_intelligence/frontend/BIFilterValueInput.tsx
index f805330a1e8a..0f702b3d5f60 100644
--- a/products/business_intelligence/frontend/BIFilterValueInput.tsx
+++ b/products/business_intelligence/frontend/BIFilterValueInput.tsx
@@ -30,21 +30,31 @@ export function BIFilterValueInput({ index }: { index: number }): JSX.Element |
return null
}
const validationError = getBIFilterValidationError(filter)
- if (filter.operator === 'in' || filter.operator === 'not_in') {
+ const multiple = filter.operator === 'in' || filter.operator === 'not_in'
+ if (multiple || (!isDateTimeBIField(filter.field) && filter.operator !== 'between')) {
return (
- <div className="flex min-w-0 flex-col gap-1">
+ <div
+ className="flex min-w-0 flex-col gap-1"
+ onInput={(event) => {
+ if (!multiple && event.target instanceof HTMLInputElement && event.target.value === '') {
+ setFilterValue(index, '')
+ }
+ }}
+ >
<LemonInputSelect
- mode="multiple"
- value={filter.values ?? []}
+ mode={multiple ? 'multiple' : 'single'}
+ value={filter.values ?? (multiple || !filter.value ? [] : [filter.value])}
options={(options ?? []).map((value) => ({ key: value, label: value || '(empty string)' }))}
loading={optionsLoading}
status={validationError ? 'danger' : 'default'}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
- onChange={(values) => updateFilter(index, { values })}
+ onChange={(values) =>
+ updateFilter(index, multiple ? { values } : { values, value: values[0] ?? '' })
+ }
onInputChange={setSearch}
disableFiltering
- placeholder={filter.operator === 'in' ? 'All values' : 'No excluded values'}
+ placeholder={multiple ? (filter.operator === 'in' ? 'All values' : 'No excluded values') : 'Value'}
title={`Values for ${filter.field.name}`}
allowCustomValues
disableCommaSplitting
diff --git a/products/business_intelligence/frontend/BIMeasureAnalysis.tsx b/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
index 3ed4cbdeec73..9ce98171b9b9 100644
--- a/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
+++ b/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
@@ -9,13 +9,41 @@ import { getBIMissingDatesDisabledReason } from './biTimeSeries'
export function BIMeasureAnalysis({ index }: { index: number }): JSX.Element {
const { config } = useValues(biEditorLogic)
- const { setTableCalculation, editMeasureSettings } = useActions(biEditorLogic)
+ const { setTableCalculation, editMeasureSettings, updateMeasureSettings } = useActions(biEditorLogic)
const value = config.values[index]
const calculation = value.tableCalculation
const missingDates = getBIMissingDatesDisabledReason(config) ? undefined : config.missingDates
return (
<div className="flex min-w-0 flex-col gap-1 border-t pt-2">
<LemonLabel className="truncate">{getBIValuePillLabel(value)}</LemonLabel>
+ <div className="flex flex-wrap gap-1">
+ <LemonSelect
+ size="xsmall"
+ aria-label={`Series style for ${getBIValuePillLabel(value)}`}
+ value={value.display?.displayType ?? 'auto'}
+ options={[
+ { value: 'auto', label: 'Chart default' },
+ { value: 'line', label: 'Line' },
+ { value: 'bar', label: 'Bar' },
+ { value: 'area', label: 'Area' },
+ ]}
+ onChange={(displayType) =>
+ updateMeasureSettings(index, { display: { ...value.display, displayType } })
+ }
+ />
+ <LemonSelect
+ size="xsmall"
+ aria-label={`Axis for ${getBIValuePillLabel(value)}`}
+ value={value.display?.yAxisPosition ?? 'left'}
+ options={[
+ { value: 'left', label: 'Left axis' },
+ { value: 'right', label: 'Right axis' },
+ ]}
+ onChange={(yAxisPosition) =>
+ updateMeasureSettings(index, { display: { ...value.display, yAxisPosition } })
+ }
+ />
+ </div>
<LemonSelect
size="xsmall"
fullWidth
diff --git a/products/business_intelligence/frontend/BIPivotTable.tsx b/products/business_intelligence/frontend/BIPivotTable.tsx
index 5765692ec93a..09c8def140f6 100644
--- a/products/business_intelligence/frontend/BIPivotTable.tsx
+++ b/products/business_intelligence/frontend/BIPivotTable.tsx
@@ -7,6 +7,7 @@ import { BIConfig } from '~/queries/schema/schema-business-intelligence'
import { ChartSettings } from '~/queries/schema/schema-general'
import { captureBIWorksheetAction } from './biEditorAnalytics'
+import { getBIFieldPillLabel } from './biEditorTypes'
import { biPivotCellKey, biPivotKey, BIPivotMember, buildBIPivotModel, visibleBIPivotMembers } from './biPivot'
import { formatBIMeasure, getBIResultMeasures } from './biResultPresentation'
@@ -80,7 +81,7 @@ export function BIPivotTable({
const headerRows = Array.from({ length: config.columns.length }, (_, depth) => {
const cells: { title: React.ReactNode; colSpan: number; key: string }[] = [
{
- title: depth === 0 ? config.columns.map((field) => field.name).join(' / ') : '',
+ title: depth === 0 ? config.columns.map(getBIFieldPillLabel).join(' / ') : '',
colSpan: 1,
key: 'rows',
},
@@ -123,7 +124,7 @@ export function BIPivotTable({
columns={[
{
key: 'rows',
- title: config.rows.map((field) => field.name).join(' / '),
+ title: config.rows.map(getBIFieldPillLabel).join(' / '),
render: (_, member) => (
<div className="flex items-center gap-1 whitespace-nowrap">
{member.path.slice(1).map((_, index) => (
diff --git a/products/business_intelligence/frontend/BIResultSummary.tsx b/products/business_intelligence/frontend/BIResultSummary.tsx
index 9b0a155f0789..b460142a89d3 100644
--- a/products/business_intelligence/frontend/BIResultSummary.tsx
+++ b/products/business_intelligence/frontend/BIResultSummary.tsx
@@ -27,9 +27,9 @@ export function BIResultSummary({ tabId }: { tabId: string }): JSX.Element | nul
className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t px-3 py-2 text-xs text-secondary"
data-attr="bi-result-summary"
>
- <Tooltip title="Groups are distinct combinations of the worksheet dimensions. Marks count non-empty measure values, including comparison periods. These are aggregated results, not source rows.">
+ <Tooltip title="Groups are distinct combinations of the worksheet dimensions. Values count non-empty measure values, including comparison periods. These are aggregated results, not source rows.">
<span>
- {summary.groups.toLocaleString()} groups · {summary.marks.toLocaleString()} marks
+ {summary.groups.toLocaleString()} groups · {summary.marks.toLocaleString()} values
{summary.limited ? ' (limited)' : ''}
</span>
</Tooltip>
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
index 02f29b073b2f..7403ebf55239 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
@@ -17,6 +17,8 @@ import { Query } from '~/queries/Query/Query'
import { isDataVisualizationNode } from '~/queries/utils'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { BIChartAxis } from './BIChartAxisControls'
+import { BIChartAxisModal } from './BIChartAxisModal'
import { BIEditor } from './BIEditor'
import { biEditorLogic } from './biEditorLogic'
import { BIResultSummary } from './BIResultSummary'
@@ -32,9 +34,10 @@ export const scene: SceneExport = {
export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: string }): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
- const { activePanel } = useValues(biEditorLogic({ tabId }))
- const { setActivePanel } = useActions(biEditorLogic({ tabId }))
+ const { activePanel, dataPaneFields, dataPaneFieldsLoading } = useValues(biEditorLogic({ tabId }))
+ const { setActivePanel, startSuggestedChart } = useActions(biEditorLogic({ tabId }))
const [settingsContainer, setSettingsContainer] = useState<HTMLDivElement | null>(null)
+ const [editingAxis, setEditingAxis] = useState<BIChartAxis | null>(null)
const logic = biSceneLogic({ tabId })
const {
name,
@@ -57,6 +60,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
discardChanges,
shareWorksheet,
setVisualization,
+ setChartSettings,
setExportViewOpen,
setExportViewName,
exportView,
@@ -187,6 +191,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
insightProps: { dashboardItemId: `new-bi-${tabId}` },
showOpenEditorButton: false,
chartTypeSelectorClassName: 'hidden',
+ onEditBIAxis: setEditingAxis,
visualizationSettingsPanel: {
isOpen: activePanel === 'display',
onToggle: () => setActivePanel(activePanel === 'display' ? null : 'display'),
@@ -195,19 +200,47 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
}}
/>
) : (
- <div className="flex flex-1 items-center justify-center p-4 text-secondary">
- {worksheet.config.source
- ? worksheet.config.rows.length ||
- worksheet.config.columns.length ||
- worksheet.config.values.length
- ? 'Press Run to see the results of this worksheet.'
- : 'Drag or double-click a field to start. Dimensions define groups; measures calculate a value for each group.'
- : 'Select a table and add fields to build your worksheet.'}
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 p-4 text-secondary">
+ <span>
+ {worksheet.config.source
+ ? worksheet.config.rows.length ||
+ worksheet.config.columns.length ||
+ worksheet.config.values.length
+ ? 'Press Run to see the results of this worksheet.'
+ : 'Drag or double-click a field to start. Dimensions define groups; measures calculate a value for each group.'
+ : 'Select a table and add fields to build your worksheet.'}
+ </span>
+ {worksheet.config.source &&
+ !worksheet.config.rows.length &&
+ !worksheet.config.columns.length &&
+ !worksheet.config.values.length && (
+ <LemonButton
+ type="secondary"
+ onClick={startSuggestedChart}
+ disabledReason={dataPaneFieldsLoading ? 'Loading fields' : undefined}
+ data-attr="bi-start-suggested-chart"
+ >
+ {dataPaneFields.dimensions.some((field) =>
+ ['date', 'datetime'].includes(field.type)
+ )
+ ? 'Start with daily row count'
+ : 'Start with row count'}
+ </LemonButton>
+ )}
</div>
)}
<BIResultSummary tabId={tabId} />
</BIEditor>
)}
+ {editingAxis && (
+ <BIChartAxisModal
+ key={editingAxis}
+ axis={editingAxis}
+ settings={lastRunQuery?.chartSettings ?? {}}
+ onSave={setChartSettings}
+ onClose={() => setEditingAxis(null)}
+ />
+ )}
<LemonModal
title="Save as SQL view"
isOpen={exportViewOpen}
diff --git a/products/business_intelligence/frontend/biConnectionTree.test.ts b/products/business_intelligence/frontend/biConnectionTree.test.ts
index f315d57cd193..4b683eea14e9 100644
--- a/products/business_intelligence/frontend/biConnectionTree.test.ts
+++ b/products/business_intelligence/frontend/biConnectionTree.test.ts
@@ -195,10 +195,11 @@ describe('BI connections', () => {
expect(person).toMatchObject({ state: 'ready', tableName: undefined, connections: [] })
expect(person.fields.dimensions).toEqual([
expect.objectContaining({ name: 'person.created_at', type: 'unknown', source }),
- expect.objectContaining({ name: 'person.id', type: 'unknown', source }),
expect.objectContaining({ name: 'person.properties', type: 'unknown', source }),
])
- expect(person.fields.measures).toEqual([])
+ expect(person.fields.measures).toEqual([
+ expect.objectContaining({ name: 'person.id', type: 'unknown', source }),
+ ])
expect(getPendingBIConnectionTables([person])).toEqual([])
})
diff --git a/products/business_intelligence/frontend/biEditorLogic.test.ts b/products/business_intelligence/frontend/biEditorLogic.test.ts
index 6de361fcaa20..5328f66119a8 100644
--- a/products/business_intelligence/frontend/biEditorLogic.test.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.test.ts
@@ -51,6 +51,70 @@ describe('biEditorLogic', () => {
limit: 1000,
sort: null,
}
+ it.each(['rows', 'columns'] as const)('only adds a calculated field to %s after confirmation', (shelf) => {
+ const logic = biEditorLogic({ tabId: TAB_ID })
+ logic.mount()
+ logic.actions.setAutoUpdate(false)
+ logic.actions.restoreState({ editorView: BIEditorView.BI, config })
+ logic.actions.editCalculatedField(undefined, shelf)
+ expect(logic.values.config).toEqual(config)
+ logic.actions.setCalculatedMeasureDraft(null)
+ expect(logic.values.config).toEqual(config)
+ logic.actions.editCalculatedField(undefined, shelf)
+ logic.actions.setCalculatedMeasureDraft({
+ ...logic.values.calculatedMeasureDraft!,
+ name: 'Event label',
+ expression: 'lower(event)',
+ })
+ expect(logic.values.config).toEqual(config)
+ logic.actions.saveCalculatedMeasure()
+ expect(logic.values.config[shelf].at(-1)).toMatchObject({ name: 'Event label', expression: 'lower(event)' })
+ expect(logic.values.calculatedMeasureDraft).toBeNull()
+ logic.unmount()
+ })
+ it('renames shelf labels without changing the source expression and preserves them on reload', () => {
+ const logic = biEditorLogic({ tabId: TAB_ID })
+ logic.mount()
+ logic.actions.setAutoUpdate(false)
+ logic.actions.restoreState({ editorView: BIEditorView.BI, config })
+ logic.actions.renameField('rows', 0, 'Activity')
+ const restored = parseBIEditorState(BIEditorView.BI, JSON.stringify(logic.values.config))!.config
+ expect(restored.rows[0]).toMatchObject({ name: 'event', label: 'Activity', expression: 'event' })
+ const node = buildBIQuery(restored)!.node
+ expect(node.chartSettings?.xAxisLabel).toBe('Activity')
+ expect(node.tableSettings?.columns?.[0].settings?.display?.label).toBe('Activity')
+ const warehouse = { ...restored, source: { table: 'orders' }, filters: [] }
+ expect(buildBIQuery(warehouse)!.query).toContain("(event) AS 'event'")
+ expect(buildBIQuery(warehouse)!.query).not.toContain("AS 'Activity'")
+ logic.actions.startSuggestedChart()
+ expect(logic.values.config.rows).toEqual(restored.rows)
+ logic.actions.resetConfig()
+ logic.actions.startSuggestedChart()
+ expect(logic.values.config.values[0]).toMatchObject({ customExpression: 'count(*)', shelf: 'rows' })
+ logic.actions.resetConfig()
+ databaseLogic.actions.loadDatabaseSuccess({
+ tables: {
+ events: {
+ id: 'events',
+ name: 'events',
+ type: 'posthog',
+ fields: {
+ timestamp: {
+ name: 'timestamp',
+ type: 'datetime',
+ schema_valid: true,
+ hogql_value: 'timestamp',
+ },
+ },
+ },
+ },
+ joins: [],
+ })
+ logic.actions.startSuggestedChart()
+ expect(logic.values.config.columns[0]).toMatchObject({ name: 'timestamp', dateBucket: 'day' })
+ expect(logic.values.config.chartType).toBe(ChartDisplayType.ActionsLineGraph)
+ logic.unmount()
+ })
it.each([
['remove', 0],
['remove', 1],
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 462c07b43206..0cdaf1813539 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -68,6 +68,7 @@ export interface BICalculatedMeasureDraft {
kind?: 'dimension' | 'measure'
fieldId?: string
type?: BIField['type']
+ shelf?: 'rows' | 'columns'
}
function freshBIConfig(): BIConfig {
@@ -442,8 +443,12 @@ export interface biEditorLogicActions {
toIndex: number | undefined
toShelf: BIShelf
}
- editCalculatedField: (field?: BIField) => {
+ editCalculatedField: (
+ field?: BIField,
+ shelf?: 'columns' | 'rows'
+ ) => {
field: BIField | undefined
+ shelf: 'columns' | 'rows' | undefined
}
editCalculatedMeasure: (index?: number | null) => {
index: number | null
@@ -485,6 +490,15 @@ export interface biEditorLogicActions {
removeResultFilter: (id: string) => {
id: string
}
+ renameField: (
+ shelf: Exclude<BIShelf, 'filters'>,
+ index: number,
+ name: string
+ ) => {
+ index: number
+ name: string
+ shelf: 'columns' | 'rows' | 'values'
+ }
resetConfig: () => {
value: true
}
@@ -647,6 +661,9 @@ export interface biEditorLogicActions {
customExpression: string
index: number
}
+ startSuggestedChart: () => {
+ value: true
+ }
swapRowsAndColumns: () => {
value: true
}
@@ -655,10 +672,10 @@ export interface biEditorLogicActions {
}
updateFilter: (
index: number,
- update: Partial<Pick<BIFilter, 'enabled' | 'values' | 'valueTo'>>
+ update: Partial<Pick<BIFilter, 'enabled' | 'value' | 'values' | 'valueTo'>>
) => {
index: number
- update: Partial<Pick<BIFilter, 'enabled' | 'values' | 'valueTo'>>
+ update: Partial<Pick<BIFilter, 'enabled' | 'value' | 'values' | 'valueTo'>>
}
updateMeasureSettings: (
index: number,
@@ -748,6 +765,8 @@ export const biEditorLogic = kea<biEditorLogicType>([
actions: [databaseTableListLogic, ['hydrateTableFields', 'loadDatabaseSuccess']],
})),
actions({
+ startSuggestedChart: true,
+ renameField: (shelf: Exclude<BIShelf, 'filters'>, index: number, name: string) => ({ shelf, index, name }),
editLocalField: (field: BIField, kind: 'groups' | 'bins') => ({ field, kind }),
setLocalFieldDraft: (field: BIField | null) => ({ field }),
saveLocalField: true,
@@ -776,7 +795,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setMeasureShelf: (index: number, shelf: 'rows' | 'columns') => ({ index, shelf }),
swapRowsAndColumns: true,
setColorBy: (colorBy: string | null | undefined) => ({ colorBy }),
- editCalculatedField: (field?: BIField) => ({ field }),
+ editCalculatedField: (field?: BIField, shelf?: 'rows' | 'columns') => ({ field, shelf }),
removeLocalField: (fieldId: string) => ({ fieldId }),
duplicateField: (
shelf: Exclude<BIShelf, 'filters'>,
@@ -823,7 +842,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
combineMeasures: true,
setFilterOperator: (index: number, operator: BIFilterOperator) => ({ index, operator }),
setFilterValue: (index: number, value: string) => ({ index, value }),
- updateFilter: (index: number, update: Partial<Pick<BIFilter, 'values' | 'valueTo' | 'enabled'>>) => ({
+ updateFilter: (index: number, update: Partial<Pick<BIFilter, 'value' | 'values' | 'valueTo' | 'enabled'>>) => ({
index,
update,
}),
@@ -916,6 +935,24 @@ export const biEditorLogic = kea<biEditorLogicType>([
config: [
freshBIConfig(),
{
+ renameField: (config, { shelf, index, name }) => {
+ if (!name.trim()) {
+ return config
+ }
+ return shelf === 'values'
+ ? {
+ ...config,
+ values: config.values.map((value, i) =>
+ i === index ? { ...value, display: { ...value.display, label: name.trim() } } : value
+ ),
+ }
+ : {
+ ...config,
+ [shelf]: config[shelf].map((field, i) =>
+ i === index ? { ...field, label: name.trim() } : field
+ ),
+ }
+ },
upsertLocalField: (config, { field }) => upsertBILocalField(config, field),
upsertHierarchy: (config, { hierarchy }) => ({
...config,
@@ -966,8 +1003,9 @@ export const biEditorLogic = kea<biEditorLogicType>([
aggregation: 'custom',
customExpression: field.expression,
label: field.name,
+ shelf: draft.shelf,
})
- : addFieldToConfig(updated, field, 'rows')
+ : addFieldToConfig(updated, field, draft.shelf ?? 'rows')
},
removeLocalField: (config, { fieldId }) => {
const matches = (field: BIField): boolean => (field.localFieldId ?? field.id) === fieldId
@@ -1139,7 +1177,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setFilterValue: (config, { index, value }) => ({
...config,
filters: config.filters.map((filter, filterIndex) =>
- filterIndex === index ? { ...filter, value } : filter
+ filterIndex === index ? { ...filter, value, values: undefined } : filter
),
}),
updateFilter: (config, { index, update }) => ({
@@ -1391,7 +1429,35 @@ export const biEditorLogic = kea<biEditorLogicType>([
captureBIWorksheetAction('local_field_saved', values.config)
actions.runAfterChange()
},
- editCalculatedField: ({ field }) => {
+ startSuggestedChart: () => {
+ const config = values.config
+ if (!config.source || config.rows.length || config.columns.length || config.values.length) {
+ return
+ }
+ const dateField = values.dataPaneFields.dimensions.find((field) =>
+ ['date', 'datetime'].includes(field.type)
+ )
+ actions.restoreState({
+ editorView: values.editorView,
+ config: {
+ ...config,
+ columns: dateField ? [{ ...dateField, dateBucket: 'day' }] : [],
+ values: [
+ {
+ field: blankField(config.source, 'bi-default-count'),
+ aggregation: 'custom',
+ customExpression: 'count(*)',
+ label: 'Count of rows',
+ shelf: 'rows',
+ },
+ ],
+ chartType: dateField ? ChartDisplayType.ActionsLineGraph : ChartDisplayType.BoldNumber,
+ },
+ })
+ actions.runAfterChange()
+ },
+ renameField: () => actions.runAfterChange(),
+ editCalculatedField: ({ field, shelf }) => {
if (!values.config.source) {
return
}
@@ -1405,6 +1471,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
name: field?.name ?? '',
expression: field?.expression ?? '',
type: field?.type ?? 'string',
+ shelf,
})
},
removeLocalField: () => actions.runAfterChange(),
diff --git a/products/business_intelligence/frontend/biEditorOptions.tsx b/products/business_intelligence/frontend/biEditorOptions.tsx
index 6769a6e248ed..2e6d0cb509f8 100644
--- a/products/business_intelligence/frontend/biEditorOptions.tsx
+++ b/products/business_intelligence/frontend/biEditorOptions.tsx
@@ -1,7 +1,22 @@
-import { IconGraph, IconLifecycle, IconMagicWand, IconPieChart, IconPulse, IconTrends } from '@posthog/icons'
+import {
+ IconGraph,
+ IconLifecycle,
+ IconMagicWand,
+ IconPieChart,
+ IconPulse,
+ IconScatter,
+ IconTrends,
+} from '@posthog/icons'
import { FEATURE_FLAGS } from 'lib/constants'
-import { Icon123, IconAreaChart, IconDonutChart, IconHeatmap, IconTableChart } from 'lib/lemon-ui/icons'
+import {
+ Icon123,
+ IconAreaChart,
+ IconDonutChart,
+ IconHeatmap,
+ IconProportionBarChart,
+ IconTableChart,
+} from 'lib/lemon-ui/icons'
import { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { dateMapping } from 'lib/utils/dateFilters'
@@ -36,6 +51,9 @@ export const CHART_TYPE_OPTIONS: { value: ChartDisplayType; label: string; icon:
{ value: ChartDisplayType.ActionsStackedBar, label: 'Stacked bar chart', icon: <IconLifecycle /> },
{ value: ChartDisplayType.ActionsPie, label: 'Pie chart', icon: <IconPieChart /> },
{ value: ChartDisplayType.ActionsDonut, label: 'Donut chart', icon: <IconDonutChart /> },
+ { value: ChartDisplayType.ActionsProportionBar, label: 'Proportion bar', icon: <IconProportionBarChart /> },
+ { value: ChartDisplayType.ScatterPlot, label: 'Scatter plot', icon: <IconScatter /> },
+ { value: ChartDisplayType.BoxPlot, label: 'Box plot', icon: <IconGraph /> },
]
export function getChartTypeOptions(featureFlags: FeatureFlagsSet): typeof CHART_TYPE_OPTIONS {
diff --git a/products/business_intelligence/frontend/biEditorTypes.test.ts b/products/business_intelligence/frontend/biEditorTypes.test.ts
index a36fd0d0664f..2a97e477de05 100644
--- a/products/business_intelligence/frontend/biEditorTypes.test.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.test.ts
@@ -63,6 +63,30 @@ const countryField: BIField = {
}
describe('BI editor query generation', () => {
+ test.each(['month', 'quarter', 'day_of_week'] as const)(
+ 'uses numeric %s date parts for scatter axes',
+ (datePart) => {
+ const result = buildBIQuery({
+ ...DEFAULT_BI_CONFIG,
+ source: timestampField.source,
+ rows: [{ ...timestampField, datePart }],
+ chartType: ChartDisplayType.ScatterPlot,
+ })!
+ expect(result.node.chartSettings?.xAxis?.column).not.toBe('count')
+ expect(result.node.chartSettings?.yAxis).toEqual([{ column: 'count' }])
+ expect(
+ getBIChartFit(
+ {
+ ...DEFAULT_BI_CONFIG,
+ source: timestampField.source,
+ rows: [{ ...timestampField, datePart }],
+ chartType: ChartDisplayType.ScatterPlot,
+ },
+ ChartDisplayType.ScatterPlot
+ ).fits
+ ).toBe(true)
+ }
+ )
it.each(['month', 'quarter', 'year'] as const)(
'aligns %s comparison buckets with calendar arithmetic',
(dateBucket) => {
@@ -150,6 +174,10 @@ describe('BI editor query generation', () => {
expect(result.node.source.filters?.dateRange?.date_from).toBe('-30d')
})
test.each<{ filter: BIFilter; expected: string | null }>([
+ { filter: { field: eventField, operator: 'equals', value: '', values: [''] }, expected: "event = ''" },
+ { filter: { field: eventField, operator: 'not_equals', value: '', values: [''] }, expected: "event != ''" },
+ { filter: { field: eventField, operator: 'equals', value: '', values: [] }, expected: null },
+ { filter: { field: eventField, operator: 'equals', value: '' }, expected: null },
{
filter: { field: eventField, operator: 'in', value: '', values: ["sign'up", 'a,b', ''] },
expected: "event IN ('sign\\'up', 'a,b', '')",
@@ -315,6 +343,12 @@ describe('BI editor query generation', () => {
xAxisLabel: 'event',
leftYAxisSettings: { label: 'SUM(revenue)' },
},
+ tableSettings: {
+ columns: [
+ { column: 'event', settings: { display: { label: 'event' } } },
+ { column: 'sum_revenue' },
+ ],
+ },
},
})
})
@@ -650,6 +684,9 @@ describe('BI editor query generation', () => {
['id', 'integer', 'count'],
['uuid', 'string', 'count'],
['events_id', 'integer', 'count'],
+ ['person_id', 'string', 'count'],
+ ['distinct_id', 'string', 'count'],
+ ['user_id', 'integer', 'count'],
['revenue', 'float', 'sum'],
['event', 'string', 'count_distinct'],
] as const)('uses %s fields with type %s as a %s value', (name, type, aggregation) => {
@@ -772,13 +809,13 @@ describe('BI editor query generation', () => {
const userIdField: BIField = { ...revenueField, id: 'warehouse:events:user_id', name: 'user_id', type: 'integer' }
test.each([
- ['userId', false],
- ['accountId', false],
- ['userID', false],
- ['accountUuid', false],
- ['accountUUID', false],
- ['USER_ID', false],
- ['UUID', false],
+ ['userId', true],
+ ['accountId', true],
+ ['userID', true],
+ ['accountUuid', true],
+ ['accountUUID', true],
+ ['USER_ID', true],
+ ['UUID', true],
['grid', true],
['paid', true],
])('classifies numeric field %s as a measure: %s', (name, isMeasure) => {
@@ -819,7 +856,7 @@ describe('BI editor query generation', () => {
['a measure dropped on rows becomes a value', revenueField, 'rows', revenueField, 'values'],
['a measure dropped on columns becomes a value', revenueField, 'columns', revenueField, 'values'],
['a measure dropped on filters stays a filter', revenueField, 'filters', revenueField, 'filters'],
- ['a numeric identifier stays a dimension', userIdField, 'rows', userIdField, 'rows'],
+ ['a numeric identifier becomes a measure', userIdField, 'rows', userIdField, 'values'],
[
'a timestamp on rows is bucketed by day',
timestampField,
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 46c1a36b23cd..744b3c88c1a7 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -1,5 +1,6 @@
import { dayjs } from 'lib/dayjs'
+import { getAutoBoxPlotSettings } from '~/queries/nodes/DataVisualization/Components/Charts/sqlBoxPlotAdapter'
import {
BIConfig,
BISort,
@@ -85,7 +86,9 @@ export function changeBIFilterOperator(filter: BIFilter, operator: BIFilterOpera
return {
...filter,
operator,
- ...(isMultiple ? { values: filter.value ? [filter.value] : [] } : { value: filter.values?.[0] ?? '' }),
+ ...(isMultiple
+ ? { values: filter.values ?? (filter.value ? [filter.value] : []) }
+ : { value: filter.values?.[0] ?? '', values: filter.values?.slice(0, 1) }),
}
}
@@ -99,9 +102,30 @@ export interface BIQueryBuildResult {
node: DataVisualizationNode
}
+function mergeBIAxisLabel(
+ current: string | undefined,
+ previous: string | undefined,
+ generated: string | undefined
+): string | undefined {
+ return current !== previous ? (current ?? generated) : generated
+}
+
+function getBIChartColumnLabel(settings: ChartSettings | undefined, column: string): string | undefined {
+ if (settings?.xAxis?.column === column) {
+ return settings.xAxisLabel
+ }
+ const axis = settings?.yAxis?.find((axis) => axis.column === column)
+ return (
+ axis?.settings?.display?.label ??
+ (settings?.yAxis?.length === 1 ? settings.leftYAxisSettings?.label : undefined)
+ )
+}
+
export function mergeBIChartSettings(
current: ChartSettings | undefined,
- generated: ChartSettings | undefined
+ generated: ChartSettings | undefined,
+ previousDefaults?: ChartSettings,
+ preserveNumericAxes = false
): ChartSettings | undefined {
if (!generated) {
if (current?.seriesBreakdownColumn) {
@@ -110,10 +134,64 @@ export function mergeBIChartSettings(
}
return current
}
+ if (preserveNumericAxes && current?.xAxis?.column) {
+ const axes = [generated.xAxis, ...(generated.yAxis ?? [])].filter((axis) => axis?.column)
+ const selectedX = axes.find((axis) => axis?.column === current.xAxis?.column)
+ const selectedY = current.yAxis?.filter(
+ (axis) => axis.column !== selectedX?.column && axes.some((available) => available?.column === axis.column)
+ )
+ if (selectedX && selectedY?.length) {
+ return {
+ ...current,
+ ...generated,
+ xAxis: {
+ ...selectedX,
+ ...current.xAxis,
+ settings: mergeBIMeasureSettings(current.xAxis.settings, selectedX.settings),
+ },
+ xAxisLabel: mergeBIAxisLabel(
+ current.xAxisLabel,
+ getBIChartColumnLabel(previousDefaults, selectedX.column),
+ getBIChartColumnLabel(generated, selectedX.column)
+ ),
+ yAxis: selectedY.map((axis) => ({
+ ...axis,
+ settings: mergeBIMeasureSettings(
+ axis.settings,
+ axes.find((available) => available?.column === axis.column)?.settings
+ ),
+ })),
+ leftYAxisSettings: {
+ ...generated.leftYAxisSettings,
+ ...current.leftYAxisSettings,
+ label: mergeBIAxisLabel(
+ current.leftYAxisSettings?.label,
+ selectedY.length === 1
+ ? getBIChartColumnLabel(previousDefaults, selectedY[0].column)
+ : previousDefaults?.leftYAxisSettings?.label,
+ selectedY.length === 1
+ ? getBIChartColumnLabel(generated, selectedY[0].column)
+ : generated.leftYAxisSettings?.label
+ ),
+ },
+ }
+ }
+ }
return {
...current,
...generated,
- leftYAxisSettings: { ...current?.leftYAxisSettings, ...generated.leftYAxisSettings },
+ xAxisLabel:
+ current?.xAxis?.column === generated.xAxis?.column && current?.xAxisLabel !== previousDefaults?.xAxisLabel
+ ? (current?.xAxisLabel ?? generated.xAxisLabel)
+ : generated.xAxisLabel,
+ leftYAxisSettings: {
+ ...generated.leftYAxisSettings,
+ ...current?.leftYAxisSettings,
+ label:
+ current?.leftYAxisSettings?.label !== previousDefaults?.leftYAxisSettings?.label
+ ? (current?.leftYAxisSettings?.label ?? generated.leftYAxisSettings?.label)
+ : generated.leftYAxisSettings?.label,
+ },
xAxis: generated.xAxis
? {
...(current?.xAxis?.column === generated.xAxis.column ? current.xAxis : {}),
@@ -129,6 +207,7 @@ export function mergeBIChartSettings(
settings: mergeBIMeasureSettings(saved?.settings, axis.settings),
}
}) ?? current?.yAxis,
+ boxPlot: current?.boxPlot || generated.boxPlot ? { ...generated.boxPlot, ...current?.boxPlot } : undefined,
heatmap: current?.heatmap || generated.heatmap ? { ...current?.heatmap, ...generated.heatmap } : undefined,
}
}
@@ -243,6 +322,10 @@ export function isNumericBIField(field: BIField): boolean {
return NUMERIC_FIELD_TYPES.has(field.type)
}
+export function isNumericBIResultField(field: BIField): boolean {
+ return isNumericBIField(field) || !!field.datePart
+}
+
export function isDateTimeBIField(field: BIField): boolean {
return !field.datePart && (field.type === 'date' || field.type === 'datetime')
}
@@ -255,8 +338,7 @@ export function isBIFieldCompatible(source: BIDataSource | null, field: BIField)
}
export function defaultAggregationForField(field: BIField): BIAggregation {
- const baseTableName = field.source.table.replaceAll('`', '').split('.').pop() ?? field.source.table
- if (['id', 'uuid', `${baseTableName}_id`].includes(field.name)) {
+ if (isIdentifierBIField(field)) {
return 'count'
}
@@ -265,17 +347,20 @@ export function defaultAggregationForField(field: BIField): BIAggregation {
const IDENTIFIER_FIELD_NAME_REGEX = /(^|_)(id|uuid)$/i
-/** Numeric fields that are not identifiers aggregate by default, like measures in a BI tool. */
+function isIdentifierBIField(field: BIField): boolean {
+ return IDENTIFIER_FIELD_NAME_REGEX.test(
+ field.name
+ .split('.')
+ .pop()!
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
+ )
+}
+
export function isBIMeasureField(field: BIField): boolean {
if (field.localDefinition?.kind === 'expression') {
return field.localDefinition.aggregate
}
- return (
- !field.localDefinition &&
- isNumericBIField(field) &&
- defaultAggregationForField(field) !== 'count' &&
- !IDENTIFIER_FIELD_NAME_REGEX.test(field.name.replace(/([a-z0-9])([A-Z])/g, '$1_$2'))
- )
+ return !field.localDefinition && (isNumericBIField(field) || isIdentifierBIField(field))
}
export const BI_SHELF_PILL_DRAG_MIME_TYPE = 'application/x-posthog-bi-shelf-pill'
@@ -384,6 +469,8 @@ export function getBIChartFit(config: BIConfig, chartType: ChartDisplayType): BI
const columnCount = config.columns.length
const dimensionCount = rowCount + columnCount
const hasDateDimension = [...config.rows, ...config.columns].some(isDateTimeBIField)
+ const numericColumnCount =
+ [...config.rows, ...config.columns].filter(isNumericBIResultField).length + Math.max(1, config.values.length)
switch (chartType) {
case ChartDisplayType.Auto:
@@ -394,6 +481,12 @@ export function getBIChartFit(config: BIConfig, chartType: ChartDisplayType): BI
}
case ChartDisplayType.ActionsTable:
return { fits: true, requirement: 'any combination of fields' }
+ case ChartDisplayType.ActionsProportionBar:
+ return { fits: numericColumnCount >= 1, requirement: 'at least 1 numeric column' }
+ case ChartDisplayType.ScatterPlot:
+ return { fits: numericColumnCount >= 2, requirement: 'at least 2 numeric columns, one for each axis' }
+ case ChartDisplayType.BoxPlot:
+ return { fits: numericColumnCount >= 6, requirement: '6 numeric summary columns' }
case ChartDisplayType.ActionsLineGraph:
case ChartDisplayType.ActionsAreaGraph:
return {
@@ -472,6 +565,7 @@ function parseBIFieldValue(value: unknown): BIField | null {
(candidate.localDefinition !== undefined && !!localFieldError(candidate.localDefinition)) ||
typeof candidate.id !== 'string' ||
typeof candidate.name !== 'string' ||
+ (candidate.label !== undefined && typeof candidate.label !== 'string') ||
typeof candidate.expression !== 'string' ||
typeof candidate.type !== 'string' ||
(candidate.localFieldId !== undefined && typeof candidate.localFieldId !== 'string') ||
@@ -821,9 +915,11 @@ export function getBIFilterValidationError(filter: BIFilter): string | null {
const values =
filter.operator === 'in' || filter.operator === 'not_in'
? (filter.values ?? [])
- : [filter.value, ...(filter.operator === 'between' ? [filter.valueTo ?? ''] : [])].filter(
- (value) => value.trim() !== ''
- )
+ : filter.operator !== 'between' && filter.values
+ ? filter.values.slice(0, 1)
+ : [filter.value, ...(filter.operator === 'between' ? [filter.valueTo ?? ''] : [])].filter(
+ (value) => value.trim() !== ''
+ )
return values.some(
(value) =>
!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value.trim()) || !Number.isFinite(Number(value))
@@ -872,7 +968,11 @@ export function getBIFilterSummary(filter: BIFilter): string {
greater_than: '> ',
less_than: '< ',
}[filter.operator]
- return filter.value ? `${prefix}${filter.value}` : 'All values'
+ return filter.value
+ ? `${prefix}${filter.value}`
+ : ['equals', 'not_equals'].includes(filter.operator) && filter.values?.includes('')
+ ? `${prefix}(empty string)`
+ : 'All values'
}
}
}
@@ -912,7 +1012,10 @@ function filterExpression(filter: BIFilter): string | null {
].filter(Boolean)
return bounds.length ? `(${bounds.join(' AND ')})` : null
}
- if (!filter.value.trim()) {
+ if (
+ !filter.value.trim() &&
+ !(['equals', 'not_equals'].includes(filter.operator) && filter.values?.includes(filter.value))
+ ) {
return null
}
@@ -1256,6 +1359,9 @@ const PILL_AGGREGATION_PREFIXES: Record<Exclude<BIAggregation, 'custom'>, string
}
export function getBIFieldPillLabel(field: BIField): string {
+ if (field.label?.trim()) {
+ return field.label.trim()
+ }
const name = field.name || field.expression.trim()
if (!name) {
return 'New calculation'
@@ -1268,6 +1374,9 @@ export function getBIFieldPillLabel(field: BIField): string {
}
export function getBIValuePillLabel(value: BIValue): string {
+ if (value.display?.label?.trim()) {
+ return value.display.label.trim()
+ }
if (value.tableCalculation) {
return `${BI_TABLE_CALCULATIONS.find((option) => option.value === value.tableCalculation?.type)?.label} · ${getBIValuePillLabel({ ...value, tableCalculation: undefined })}`
}
@@ -1540,6 +1649,40 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
}
}
+ if (config.chartType === ChartDisplayType.ScatterPlot) {
+ const numericColumns = [
+ ...getBIResultDimensions(config)
+ .filter(({ field }) => isNumericBIResultField(field))
+ .map(({ column, field }) => ({ column, label: getBIFieldPillLabel(field) })),
+ ...(configuredValues.length
+ ? configuredValues.map(({ alias, value }) => ({ column: alias, label: getBIValuePillLabel(value) }))
+ : [{ column: 'count', label: 'Count of rows' }]),
+ ]
+ const [x, ...ys] = numericColumns
+ seriesSettings = {
+ ...seriesSettings,
+ xAxis: x ? { column: x.column } : undefined,
+ xAxisLabel: x?.label,
+ yAxis: ys.map(({ column }) => ({
+ column,
+ ...calculatedFormats.find((format) => format.column === column),
+ })),
+ leftYAxisSettings: { label: ys.length === 1 ? ys[0].label : undefined },
+ seriesBreakdownColumn: undefined,
+ }
+ }
+
+ if (config.chartType === ChartDisplayType.BoxPlot) {
+ const columns = [
+ ...getBIResultDimensions(config).map(({ column, field }) => ({
+ name: column,
+ type: { isNumerical: isNumericBIResultField(field) },
+ })),
+ ...configuredValues.map(({ alias }) => ({ name: alias, type: { isNumerical: true } })),
+ ].map((column, dataIndex) => ({ ...column, dataIndex }))
+ seriesSettings = { ...seriesSettings, boxPlot: getAutoBoxPlotSettings(columns) }
+ }
+
return {
query,
node: {
@@ -1552,7 +1695,7 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
filters: getBIQueryFilters(config),
},
display: config.chartType,
- ...(calculatedFormats.length
+ ...(calculatedFormats.length || dimensions.length
? {
tableSettings: {
columns: [
@@ -1565,9 +1708,24 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
? dimension.alias
: fieldExpression(dimension.field)
)),
- ...configuredValues.map((value) => value.alias),
+ ...(configuredValues.length ? configuredValues.map((value) => value.alias) : ['count']),
...(comparing ? ['bi_comparison'] : []),
- ].map((column) => calculatedFormats.find((format) => format.column === column) ?? { column }),
+ ].map((column) => {
+ const dimension = dimensions.find(
+ (dimension) =>
+ (hasBIAnalysis(config) || comparing || hasSeriesBreakdown || isPivotTable
+ ? dimension.alias
+ : fieldExpression(dimension.field)) === column
+ )
+ return (
+ calculatedFormats.find((format) => format.column === column) ?? {
+ column,
+ ...(dimension
+ ? { settings: { display: { label: getBIFieldPillLabel(dimension.field) } } }
+ : {}),
+ }
+ )
+ }),
},
}
: {}),
diff --git a/products/business_intelligence/frontend/biMeasureSettings.test.ts b/products/business_intelligence/frontend/biMeasureSettings.test.ts
index 2e280c287bc3..6e089592823a 100644
--- a/products/business_intelligence/frontend/biMeasureSettings.test.ts
+++ b/products/business_intelligence/frontend/biMeasureSettings.test.ts
@@ -48,6 +48,39 @@ const config: BIConfig = {
}
describe('BI measure display', () => {
+ it('keeps edited axis labels while refreshing generated labels after a field rename', () => {
+ const original = buildBIQuery(config)!.node.chartSettings!
+ const renamed = buildBIQuery({ ...config, rows: [{ ...config.rows[0], name: 'Order date' }] })!.node
+ .chartSettings!
+ expect(mergeBIChartSettings(original, renamed, original)?.xAxisLabel).toBe('DAY(Order date)')
+ const edited = {
+ ...original,
+ xAxisLabel: 'Date',
+ leftYAxisSettings: { label: 'Revenue', scale: 'logarithmic' as const },
+ }
+ const merged = mergeBIChartSettings(edited, renamed, original)
+ expect(merged?.xAxisLabel).toBe('Date')
+ expect(merged?.leftYAxisSettings).toMatchObject({ label: 'Revenue', scale: 'logarithmic' })
+ expect(
+ mergeBIChartSettings(edited, { ...renamed, xAxis: { column: 'country' }, xAxisLabel: 'Country' }, original)
+ ?.xAxisLabel
+ ).toBe('Country')
+ const tableDefaults = buildBIQuery(config)!.node.tableSettings!
+ const renamedTable = buildBIQuery({ ...config, rows: [{ ...config.rows[0], name: 'Order date' }] })!.node
+ .tableSettings!
+ expect(
+ mergeBITableSettings(tableDefaults, renamedTable, tableDefaults)?.columns?.[0].settings?.display?.label
+ ).toBe('DAY(Order date)')
+ const editedTable = {
+ ...tableDefaults,
+ columns: tableDefaults.columns?.map((column, index) =>
+ index === 0 ? { ...column, settings: { display: { label: 'Date' } } } : column
+ ),
+ }
+ expect(
+ mergeBITableSettings(editedTable, renamedTable, tableDefaults)?.columns?.[0].settings?.display?.label
+ ).toBe('Date')
+ })
it.each([ChartDisplayType.ActionsBar, ChartDisplayType.TwoDimensionalHeatmap])(
'persists independent formats and axes for %s',
(chartType) => {
diff --git a/products/business_intelligence/frontend/biMeasureSettings.ts b/products/business_intelligence/frontend/biMeasureSettings.ts
index 08a360b19d81..16a465448c35 100644
--- a/products/business_intelligence/frontend/biMeasureSettings.ts
+++ b/products/business_intelligence/frontend/biMeasureSettings.ts
@@ -58,7 +58,8 @@ export function mergeBIMeasureSettings(
export function mergeBITableSettings(
current: TableSettings | undefined,
- generated: TableSettings | undefined
+ generated: TableSettings | undefined,
+ previousDefaults?: TableSettings
): TableSettings | undefined {
if (!generated) {
return current
@@ -68,7 +69,18 @@ export function mergeBITableSettings(
...generated,
columns: generated.columns?.map((column) => {
const saved = current?.columns?.find((previous) => previous.column === column.column)
- return { ...saved, ...column, settings: mergeBIMeasureSettings(saved?.settings, column.settings) }
+ const settings = mergeBIMeasureSettings(saved?.settings, column.settings)
+ const savedLabel = saved?.settings?.display?.label
+ const previousLabel = previousDefaults?.columns?.find((previous) => previous.column === column.column)
+ ?.settings?.display?.label
+ return {
+ ...saved,
+ ...column,
+ settings:
+ previousDefaults && savedLabel !== undefined && savedLabel !== previousLabel
+ ? { ...settings, display: { ...settings?.display, label: savedLabel } }
+ : settings,
+ }
}),
}
}
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index 5ea0a1a79b9a..c1e61e5a6146 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -174,6 +174,206 @@ describe('biSceneLogic', () => {
expect(logic.values.lastRunQuery?.config.limit).toBe(100)
})
+ it.each([false, true])(
+ 'preserves a custom axis label when renaming an aliased dimension (Top N: %s)',
+ async (topN) => {
+ logic.actions.restoreWorksheet(
+ worksheet({
+ ...config,
+ ...(topN
+ ? { topN: { fieldId: eventField.id, count: 10, measureIndex: 0, includeOther: true } }
+ : {}),
+ })
+ )
+ editor.actions.setAutoUpdate(false)
+ logic.actions.runQuery()
+ const source = logic.values.worksheet.source
+ logic.actions.setChartSettings({ ...logic.values.worksheet.chartSettings, xAxisLabel: 'Custom date label' })
+ await expectLogic(editor, () =>
+ editor.actions.renameField('columns', 0, 'Activity date')
+ ).toFinishAllListeners()
+ expect(logic.values.worksheet.source).toEqual(source)
+ expect(logic.values.worksheet.chartSettings?.xAxisLabel).toBe('Custom date label')
+ }
+ )
+
+ it('saves axis settings without running pending filter or shelf edits', async () => {
+ logic.actions.restoreWorksheet(worksheet())
+ editor.actions.setAutoUpdate(false)
+ logic.actions.runQuery()
+ const displayed = logic.values.lastRunQuery!
+ editor.actions.addFieldToShelf(eventField, 'filters')
+ editor.actions.setFilterValue(0, 'purchase')
+ editor.actions.setLimit(100)
+ await expectLogic(logic).toFinishAllListeners()
+ const draft = logic.values.worksheet.source
+ logic.actions.setChartSettings({ ...displayed.chartSettings, xAxisLabel: 'Custom date label' })
+ expect(logic.values.lastRunQuery?.source).toEqual(displayed.source)
+ expect(logic.values.lastRunQuery?.config).toEqual(displayed.config)
+ expect(logic.values.lastRunQuery?.chartSettings?.xAxisLabel).toBe('Custom date label')
+ expect(logic.values.worksheet.source).toEqual(draft)
+ expect(logic.values.worksheet.config.filters[0].value).toBe('purchase')
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.source).toEqual(draft)
+ expect(logic.values.lastRunQuery?.chartSettings?.xAxisLabel).toBe('Custom date label')
+ })
+
+ it('initializes numeric scatter axes when switching a rendered categorical chart', async () => {
+ const measure = {
+ ...eventField,
+ id: 'revenue',
+ name: 'revenue',
+ expression: 'properties.revenue',
+ type: 'float' as const,
+ }
+ logic.actions.restoreWorksheet(
+ worksheet({
+ ...config,
+ columns: [],
+ values: [
+ { field: measure, aggregation: 'sum' },
+ { field: measure, aggregation: 'average' },
+ ],
+ })
+ )
+ editor.actions.setAutoUpdate(false)
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.chartSettings?.xAxis?.column).toBe('event')
+ const measures = logic.values.lastRunQuery!.chartSettings!.yAxis!
+ editor.actions.setChartType(ChartDisplayType.ScatterPlot)
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.chartSettings).toMatchObject({
+ xAxis: { column: measures[0].column },
+ yAxis: [{ column: measures[1].column }],
+ })
+ editor.actions.setChartType(ChartDisplayType.ActionsBar)
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.chartSettings?.xAxis?.column).toBe('event')
+ expect(logic.values.lastRunQuery?.chartSettings?.yAxis).toHaveLength(2)
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('initializes box plot mappings without changing the returned columns', async () => {
+ const statistics = ['min', 'p25', 'median', 'mean', 'p75', 'max']
+ logic.actions.restoreWorksheet(
+ worksheet({
+ ...config,
+ columns: [],
+ values: [],
+ rows: statistics.map((name) => ({
+ ...eventField,
+ id: name,
+ name,
+ expression: name,
+ type: 'float',
+ })),
+ })
+ )
+ editor.actions.setAutoUpdate(false)
+ logic.actions.runQuery()
+ editor.actions.setChartType(ChartDisplayType.BoxPlot)
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.chartSettings?.boxPlot).toMatchObject(
+ Object.fromEntries(statistics.map((name) => [`${name}Column`, name]))
+ )
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('keeps generated axis defaults aligned after an unrelated axis edit', async () => {
+ logic.actions.restoreWorksheet(
+ worksheet({ ...config, columns: [], values: [{ field: eventField, aggregation: 'count' }] })
+ )
+ editor.actions.setAutoUpdate(false)
+ editor.actions.renameField('values', 0, 'First count')
+ logic.actions.runQuery()
+ logic.actions.setChartSettings({ ...logic.values.lastRunQuery!.chartSettings, xAxisLabel: 'Custom events' })
+ editor.actions.renameField('values', 0, 'Second count')
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.chartSettings?.leftYAxisSettings?.label).toBe('Second count')
+ expect(logic.values.lastRunQuery?.chartSettings?.xAxisLabel).toBe('Custom events')
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('preserves implicit count formatting and valid saved scatter axes', async () => {
+ logic.actions.restoreWorksheet(worksheet({ ...config, columns: [] }))
+ logic.actions.setVisualization({
+ ...logic.values.worksheet,
+ tableSettings: {
+ columns: [
+ { column: 'event' },
+ { column: 'count', settings: { display: { label: 'Records' }, formatting: { decimalPlaces: 2 } } },
+ ],
+ },
+ })
+ expect(
+ logic.values.worksheet.tableSettings?.columns?.find(({ column }) => column === 'count')?.settings
+ ).toMatchObject({ display: { label: 'Records' }, formatting: { decimalPlaces: 2 } })
+ logic.actions.restoreWorksheet(
+ worksheet({
+ ...config,
+ chartType: ChartDisplayType.ScatterPlot,
+ rows: [],
+ columns: [],
+ values: [
+ { field: eventField, aggregation: 'count' },
+ { field: eventField, aggregation: 'count_distinct' },
+ ],
+ })
+ )
+ const settings = logic.values.worksheet.chartSettings!
+ const x = settings.xAxis!.column
+ const y = settings.yAxis![0].column
+ logic.actions.setChartSettings({ ...settings, xAxis: { column: y }, yAxis: [{ column: x }] })
+ expect(logic.values.worksheet.chartSettings).toMatchObject({ xAxis: { column: y }, yAxis: [{ column: x }] })
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it.each([false, true])('updates generated scatter titles after renames with swapped axes=%s', async (swapped) => {
+ const state = {
+ ...config,
+ rows: [],
+ columns: [],
+ chartType: ChartDisplayType.ScatterPlot,
+ values: [
+ { field: eventField, aggregation: 'count' as const },
+ { field: eventField, aggregation: 'count_distinct' as const },
+ ],
+ }
+ const saved = worksheet(state)
+ if (swapped) {
+ saved.chartSettings = {
+ ...saved.chartSettings,
+ xAxis: saved.chartSettings!.yAxis![0],
+ yAxis: [saved.chartSettings!.xAxis!],
+ xAxisLabel: saved.chartSettings!.leftYAxisSettings?.label,
+ leftYAxisSettings: { label: saved.chartSettings!.xAxisLabel },
+ }
+ }
+ logic.actions.restoreWorksheet(saved)
+ editor.actions.setAutoUpdate(false)
+ editor.actions.renameField('values', 0, 'New count')
+ editor.actions.renameField('values', 1, 'New distinct count')
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.chartSettings?.xAxisLabel).toBe(swapped ? 'New distinct count' : 'New count')
+ expect(logic.values.lastRunQuery?.chartSettings?.leftYAxisSettings?.label).toBe(
+ swapped ? 'New count' : 'New distinct count'
+ )
+ expect(logic.values.lastRunQuery?.chartSettings?.xAxis?.column).toBe(saved.chartSettings?.xAxis?.column)
+ logic.actions.setChartSettings({
+ ...logic.values.lastRunQuery!.chartSettings,
+ xAxisLabel: 'Custom X',
+ leftYAxisSettings: { label: 'Custom Y' },
+ })
+ editor.actions.renameField('values', 0, 'Later count')
+ editor.actions.renameField('values', 1, 'Later distinct count')
+ logic.actions.runQuery()
+ expect(logic.values.lastRunQuery?.chartSettings).toMatchObject({
+ xAxisLabel: 'Custom X',
+ leftYAxisSettings: { label: 'Custom Y' },
+ })
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
it('tracks the first successful chart once, without counting empty results or reruns', async () => {
const capture = jest.spyOn(posthog, 'capture').mockImplementation()
logic.actions.restoreWorksheet(worksheet())
@@ -230,6 +430,14 @@ describe('biSceneLogic', () => {
node.chartSettings!.yAxis![0].settings = { formatting: { prefix: '$', suffix: '' } }
node.chartSettings!.goalLines = [{ label: 'Average', value: 0, calculation: 'mean', scope: 'series' }]
logic.actions.restoreWorksheet(node)
+ logic.actions.setVisualization({
+ ...logic.values.worksheet,
+ chartSettings: {
+ ...logic.values.worksheet.chartSettings,
+ xAxisLabel: 'Event date',
+ leftYAxisSettings: { label: 'Revenue', scale: 'logarithmic' },
+ },
+ })
logic.actions.setName('Revenue worksheet')
await expectLogic(logic, () => logic.actions.saveInsight()).toFinishAllListeners()
expect(save).toHaveBeenCalledTimes(1)
@@ -246,6 +454,11 @@ describe('biSceneLogic', () => {
expect(logic.values.worksheet.config).toEqual({ ...config, hierarchies: [hierarchy] })
expect(logic.values.worksheet.chartSettings?.yAxis?.[0].settings?.formatting?.prefix).toBe('$')
expect(logic.values.worksheet.chartSettings?.goalLines).toEqual(node.chartSettings!.goalLines)
+ expect(logic.values.worksheet.chartSettings?.xAxisLabel).toBe('Event date')
+ expect(logic.values.worksheet.chartSettings?.leftYAxisSettings).toMatchObject({
+ label: 'Revenue',
+ scale: 'logarithmic',
+ })
expect(logic.values.hasUnsavedChanges).toBe(false)
})
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index 48b9eb8f6573..2b37b178b777 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -28,9 +28,9 @@ import { urls } from 'scenes/urls'
import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
-import { HogQLFilters, NodeKind, VisualizationNode } from '~/queries/schema/schema-general'
+import { ChartSettings, HogQLFilters, NodeKind, VisualizationNode } from '~/queries/schema/schema-general'
import { isBIVisualizationNode } from '~/queries/utils'
-import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { AccessControlLevel, AccessControlResourceType, ChartDisplayType } from '~/types'
import { warehouseSavedQueriesCreate } from 'products/data_warehouse/frontend/generated/api'
import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'
@@ -94,6 +94,7 @@ export interface biSceneLogicValues {
currentTeamId: number | null // teamLogic
canRedo: boolean
canUndo: boolean
+ chartSettingsDefaults: ChartSettings | null
copyDisabledReason: string | undefined
dataNodeKey: string
exportViewName: string
@@ -123,8 +124,8 @@ export interface biSceneLogicActions {
runAfterChange: () => {
value: true
} // biEditorLogic
- setChartType: (chartType: import('~/types').ChartDisplayType) => {
- chartType: import('~/types').ChartDisplayType
+ setChartType: (chartType: ChartDisplayType) => {
+ chartType: ChartDisplayType
} // biEditorLogic
cancelQuery: () => {
value: true
@@ -214,6 +215,12 @@ export interface biSceneLogicActions {
selectConnection: (connectionId: string | null) => {
connectionId: string | null
}
+ setChartSettings: (chartSettings: ChartSettings) => {
+ chartSettings: ChartSettings
+ }
+ setChartSettingsDefaults: (defaults: ChartSettings | undefined) => {
+ defaults: ChartSettings | undefined
+ }
setExportViewName: (name: string) => {
name: string
}
@@ -251,7 +258,8 @@ export interface biSceneLogicMeta {
worksheet: (
config: BIConfig,
generatedQuery: BIQueryBuildResult | null,
- visualization: BIVisualizationNode
+ visualization: BIVisualizationNode,
+ chartSettingsDefaults: ChartSettings | null
) => BIVisualizationNode
hasUnsavedChanges: (worksheet: BIVisualizationNode, name: string, insight: InsightApi | null) => boolean
saveDisabledReason: (
@@ -294,6 +302,8 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
restoreHistory: true,
restoreWorksheet: (worksheet: BIVisualizationNode) => ({ worksheet }),
setVisualization: (visualization: VisualizationNode) => ({ visualization }),
+ setChartSettings: (chartSettings: ChartSettings) => ({ chartSettings }),
+ setChartSettingsDefaults: (defaults: ChartSettings | undefined) => ({ defaults }),
setName: (name: string) => ({ name }),
runQuery: true,
cancelQuery: true,
@@ -406,10 +416,19 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
: state,
},
],
+ chartSettingsDefaults: [
+ null as ChartSettings | null,
+ {
+ setChartSettingsDefaults: (_, { defaults }) => defaults ?? null,
+ restoreWorksheet: () => null,
+ setVisualization: () => null,
+ },
+ ],
visualization: [
emptyWorksheet(),
{
restoreWorksheet: (_, { worksheet }) => worksheet,
+ setChartSettings: (state, { chartSettings }) => ({ ...state, chartSettings }),
setVisualization: (state, { visualization }) => ({
...state,
...visualization,
@@ -441,11 +460,12 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
],
dataNodeKey: [(_, props) => [props.tabId], (tabId: string): string => `InsightViz.new-bi-${tabId}`],
worksheet: [
- (s) => [s.config, s.generatedQuery, s.visualization],
+ (s) => [s.config, s.generatedQuery, s.visualization, s.chartSettingsDefaults],
(
config: BIConfig,
generatedQuery: BIQueryBuildResult | null,
- visualization: BIVisualizationNode
+ visualization: BIVisualizationNode,
+ chartSettingsDefaults: ChartSettings | null
): BIVisualizationNode => ({
...visualization,
...generatedQuery?.node,
@@ -455,8 +475,17 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
source: generatedQuery
? mergeBIQuerySource(visualization.source, generatedQuery.node.source)
: { ...visualization.source, query: '' },
- chartSettings: mergeBIChartSettings(visualization.chartSettings, generatedQuery?.node.chartSettings),
- tableSettings: mergeBITableSettings(visualization.tableSettings, generatedQuery?.node.tableSettings),
+ chartSettings: mergeBIChartSettings(
+ visualization.chartSettings,
+ generatedQuery?.node.chartSettings,
+ chartSettingsDefaults ?? buildBIQuery(visualization.config)?.node.chartSettings,
+ config.chartType === ChartDisplayType.ScatterPlot
+ ),
+ tableSettings: mergeBITableSettings(
+ visualization.tableSettings,
+ generatedQuery?.node.tableSettings,
+ buildBIQuery(visualization.config)?.node.tableSettings
+ ),
}),
],
hasUnsavedChanges: [
@@ -679,6 +708,16 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
}
},
cancelQuery: () => dataNodeLogic.findMounted({ key: values.dataNodeKey })?.actions.cancelQuery(),
+ setChartSettings: ({ chartSettings }) => {
+ actions.setChartSettingsDefaults(
+ buildBIQuery(values.lastRunQuery?.config ?? values.config)?.node.chartSettings
+ )
+ if (values.lastRunQuery) {
+ actions.setLastRunQuery({ ...values.lastRunQuery, chartSettings })
+ }
+ actions.syncWorksheetUrl()
+ actions.recordWorksheet()
+ },
setVisualization: ({ visualization }) => {
const config = applyBIDateRange(values.config, visualization.source.filters?.dateRange)
if (config !== values.config) {
diff --git a/products/business_intelligence/frontend/components/BIConditionGroups.tsx b/products/business_intelligence/frontend/components/BIConditionGroups.tsx
index 7aa37c024bba..446a3e14b92c 100644
--- a/products/business_intelligence/frontend/components/BIConditionGroups.tsx
+++ b/products/business_intelligence/frontend/components/BIConditionGroups.tsx
@@ -2,6 +2,8 @@ import { useState } from 'react'
import { LemonButton, LemonModal, LemonSelect, LemonTag } from '@posthog/lemon-ui'
+import { FloatingContainerContext } from 'lib/hooks/useFloatingContainerContext'
+
import { BIConditionGroup } from '~/queries/schema/schema-business-intelligence'
import {
@@ -105,6 +107,7 @@ export function BIConditionGroups({
onChange: (group: BIConditionGroup) => void
}): JSX.Element {
const [open, setOpen] = useState(false)
+ const [modalOverlay, setModalOverlay] = useState<HTMLDivElement | null>(null)
const normalized = normalizeBIConditionGroup(
group,
options.map((option) => option.value)
@@ -121,6 +124,8 @@ export function BIConditionGroups({
<LemonModal
title={title}
isOpen={open}
+ forceAbovePopovers
+ overlayRef={setModalOverlay}
onClose={() => setOpen(false)}
width={560}
footer={
@@ -133,7 +138,9 @@ export function BIConditionGroups({
Add a group, then move filters into it. Empty groups have no effect. Ungroup moves its filters and
nested groups into the parent group.
</p>
- <GroupEditor root={normalized} group={normalized} path={[]} options={options} onChange={onChange} />
+ <FloatingContainerContext.Provider value={modalOverlay}>
+ <GroupEditor root={normalized} group={normalized} path={[]} options={options} onChange={onChange} />
+ </FloatingContainerContext.Provider>
</LemonModal>
</>
)
diff --git a/products/business_intelligence/frontend/components/BIExpressionPopover.tsx b/products/business_intelligence/frontend/components/BIExpressionPopover.tsx
index 1c79782816ab..46671a0fcb64 100644
--- a/products/business_intelligence/frontend/components/BIExpressionPopover.tsx
+++ b/products/business_intelligence/frontend/components/BIExpressionPopover.tsx
@@ -1,4 +1,5 @@
-import { LemonDropdown } from '@posthog/lemon-ui'
+import { IconX } from '@posthog/icons'
+import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'
import { HogQLEditor } from 'lib/components/HogQLEditor/HogQLEditor'
@@ -32,6 +33,16 @@ export function BIExpressionPopover({
placement="bottom-start"
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>
+ <LemonButton
+ icon={<IconX />}
+ size="xsmall"
+ type="tertiary"
+ aria-label="Close expression editor"
+ onClick={onClose}
+ />
+ </div>
<HogQLEditor
value={value}
placeholder={placeholder}
diff --git a/products/business_intelligence/frontend/components/BIFieldNameModal.tsx b/products/business_intelligence/frontend/components/BIFieldNameModal.tsx
new file mode 100644
index 000000000000..37391a4dd0be
--- /dev/null
+++ b/products/business_intelligence/frontend/components/BIFieldNameModal.tsx
@@ -0,0 +1,39 @@
+import { useState } from 'react'
+
+import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
+
+export function BIFieldNameModal({
+ name,
+ onSave,
+ onClose,
+}: {
+ name: string
+ onSave: (name: string) => void
+ onClose: () => void
+}): JSX.Element {
+ const [draft, setDraft] = useState(name)
+ return (
+ <LemonModal
+ title="Rename field"
+ isOpen
+ onClose={onClose}
+ footer={
+ <LemonButton
+ type="primary"
+ disabledReason={!draft.trim() ? 'Enter a name' : undefined}
+ onClick={() => {
+ onSave(draft.trim())
+ onClose()
+ }}
+ >
+ Save name
+ </LemonButton>
+ }
+ >
+ <LemonInput aria-label="Field name" value={draft} onChange={setDraft} autoFocus />
+ <p className="mt-2 mb-0 text-secondary">
+ This name applies to this field in this worksheet. The source field stays the same.
+ </p>
+ </LemonModal>
+ )
+}
diff --git a/products/business_intelligence/frontend/components/BIFieldPill.tsx b/products/business_intelligence/frontend/components/BIFieldPill.tsx
index 5d12d803a8ed..493b9491db8f 100644
--- a/products/business_intelligence/frontend/components/BIFieldPill.tsx
+++ b/products/business_intelligence/frontend/components/BIFieldPill.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { useState } from 'react'
import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'
import { LemonMenu, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
@@ -20,6 +21,7 @@ import {
import { BIExpressionPopover } from 'products/business_intelligence/frontend/components/BIExpressionPopover'
import { BIPill } from 'products/business_intelligence/frontend/components/BIPill'
+import { BIFieldNameModal } from './BIFieldNameModal'
import { BIShelfDropTarget } from './BIShelfDropTarget'
type ExpressionTarget = 'field' | 'aggregation'
@@ -32,6 +34,7 @@ export function BIFieldPill({
shelf: Exclude<BIShelf, 'filters'>
index: number
}): JSX.Element | null {
+ const [nameDraft, setNameDraft] = useState<string | null>(null)
const { config, activeExpressionEditorId, activeExpressionEditorTarget, sortOptions } = useValues(biEditorLogic)
const {
addFieldToShelf,
@@ -48,6 +51,7 @@ export function BIFieldPill({
setSort,
setValueAggregation,
setValueCustomExpression,
+ renameField,
} = useActions(biEditorLogic)
const value = shelf === 'values' ? config.values[index] : null
@@ -118,6 +122,7 @@ export function BIFieldPill({
: null,
{
items: [
+ { label: 'Rename', onClick: () => setNameDraft(label) },
{ label: 'Duplicate', onClick: () => duplicateField(shelf, index) },
isMeasure
? {
@@ -181,35 +186,44 @@ export function BIFieldPill({
]
return (
- <BIExpressionPopover
- visible={expressionTarget !== null}
- value={expressionTarget === 'aggregation' ? (value?.customExpression ?? '') : field.expression}
- source={field.source}
- placeholder={expressionTarget === 'aggregation' ? 'For example: sum(amount) / count()' : undefined}
- onChange={(nextExpression) =>
- expressionTarget === 'aggregation'
- ? setValueCustomExpression(index, nextExpression)
- : setFieldExpression(shelf, index, nextExpression)
- }
- onClose={() => {
- if (activeExpressionEditorId === editorKey) {
- setActiveExpressionEditorId(null)
+ <>
+ {nameDraft !== null && (
+ <BIFieldNameModal
+ name={nameDraft}
+ onSave={(name) => renameField(shelf, index, name)}
+ onClose={() => setNameDraft(null)}
+ />
+ )}
+ <BIExpressionPopover
+ visible={expressionTarget !== null}
+ value={expressionTarget === 'aggregation' ? (value?.customExpression ?? '') : field.expression}
+ source={field.source}
+ placeholder={expressionTarget === 'aggregation' ? 'For example: sum(amount) / count()' : undefined}
+ onChange={(nextExpression) =>
+ expressionTarget === 'aggregation'
+ ? setValueCustomExpression(index, nextExpression)
+ : setFieldExpression(shelf, index, nextExpression)
}
- }}
- >
- <BIShelfDropTarget shelf={shelf} index={index} className="inline-flex min-w-0 max-w-[min(18rem,100%)]">
- <LemonMenu items={items} placement="bottom-start">
- <BIPill
- kind={isMeasure ? 'measure' : 'dimension'}
- label={label}
- shelf={shelf}
- index={index}
- incomplete={incomplete}
- aria-label={`${label} options`}
- data-attr={`bi-editor-${shelf}-pill`}
- />
- </LemonMenu>
- </BIShelfDropTarget>
- </BIExpressionPopover>
+ onClose={() => {
+ if (activeExpressionEditorId === editorKey) {
+ setActiveExpressionEditorId(null)
+ }
+ }}
+ >
+ <BIShelfDropTarget shelf={shelf} index={index} className="inline-flex min-w-0 max-w-[min(18rem,100%)]">
+ <LemonMenu items={items} placement="bottom-start">
+ <BIPill
+ kind={isMeasure ? 'measure' : 'dimension'}
+ label={label}
+ shelf={shelf}
+ index={index}
+ incomplete={incomplete}
+ aria-label={`${label} options`}
+ data-attr={`bi-editor-${shelf}-pill`}
+ />
+ </LemonMenu>
+ </BIShelfDropTarget>
+ </BIExpressionPopover>
+ </>
)
}
diff --git a/products/business_intelligence/frontend/components/BIFilterEditor.tsx b/products/business_intelligence/frontend/components/BIFilterEditor.tsx
index 30b498a0a5fd..09f0d08cb338 100644
--- a/products/business_intelligence/frontend/components/BIFilterEditor.tsx
+++ b/products/business_intelligence/frontend/components/BIFilterEditor.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconPencil } from '@posthog/icons'
+import { IconPencil, IconX } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
import { HogQLDropdown } from 'lib/components/HogQLDropdown/HogQLDropdown'
@@ -30,6 +30,16 @@ export function BIFilterEditor({ index, onDone }: { index: number; onDone: () =>
return (
<div className="flex w-80 flex-col gap-3 p-1">
+ <div className="flex items-center justify-between">
+ <span className="font-semibold">Edit filter</span>
+ <LemonButton
+ icon={<IconX />}
+ type="tertiary"
+ size="xsmall"
+ aria-label="Close filter editor"
+ onClick={onDone}
+ />
+ </div>
<div className="flex flex-col gap-1">
<LemonLabel>Field</LemonLabel>
<HogQLDropdown
diff --git a/products/business_intelligence/frontend/components/BIFiltersCard.tsx b/products/business_intelligence/frontend/components/BIFiltersCard.tsx
index 15f24eafafbe..fbfb843ccf29 100644
--- a/products/business_intelligence/frontend/components/BIFiltersCard.tsx
+++ b/products/business_intelligence/frontend/components/BIFiltersCard.tsx
@@ -1,6 +1,7 @@
import { useActions, useValues } from 'kea'
+import { useState } from 'react'
-import { IconFilter, IconPlus } from '@posthog/icons'
+import { IconFilter, IconPlus, IconX } from '@posthog/icons'
import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
@@ -12,6 +13,7 @@ import { BIResultFiltersCard } from './BIResultFiltersCard'
import { BIShelfDropTarget } from './BIShelfDropTarget'
export function BIFiltersCard(): JSX.Element {
+ const [resultFiltersOpen, setResultFiltersOpen] = useState(false)
const { config } = useValues(biEditorLogic)
const { addBlankFieldToShelf, setFilterGroup } = useActions(biEditorLogic)
@@ -49,10 +51,21 @@ export function BIFiltersCard(): JSX.Element {
/>
)}
<LemonDropdown
+ visible={resultFiltersOpen}
+ onVisibilityChange={setResultFiltersOpen}
closeOnClickInside={false}
placement="bottom-end"
overlay={
<div className="w-72">
+ <div className="flex justify-end">
+ <LemonButton
+ icon={<IconX />}
+ type="tertiary"
+ size="xsmall"
+ aria-label="Close result filters"
+ onClick={() => setResultFiltersOpen(false)}
+ />
+ </div>
<BIResultFiltersCard />
</div>
}
diff --git a/products/business_intelligence/frontend/components/BIShelfStrip.tsx b/products/business_intelligence/frontend/components/BIShelfStrip.tsx
index 5104db203897..50229868a06e 100644
--- a/products/business_intelligence/frontend/components/BIShelfStrip.tsx
+++ b/products/business_intelligence/frontend/components/BIShelfStrip.tsx
@@ -23,7 +23,7 @@ export function BIShelfStrip({
children: ReactNode[]
}): JSX.Element {
const { config } = useValues(biEditorLogic)
- const { addBlankFieldToShelf } = useActions(biEditorLogic)
+ const { editCalculatedField } = useActions(biEditorLogic)
return (
<BIShelfDropTarget shelf={shelf} className="flex min-h-9 items-stretch rounded-none border-b">
@@ -41,7 +41,7 @@ export function BIShelfStrip({
tooltip="Add a calculated field"
aria-label={`Add a calculated field to ${title.toLowerCase()}`}
disabledReason={!config.source ? 'Select a data source first' : undefined}
- onClick={() => addBlankFieldToShelf(shelf)}
+ onClick={() => editCalculatedField(undefined, shelf)}
data-attr={`bi-editor-${shelf}-add-field`}
/>
</div>
diff --git a/products/business_intelligence/package.json b/products/business_intelligence/package.json
index 32dc6d5e94b9..69adba778a92 100644
--- a/products/business_intelligence/package.json
+++ b/products/business_intelligence/package.json
@@ -10,6 +10,8 @@
"posthog-js": "catalog:"
},
"devDependencies": {
+ "@testing-library/react": "^14.3.1",
+ "@testing-library/user-event": "^14.6.1",
"kea-test-utils": "catalog:"
},
"peerDependencies": {
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index df98481466ea..40e285a2338b 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9533,6 +9533,7 @@ export interface BIFieldApi {
datePart?: DatePartApi | null
expression: string
id: string
+ label?: string | null
localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | BILocalFieldDefinition3Api | null
localFieldId?: string | null
name: string
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 38bb5892fdbc..5209c9ff1722 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -4653,6 +4653,7 @@ export namespace Schemas {
datePart?: (DatePart | null) | undefined;
expression: string;
id: string;
+ label?: (string | null) | undefined;
localDefinition?:
| (
| BILocalFieldDefinition1
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 132f679e9bfc..bbb08c64c915 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8397,6 +8397,7 @@ export interface BIFieldApi {
datePart?: DatePartApi | null
expression: string
id: string
+ label?: string | null
localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | BILocalFieldDefinition3Api | null
localFieldId?: string | null
name: string
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6bba5566c5cb..b665726bdf27 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10896,6 +10896,7 @@ export namespace Schemas {
datePart?: DatePart | null;
expression: string;
id: string;
+ label?: string | null;
localDefinition?: BILocalFieldDefinition1 | BILocalFieldDefinition2 | BILocalFieldDefinition3 | null;
localFieldId?: string | null;
name: string;