Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(bi): add worksheet library, history, and result filters (#113191)

Marius Andra07b019f813d0
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 61a4d858b1b3..0b67fdbd6740 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -24,7 +24,7 @@ Insights can be saved or updated before running the SQL. Updating a view still r
## Choosing data in Business intelligence
-**Business intelligence** opens a visual worksheet at `/bi`, separately from the SQL editor, when the `sql-editor-bi-mode` feature flag is enabled. Both products keep their own unsaved working copies, including edits to the same saved view, insight, or draft. Existing SQL working copies remain available. Worksheet breadcrumbs preserve the visual configuration, and existing SQL editor links with `mode=bi` open in Business intelligence.
+**Business intelligence** lists saved worksheets at `/bi` when the `sql-editor-bi-mode` feature flag is enabled. Search all worksheets or switch to those viewed in the last 30 days. **New worksheet** opens `/bi/new`; selecting a saved worksheet opens `/bi/<short_id>` in edit mode. The project tree's **New → Worksheet** entry opens the same editor. Worksheets retain their insight identities and folder placements, but use their own file subtype and no longer appear in the Product analytics insights list. Legacy `/bi?open_insight=...` links and shared worksheet URLs still open the editor. Business intelligence and SQL keep separate unsaved working copies, and existing SQL editor links with `mode=bi` open in Business intelligence.
Choose a connection in the **Data** panel, then select a table below it. **Run** is the first toolbar action, before **Swap rows and columns**.
@@ -32,11 +32,13 @@ Choose a connection in the **Data** panel, then select a table below it. **Run**
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.
+**Undo** and **Redo** restore shelves, filters, calculations, formatting, chart settings, and worksheet names. The editor keeps the last 100 changes during a visit; opening another worksheet or discarding changes starts a new history. Use Cmd/Ctrl+Z and Cmd/Ctrl+Shift+Z outside text inputs. Undo respects **Auto update**: with it off, click **Run** to refresh results. **Save a copy** creates a separate worksheet and opens it in the editor without changing the original or copying its dashboard placements. Copy failures leave the original and your edits in place. Usage tracking adds `undo`, `redo`, and `copied` actions.
+
For older saves without worksheet configuration, discarding query edits preserves the current source and shelves.
SQL query-scan advisories are hidden in Business intelligence. Query errors and warnings about stale sources or restricted data remain visible.
-Saving a worksheet as an insight preserves its connection, table, shelves, measures, filters, chart type, limit, sort order, and visualization settings in a `BIVisualizationNode`. The wrapper contains the worksheet configuration and a plain `HogQLQuery` source. Saved insights use the normal insight view; **Edit** reopens Business intelligence when the feature is enabled, including from a dashboard. **Discard changes** restores the saved worksheet. **Save as SQL view** exports only the generated SQL to a warehouse view; save an insight to retain editable worksheet state.
+Saving a worksheet preserves its connection, table, shelves, measures, filters, chart type, limit, sort order, and visualization settings in a `BIVisualizationNode`. The wrapper contains the worksheet configuration and a plain `HogQLQuery` source. Saving keeps the worksheet in the BI editor; dashboard tiles can still use the normal insight view. **Edit** reopens Business intelligence when the feature is enabled, including from a dashboard. Leaving a worksheet with unsaved edits asks for confirmation, including when returning to **Worksheets**. **Discard changes** restores the saved worksheet. **Save as SQL view** exports only the generated SQL to a warehouse view; save a worksheet to retain editable worksheet state.
Older saves containing only SQL still open in the SQL editor. Their original shelves cannot be reconstructed without the worksheet configuration from a draft or shared URL.
@@ -62,7 +64,7 @@ The **Analysis** card ranks **Top N** categories by a selected measure across th
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.
-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. 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.
+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.
@@ -93,6 +95,12 @@ part, or custom SQL condition, or to remove the filter. Filter changes respect t
auto-update setting and are preserved with its saved configuration.
Numeric filters preserve the precision of entered values. Invalid numbers show an error and prevent the worksheet from running until corrected or disabled.
+**Row filters** apply before aggregation. **Result filters** apply to aggregated measures, calculated measures, and table calculations after they run, before sorting and the final row limit. For example, add result filters for revenue greater than 1,000 and purchase count at least five. Each filter can be disabled without removing it. Removing a measure removes its result filters; the remaining filters keep their measure assignments. If a filter or Top N uses the default Count, adding another measure keeps Count on the worksheet so that condition keeps its target.
+
+Both cards have **AND / OR groups**. Choose **AND (match all)** or **OR (match any)**, add nested groups, and move existing filters into them. Empty groups have no effect. Ungroup moves its conditions and nested groups into the immediate parent group. Existing worksheets retain their flat AND conditions. Date ranges and dashboard filters always combine with worksheet row conditions using AND; drill-down selections do too.
+
+Top N selects categories before result filters run. Comparison periods apply the same result conditions independently. Result filters hide detail groups; totals still aggregate all data matching the row filters. Table calculations use the full aggregated result before result filtering. Query usage events include result-filter and group counts without their values.
+
## Apple Ads in Marketing analytics
Marketing analytics support is controlled by the boolean organization flag `marketing-analytics-apple-ads` and is off by default.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3646ac8fdf4e..e08aa80d7fcd 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6390,6 +6390,10 @@ snapshots:
hash: v1.k794b7964.47dc280e27c512035ac74d86134e2b5771f84b1454556c492f6319d9d3ffa29f.l0n9noDhYfjTrpN-tlvi5TJq4RJCDIkUCFKse51o1O4
products-autoresearch-probability-histogram--single-bucket--light:
hash: v1.k794b7964.492095448990e600a399d4212b8fb96e8f95c2e7bdafb3f84d8bdc10467fbf4e.1OfZFFoGzmeH8sxtbwrD-H9bR_n08l9kV63NB2Sv1jU
+ products-business-intelligence-worksheets--worksheets--dark:
+ hash: v1.k794b7964.07d353f8f721fee4df50f532e578c185cb89a6e61838a84828b5d6aa8d074933.Vug8TcMYcUt4yrU-GMl8VkVhxa2sYMsjdHIOs3XbW6Q
+ products-business-intelligence-worksheets--worksheets--light:
+ hash: v1.k794b7964.e90e46bb924e56d9c070a598383f0921ea8228a4c0e496f5c74f48786f573f20.YO56ekCK2pncH_qlfkRjVVKdEKYu0mNRGsaCMxFCBu4
products-dashboards--dashboard-states--dark:
hash: v1.k794b7964.cc591635f83447f7bcfb802062302b8b1bbcd51826110b12fa0f68d4830dcfd3.CIgt_KxCyQRgbn7DPF4MDXc5JBlSxbaCPS0Snyx3cRs
products-dashboards--dashboard-states--light:
@@ -9615,65 +9619,65 @@ snapshots:
scenes-app-data-warehouse-settings-schemas--multi-schema--light:
hash: v1.k794b7964.2f4bd6098d8c54c0b25ed9ee0ef7770a59c4d343191d065b0814299a27a42a22.6jWN3F1ozzMy7KZRTYHY1XPxasFL_u2H8Ybw9WcDjfk
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--dark:
- hash: v1.k794b7964.7c3ba7dcba4d146dcd981b53037f3912d6af86308e5e1adc22a8729a25bcb00d.KfK0rjNQs1Mq4ycTPoMmd69Af-K_70f91oM-rj2yR2M
+ hash: v1.k794b7964.1c0c14cdee7bfc208f3463612a7258ffb18eab85743802b57a550056c4f13063.ubWAo_M3qsL1pI4N1wkAao5VS5nYOPWSeYNpS_lk0G4
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
- hash: v1.k794b7964.91a5ebb4db27dd9ec682f7ecf99ab0fa62f3c7c9c62c1f29dc90896413bf7ced.6QZ4OSvFzyH_FRA43WISTYI1HDdHaw9VGkm06ryuc_g
+ hash: v1.k794b7964.269c7d97582f9c850fb1a04b18ff407237c23197f1b3bf5c1943f46a1fd15802.tcOzXErjnX_icjhtqI84VAAkHnsarpFsVbe2_nt1eao
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
- hash: v1.k794b7964.3a38920408bdcad54bb67ccadc35a6fc89b2fe516b4339ffbb63f317aac2f5a1.u2bU-Axy4V9EsASdg2T5-LqqP6YEBdJSNSk2me6JMzc
+ hash: v1.k794b7964.45c0fd56c6b085e1a229c0dfd35a4e25462d2a75149b7532d040e31b30ddab0b.qPhdMdfKxNPosoOCX3wJ_Vm_CQuGVbOGktCSowg9Mu4
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
- hash: v1.k794b7964.557db2126160c0ba498af0b74177bfbee43479502bb025ee0d32b921dd805bcd.TNR2t8RdGAGKaNmQowUYWEOyoQcpRxvoc7PVO5Fqclo
+ hash: v1.k794b7964.26487b780e4c42f39ad7c3cfbbfb492c1c72c40b65143b0dcab9afe4e98aad02.Xp41xep3O_h5SgMD_bAwFWNDAljTfr6fS2h5PJPIEOc
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.3714f8c3a28ac56d7380305dc16ea9a42cf5bb250d2ecd44e0ee7e202f19bb39.Zm_9lhFlLiIfMR2ErOrduQnvQmORXpT2IBXo_ovo5nk
+ hash: v1.k794b7964.30fa64956a72d0e5ad04915a689ab4ae2f28033b1ccf2ed64aba828fdf72376e.OK5R-iy-rRpBfuvZMttjS35Mk9xbsw2k1lohMWcdPoo
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.1935edcfcf29d34595696392fd4978b775b6eaf66fb5dcb734df808591a2c593.y57z1-4L6Tt62192ZikMwh9oHmGvTtiAQoJcA_W_VPo
+ hash: v1.k794b7964.e94d9579f06adc1ce94daa983313f3ad61d31d719eac7ea7c7e98f464eda46df.OM_zpS2uSuzdRWdOeIunASj-usUdZ2nGj70neegODjI
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.ddda7e3729ba2d0ba078ceceee1e8ef44308224557dd3bd2ac4883c3454c6800.NFaSC9E62GVTwg1gtlF-F_pTLx5JnxIqFn-8bkRDLc4
+ hash: v1.k794b7964.6f2e46f7552afbb1f0bda49cc6e4535b7257635b4695e38fe437f690dde859a5.GQzEq7sbnYcMbGLMI7caHm8JAfVwXQdbc4-gdpT6gOo
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.1583664cd6af59ea5d5f9278c943991856499b8362566f856e26ac3f8d344f90.YTsTB6R6yQBWYh89IBP_k5i58-89BUe5p6JWzhCaxjU
+ hash: v1.k794b7964.a12e98f924a33220030ff2b509f3fe1d5ce2069393d8a6171ac26850e6a3d11f.4OuGkRNpmwzAOpGJtR5XMML4RBS4023RYjt0YA2Ou9M
scenes-app-data-warehouse-sql-editor--bi-drilldown--dark:
- hash: v1.k794b7964.998cdecacb01c35e5707e5c3613da920fa045de78720f4f56473f25d05c899b4.DPaHE2T5QLyltGIWjg4V_xL9eXzIsvHpzSHkSaz23bE
+ hash: v1.k794b7964.182a98228bfd31547d3da94736c9f4edd46bcf2df159f7b2f205366e1b2861bb.lTR1rIlnk0Fv3y7XjHRI-bvfL6Z7C2O5t3h3pl9yG5A
scenes-app-data-warehouse-sql-editor--bi-drilldown--light:
- hash: v1.k794b7964.62e7e289747afb5cc8b29c93abe8bf1deb46d2f82a2b23ab7623395cbdc848fc.NkSleFNd-9Nnu9YQ922yfr5GuIz_5H6coq3Q9bweFNU
+ hash: v1.k794b7964.7c6a504d11a8b8ac5b6520d91e4ba717f8b3cd06a954d63009cd190aba5b81e3.j-8gZpi8prOIMMRnYxkxe4NJV8IujxqYLRUuENWtj4Q
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.2d718ad3e78bc2d0f1bbc83351522d5b55036a9fa1073fe6a5a8ca1bfe8e65e9.KU5IvJLSvc0J-4bXkCemSuxmC2mssmt7Vteqa95s4Ck
+ hash: v1.k794b7964.75a1949bbd8748f00d23ddc008119f02da05aa706e249e0de22f52d190573e5d.EEZrbUJMBV-O_uYt1lTdXS46E18VXwX_BRanLkK4wVE
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.f7f333660f184f6fcdd924fcb44658b15fe395cfb9dac95dc9ef3283cfb5b868.1rCp3Jopv0g8mLCB0iF2BBEPQT90mnAq1_362nfWm0I
+ hash: v1.k794b7964.8a0b77f15ee41eaafd7bd02c480186da594ce65030444d7a4789ef5f63310902.TV_DYJ0uCn9pghwZig4ljMlapMFTgCr3Tdynfwq0TFY
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
- hash: v1.k794b7964.e0fb976b6bdfbf27f6e09b3ed3e3fabedd76e45108bf36788ad1e66936e2a033.GKUlNn5vh22nWqslSOm4yf__RxLpH7LP0fzi4RA1w3w
+ hash: v1.k794b7964.02b2c5ef535309fbabbc662d0a18c0aa63186b35a5b2b66d141f0a238d5f11ab.Wkl7IYUP_AQq3I5eRVBzl8fDMvmDEYE6oa9q_iF2_Xc
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
- hash: v1.k794b7964.edd4895cf4b6cb5ceeaaf2758f77e5ea28d09adae19900964290ee2a99b05032.bsJ7Ve5ShLuTbpTgC6jg-H-Vy_XnHDidWzpYVZjoETY
+ hash: v1.k794b7964.a617727cf00b1a3e9eadc5e327bc51685aa1fece1f3347fa2f3213d433214805.9IY8Hk8zebtKx6bbkP56iIQ0MgU3rEu3wihYVovPBfE
scenes-app-data-warehouse-sql-editor--bi-measure-display--dark:
- hash: v1.k794b7964.a1221958b54ce4c01db587fcebaaa881afc48770e7ea7296ae541e6fbc92ddb6.RlaaoGK24OkRQgxMFHNUGVNHIBkjyuJG3Q-PDm5O_P0
+ hash: v1.k794b7964.9e0d3533dd5ae0783cc0420475e78e5fe5f87d47a43d6630524882ef9a9f77f7.uf0QFgT2W9wcED0qCCDISHHTYTX--hklwiBQTkyPLpo
scenes-app-data-warehouse-sql-editor--bi-measure-display--light:
- hash: v1.k794b7964.be079b47569b27bdaf21d949cf933cf4b928b98445c42f122c7037f73a589289.oW2_9vZ_t3wsfLDmumhINHXqdX3_eyR0Ii_qrLzsCpg
+ hash: v1.k794b7964.c50185dcf01dc16647795157545a16269ea79403bd04fc6b63d86d2e9991fd12.6C4Pz3LIrHUbp1LbYcRE2vN_HJjikyQQeonijKS2o1A
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
- hash: v1.k794b7964.688f7e5c279a8c76d6ad80a838fe53ebb72218b81d9dfbd9980f91f776c60add.1ZzBchGNvUZLZcDhGxpG2DUcotfx7r0Rtrk0jht_P_4
+ hash: v1.k794b7964.1465b53318ebd4ee942d581040704a8ddeb4de51ffde9e97156d522a687eb6f3.BdVfCS9JBCZ9M6vpFXcgP8Pt8QypLoWlxasjCUiuESo
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
- hash: v1.k794b7964.e46291bba4fa9213504d21faaf854274fa649e5392bbeb804a92ab0a001c0fae.viUWEK4Z-FTHCCMx6dga9gR-P4BsbJxIm4I8MHFOyds
+ hash: v1.k794b7964.0510cf589eabe8a04dde3c7d79c8f00aa4d955a90e7fcf98fc1064eb3beb56c7.yRTPbMpWSZqepxgtBV2EKACf9uxXwaK-KmNLop0ohCc
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
- hash: v1.k794b7964.a8dbe9e2e507ec626b4ff1f18850a01b015be95b62349fa9a6fe2a1b02153980.A0D-4fqdTvQmxbO_kCbKFUu-8UaWiX-ak_rCDRAdAWc
+ hash: v1.k794b7964.9dc96eb2daf79469feaca37095206831653772abcbc11dbc2b379ef8217dfe2b.LwIwT2PobleBmqlU_x5mAnmqG5Ss9JzkAALIuGaZzLo
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
- hash: v1.k794b7964.3d945861e6339b230514c51d4b2549566dfe8fa2dd2678d4e7020b9247a560e2.qDrXX6M4_NFq_J7VgYVhI6eD1JEX6F9FxcSGuUn_zYc
+ hash: v1.k794b7964.a236e635d84b889d4434aef46e1d62e88a44ec69b3f7dce7677a609889acb37b.qMwKzI_jQgHg_LDcHYkz_FvhLJpQEJ5lvcOoYPpC1vo
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--dark:
- hash: v1.k794b7964.29e47b8081a660e650626e9dc164677155090196ae93929016ae66cf7215c610.v0jpdqnGmckkHt3lvvWX_lC-obgLb_ZgotyRK0lTi-o
+ hash: v1.k794b7964.b5d8a1e1bb51f906561c748473e1154a390aaac2528c78c9aa52231fe731f450.t5sCvzOO_DUpmrH9_xzf7iaWx4XEVfQmYwWg99U7Ctk
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--light:
- hash: v1.k794b7964.96af9d53d6dd518a415ac307418a686cbdf812e5a5e9a24e7e102021a82deec1.583jNzqlQwpVJxk6Z0mXWKph56LiFaUEjqldejQDbjU
+ hash: v1.k794b7964.cc07ceb5b769532f3d5308b04b517117ccca28af33bacf5099c408d878c7d975.p4TeTt9FkKRTBK9GRmMWC_I9JUHAnLVr0r0o9SlG77c
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.0e4b7a9bdc45c165ec3268d806e77a450d52782294ad6503755b10e133260709.4DZQHapDrToWMcNfdkOSoX_fbd5xtqTo2TRFTzUl0MU
+ hash: v1.k794b7964.35e0d26ddb61c938132c00f550654180f9d66c7e6455cb12de6ce6ff553149d1.JdzMNnT9WMC96ulinxtMP0iIresbveLSSXw4okvzvI8
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.c481fb25f29c59e61a2cdbeeaed552dd9e43111247eea0e60280fd648065a1fc.E5xy4FSrXniwK-fOFRWjNty-r-ty4OEYbC1wFnhzaBs
+ hash: v1.k794b7964.dddc2df920032cab6abdb3bbb4aef0b6b13b35f02ddd5175d5caa27598f70ae4.ygQ4_htltBtYmRMCT11MV4kn6B8-gnnRzxqgNr8q-ew
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.06c1b8aa2a1d5a7ee7cc9175280da635552884f8337d47c4ad8e78cdf5dc5d60.wwx8fbd3OYzMNuewloPd5guoMw2BXj2otqGzoHDyo8E
+ hash: v1.k794b7964.9590f61c158e618f53c3dc02d81ec8bef1e3b2aa3174b8a508753d70fb887bce.DFSx0W35zC94NC4jIuTaEaZKVAw3nQEyBfVGv9QbGOs
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.759dd0ef5d49d64bd54fb44db6ad4a3ac98382899d8d1a6040fda5806f127046.p2EBmtbQy4RIEWVzIY2EwiILDHNkl709wXqywY4iKJ8
+ hash: v1.k794b7964.269778fa1ecd6129869d4386ba170f0ef864a465a38869a08167aa33823b2bb2.kURs3yUf_yw4EpuyE584CyppEsK-yvo0nqxtK_BlzDE
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.24b439b90164ae7db044155845ca7672d56a4cba3114d585495e5dda13f24767.wjZpVrMTZpKpD3Ih75kZd7Q0gbrlPNB-GP22OYGTzZE
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
hash: v1.k794b7964.a81476825e10522264b1bc91fdd971de2742ac5a58336132a16c5783d3341fb1.7U0EUeE-WqdHuHI4EedMwFE35R94newfE_FFgsD3Do4
scenes-app-data-warehouse-sql-editor--bi-table-analysis--dark:
- hash: v1.k794b7964.d1eb6fb0097797be8f429fa327832d256c81e228346a0aa9b179c252aaf503bd.zSgex6hIhmVM0_wh_N96Q5O6df2PD132hnhf_xDS4yM
+ hash: v1.k794b7964.49f5669675851052d30b2593306b0c3daa4b91c4d7132bb399a41aeb42369a38.5bbHWSZ3xiH0DyKrViYMZnUVGKyKyJEpMMFhixZFe88
scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
- hash: v1.k794b7964.fd08e546d9b39a9f171ea7758a53f432d37f75aed10eee8fb306ae5a3ce45772.ioSY6nkFkuP7ng47uTC2GaiZPZr77iltYBtGs5Rhp9M
+ hash: v1.k794b7964.e2ec7aa57a315f6031b34577a2b91eed39577a1b433a5dae7c0680bb1ea664ef.lIPQ12OAA_CzHjaNfMPn_L23loJ9zDE0y9ihzu4e9WE
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/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
index c8f5fded140e..adecedffd3ad 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
@@ -535,7 +535,7 @@ export const ProductIconWrapper = ({ type, children, colorOverride }: ProductIco
export function getFileSystemIconType(item: Pick<FileSystemEntry, 'type' | 'meta'>): FileSystemIconType | undefined {
if (item.type === 'insight' && typeof item.meta?.insight_type === 'string') {
const insightIconType = `insight/${item.meta.insight_type}` as FileSystemIconType
- if (insightIconType in iconTypes) {
+ if (insightIconType in iconTypes || insightIconType in fileSystemTypes) {
return insightIconType
}
}
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index e9adf6118e71..429a2baf9801 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -51,6 +51,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
Autoresearch: () => import('../../products/autoresearch/frontend/AutoresearchScene'),
AutoresearchNew: () => import('../../products/autoresearch/frontend/AutoresearchNewScene'),
AutoresearchPipeline: () => import('../../products/autoresearch/frontend/AutoresearchPipelineScene'),
+ BusinessIntelligenceHome: () => import('../../products/business_intelligence/frontend/BIWorksheetsScene'),
BusinessIntelligence: () => import('../../products/business_intelligence/frontend/BusinessIntelligenceScene'),
BusinessKnowledge: () => import('../../products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene'),
BusinessKnowledgePlayground: () =>
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 1e7c0bbb84d0..1845f2c0c03c 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -113,7 +113,9 @@ export const productRoutes: Record<string, [string, string]> = {
'/autoresearch': ['Autoresearch', 'autoresearch'],
'/autoresearch/new': ['AutoresearchNew', 'autoresearchNew'],
'/autoresearch/:id': ['AutoresearchPipeline', 'autoresearchPipeline'],
- '/bi': ['BusinessIntelligence', 'businessIntelligence'],
+ '/bi': ['BusinessIntelligenceHome', 'businessIntelligence'],
+ '/bi/new': ['BusinessIntelligence', 'businessIntelligenceNew'],
+ '/bi/:insightShortId': ['BusinessIntelligence', 'businessIntelligenceWorksheet'],
'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],
'/business-knowledge/settings': ['BusinessKnowledgeSettings', 'businessKnowledgeSettings'],
'/business-knowledge/playground': ['BusinessKnowledgePlayground', 'businessKnowledgePlayground'],
@@ -669,6 +671,7 @@ export const productConfiguration: Record<string, any> = {
},
AutoresearchNew: { name: 'New model', projectBased: true },
AutoresearchPipeline: { name: 'Autoresearch model', projectBased: true },
+ BusinessIntelligenceHome: { name: 'Worksheets', projectBased: true, iconType: 'business_intelligence' },
BusinessIntelligence: {
name: 'Business intelligence',
projectBased: true,
@@ -1320,6 +1323,8 @@ export const productUrls = {
autoresearch: (): string => '/autoresearch',
autoresearchNew: (): string => '/autoresearch/new',
autoresearchPipeline: (id: string): string => `/autoresearch/${id}`,
+ businessIntelligenceNew: (): string => '/bi/new',
+ businessIntelligenceWorksheet: (insightShortId: string): string => `/bi/${encodeURIComponent(insightShortId)}`,
businessIntelligence: ({
insightShortId,
viewId,
@@ -1918,6 +1923,13 @@ export const fileSystemTypes = {
iconColor: ['var(--color-product-product-analytics-light)'],
filterKey: 'insight',
},
+ 'insight/bi': {
+ name: 'Worksheet',
+ iconType: 'business_intelligence',
+ href: (ref: string) => urls.businessIntelligenceWorksheet(ref),
+ listHref: () => urls.businessIntelligence(),
+ filterKey: 'insight',
+ },
notebook: {
name: 'Notebook',
iconType: 'notebook',
@@ -2153,6 +2165,14 @@ export const getTreeItemsNew = (): FileSystemImport[] => [
iconType: 'survey',
iconColor: ['var(--color-product-surveys-light)'] as FileSystemIconColor,
},
+ {
+ path: 'Worksheet',
+ type: 'insight',
+ iconType: 'business_intelligence',
+ href: `${urls.businessIntelligenceNew()}#q=`,
+ flag: FEATURE_FLAGS.SQL_EDITOR_BI_MODE,
+ sceneKeys: ['BusinessIntelligence', 'BusinessIntelligenceHome'],
+ },
]
/** This const is auto-generated, as is the whole file */
@@ -2270,7 +2290,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
href: urls.businessIntelligence(),
flag: FEATURE_FLAGS.SQL_EDITOR_BI_MODE,
sceneKey: 'BusinessIntelligence',
- sceneKeys: ['BusinessIntelligence'],
+ sceneKeys: ['BusinessIntelligenceHome', 'BusinessIntelligence'],
},
{
path: 'Business knowledge',
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 7c44d455928e..3e3a661b3ae8 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6144,6 +6144,29 @@
"enum": ["count", "count_distinct", "sum", "average", "minimum", "maximum", "custom"],
"type": "string"
},
+ "BIConditionGroup": {
+ "additionalProperties": false,
+ "properties": {
+ "filters": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "groups": {
+ "items": {
+ "$ref": "#/definitions/BIConditionGroup"
+ },
+ "type": "array"
+ },
+ "operator": {
+ "enum": ["AND", "OR"],
+ "type": "string"
+ }
+ },
+ "required": ["operator", "filters", "groups"],
+ "type": "object"
+ },
"BIConfig": {
"additionalProperties": false,
"properties": {
@@ -6182,6 +6205,18 @@
"limit": {
"$ref": "#/definitions/BIQueryLimit"
},
+ "resultFilterGroup": {
+ "$ref": "#/definitions/BIConditionGroup"
+ },
+ "resultFilters": {
+ "items": {
+ "$ref": "#/definitions/BIResultFilter"
+ },
+ "type": "array"
+ },
+ "rowFilterGroup": {
+ "$ref": "#/definitions/BIConditionGroup"
+ },
"rows": {
"items": {
"$ref": "#/definitions/BIField"
@@ -6319,6 +6354,42 @@
"enum": [100, 1000, 10000, 50000],
"type": "number"
},
+ "BIResultFilter": {
+ "additionalProperties": false,
+ "properties": {
+ "enabled": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ },
+ "measureIndex": {
+ "$ref": "#/definitions/non_negative_integer"
+ },
+ "operator": {
+ "enum": [
+ "equals",
+ "not_equals",
+ "greater_than",
+ "less_than",
+ "greater_than_or_equal",
+ "less_than_or_equal",
+ "between",
+ "is_set",
+ "is_not_set"
+ ],
+ "type": "string"
+ },
+ "value": {
+ "type": "string"
+ },
+ "valueTo": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "measureIndex", "operator", "value"],
+ "type": "object"
+ },
"BISort": {
"additionalProperties": false,
"properties": {
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index 6a938a013e69..5d0b14ffa2d7 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -124,9 +124,36 @@ export interface BIConfig {
columns: BIField[]
values: BIValue[]
filters: BIFilter[]
+ rowFilterGroup?: BIConditionGroup
+ resultFilters?: BIResultFilter[]
+ resultFilterGroup?: BIConditionGroup
limit: BIQueryLimit
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISort | null
topN?: BITopN
totals?: BITotals
}
+
+export interface BIConditionGroup {
+ operator: 'AND' | 'OR'
+ filters: string[]
+ groups: BIConditionGroup[]
+}
+
+export interface BIResultFilter {
+ id: string
+ measureIndex: non_negative_integer
+ operator:
+ | 'equals'
+ | 'not_equals'
+ | 'greater_than'
+ | 'less_than'
+ | 'greater_than_or_equal'
+ | 'less_than_or_equal'
+ | 'between'
+ | 'is_set'
+ | 'is_not_set'
+ value: string
+ valueTo?: string
+ enabled?: boolean
+}
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
index 4d6b8034911a..586dec899a73 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
@@ -115,6 +115,7 @@ function insightsListParams(filters: SavedInsightFilters): Record<string, any> {
saved: true,
// PostHog no longer generates these, and the flag Usage tab still shows the same charts
hide_feature_flag_insights: true,
+ exclude_bi: true,
...(filters.favorited && { favorited: true }),
...(filters.search && { search: filters.search }),
...(filters.insightType?.toLowerCase() !== 'all types' && {
@@ -148,7 +149,15 @@ function insightsListParams(filters: SavedInsightFilters): Record<string, any> {
}
/** Params that scope, page, or sort the list rather than filter it. */
-const NON_NARROWING_PARAM_KEYS = ['order', 'limit', 'offset', 'saved', 'user', 'hide_feature_flag_insights']
+const NON_NARROWING_PARAM_KEYS = [
+ 'order',
+ 'limit',
+ 'offset',
+ 'saved',
+ 'user',
+ 'hide_feature_flag_insights',
+ 'exclude_bi',
+]
/**
* Whether any filter that narrows the insights list is active, i.e. the API request would carry a
diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.py
index a06b1f1399c7..cc8ef73153e1 100644
--- a/posthog/api/file_system/file_system.py
+++ b/posthog/api/file_system/file_system.py
@@ -637,7 +637,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if (entry_type, ref, team_id) in denied:
continue
insight_types[(team_id, ref)] = get_file_system_insight_type(
- nested_kind or source_kind or kind, legacy_type
+ "BI" if kind == "BIVisualizationNode" else nested_kind or source_kind or kind, legacy_type
)
if source_kind == "HogQLQuery":
content_types[(entry_type, team_id, ref)] = "application/sql"
@@ -650,6 +650,8 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
ref = str(item.get("ref"))
if item.get("type") == "insight":
metadata["insight_type"] = insight_types.get((team_id, ref))
+ if metadata["insight_type"] == "bi":
+ item["href"] = f"/bi/{ref}"
if include_content_type:
metadata["content_type"] = content_types.get((str(item["type"]), team_id, ref), "application/json")
item["meta"] = metadata
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index df9e13eaff80..9050313ef2db 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -150,13 +150,16 @@ class TestFileSystemAPI(APIBaseTest):
queries = [
{"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},
{"kind": "InsightVizNode", "source": {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery"}}},
+ {"kind": "BIVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},
None,
]
- for query, expected_type in zip(queries, ["hog", "hog", "paths"]):
+ for query, expected_type in zip(queries, ["hog", "hog", "bi", "paths"]):
Insight.objects.filter(team=self.team, pk=insight.pk).update(query=query, filters={"insight": "JOURNEYS"})
response = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"type": "insight"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["results"][0]["meta"]["insight_type"], expected_type)
+ if expected_type == "bi":
+ self.assertEqual(response.json()["results"][0]["href"], f"/bi/{insight.short_id}")
def test_list_rejects_invalid_content_type_parameter(self) -> None:
response = self.client.get(f"/api/projects/{self.team.id}/file_system/", {"include_content_type": "invalid"})
diff --git a/posthog/schema.py b/posthog/schema.py
index 3fda240c40a3..7d705863161b 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -219,6 +219,8 @@ from posthog.schema_enums import (
NodeKind as NodeKind,
OpenAIAdsDefaultSources as OpenAIAdsDefaultSources,
Operator as Operator,
+ Operator1 as Operator1,
+ Operator2 as Operator2,
OrderBy as OrderBy,
OrderDirection as OrderDirection,
OrderDirection1 as OrderDirection1,
@@ -945,6 +947,15 @@ class AssistantUpdateEvent(BaseModel):
tool_call_id: str
+class BIConditionGroup(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ filters: list[str]
+ groups: list[BIConditionGroup]
+ operator: Operator1
+
+
class BIDataSource(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -5012,6 +5023,18 @@ class BIFilter(BaseModel):
values: list[str] | None = None
+class BIResultFilter(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ enabled: bool | None = None
+ id: str
+ measureIndex: conint(ge=0)
+ operator: Operator2
+ value: str
+ valueTo: str | None = None
+
+
class BISort(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -11120,6 +11143,9 @@ class BIConfig(BaseModel):
dateRange: DateRange | None = None
filters: list[BIFilter]
limit: BIQueryLimit
+ resultFilterGroup: BIConditionGroup | None = None
+ resultFilters: list[BIResultFilter] | None = None
+ rowFilterGroup: BIConditionGroup | None = None
rows: list[BIField]
sort: BISort | None = Field(
default=None,
@@ -34451,6 +34477,7 @@ class VisualizationArtifactContent(BaseModel):
)
+BIConditionGroup.model_rebuild()
ProsemirrorJSONContent.model_rebuild()
PropertyGroupFilterValue.model_rebuild()
HumanMessage.model_rebuild()
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index c922c8d60d3c..7d4d64da4a41 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -631,6 +631,11 @@ class BIAggregation(StrEnum):
CUSTOM = "custom"
+class Operator1(StrEnum):
+ AND_ = "AND"
+ OR_ = "OR"
+
+
class BIDateBucket(StrEnum):
MINUTE = "minute"
HOUR = "hour"
@@ -663,6 +668,18 @@ class BIQueryLimit(float, Enum):
NUMBER_50000 = 50000
+class Operator2(StrEnum):
+ EQUALS = "equals"
+ NOT_EQUALS = "not_equals"
+ GREATER_THAN = "greater_than"
+ LESS_THAN = "less_than"
+ GREATER_THAN_OR_EQUAL = "greater_than_or_equal"
+ LESS_THAN_OR_EQUAL = "less_than_or_equal"
+ BETWEEN = "between"
+ IS_SET = "is_set"
+ IS_NOT_SET = "is_not_set"
+
+
class BISortDirection(StrEnum):
ASC = "asc"
DESC = "desc"
diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsx
index 853c68cc72cc..ed01ce13ddb0 100644
--- a/products/business_intelligence/frontend/BIDrilldownModal.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx
@@ -46,7 +46,9 @@ export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldow
}
disabledReason={
!queries.worksheet
- ? 'Open comparison-period rows below to explore their original dates'
+ ? selection?.previous
+ ? 'Open comparison-period rows below to explore their original dates'
+ : 'Maximum filter group depth reached. View the underlying rows instead.'
: undefined
}
>
diff --git a/products/business_intelligence/frontend/BIEditor.tsx b/products/business_intelligence/frontend/BIEditor.tsx
index 0ab61adf9f6a..7a6d2949bdb1 100644
--- a/products/business_intelligence/frontend/BIEditor.tsx
+++ b/products/business_intelligence/frontend/BIEditor.tsx
@@ -22,6 +22,7 @@ import { BIToolbar } from 'products/business_intelligence/frontend/components/BI
import { BIAnalysisControls } from './BIAnalysisControls'
import { BIMeasureSettingsModal } from './BIMeasureSettingsModal'
+import { BIResultFiltersCard } from './components/BIResultFiltersCard'
/**
* A worksheet laid out like desktop BI tools: data pane, filter and marks cards, rows and columns
@@ -92,6 +93,7 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
>
<div className="min-h-0 overflow-y-auto">
<BIFiltersCard />
+ <BIResultFiltersCard />
<BIMarksCard />
<BIAnalysisControls />
</div>
@@ -130,7 +132,7 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
<div className="hidden w-44 shrink-0 flex-col overflow-y-auto border-l bg-surface-primary @3xl/bi-editor:flex @6xl/bi-editor:w-80">
{config.filters.length > 0 && (
<section className="border-b p-2" aria-label="Quick filters">
- <h3 className="mb-2 text-xs font-semibold">Filters</h3>
+ <h3 className="mb-2 text-xs font-semibold">Row filters</h3>
<div className="grid grid-cols-1 items-start gap-x-2 gap-y-2 @6xl/bi-editor:grid-cols-2">
{config.filters.map((filter, index) => (
<BIFilterControl key={filter.field.id} index={index} />
diff --git a/products/business_intelligence/frontend/BIWorksheetsScene.stories.tsx b/products/business_intelligence/frontend/BIWorksheetsScene.stories.tsx
new file mode 100644
index 000000000000..04f35bbfae0c
--- /dev/null
+++ b/products/business_intelligence/frontend/BIWorksheetsScene.stories.tsx
@@ -0,0 +1,43 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+
+import { mswDecorator } from '~/mocks/browser'
+
+const meta: Meta = {
+ title: 'Products/Business intelligence/Worksheets',
+ component: App,
+ decorators: [mswDecorator({})],
+ parameters: {
+ layout: 'fullscreen',
+ pageUrl: '/bi',
+ featureFlags: [FEATURE_FLAGS.SQL_EDITOR_BI_MODE],
+ testOptions: { waitForSelector: '[data-attr="bi-worksheet-link"]' },
+ msw: {
+ mocks: {
+ get: {
+ '/api/projects/:team_id/insights/': {
+ count: 2,
+ results: [
+ {
+ id: 1,
+ short_id: 'revenue',
+ name: 'Revenue by country',
+ last_modified_at: '2026-01-01T12:00:00Z',
+ },
+ {
+ id: 2,
+ short_id: 'activity',
+ name: 'Weekly activity',
+ last_modified_at: '2026-01-01T10:00:00Z',
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+}
+export default meta
+export const Worksheets: StoryObj = {}
diff --git a/products/business_intelligence/frontend/BIWorksheetsScene.tsx b/products/business_intelligence/frontend/BIWorksheetsScene.tsx
new file mode 100644
index 000000000000..a3c576fe21c5
--- /dev/null
+++ b/products/business_intelligence/frontend/BIWorksheetsScene.tsx
@@ -0,0 +1,98 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlus } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonInput, LemonSegmentedButton, LemonTable, Link } from '@posthog/lemon-ui'
+
+import { NotFound } from 'lib/components/NotFound'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { biWorksheetsLogic } from './biWorksheetsLogic'
+
+export const scene: SceneExport = { component: BIWorksheetsScene, logic: biWorksheetsLogic }
+
+export function BIWorksheetsScene(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { worksheets, worksheetsLoading, search, page, recent, error } = useValues(biWorksheetsLogic)
+ const { setSearch, setPage, setRecent, loadWorksheets } = useActions(biWorksheetsLogic)
+ if (!featureFlags[FEATURE_FLAGS.SQL_EDITOR_BI_MODE]) {
+ return <NotFound object="page" />
+ }
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Worksheets"
+ description="Explore your data with visual worksheets."
+ resourceType={{ type: 'business_intelligence' }}
+ actions={
+ <LemonButton type="primary" icon={<IconPlus />} to={`${urls.businessIntelligenceNew()}#q=`}>
+ New worksheet
+ </LemonButton>
+ }
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput type="search" placeholder="Search worksheets" value={search} onChange={setSearch} />
+ <LemonSegmentedButton
+ value={recent ? 'recent' : 'all'}
+ onChange={(value) => setRecent(value === 'recent')}
+ options={[
+ { value: 'all', label: 'All worksheets' },
+ { value: 'recent', label: 'Recently viewed' },
+ ]}
+ />
+ </div>
+ {error ? (
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => loadWorksheets() }}>
+ Couldn't load worksheets.
+ </LemonBanner>
+ ) : (
+ <LemonTable
+ dataSource={worksheets?.results ?? []}
+ loading={worksheetsLoading}
+ rowKey="id"
+ emptyState={
+ search
+ ? 'No matching worksheets.'
+ : recent
+ ? 'No worksheets viewed in the last 30 days.'
+ : 'Create a worksheet to explore your data.'
+ }
+ columns={[
+ {
+ title: 'Name',
+ key: 'name',
+ render: (_, worksheet) => (
+ <Link
+ data-attr="bi-worksheet-link"
+ to={urls.businessIntelligenceWorksheet(worksheet.short_id)}
+ >
+ {worksheet.name || worksheet.derived_name || 'Untitled worksheet'}
+ </Link>
+ ),
+ },
+ {
+ title: recent ? 'Last viewed' : 'Last modified',
+ key: 'updated',
+ render: (_, worksheet) =>
+ dayjs(recent ? worksheet.last_viewed_at : worksheet.last_modified_at).fromNow(),
+ },
+ ]}
+ pagination={{
+ controlled: true,
+ currentPage: page,
+ pageSize: 50,
+ entryCount: worksheets?.count ?? 0,
+ onForward: () => setPage(page + 1),
+ onBackward: () => setPage(page - 1),
+ }}
+ />
+ )}
+ </SceneContent>
+ )
+}
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
index 3fb176dfc173..195b800269b4 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
@@ -6,9 +6,11 @@ import { LemonBanner, LemonButton, LemonInput, LemonModal, Spinner } from '@post
import { AccessDenied } from 'lib/components/AccessDenied'
import { NotFound } from 'lib/components/NotFound'
import { FEATURE_FLAGS } from 'lib/constants'
+import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { userHasAccess } from 'lib/utils/accessControlUtils'
import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { Query } from '~/queries/Query/Query'
import { isDataVisualizationNode } from '~/queries/utils'
@@ -38,6 +40,9 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
exportViewOpen,
exportViewName,
exportedViewLoading,
+ canUndo,
+ canRedo,
+ copyDisabledReason,
} = useValues(logic)
const {
setName,
@@ -48,8 +53,22 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
setExportViewOpen,
setExportViewName,
exportView,
+ undo,
+ redo,
} = useActions(logic)
+ useKeyboardHotkeys({
+ z: {
+ willHandleEvent: true,
+ action: (event) => {
+ if ((event.metaKey || event.ctrlKey) && !event.altKey && (event.shiftKey ? canRedo : canUndo)) {
+ event.preventDefault()
+ event.shiftKey ? redo() : undo()
+ }
+ },
+ },
+ })
+
if (!featureFlags[FEATURE_FLAGS.SQL_EDITOR_BI_MODE]) {
return <NotFound object="page" />
}
@@ -64,6 +83,9 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
<BindLogic logic={biSceneLogic} props={{ tabId }}>
<div className="flex h-full min-h-0 flex-col" data-attr="bi-worksheet">
<header className="flex flex-wrap items-center gap-2 border-b px-3 py-2">
+ <LemonButton size="small" to={urls.businessIntelligence()}>
+ Worksheets
+ </LemonButton>
<LemonInput
aria-label="Worksheet name"
value={name}
@@ -71,6 +93,21 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
maxLength={400}
className="min-w-40 flex-1"
/>
+ <LemonButton size="small" onClick={undo} disabledReason={!canUndo ? 'Nothing to undo' : undefined}>
+ Undo
+ </LemonButton>
+ <LemonButton size="small" onClick={redo} disabledReason={!canRedo ? 'Nothing to redo' : undefined}>
+ Redo
+ </LemonButton>
+ <LemonButton
+ size="small"
+ onClick={() => saveInsight({ asCopy: true })}
+ loading={insightLoading}
+ disabledReason={copyDisabledReason}
+ data-attr="bi-save-copy"
+ >
+ Save a copy
+ </LemonButton>
<LemonButton
size="small"
icon={<IconShare />}
@@ -103,7 +140,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
<LemonButton
type="primary"
size="small"
- onClick={saveInsight}
+ onClick={() => saveInsight()}
loading={insightLoading}
disabledReason={saveDisabledReason}
data-attr="bi-save-insight"
diff --git a/products/business_intelligence/frontend/biAnalysis.test.ts b/products/business_intelligence/frontend/biAnalysis.test.ts
index d4ac1e03b167..3ca1e259c5c1 100644
--- a/products/business_intelligence/frontend/biAnalysis.test.ts
+++ b/products/business_intelligence/frontend/biAnalysis.test.ts
@@ -20,6 +20,79 @@ const config: BIConfig = {
}
describe('BI analysis queries', () => {
+ it.each([false, true])(
+ 'filters aggregated and calculated results before the final limit (comparison: %s)',
+ (compare) => {
+ const worksheet: BIConfig = {
+ ...config,
+ dateRange: { date_from: '-7d' },
+ compareFilter: { compare },
+ values: [
+ config.values[0],
+ { field: field('event'), aggregation: 'count' },
+ {
+ field: field('calculation', 'float'),
+ aggregation: 'custom',
+ customExpression: 'sum(properties.amount) / count(*)',
+ label: 'Revenue per purchase',
+ tableCalculation: { type: 'running_total' },
+ },
+ ],
+ resultFilters: [
+ { id: 'revenue', measureIndex: 0, operator: 'greater_than', value: '1000' },
+ { id: 'purchases', measureIndex: 1, operator: 'greater_than_or_equal', value: '5' },
+ { id: 'calculation', measureIndex: 2, operator: 'between', value: '20', valueTo: '100' },
+ ],
+ resultFilterGroup: {
+ operator: 'AND',
+ filters: ['revenue'],
+ groups: [{ operator: 'OR', filters: ['purchases', 'calculation'], groups: [] }],
+ },
+ }
+ const parsed = parseBIEditorState(BIEditorView.BI, worksheet)!.config
+ expect(parsed.resultFilters).toEqual(worksheet.resultFilters)
+ expect(parsed.resultFilterGroup).toEqual(worksheet.resultFilterGroup)
+ const query = buildBIQuery(parsed)!.query
+ expect(query).toContain('sum_properties_amount > 1000')
+ expect(query).toContain('count_event_2 >= 5')
+ expect(query).toContain('"Revenue per purchase_3" >= 20 AND "Revenue per purchase_3" <= 100')
+ expect(query).toMatch(/bi_filtered AS \(SELECT \* FROM bi_calculated WHERE .* AND .* OR /)
+ expect(query).toContain('OVER (PARTITION BY bi_column_event')
+ expect(query.match(/LIMIT/g)).toHaveLength(1)
+ expect(query.indexOf('bi_filtered AS')).toBeGreaterThan(query.indexOf('bi_calculated AS'))
+ expect(query.endsWith('LIMIT 1000')).toBe(true)
+ if (compare) {
+ expect(query).toContain('FROM bi_previous')
+ expect(query).toContain('UNION ALL')
+ }
+ }
+ )
+
+ it.each(['1 OR 1=1', 'Infinity', '1; DROP TABLE events', '1e999'])(
+ 'rejects invalid result values instead of interpolating them: %s',
+ (value) => {
+ const worksheet: BIConfig = {
+ ...config,
+ resultFilters: [{ id: 'measure', measureIndex: 0, operator: 'greater_than', value }],
+ }
+ expect(buildBIQuery(worksheet)).toBeNull()
+ expect(
+ buildBIQuery({ ...worksheet, resultFilters: [{ ...worksheet.resultFilters![0], enabled: false }] })
+ ).not.toBeNull()
+ }
+ )
+
+ it('keeps totals independent of result filters and filters before reserving the summary row budget', () => {
+ const query = buildBIQuery({
+ ...config,
+ chartType: ChartDisplayType.ActionsTable,
+ totals: { rows: true },
+ resultFilters: [{ id: 'measure', measureIndex: 0, operator: 'greater_than', value: '100' }],
+ })!.query
+ expect(query).toContain('FROM bi_calculated WHERE bi_grouping != 0 OR ((sum_properties_amount > 100))')
+ expect(query).toContain('AS bi_rank FROM bi_filtered)')
+ })
+
it.each(BI_TABLE_CALCULATIONS)('persists and calculates $value before limiting results', ({ value: type }) => {
const worksheet: BIConfig = {
...config,
diff --git a/products/business_intelligence/frontend/biAnalysis.ts b/products/business_intelligence/frontend/biAnalysis.ts
index 0a3c215adffd..8efcb456d040 100644
--- a/products/business_intelligence/frontend/biAnalysis.ts
+++ b/products/business_intelligence/frontend/biAnalysis.ts
@@ -69,6 +69,7 @@ export interface BIAnalysisInput {
where: string
orderBy: string | null
resultLimit?: number
+ resultWhere?: string | null
previousWhere?: string
previousDimensions?: string[]
}
@@ -76,6 +77,7 @@ export interface BIAnalysisInput {
export function hasBIAnalysis(config: BIConfig): boolean {
return (
!!config.topN ||
+ !!config.resultFilters?.length ||
config.values.some((value) => !!value.tableCalculation) ||
!!(config.totals?.rows || config.totals?.columns || config.totals?.subtotals)
)
@@ -203,6 +205,12 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
const periodQuery = (previous: boolean): string =>
`SELECT ${[...aliases, ...calculations, ...(totals ? ['bi_grouping', ...groupingFlags] : []), ...(input.previousWhere ? [`${escapeHogQLString(previous ? comparisonLabel : 'Current period')} AS bi_period`] : [])].join(', ')} FROM bi_${previous ? 'previous' : 'current'}`
ctes.push(`bi_calculated AS (${periods.map(periodQuery).join(' UNION ALL ')})`)
+ const results = input.resultWhere ? 'bi_filtered' : 'bi_calculated'
+ if (input.resultWhere) {
+ ctes.push(
+ `bi_filtered AS (SELECT * FROM bi_calculated WHERE ${totals ? 'bi_grouping != 0 OR ' : ''}(${input.resultWhere}))`
+ )
+ }
const displayedDimension = (dimension: BIAnalysisDimension, index: number): string => {
let expression = dimension.alias
if (dimension === topDimension && config.topN?.includeOther) {
@@ -249,7 +257,7 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
if (totals) {
// Reserve at least half the result budget for detail cells when summaries alone exceed it.
ctes.push(
- `bi_ranked AS (SELECT *, row_number() OVER (PARTITION BY bi_grouping = 0 ORDER BY bi_grouping DESC${order ? `, ${order}` : ''}) AS bi_rank FROM bi_calculated)`
+ `bi_ranked AS (SELECT *, row_number() OVER (PARTITION BY bi_grouping = 0 ORDER BY bi_grouping DESC${order ? `, ${order}` : ''}) AS bi_rank FROM ${results})`
)
}
for (const { alias } of dimensions) {
@@ -258,5 +266,5 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
break
}
}
- return `WITH ${ctes.join(',\n')}\nSELECT ${select.join(', ')} FROM ${totals ? 'bi_ranked' : 'bi_calculated'} AS bi_result${totals ? ` WHERE bi_grouping = 0 OR bi_rank <= ${Math.floor(config.limit / 2)}` : ''}${totals || order ? ` ORDER BY ${[...(totals ? ['bi_grouping DESC'] : []), ...(order ? [order] : [])].join(', ')}` : ''} LIMIT ${input.resultLimit ?? config.limit}`
+ return `WITH ${ctes.join(',\n')}\nSELECT ${select.join(', ')} FROM ${totals ? 'bi_ranked' : results} AS bi_result${totals ? ` WHERE bi_grouping = 0 OR bi_rank <= ${Math.floor(config.limit / 2)}` : ''}${totals || order ? ` ORDER BY ${[...(totals ? ['bi_grouping DESC'] : []), ...(order ? [order] : [])].join(', ')}` : ''} LIMIT ${input.resultLimit ?? config.limit}`
}
diff --git a/products/business_intelligence/frontend/biDrilldown.test.ts b/products/business_intelligence/frontend/biDrilldown.test.ts
index fe7a12491542..20503cf827e7 100644
--- a/products/business_intelligence/frontend/biDrilldown.test.ts
+++ b/products/business_intelligence/frontend/biDrilldown.test.ts
@@ -1,9 +1,9 @@
-import { BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { BIConditionGroup, BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
import { NodeKind } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
import { getBIChartRecord, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'
-import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { BIEditorView, buildBIQuery, DEFAULT_BI_CONFIG, parseBIEditorState } from './biEditorTypes'
const field = (name: string, type: BIField['type'] = 'string'): BIField => ({
id: name,
@@ -28,6 +28,60 @@ function buildWorksheet(config: BIConfig): { node: BIVisualizationNode } {
}
describe('BI drill-down', () => {
+ it('keeps grouped filters loadable across repeated drill-downs', () => {
+ let node = buildWorksheet({
+ ...config,
+ rowFilterGroup: { operator: 'OR', filters: config.filters.map((filter) => filter.field.id), groups: [] },
+ }).node
+ for (let index = 0; index < 10; index++) {
+ const selection = getBIDrillSelection(node.config, { bi_column_event: 'purchase' })
+ const queries = getBIDrillQueries(node, selection)!
+ expect(queries.worksheet).not.toBeNull()
+ node = queries.worksheet!
+ expect(parseBIEditorState(BIEditorView.BI, node.config)).not.toBeNull()
+ expect(node.config.filters).toHaveLength(config.filters.length + index + 1)
+ expect(queries.rows.source.query).toContain("properties.environment = 'production'")
+ expect(queries.rows.source.query).toContain("event = 'purchase'")
+ }
+ })
+
+ it.each(['AND', 'OR'] as const)('preserves rows at the group depth limit (root: %s)', (operator) => {
+ let group: BIConditionGroup = {
+ operator,
+ filters: config.filters.map((filter) => filter.field.id),
+ groups: [],
+ }
+ for (let index = 0; index < 8; index++) {
+ group = { operator: group.operator === 'AND' ? 'OR' : 'AND', filters: [], groups: [group] }
+ }
+ const node = buildWorksheet({ ...config, rowFilterGroup: group }).node
+ expect(parseBIEditorState(BIEditorView.BI, node.config)).not.toBeNull()
+ const selection = getBIDrillSelection(node.config, { bi_column_event: 'purchase' })
+ const queries = getBIDrillQueries(node, selection)!
+ expect(queries.rows.source.query).toContain("properties.environment = 'production'")
+ expect(queries.rows.source.query).toContain("event = 'purchase'")
+ if (operator === 'AND') {
+ expect(queries.worksheet).not.toBeNull()
+ expect(parseBIEditorState(BIEditorView.BI, queries.worksheet!.config)).not.toBeNull()
+ } else {
+ expect(queries.worksheet).toBeNull()
+ }
+ })
+
+ it('combines an OR group with the selected cell using AND', () => {
+ const grouped: BIConfig = {
+ ...config,
+ filters: [...config.filters, { field: field('event'), operator: 'equals', value: 'purchase' }],
+ rowFilterGroup: { operator: 'OR', filters: config.filters.map((filter) => filter.field.id), groups: [] },
+ }
+ const selection = getBIDrillSelection(grouped, { bi_row_timestamp: '2026-06-01', bi_column_event: 'signup' })
+ const queries = getBIDrillQueries(buildWorksheet(grouped).node, selection)!
+ expect(queries.rows.source.query).toContain(
+ "AND ((properties.environment = 'production') OR (event = 'purchase'))"
+ )
+ expect(queries.rows.source.query).toContain("(event = 'signup') AND")
+ })
+
it('uses raw date and category values, escapes labels, and preserves effective dashboard filters', () => {
const node = buildWorksheet(config)!.node
node.source.variables = { variable: { variableId: 'variable', code_name: 'plan', value: 'starter' } }
diff --git a/products/business_intelligence/frontend/biDrilldown.ts b/products/business_intelligence/frontend/biDrilldown.ts
index ab8441cd7ac1..b38106d71f5b 100644
--- a/products/business_intelligence/frontend/biDrilldown.ts
+++ b/products/business_intelligence/frontend/biDrilldown.ts
@@ -19,6 +19,7 @@ import {
fieldExpression,
getBIResultDimensions,
} from './biEditorTypes'
+import { isBIConditionGroup, normalizeBIConditionGroup } from './biFilterGroups'
export interface BIDrillSelection {
filters: BIFilter[]
@@ -188,10 +189,34 @@ export function getBIDrillQueries(
if (!saved) {
return null
}
+ const selectionFilters = saved.rowFilterGroup
+ ? selection.filters.map((filter, index) => ({
+ ...filter,
+ field: { ...filter.field, id: `drill:${saved.filters.length + index}:${filter.field.id}` },
+ }))
+ : selection.filters
+ const existingGroup = saved.rowFilterGroup
+ ? normalizeBIConditionGroup(
+ saved.rowFilterGroup,
+ saved.filters.map((filter) => filter.field.id)
+ )
+ : undefined
const config: BIConfig = {
...saved,
dateRange: node.source.filters?.dateRange ?? saved.dateRange,
- filters: [...saved.filters, ...selection.filters],
+ filters: [...saved.filters, ...selectionFilters],
+ ...(existingGroup
+ ? {
+ rowFilterGroup: {
+ operator: 'AND' as const,
+ filters: [
+ ...selectionFilters.map((filter) => filter.field.id),
+ ...(existingGroup.operator === 'AND' ? existingGroup.filters : []),
+ ],
+ groups: existingGroup.operator === 'AND' ? existingGroup.groups : [existingGroup],
+ },
+ }
+ : {}),
topN: undefined,
}
const source = buildBIRowsQuery(config, selection.previous)
@@ -200,7 +225,10 @@ export function getBIDrillQueries(
}
source.filters = { ...source.filters, ...node.source.filters }
source.variables = node.source.variables
- const generated = selection.previous ? null : buildBIQuery(config)?.node
+ const generated =
+ selection.previous || (config.rowFilterGroup && !isBIConditionGroup(config.rowFilterGroup))
+ ? null
+ : buildBIQuery(config)?.node
const worksheet: BIVisualizationNode | null = generated
? { ...generated, kind: NodeKind.BIVisualizationNode, config }
: null
diff --git a/products/business_intelligence/frontend/biEditorAnalytics.ts b/products/business_intelligence/frontend/biEditorAnalytics.ts
index 2910861e78b8..653ce9b242a1 100644
--- a/products/business_intelligence/frontend/biEditorAnalytics.ts
+++ b/products/business_intelligence/frontend/biEditorAnalytics.ts
@@ -1,6 +1,6 @@
import posthog from 'posthog-js'
-import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+import { BIConditionGroup, BIConfig } from '~/queries/schema/schema-business-intelligence'
import { type BIEditorState, BIEditorView } from 'products/business_intelligence/frontend/biEditorTypes'
@@ -18,6 +18,10 @@ function uniqueSorted<T extends string>(values: T[]): T[] {
return [...new Set(values)].sort()
}
+function filterGroupCount(group: BIConditionGroup | undefined): number {
+ return group ? 1 + group.groups.reduce((count, child) => count + filterGroupCount(child), 0) : 0
+}
+
function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown> {
const fields = [
...config.rows,
@@ -31,6 +35,9 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
config.filters.filter((filter) => filter.operator === 'custom').length
return {
+ result_filter_count: config.resultFilters?.length ?? 0,
+ row_filter_group_count: filterGroupCount(config.rowFilterGroup),
+ result_filter_group_count: filterGroupCount(config.resultFilterGroup),
source_kind: config.source ? (config.source.connectionId ? 'external_connection' : 'project_data') : 'none',
chart_type: config.chartType,
row_count: config.rows.length,
@@ -73,6 +80,9 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
}
export type BIWorksheetAction =
+ | 'undo'
+ | 'redo'
+ | 'copied'
| 'opened'
| 'source_selected'
| 'first_chart'
diff --git a/products/business_intelligence/frontend/biEditorLogic.test.ts b/products/business_intelligence/frontend/biEditorLogic.test.ts
index b7e0aadddae2..9a0039d8fc17 100644
--- a/products/business_intelligence/frontend/biEditorLogic.test.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.test.ts
@@ -11,7 +11,7 @@ import { ChartDisplayType } from '~/types'
import { biConnectionsLogic } from './biConnectionsLogic'
import { biEditorLogic } from './biEditorLogic'
-import { BIEditorView, getBIFieldPillLabel } from './biEditorTypes'
+import { BIEditorView, buildBIQuery, getBIFieldPillLabel, parseBIEditorState } from './biEditorTypes'
describe('biEditorLogic', () => {
const TAB_ID = 'bi-test'
@@ -51,7 +51,7 @@ describe('biEditorLogic', () => {
limit: 1000,
sort: null,
}
- it.each([0, 1, 2])('keeps Top N attached to its measure when removing value %s', (index) => {
+ it.each([0, 1, 2])('keeps Top N and result filters attached to their measures when removing value %s', (index) => {
const logic = biEditorLogic({ tabId: TAB_ID })
logic.mount()
logic.actions.setAutoUpdate(false)
@@ -64,9 +64,21 @@ describe('biEditorLogic', () => {
aggregation: 'sum',
})),
topN: { fieldId: eventField.id, count: 5, measureIndex: 1, includeOther: false },
+ resultFilters: [0, 1, 2].map((measureIndex) => ({
+ id: `filter-${measureIndex}`,
+ measureIndex,
+ operator: 'greater_than',
+ value: '5',
+ })),
},
})
logic.actions.removeFieldFromShelf('values', index)
+ expect(logic.values.config.resultFilters).toHaveLength(2)
+ for (const filter of logic.values.config.resultFilters!) {
+ expect(logic.values.config.values[filter.measureIndex].field.id).toBe(
+ filter.id.replace('filter-', 'measure-')
+ )
+ }
if (index === 1) {
expect(logic.values.config.topN).toBeUndefined()
} else {
@@ -76,6 +88,47 @@ describe('biEditorLogic', () => {
logic.unmount()
})
+ it.each(['field', 'blank', 'calculation', 'move'] as const)(
+ 'preserves a Count result filter when adding the first measure via %s',
+ (method) => {
+ const logic = biEditorLogic({ tabId: TAB_ID })
+ logic.mount()
+ logic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: {
+ ...config,
+ chartType: ChartDisplayType.ActionsTable,
+ resultFilters: [{ id: 'count-filter', measureIndex: 0, operator: 'greater_than', value: '5' }],
+ },
+ })
+ if (method === 'field') {
+ logic.actions.addFieldToShelf(eventField, 'values')
+ } else if (method === 'blank') {
+ logic.actions.addBlankFieldToShelf('values')
+ logic.actions.setFieldExpression('values', 1, 'event')
+ } else if (method === 'calculation') {
+ logic.actions.upsertCalculatedMeasure({
+ index: null,
+ name: 'Revenue',
+ expression: 'sum(properties.amount)',
+ })
+ } else {
+ logic.actions.moveFieldToShelf('rows', 0, 'values')
+ }
+ const updated = logic.values.config
+ expect(updated.values).toHaveLength(2)
+ expect(updated.values[updated.resultFilters![0].measureIndex]).toMatchObject({
+ label: 'Count',
+ customExpression: 'count(*)',
+ })
+ const query = buildBIQuery(updated)!.query
+ expect(query).toContain('count(*) AS Count')
+ expect(query).toContain('Count > 5')
+ expect(parseBIEditorState(BIEditorView.BI, updated)!.config).toEqual(updated)
+ logic.unmount()
+ }
+ )
+
it('offers every sidebar table while excluding hidden PostHog tables', () => {
const biLogic = biEditorLogic({ tabId: TAB_ID })
biLogic.mount()
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 4d86ad427f02..532bf21b9826 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -18,6 +18,8 @@ import {
BIValue,
BIQueryLimit,
BISort,
+ BIConditionGroup,
+ BIResultFilter,
} from '~/queries/schema/schema-business-intelligence'
import { CompareFilter, DatabaseSchemaTable, DateRange } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
@@ -89,6 +91,9 @@ function setDataSourceInConfig(config: BIConfig, source: BIDataSource): BIConfig
values: [],
filters: [],
dateField: defaultDateFilter?.field ?? getBIDateField({ ...config, source, dateField: undefined }),
+ rowFilterGroup: undefined,
+ resultFilters: undefined,
+ resultFilterGroup: undefined,
dateRange: { date_from: defaultDateFilter ? '-7d' : 'all' },
sort: null,
}
@@ -104,6 +109,24 @@ function blankField(source: BIDataSource, fieldId: string): BIField {
}
}
+function addValueToConfig(config: BIConfig, value: BIValue): BIConfig {
+ const preserveCount =
+ !config.values.length &&
+ (config.resultFilters?.some((filter) => filter.measureIndex === 0) || config.topN?.measureIndex === 0)
+ const values: BIValue[] =
+ preserveCount && config.source
+ ? [
+ {
+ field: blankField(config.source, 'bi-default-count'),
+ aggregation: 'custom',
+ customExpression: 'count(*)',
+ label: 'Count',
+ },
+ ]
+ : config.values
+ return { ...config, values: [...values, value] }
+}
+
function addFieldToConfig(config: BIConfig, field: BIField, shelf: BIShelf): BIConfig {
if (!isBIFieldCompatible(config.source, field)) {
return config
@@ -120,11 +143,7 @@ function addFieldToConfig(config: BIConfig, field: BIField, shelf: BIShelf): BIC
}
return { ...sourceConfig, source, [shelf]: [...sourceConfig[shelf], field] }
case 'values':
- return {
- ...sourceConfig,
- source,
- values: [...sourceConfig.values, { field, aggregation: defaultAggregationForField(field) }],
- }
+ return addValueToConfig(sourceConfig, { field, aggregation: defaultAggregationForField(field) })
case 'filters':
if (
sourceConfig.filters.some(
@@ -181,6 +200,12 @@ function removeFieldFromConfig(config: BIConfig, shelf: BIShelf, index: number):
return {
...config,
values: config.values.filter((_, valueIndex) => valueIndex !== index),
+ resultFilters: config.resultFilters
+ ?.filter((filter) => filter.measureIndex !== index)
+ .map((filter) => ({
+ ...filter,
+ measureIndex: filter.measureIndex > index ? filter.measureIndex - 1 : filter.measureIndex,
+ })),
topN:
!config.topN || config.topN.measureIndex === index
? undefined
@@ -317,6 +342,9 @@ export interface biEditorLogicActions {
field: BIField
shelf: BIShelf
}
+ addResultFilter: () => {
+ id: string
+ }
clearActiveDropShelf: (shelf: BIShelf) => {
shelf: BIShelf
}
@@ -345,6 +373,9 @@ export interface biEditorLogicActions {
index: number
shelf: BIShelf
}
+ removeResultFilter: (id: string) => {
+ id: string
+ }
resetConfig: () => {
value: true
}
@@ -419,6 +450,13 @@ export interface biEditorLogicActions {
customExpression: string
index: number
}
+ setFilterGroup: (
+ scope: 'result' | 'row',
+ group: BIConditionGroup
+ ) => {
+ group: BIConditionGroup
+ scope: 'result' | 'row'
+ }
setFilterOperator: (
index: number,
operator: BIFilterOperator
@@ -489,6 +527,13 @@ export interface biEditorLogicActions {
index: number
settings: Pick<BIValue, 'display' | 'formatting'>
}
+ updateResultFilter: (
+ id: string,
+ update: Partial<BIResultFilter>
+ ) => {
+ id: string
+ update: Partial<BIResultFilter>
+ }
upsertCalculatedMeasure: (draft: BICalculatedMeasureDraft) => {
draft: BICalculatedMeasureDraft
fieldId: string
@@ -553,6 +598,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
actions: [databaseTableListLogic, ['hydrateTableFields', 'loadDatabaseSuccess']],
})),
actions({
+ setFilterGroup: (scope: 'row' | 'result', group: BIConditionGroup) => ({ scope, group }),
+ addResultFilter: () => ({ id: uuid() }),
+ updateResultFilter: (id: string, update: Partial<BIResultFilter>) => ({ id, update }),
+ removeResultFilter: (id: string) => ({ id }),
setEditorView: (editorView: BIEditorView) => ({ editorView }),
restoreState: (state: BIEditorState) => ({ state }),
addFieldToShelf: (field: BIField, shelf: BIShelf) => ({ field, shelf }),
@@ -698,15 +747,35 @@ export const biEditorLogic = kea<biEditorLogicType>([
customExpression: draft.expression.trim(),
label: draft.name.trim(),
}
- return {
- ...config,
- values:
- draft.index === null
- ? [...config.values, value]
- : config.values.map((current, index) => (index === draft.index ? value : current)),
- }
+ return draft.index === null
+ ? addValueToConfig(config, value)
+ : {
+ ...config,
+ values: config.values.map((current, index) => (index === draft.index ? value : current)),
+ }
},
addFieldToShelf: (config, { field, shelf }) => addFieldToConfig(config, field, shelf),
+ setFilterGroup: (config, { scope, group }) => ({
+ ...config,
+ [scope === 'row' ? 'rowFilterGroup' : 'resultFilterGroup']: group,
+ }),
+ addResultFilter: (config, { id }) => ({
+ ...config,
+ resultFilters: [
+ ...(config.resultFilters ?? []),
+ { id, measureIndex: 0, operator: 'greater_than', value: '' },
+ ],
+ }),
+ updateResultFilter: (config, { id, update }) => ({
+ ...config,
+ resultFilters: config.resultFilters?.map((filter) =>
+ filter.id === id ? { ...filter, ...update, id } : filter
+ ),
+ }),
+ removeResultFilter: (config, { id }) => ({
+ ...config,
+ resultFilters: config.resultFilters?.filter((filter) => filter.id !== id),
+ }),
addBlankFieldToShelf: (config, { shelf, fieldId }) =>
config.source ? addFieldToConfig(config, blankField(config.source, fieldId), shelf) : config,
removeFieldFromShelf: (config, { shelf, index }) => removeFieldFromConfig(config, shelf, index),
@@ -924,6 +993,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
}
},
upsertCalculatedMeasure: () => actions.runAfterChange(),
+ setFilterGroup: () => actions.runAfterChange(),
+ addResultFilter: () => actions.runAfterChange(),
+ updateResultFilter: () => actions.runAfterChange(),
+ removeResultFilter: () => actions.runAfterChange(),
loadDatabaseSuccess: () => {
if (values.config.source && (values.config.source.connectionId ?? null) === values.databaseConnectionId) {
actions.hydrateTableFields([values.config.source.table])
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index f5dc799d4219..8816e58f9cc2 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -11,6 +11,7 @@ import {
BIValue,
BIFilter,
BIFilterOperator,
+ BIResultFilter,
} from '~/queries/schema/schema-business-intelligence'
import {
ChartSettings,
@@ -36,6 +37,12 @@ import {
isBITableCalculation,
} from './biAnalysis'
import { biComparisonCategory, getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
+import {
+ buildBIConditionExpression,
+ isBIConditionGroup,
+ isBIResultFilter,
+ normalizeBIConditionGroup,
+} from './biFilterGroups'
import { getBIMeasureSettings, isBIMeasureSettings, mergeBIMeasureSettings } from './biMeasureSettings'
import { getBIFiltersPlaceholder, getBIQueryFilters, normalizeBIDates } from './biQueryFilters'
@@ -153,6 +160,24 @@ export function normalizeBIConfig(config: BIConfig): BIConfig {
normalized = { ...normalized, topN: undefined }
}
+ if (normalized.rowFilterGroup) {
+ normalized = {
+ ...normalized,
+ rowFilterGroup: normalizeBIConditionGroup(
+ normalized.rowFilterGroup,
+ normalized.filters.map((filter) => filter.field.id)
+ ),
+ }
+ }
+ if (normalized.resultFilterGroup) {
+ normalized = {
+ ...normalized,
+ resultFilterGroup: normalizeBIConditionGroup(
+ normalized.resultFilterGroup,
+ (normalized.resultFilters ?? []).map((filter) => filter.id)
+ ),
+ }
+ }
return normalized
}
@@ -560,6 +585,10 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
if (
source === undefined ||
+ (candidate.rowFilterGroup !== undefined && !isBIConditionGroup(candidate.rowFilterGroup)) ||
+ (candidate.resultFilterGroup !== undefined && !isBIConditionGroup(candidate.resultFilterGroup)) ||
+ (candidate.resultFilters !== undefined &&
+ (!Array.isArray(candidate.resultFilters) || !candidate.resultFilters.every(isBIResultFilter))) ||
sort === undefined ||
!Object.values(ChartDisplayType).includes(candidate.chartType as ChartDisplayType) ||
!rows ||
@@ -577,6 +606,9 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
const config: BIConfig = {
source,
+ ...(candidate.rowFilterGroup ? { rowFilterGroup: candidate.rowFilterGroup } : {}),
+ ...(candidate.resultFilterGroup ? { resultFilterGroup: candidate.resultFilterGroup } : {}),
+ ...(candidate.resultFilters ? { resultFilters: candidate.resultFilters } : {}),
...(candidate.topN ? { topN: candidate.topN } : {}),
...(candidate.totals ? { totals: candidate.totals } : {}),
...(candidate.compareFilter !== undefined ? { compareFilter: candidate.compareFilter } : {}),
@@ -813,6 +845,84 @@ function filterExpression(filter: BIFilter): string | null {
}
}
+export function buildBIRowFilterExpressions(config: BIConfig, excludedIndex?: number): string[] {
+ const filters = config.filters.filter(
+ (filter, index) =>
+ index !== excludedIndex &&
+ (filter.field.expression.trim() || filter.field.name.trim() || filter.operator === 'custom')
+ )
+ if (!config.rowFilterGroup) {
+ return filters.map(filterExpression).filter((expression): expression is string => !!expression)
+ }
+ const group = normalizeBIConditionGroup(
+ config.rowFilterGroup,
+ filters.map((filter) => filter.field.id)
+ )
+ const expression = buildBIConditionExpression(
+ group,
+ new Map(filters.map((filter) => [filter.field.id, filterExpression(filter)]))
+ )
+ return expression ? [expression] : []
+}
+
+function resultAsRowFilter(config: BIConfig, filter: BIResultFilter): BIFilter | null {
+ const value = config.values[filter.measureIndex]
+ const alias = config.values.length
+ ? computeBIQueryParts(config).configuredValues.find((part) => part.value === value)?.alias
+ : filter.measureIndex === 0
+ ? 'count'
+ : undefined
+ if (!alias || !config.source) {
+ return null
+ }
+ return {
+ field: {
+ id: filter.id,
+ name: alias,
+ expression: escapeRawPropertyAsHogQLIdentifier(alias),
+ type: 'float',
+ source: config.source,
+ },
+ operator:
+ filter.operator === 'greater_than_or_equal' || filter.operator === 'less_than_or_equal'
+ ? 'between'
+ : filter.operator,
+ value: filter.operator === 'less_than_or_equal' ? '' : filter.value,
+ valueTo:
+ filter.operator === 'less_than_or_equal'
+ ? filter.value
+ : filter.operator === 'greater_than_or_equal'
+ ? ''
+ : filter.valueTo,
+ enabled: filter.enabled,
+ }
+}
+
+export function getBIResultFilterValidationError(config: BIConfig, filter: BIResultFilter): string | null {
+ if (filter.enabled === false) {
+ return null
+ }
+ const row = resultAsRowFilter(config, filter)
+ return row ? getBIFilterValidationError(row) : 'Select a valid measure for this result filter.'
+}
+
+function buildBIResultFilterExpression(config: BIConfig): string | null {
+ const filters = config.resultFilters ?? []
+ const group = normalizeBIConditionGroup(
+ config.resultFilterGroup,
+ filters.map((filter) => filter.id)
+ )
+ return buildBIConditionExpression(
+ group,
+ new Map(
+ filters.map((filter) => {
+ const row = resultAsRowFilter(config, filter)
+ return [filter.id, row ? filterExpression(row) : null]
+ })
+ )
+ )
+}
+
export function buildBIFilterOptionsQuery(config: BIConfig, index: number): HogQLQuery | null {
config = normalizeBIConfig(config)
const filter = config.filters[index]
@@ -824,14 +934,7 @@ export function buildBIFilterOptionsQuery(config: BIConfig, index: number): HogQ
return null
}
const expression = fieldExpression(filter.field)
- const conditions = config.filters
- .filter(
- (other, otherIndex) =>
- otherIndex !== index &&
- (other.field.expression.trim() || other.field.name.trim() || other.operator === 'custom')
- )
- .map(filterExpression)
- .filter((condition): condition is string => !!condition)
+ const conditions = buildBIRowFilterExpressions(config, index)
return {
kind: NodeKind.HogQLQuery,
connectionId: config.source.connectionId,
@@ -943,7 +1046,7 @@ export function buildBIRowsQuery(config: BIConfig, previous = false): HogQLQuery
const placeholder = getBIFiltersPlaceholder(config)
const conditions = [
previous ? placeholder.replace('{filters', '{filters.previous') : placeholder,
- ...config.filters.map(filterExpression).filter(Boolean),
+ ...buildBIRowFilterExpressions(config),
]
return {
kind: NodeKind.HogQLQuery,
@@ -966,7 +1069,7 @@ export function buildBITopMembership(config: BIConfig): string | null {
if (!measure) {
return null
}
- const conditions = [getBIFiltersPlaceholder(config), ...config.filters.map(filterExpression).filter(Boolean)]
+ const conditions = [getBIFiltersPlaceholder(config), ...buildBIRowFilterExpressions(config)]
const top = `SELECT ${expression} AS bi_key FROM ${escapePropertyAsHogQLIdentifier(config.source.table)} WHERE ${conditions.map((condition) => `(${condition})`).join(' AND ')} GROUP BY bi_key ORDER BY ${measure} DESC, bi_key ASC LIMIT ${config.topN.count}`
return `((${expression} IS NOT NULL AND ${expression} IN (SELECT bi_key FROM (${top}) WHERE bi_key IS NOT NULL)) OR (${expression} IS NULL AND (SELECT count(*) FROM (${top}) WHERE bi_key IS NULL) > 0))`
}
@@ -1104,7 +1207,11 @@ function buildOrderByExpression(
export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQueryBuildResult | null {
config = normalizeBIConfig(config)
- if (!config.source || config.filters.some(getBIFilterValidationError)) {
+ if (
+ !config.source ||
+ config.filters.some(getBIFilterValidationError) ||
+ config.resultFilters?.some((filter) => getBIResultFilterValidationError(config, filter))
+ ) {
return null
}
@@ -1140,15 +1247,7 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
)
: ['count(*) AS count']
const selectExpressions = [...dimensionSelectExpressions, ...valueExpressions]
- const filters = config.filters
- .filter(
- (filter) =>
- filter.field.expression.trim() ||
- filter.field.name.trim() ||
- (filter.operator === 'custom' && filter.customExpression?.trim())
- )
- .map(filterExpression)
- .filter((filter): filter is string => !!filter)
+ const filters = buildBIRowFilterExpressions(config)
const queryParts = [
`SELECT\n ${selectExpressions.join(',\n ')}`,
`FROM ${escapePropertyAsHogQLIdentifier(config.source.table)}`,
@@ -1265,6 +1364,7 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
where: where(false),
orderBy: orderByExpression,
resultLimit,
+ resultWhere: buildBIResultFilterExpression(config),
...(comparing
? {
previousWhere: where(true),
diff --git a/products/business_intelligence/frontend/biFilterGroups.test.ts b/products/business_intelligence/frontend/biFilterGroups.test.ts
new file mode 100644
index 000000000000..0765c567e56f
--- /dev/null
+++ b/products/business_intelligence/frontend/biFilterGroups.test.ts
@@ -0,0 +1,110 @@
+import { BIConditionGroup, BIConfig, BIField } from '~/queries/schema/schema-business-intelligence'
+
+import {
+ BIEditorView,
+ DEFAULT_BI_CONFIG,
+ buildBIFilterOptionsQuery,
+ buildBIQuery,
+ buildBIRowsQuery,
+ parseBIEditorState,
+} from './biEditorTypes'
+import { moveBICondition, ungroupBIConditionGroup } from './biFilterGroups'
+
+const field = (name: string): BIField => ({
+ id: name,
+ name,
+ expression: name,
+ type: 'string',
+ source: { table: 'events' },
+})
+const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ filters: ['event', 'properties.plan', 'properties.country'].map((name) => ({
+ field: field(name),
+ operator: 'equals',
+ value: 'example',
+ })),
+}
+
+describe('BI filter groups', () => {
+ it('ungroups into the immediate parent while preserving nested conditions and sibling groups', () => {
+ const group: BIConditionGroup = {
+ operator: 'OR',
+ filters: [],
+ groups: [
+ {
+ operator: 'AND',
+ filters: [],
+ groups: [
+ {
+ operator: 'OR',
+ filters: ['event'],
+ groups: [
+ { operator: 'OR', filters: ['properties.plan', 'properties.country'], groups: [] },
+ ],
+ },
+ { operator: 'AND', filters: [], groups: [] },
+ ],
+ },
+ ],
+ }
+ const updated = ungroupBIConditionGroup(group, [0, 0])
+ const parsed = parseBIEditorState(BIEditorView.BI, { ...config, rowFilterGroup: updated })!.config
+ expect(parsed.rowFilterGroup?.filters).toEqual([])
+ expect(parsed.rowFilterGroup?.groups[0].filters).toEqual(['event'])
+ expect(parsed.rowFilterGroup?.groups[0].groups).toEqual([
+ group.groups[0].groups[0].groups[0],
+ group.groups[0].groups[1],
+ ])
+ for (const query of [buildBIQuery(parsed)!.query, buildBIRowsQuery(parsed)!.query]) {
+ expect(query).toContain(
+ "(event = 'example') AND ((properties.plan = 'example') OR (properties.country = 'example'))"
+ )
+ }
+ })
+
+ it('moves conditions into nested groups and preserves precedence in charts, rows and suggestions', () => {
+ const group = moveBICondition(
+ {
+ operator: 'AND',
+ filters: config.filters.map((filter) => filter.field.id),
+ groups: [{ operator: 'OR', filters: [], groups: [] }],
+ },
+ 'event',
+ [0]
+ )
+ const nested = moveBICondition(group, 'properties.plan', [0])
+ const worksheet = { ...config, rowFilterGroup: nested }
+ const parsed = parseBIEditorState(BIEditorView.BI, worksheet)!.config
+ expect(parsed.rowFilterGroup).toEqual(nested)
+ for (const query of [buildBIQuery(parsed)!.query, buildBIRowsQuery(parsed)!.query]) {
+ expect(query).toContain(
+ "(properties.country = 'example') AND ((event = 'example') OR (properties.plan = 'example'))"
+ )
+ expect(query.match(/event = 'example'/g)).toHaveLength(1)
+ }
+ const suggestions = buildBIFilterOptionsQuery(parsed, 0)!.query
+ expect(suggestions).not.toContain("event = 'example'")
+ expect(suggestions).toContain("properties.plan = 'example'")
+ expect(suggestions).toContain("properties.country = 'example'")
+ expect(
+ buildBIQuery({ ...parsed, filters: parsed.filters.map((filter) => ({ ...filter, enabled: false })) })!.query
+ ).not.toContain("= 'example'")
+ })
+
+ it.each([
+ { rowFilterGroup: { operator: 'X', filters: [], groups: [] } },
+ { rowFilterGroup: { operator: 'OR', filters: [], groups: [null] } },
+ { resultFilters: [{ id: 'bad', measureIndex: -1, operator: 'equals', value: '1' }] },
+ { resultFilters: [{ id: 'bad', measureIndex: 0, operator: 'custom', value: '1' }] },
+ ])('rejects malformed persisted filter configuration: %j', (update) => {
+ expect(parseBIEditorState(BIEditorView.BI, { ...config, ...update })).toBeNull()
+ })
+
+ it('filters the implicit count and fails closed for missing measures', () => {
+ const filter = { id: 'count', measureIndex: 0, operator: 'greater_than' as const, value: '9007199254740993' }
+ expect(buildBIQuery({ ...config, resultFilters: [filter] })!.query).toContain('count > 9007199254740993')
+ expect(buildBIQuery({ ...config, resultFilters: [{ ...filter, measureIndex: 1 }] })).toBeNull()
+ })
+})
diff --git a/products/business_intelligence/frontend/biFilterGroups.ts b/products/business_intelligence/frontend/biFilterGroups.ts
new file mode 100644
index 000000000000..08302227c92b
--- /dev/null
+++ b/products/business_intelligence/frontend/biFilterGroups.ts
@@ -0,0 +1,104 @@
+import { BIConditionGroup, BIResultFilter } from '~/queries/schema/schema-business-intelligence'
+
+export function isBIConditionGroup(value: unknown, depth = 0): value is BIConditionGroup {
+ if (!value || typeof value !== 'object' || depth > 8) {
+ return false
+ }
+ const group = value as BIConditionGroup
+ return (
+ ['AND', 'OR'].includes(group.operator) &&
+ Array.isArray(group.filters) &&
+ group.filters.every((id) => typeof id === 'string') &&
+ Array.isArray(group.groups) &&
+ group.groups.every((child) => isBIConditionGroup(child, depth + 1))
+ )
+}
+
+export function isBIResultFilter(value: unknown): value is BIResultFilter {
+ if (!value || typeof value !== 'object') {
+ return false
+ }
+ const filter = value as BIResultFilter
+ return (
+ typeof filter.id === 'string' &&
+ Number.isInteger(filter.measureIndex) &&
+ filter.measureIndex >= 0 &&
+ [
+ 'equals',
+ 'not_equals',
+ 'greater_than',
+ 'less_than',
+ 'greater_than_or_equal',
+ 'less_than_or_equal',
+ 'between',
+ 'is_set',
+ 'is_not_set',
+ ].includes(filter.operator) &&
+ typeof filter.value === 'string' &&
+ (filter.valueTo === undefined || typeof filter.valueTo === 'string') &&
+ (filter.enabled === undefined || typeof filter.enabled === 'boolean')
+ )
+}
+
+export function normalizeBIConditionGroup(group: BIConditionGroup | undefined, ids: string[]): BIConditionGroup {
+ const remaining = new Set(ids)
+ const visit = (node: BIConditionGroup): BIConditionGroup => ({
+ operator: node.operator,
+ filters: node.filters.filter((id) => remaining.delete(id)),
+ groups: node.groups.map(visit),
+ })
+ const normalized = visit(group ?? { operator: 'AND', filters: [], groups: [] })
+ return { ...normalized, filters: [...normalized.filters, ...remaining] }
+}
+
+export function buildBIConditionExpression(
+ group: BIConditionGroup,
+ expressions: Map<string, string | null>
+): string | null {
+ const parts = [
+ ...group.filters.map((id) => expressions.get(id)),
+ ...group.groups.map((child) => buildBIConditionExpression(child, expressions)),
+ ].filter((part): part is string => !!part)
+ return parts.length ? parts.map((part) => `(${part})`).join(` ${group.operator} `) : null
+}
+
+export function updateBIConditionGroup(
+ group: BIConditionGroup,
+ path: number[],
+ update: (node: BIConditionGroup) => BIConditionGroup
+): BIConditionGroup {
+ return path.length
+ ? {
+ ...group,
+ groups: group.groups.map((child, index) =>
+ index === path[0] ? updateBIConditionGroup(child, path.slice(1), update) : child
+ ),
+ }
+ : update(group)
+}
+
+export function moveBICondition(group: BIConditionGroup, id: string, path: number[]): BIConditionGroup {
+ const remove = (node: BIConditionGroup): BIConditionGroup => ({
+ ...node,
+ filters: node.filters.filter((filter) => filter !== id),
+ groups: node.groups.map(remove),
+ })
+ return updateBIConditionGroup(remove(group), path, (node) => ({ ...node, filters: [...node.filters, id] }))
+}
+
+export function ungroupBIConditionGroup(root: BIConditionGroup, path: number[]): BIConditionGroup {
+ if (!path.length) {
+ return root
+ }
+ return updateBIConditionGroup(root, path.slice(0, -1), (parent) => {
+ const index = path[path.length - 1]
+ const group = parent.groups[index]
+ return group
+ ? {
+ ...parent,
+ filters: [...parent.filters, ...group.filters],
+ groups: parent.groups.flatMap((child, childIndex) => (childIndex === index ? group.groups : [child])),
+ }
+ : parent
+ })
+}
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index d9017683cd82..0ab03d2d6a0f 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -105,19 +105,57 @@ describe('biSceneLogic', () => {
]
},
'/api/projects/:team_id/insights/': save,
+ '/api/projects/:team_id/insights/viewed/': [201],
'/api/projects/:team_id/warehouse_saved_queries/': exportView,
},
patch: { '/api/projects/:team_id/insights/:id/': save },
delete: { '/api/environments/:team_id/query/:id/': [204] },
})
initKeaTests()
- router.actions.push(urls.businessIntelligence(), {}, { q: '' })
+ router.actions.push(urls.businessIntelligenceNew(), {}, { q: '' })
logic = biSceneLogic({ tabId: 'bi-test' })
logic.mount()
editor = biEditorLogic({ tabId: 'bi-test' })
})
afterEach(() => logic.unmount())
+ it.each([false, true])('protects unsaved worksheet edits when navigating away (saved: %s)', async (saved) => {
+ const confirm = jest.spyOn(window, 'confirm').mockReturnValue(false)
+ try {
+ expect(logic.values.hasUnsavedChanges).toBe(false)
+ if (saved) {
+ await expectLogic(logic, () =>
+ router.actions.push(urls.businessIntelligenceWorksheet(stored.short_id))
+ ).toFinishAllListeners()
+ }
+ logic.actions.setName('Edited worksheet')
+ editor.actions.setDataSource({ table: 'events' })
+ await expectLogic(logic).toFinishAllListeners()
+ const editorPath = router.values.location.pathname
+ expect(confirm).not.toHaveBeenCalled()
+
+ router.actions.push(urls.businessIntelligence())
+ expect(confirm).toHaveBeenCalledTimes(1)
+ expect(router.values.location.pathname).toBe(editorPath)
+ expect(logic.values.name).toBe('Edited worksheet')
+
+ confirm.mockReturnValue(true)
+ router.actions.push(urls.businessIntelligence())
+ expect(router.values.location.pathname).toBe('/project/997/bi')
+ logic.unmount()
+ router.actions.push(
+ saved ? urls.businessIntelligenceWorksheet(stored.short_id) : urls.businessIntelligenceNew()
+ )
+ logic = biSceneLogic({ tabId: 'bi-test' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.name).toBe(saved ? stored.name : 'Untitled worksheet')
+ expect(logic.values.hasUnsavedChanges).toBe(false)
+ } finally {
+ confirm.mockRestore()
+ }
+ })
+
it('waits for Run after selecting a table unless auto update is enabled', async () => {
editor.actions.setDataSource({ table: 'events' })
await expectLogic(logic).toFinishAllListeners()
@@ -186,6 +224,7 @@ describe('biSceneLogic', () => {
logic.actions.setName('Revenue worksheet')
await expectLogic(logic, () => logic.actions.saveInsight()).toFinishAllListeners()
expect(save).toHaveBeenCalledTimes(1)
+ expect(router.values.location.pathname).toBe('/project/997/bi/bi-test')
expect(stored.query).toMatchObject({ kind: NodeKind.BIVisualizationNode, config })
expect(stored.query.source).not.toHaveProperty('biConfig')
logic.unmount()
@@ -226,6 +265,82 @@ describe('biSceneLogic', () => {
expect(save).not.toHaveBeenCalled()
})
+ it('undoes shelves, filters, calculations and formatting without running a query, and branches after undo', async () => {
+ await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
+ const snapshots = [JSON.parse(JSON.stringify(logic.values.worksheet))]
+ const edits = [
+ () => editor.actions.addFieldToShelf(eventField, 'filters'),
+ () => editor.actions.setFilterValue(0, '$pageview'),
+ () => editor.actions.addFieldToShelf(eventField, 'values'),
+ () => editor.actions.setTableCalculation(0, { type: 'running_total' }),
+ () => editor.actions.updateMeasureSettings(0, { formatting: { prefix: '€' } }),
+ () => editor.actions.addResultFilter(),
+ () => editor.actions.updateResultFilter(editor.values.config.resultFilters![0].id, { value: '100' }),
+ () => editor.actions.setFilterGroup('row', { operator: 'OR', filters: ['event'], groups: [] }),
+ () => editor.actions.removeFieldFromShelf('columns', 0),
+ () => logic.actions.setVisualization({ ...logic.values.worksheet, chartSettings: { showLegend: false } }),
+ ]
+ for (const edit of edits) {
+ edit()
+ snapshots.push(JSON.parse(JSON.stringify(logic.values.worksheet)))
+ }
+ const lastRun = logic.values.lastRunQuery
+ for (let index = snapshots.length - 2; index >= 0; index--) {
+ logic.actions.undo()
+ expect(JSON.parse(JSON.stringify(logic.values.worksheet))).toEqual(snapshots[index])
+ expect(logic.values.lastRunQuery).toEqual(lastRun)
+ }
+ expect(logic.values.canUndo).toBe(false)
+ for (const snapshot of snapshots.slice(1)) {
+ logic.actions.redo()
+ expect(JSON.parse(JSON.stringify(logic.values.worksheet))).toEqual(snapshot)
+ }
+ expect(logic.values.canRedo).toBe(false)
+ logic.actions.undo()
+ editor.actions.setLimit(100)
+ expect(logic.values.canRedo).toBe(false)
+ logic.actions.discardChanges()
+ expect(logic.values.canUndo).toBe(false)
+ expect(logic.values.hasUnsavedChanges).toBe(false)
+ })
+
+ it('runs the restored worksheet when auto update is enabled', async () => {
+ await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
+ await expectLogic(editor, () => editor.actions.setAutoUpdate(true)).toFinishAllListeners()
+ await expectLogic(editor, () => editor.actions.setLimit(100)).toFinishAllListeners()
+ expect(logic.values.lastRunQuery?.config.limit).toBe(100)
+ await expectLogic(logic, () => logic.actions.undo()).toFinishAllListeners()
+ expect(logic.values.lastRunQuery?.config.limit).toBe(config.limit)
+ })
+
+ it('creates a separate worksheet copy and preserves the original, including after a failed copy', async () => {
+ await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()
+ const original = JSON.parse(JSON.stringify(stored))
+ let fail = true
+ let copy: unknown
+ const createCopy = jest.fn(async ({ request }: { request: Request }) => {
+ const payload = await request.json()
+ copy = { ...payload, id: 456, short_id: 'copy' }
+ return fail ? [500, { detail: 'Could not save copy' }] : [201, copy]
+ })
+ useMocks({
+ post: { '/api/projects/:team_id/insights/': createCopy },
+ get: { '/api/projects/:team_id/insights/': () => [200, { results: [copy] }] },
+ })
+ editor.actions.setLimit(100)
+ await expectLogic(logic, () => logic.actions.saveInsight({ asCopy: true })).toFinishAllListeners()
+ expect(logic.values.insight?.id).toBe(original.id)
+ expect(logic.values.insightLoading).toBe(false)
+ expect(logic.values.worksheet.config.limit).toBe(100)
+ fail = false
+ await expectLogic(logic, () => logic.actions.saveInsight({ asCopy: true })).toFinishAllListeners()
+ expect(save).not.toHaveBeenCalled()
+ expect(stored).toEqual(original)
+ expect(createCopy).toHaveBeenCalledTimes(2)
+ expect(router.values.location.pathname).toBe('/project/997/bi/copy')
+ expect(logic.values.insight?.name).toBe('Saved worksheet (copy)')
+ })
+
it('preserves an unfinished calculated measure when chart settings update', () => {
logic.actions.restoreWorksheet(worksheet())
editor.actions.setCalculatedMeasureDraft({
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index b9a30d23fc68..ec52219c16b4 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -15,11 +15,12 @@ import {
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
-import { router, urlToAction } from 'kea-router'
+import { beforeUnload, router, urlToAction } from 'kea-router'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { accessLevelSatisfied, toAccessControlLevel } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -29,12 +30,17 @@ 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 { isBIVisualizationNode } from '~/queries/utils'
-import { AccessControlLevel, AccessControlResourceType, InsightShortId } from '~/types'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { warehouseSavedQueriesCreate } from 'products/data_warehouse/frontend/generated/api'
import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'
import { connectionSelectorLogic } from 'products/data_warehouse/frontend/shared/logics/connectionSelectorLogic'
-import { insightsCreate, insightsList, insightsPartialUpdate } from 'products/product_analytics/frontend/generated/api'
+import {
+ insightsCreate,
+ insightsList,
+ insightsPartialUpdate,
+ insightsViewedCreate,
+} from 'products/product_analytics/frontend/generated/api'
import { BIVisualizationNodeApi, InsightApi } from 'products/product_analytics/frontend/generated/api.schemas'
import type { BIConfig } from '../../../frontend/src/queries/schema/schema-business-intelligence'
@@ -57,6 +63,17 @@ export interface BISceneLogicProps {
tabId: string
}
+export interface BIWorksheetSnapshot {
+ worksheet: BIVisualizationNode
+ name: string
+}
+
+export interface BIWorksheetHistory {
+ past: BIWorksheetSnapshot[]
+ present: BIWorksheetSnapshot | null
+ future: BIWorksheetSnapshot[]
+}
+
function emptyWorksheet(): BIVisualizationNode {
return {
kind: NodeKind.BIVisualizationNode,
@@ -75,12 +92,16 @@ export interface biSceneLogicValues {
connectionOptionsLoading: boolean // connectionSelectorLogic
connectionId: string | null // databaseTableListLogic
currentTeamId: number | null // teamLogic
+ canRedo: boolean
+ canUndo: boolean
+ copyDisabledReason: string | undefined
dataNodeKey: string
exportViewName: string
exportViewOpen: boolean
exportedView: Awaited<ReturnType<typeof warehouseSavedQueriesCreate>> | null
exportedViewLoading: boolean
hasUnsavedChanges: boolean
+ history: BIWorksheetHistory
insight: InsightApi | null
insightLoading: boolean
lastRunQuery: BIVisualizationNode | null
@@ -147,13 +168,31 @@ export interface biSceneLogicActions {
openWorksheet: () => {
value: true
}
+ pushHistory: (
+ snapshot: BIWorksheetSnapshot,
+ reset: boolean
+ ) => {
+ reset: boolean
+ snapshot: BIWorksheetSnapshot
+ }
+ recordWorksheet: (reset?: any) => {
+ reset: any
+ }
+ redo: () => {
+ value: true
+ }
+ restoreHistory: () => {
+ value: true
+ }
restoreWorksheet: (worksheet: BIVisualizationNode) => {
worksheet: BIVisualizationNode
}
runQuery: () => {
value: true
}
- saveInsight: () => any
+ saveInsight: (options?: { asCopy?: boolean }) => {
+ asCopy?: boolean
+ }
saveInsightFailure: (
error: string,
errorObject?: any
@@ -163,10 +202,14 @@ export interface biSceneLogicActions {
}
saveInsightSuccess: (
insight: InsightApi | null,
- payload?: any
+ payload?: {
+ asCopy?: boolean
+ }
) => {
insight: InsightApi | null
- payload?: any
+ payload?: {
+ asCopy?: boolean
+ }
}
selectConnection: (connectionId: string | null) => {
connectionId: string | null
@@ -192,12 +235,18 @@ export interface biSceneLogicActions {
syncWorksheetUrl: () => {
value: true
}
+ undo: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ canUndo: (history: BIWorksheetHistory) => boolean
+ canRedo: (history: BIWorksheetHistory) => boolean
+ copyDisabledReason: (generatedQuery: BIQueryBuildResult | null, name: string) => string | undefined
dataNodeKey: (tabId: string) => string
worksheet: (
config: BIConfig,
@@ -238,6 +287,11 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
actions: [biEditorLogic(props), ['restoreState', 'runAfterChange', 'resetConfig', 'setChartType']],
})),
actions({
+ recordWorksheet: (reset = false) => ({ reset }),
+ pushHistory: (snapshot: BIWorksheetSnapshot, reset: boolean) => ({ snapshot, reset }),
+ undo: true,
+ redo: true,
+ restoreHistory: true,
restoreWorksheet: (worksheet: BIVisualizationNode) => ({ worksheet }),
setVisualization: (visualization: VisualizationNode) => ({ visualization }),
setName: (name: string) => ({ name }),
@@ -269,26 +323,31 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
}
return insight
},
- saveInsight: async () => {
- if (values.saveDisabledReason) {
+ saveInsight: async (options: { asCopy?: boolean } = {}) => {
+ const asCopy = options.asCopy ?? false
+ if (asCopy ? values.copyDisabledReason : values.saveDisabledReason) {
return values.insight
}
const dashboard = Number(router.values.searchParams.dashboard)
const payload = {
- name: values.name.trim(),
+ name: asCopy ? `${values.name.trim()} (copy)` : values.name.trim(),
query: JSON.parse(JSON.stringify(values.worksheet)) as BIVisualizationNodeApi,
saved: true,
- ...(!values.insight && Number.isInteger(dashboard) && dashboard > 0
+ ...(!asCopy && !values.insight && Number.isInteger(dashboard) && dashboard > 0
? { dashboards: [dashboard] }
: {}),
}
const state = { editorView: BIEditorView.BI, config: values.config }
- const operation = values.insight ? 'update' : 'create'
- const insight = values.insight
- ? await insightsPartialUpdate(String(values.currentTeamId), values.insight.id, payload)
- : await insightsCreate(String(values.currentTeamId), payload)
+ const operation = values.insight && !asCopy ? 'update' : 'create'
+ const insight =
+ values.insight && !asCopy
+ ? await insightsPartialUpdate(String(values.currentTeamId), values.insight.id, payload)
+ : await insightsCreate(String(values.currentTeamId), payload)
captureBIEditorQuerySaved(state, 'insight', operation, !!payload.dashboards?.length)
captureBIWorksheetAction('saved', state.config, { insight_id: insight.id })
+ if (asCopy) {
+ captureBIWorksheetAction('copied', state.config, { insight_id: insight.id })
+ }
if (payload.dashboards?.length) {
captureBIWorksheetAction('added_to_dashboard', state.config, { insight_id: insight.id })
}
@@ -316,6 +375,37 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
],
})),
reducers({
+ history: [
+ { past: [], present: null, future: [] } as BIWorksheetHistory,
+ {
+ pushHistory: (state, { snapshot, reset }) =>
+ reset
+ ? { past: [], present: snapshot, future: [] }
+ : equal(state.present, snapshot)
+ ? state
+ : {
+ past: state.present ? [...state.past, state.present].slice(-100) : [],
+ present: snapshot,
+ future: [],
+ },
+ undo: (state) =>
+ state.past.length
+ ? {
+ past: state.past.slice(0, -1),
+ present: state.past[state.past.length - 1],
+ future: state.present ? [state.present, ...state.future] : state.future,
+ }
+ : state,
+ redo: (state) =>
+ state.future.length
+ ? {
+ past: state.present ? [...state.past, state.present] : state.past,
+ present: state.future[0],
+ future: state.future.slice(1),
+ }
+ : state,
+ },
+ ],
visualization: [
emptyWorksheet(),
{
@@ -338,6 +428,17 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
exportViewOpen: [false, { setExportViewOpen: (_, { open }) => open }],
}),
selectors({
+ canUndo: [(s) => [s.history], (history: BIWorksheetHistory): boolean => history.past.length > 0],
+ canRedo: [(s) => [s.history], (history: BIWorksheetHistory): boolean => history.future.length > 0],
+ copyDisabledReason: [
+ (s) => [s.generatedQuery, s.name],
+ (generatedQuery: BIQueryBuildResult | null, name: string): string | undefined =>
+ !generatedQuery
+ ? 'Select a table and resolve any invalid fields before saving'
+ : !name.trim()
+ ? 'Enter a worksheet name'
+ : undefined,
+ ],
dataNodeKey: [(_, props) => [props.tabId], (tabId: string): string => `InsightViz.new-bi-${tabId}`],
worksheet: [
(s) => [s.config, s.generatedQuery, s.visualization],
@@ -361,7 +462,8 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
hasUnsavedChanges: [
(s) => [s.worksheet, s.name, s.insight],
(worksheet: BIVisualizationNode, name: string, insight: InsightApi | null): boolean =>
- !equal(JSON.parse(JSON.stringify(worksheet)), insight?.query) || name !== insight?.name,
+ !equal(JSON.parse(JSON.stringify(worksheet)), insight?.query ?? emptyWorksheet()) ||
+ name.trim() !== (insight?.name || 'Untitled worksheet'),
],
saveDisabledReason: [
(s) => [s.generatedQuery, s.insight, s.name],
@@ -390,6 +492,39 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
],
}),
listeners(({ actions, values, props, cache }) => ({
+ recordWorksheet: ({ reset }) => {
+ if (!cache.restoringHistory) {
+ actions.pushHistory(
+ JSON.parse(JSON.stringify({ worksheet: values.worksheet, name: values.name })),
+ reset
+ )
+ }
+ },
+ undo: () => {
+ actions.restoreHistory()
+ captureBIWorksheetAction('undo', values.config)
+ },
+ redo: () => {
+ actions.restoreHistory()
+ captureBIWorksheetAction('redo', values.config)
+ },
+ restoreHistory: () => {
+ const snapshot = values.history.present
+ if (!snapshot) {
+ return
+ }
+ cache.restoringHistory = true
+ const lastRunQuery = values.lastRunQuery
+ try {
+ actions.restoreWorksheet(snapshot.worksheet)
+ actions.setName(snapshot.name)
+ actions.setLastRunQuery(lastRunQuery)
+ } finally {
+ cache.restoringHistory = false
+ }
+ actions.runAfterChange()
+ },
+ setName: () => actions.recordWorksheet(),
[dataNodeLogic({ key: `InsightViz.new-bi-${props.tabId}`, query: emptyWorksheet().source }).actionTypes
.loadDataSuccess]: ({ response }) => {
if (
@@ -413,6 +548,7 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
source: { kind: NodeKind.HogQLQuery, query: '', connectionId: values.connectionId ?? undefined },
})
actions.syncWorksheetUrl()
+ actions.recordWorksheet()
},
selectConnection: ({ connectionId }) => {
if (connectionId !== values.connectionId) {
@@ -421,6 +557,7 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
source: { kind: NodeKind.HogQLQuery, query: '', connectionId: connectionId ?? undefined },
})
actions.syncWorksheetUrl()
+ actions.recordWorksheet()
}
},
restoreWorksheet: ({ worksheet }) => {
@@ -458,20 +595,24 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
worksheet = { ...worksheet, source: { ...worksheet.source, filters: filters as HogQLFilters } }
}
actions.restoreWorksheet(worksheet)
+ actions.recordWorksheet(true)
+ void insightsViewedCreate(String(values.currentTeamId), { insight_ids: [insight.id] }).catch(() => {})
}
},
saveInsightSuccess: ({ insight }) => {
if (insight) {
+ actions.setName(insight.name || 'Untitled worksheet')
localStorage.removeItem(`bi-worksheet-${values.currentTeamId}-${props.tabId}`)
refreshTreeItem('insight', insight.short_id)
const dashboard = router.values.searchParams.dashboard
router.actions.push(
- urls.insightView(insight.short_id as InsightShortId),
+ urls.businessIntelligenceWorksheet(insight.short_id),
dashboard ? { dashboard } : {}
)
}
},
runAfterChange: async (_, breakpoint) => {
+ actions.recordWorksheet()
actions.syncWorksheetUrl()
if (!values.generatedQuery) {
const dataLogic = dataNodeLogic.findMounted({ key: values.dataNodeKey })
@@ -521,6 +662,7 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
}
actions.setLastRunQuery(values.worksheet)
actions.syncWorksheetUrl()
+ actions.recordWorksheet()
},
discardChanges: () => {
if (isBIVisualizationNode(values.insight?.query)) {
@@ -531,6 +673,7 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
actions.setName('Untitled worksheet')
}
actions.syncWorksheetUrl()
+ actions.recordWorksheet(true)
},
syncWorksheetUrl: () => {
localStorage.setItem(
@@ -538,11 +681,18 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
JSON.stringify(values.worksheet)
)
cache.lastHash = JSON.stringify(values.worksheet)
- router.actions.replace(
- urls.businessIntelligence({ insightShortId: values.insight?.short_id }),
- router.values.searchParams,
- { q: cache.lastHash }
- )
+ cache.syncingWorksheetUrl = true
+ try {
+ router.actions.replace(
+ values.insight
+ ? urls.businessIntelligenceWorksheet(values.insight.short_id)
+ : urls.businessIntelligenceNew(),
+ router.values.searchParams,
+ { q: cache.lastHash }
+ )
+ } finally {
+ cache.syncingWorksheetUrl = false
+ }
},
shareWorksheet: async () => {
actions.syncWorksheetUrl()
@@ -550,16 +700,20 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
},
openWorksheet: () => {
const { searchParams, hashParams } = router.values
+ const pathId = router.values.location.pathname.match(/\/bi\/([^/]+)$/)?.[1]
+ const insightShortId =
+ searchParams.open_insight || (pathId && pathId !== 'new' ? decodeURIComponent(pathId) : undefined)
if (searchParams.open_view) {
router.actions.replace(urls.sqlEditor({ view_id: searchParams.open_view }))
return
}
- if (searchParams.open_insight && cache.loadingId !== searchParams.open_insight) {
- cache.loadingId = searchParams.open_insight
- actions.loadInsight(searchParams.open_insight)
+ if (insightShortId && cache.loadingId !== insightShortId) {
+ cache.loadingId = insightShortId
+ cache.firstChartCaptured = false
+ actions.loadInsight(insightShortId)
return
}
- if (searchParams.open_insight) {
+ if (insightShortId) {
return
}
if (cache.lastHash !== undefined && hashParams.q === cache.lastHash) {
@@ -590,9 +744,22 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
}
actions.restoreWorksheet(worksheet)
actions.setName('Untitled worksheet')
+ actions.recordWorksheet(true)
},
})),
- urlToAction(({ actions }) => ({ '/bi': () => actions.openWorksheet() })),
+ beforeUnload(({ values, actions, cache }) => ({
+ enabled: (newLocation) =>
+ !cache.syncingWorksheetUrl &&
+ values.hasUnsavedChanges &&
+ (!newLocation || addProjectIdIfMissing(newLocation.pathname) !== router.values.location.pathname),
+ message: 'Leave worksheet? Changes you made will be discarded.',
+ onConfirm: () => actions.discardChanges(),
+ })),
+ urlToAction(({ actions }) => ({
+ '/bi': () => actions.openWorksheet(),
+ '/bi/new': () => actions.openWorksheet(),
+ '/bi/:insightShortId': () => actions.openWorksheet(),
+ })),
beforeUnmount(({ props }) => {
if (releaseConnectionScope(`bi:${props.tabId}`, databaseTableListLogic.values.connectionId)) {
databaseTableListLogic.actions.resetConnectionScope()
diff --git a/products/business_intelligence/frontend/biWorksheetsLogic.test.ts b/products/business_intelligence/frontend/biWorksheetsLogic.test.ts
new file mode 100644
index 000000000000..4c15feced0a7
--- /dev/null
+++ b/products/business_intelligence/frontend/biWorksheetsLogic.test.ts
@@ -0,0 +1,30 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { biWorksheetsLogic } from './biWorksheetsLogic'
+
+describe('worksheet library', () => {
+ beforeEach(() => {
+ useMocks({ get: { '/api/projects/:team_id/insights/': { count: 0, results: [] } } })
+ initKeaTests()
+ })
+
+ it.each([
+ ['/bi?open_insight=worksheet1', '/bi/worksheet1'],
+ ['/bi#q=', '/bi/new'],
+ ])('preserves legacy worksheet links: %s', async (url, path) => {
+ router.actions.push(url)
+ const logic = biWorksheetsLogic()
+ logic.mount()
+ try {
+ await expectLogic(logic).toFinishAllListeners()
+ expect(router.values.location.pathname).toBe(`/project/997${path}`)
+ expect(logic.values.worksheets).toBeNull()
+ } finally {
+ logic.unmount()
+ }
+ })
+})
diff --git a/products/business_intelligence/frontend/biWorksheetsLogic.ts b/products/business_intelligence/frontend/biWorksheetsLogic.ts
new file mode 100644
index 000000000000..1211fc077bee
--- /dev/null
+++ b/products/business_intelligence/frontend/biWorksheetsLogic.ts
@@ -0,0 +1,110 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { insightsList } from 'products/product_analytics/frontend/generated/api'
+
+import type { PaginatedInsightListApi } from '../../product_analytics/frontend/generated/api.schemas'
+import { captureBIWorksheetAction } from './biEditorAnalytics'
+import { DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biWorksheetsLogicValues {
+ currentTeamId: number | null // teamLogic
+ error: string | null
+ page: number
+ recent: boolean
+ search: string
+ worksheets: Awaited<ReturnType<typeof insightsList>> | null
+ worksheetsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biWorksheetsLogicActions {
+ loadWorksheets: (_: void) => void
+ loadWorksheetsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadWorksheetsSuccess: (
+ worksheets: PaginatedInsightListApi,
+ payload?: void
+ ) => {
+ worksheets: PaginatedInsightListApi
+ payload?: void
+ }
+ setPage: (page: number) => {
+ page: number
+ }
+ setRecent: (recent: boolean) => {
+ recent: boolean
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+}
+
+export type biWorksheetsLogicType = MakeLogicType<biWorksheetsLogicValues, biWorksheetsLogicActions>
+
+export const biWorksheetsLogic = kea<biWorksheetsLogicType>([
+ path(['products', 'business_intelligence', 'biWorksheetsLogic']),
+ connect({ values: [teamLogic, ['currentTeamId']] }),
+ actions({
+ setSearch: (search: string) => ({ search }),
+ setPage: (page: number) => ({ page }),
+ setRecent: (recent: boolean) => ({ recent }),
+ }),
+ reducers({
+ search: ['', { setSearch: (_, { search }) => search }],
+ page: [1, { setPage: (_, { page }) => page, setSearch: () => 1, setRecent: () => 1 }],
+ recent: [false, { setRecent: (_, { recent }) => recent }],
+ error: [null as string | null, { loadWorksheets: () => null, loadWorksheetsFailure: (_, { error }) => error }],
+ }),
+ loaders(({ values }) => ({
+ worksheets: [
+ null as Awaited<ReturnType<typeof insightsList>> | null,
+ {
+ loadWorksheets: async (_: void, breakpoint) => {
+ await breakpoint(250)
+ const response = await insightsList(String(values.currentTeamId), {
+ insight: 'BI',
+ basic: true,
+ saved: true,
+ limit: 50,
+ offset: (values.page - 1) * 50,
+ search: values.search.trim() || undefined,
+ ...(values.recent ? { order: '-last_viewed_at', last_viewed_date_from: '-30d' } : {}),
+ })
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ })),
+ listeners(({ actions }) => ({
+ setSearch: () => actions.loadWorksheets(),
+ setPage: () => actions.loadWorksheets(),
+ setRecent: () => actions.loadWorksheets(),
+ })),
+ afterMount(({ actions }) => {
+ const { searchParams, hashParams } = router.values
+ if (searchParams.open_insight || searchParams.open_view || 'q' in hashParams || hashParams.bi) {
+ router.actions.replace(
+ searchParams.open_insight
+ ? urls.businessIntelligenceWorksheet(searchParams.open_insight)
+ : urls.businessIntelligenceNew(),
+ searchParams,
+ hashParams
+ )
+ return
+ }
+ captureBIWorksheetAction('opened', DEFAULT_BI_CONFIG)
+ actions.loadWorksheets()
+ }),
+])
diff --git a/products/business_intelligence/frontend/components/BIConditionGroups.tsx b/products/business_intelligence/frontend/components/BIConditionGroups.tsx
new file mode 100644
index 000000000000..7aa37c024bba
--- /dev/null
+++ b/products/business_intelligence/frontend/components/BIConditionGroups.tsx
@@ -0,0 +1,140 @@
+import { useState } from 'react'
+
+import { LemonButton, LemonModal, LemonSelect, LemonTag } from '@posthog/lemon-ui'
+
+import { BIConditionGroup } from '~/queries/schema/schema-business-intelligence'
+
+import {
+ moveBICondition,
+ normalizeBIConditionGroup,
+ ungroupBIConditionGroup,
+ updateBIConditionGroup,
+} from '../biFilterGroups'
+
+interface FilterOption {
+ value: string
+ label: string
+}
+
+function GroupEditor({
+ root,
+ group,
+ path,
+ options,
+ onChange,
+}: {
+ root: BIConditionGroup
+ group: BIConditionGroup
+ path: number[]
+ options: FilterOption[]
+ onChange: (group: BIConditionGroup) => void
+}): JSX.Element {
+ const update = (change: (node: BIConditionGroup) => BIConditionGroup): void =>
+ onChange(updateBIConditionGroup(root, path, change))
+ return (
+ <div
+ className="flex min-w-0 flex-col gap-2 rounded border p-2"
+ data-attr="bi-filter-group"
+ data-depth={path.length}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonSelect
+ size="small"
+ value={group.operator}
+ options={[
+ { value: 'AND', label: 'AND (match all)' },
+ { value: 'OR', label: 'OR (match any)' },
+ ]}
+ onChange={(operator) => update((node) => ({ ...node, operator }))}
+ />
+ {path.length > 0 && (
+ <LemonButton size="xsmall" onClick={() => onChange(ungroupBIConditionGroup(root, path))}>
+ Ungroup
+ </LemonButton>
+ )}
+ </div>
+ {group.filters.map((id) => (
+ <LemonTag key={id} className="max-w-full whitespace-normal">
+ {options.find((option) => option.value === id)?.label}
+ </LemonTag>
+ ))}
+ {group.groups.map((child, index) => (
+ <GroupEditor
+ key={index}
+ root={root}
+ group={child}
+ path={[...path, index]}
+ options={options}
+ onChange={onChange}
+ />
+ ))}
+ <div className="flex flex-wrap gap-2">
+ <LemonSelect
+ size="small"
+ placeholder="Move filter here"
+ value={null}
+ options={options.filter((option) => !group.filters.includes(option.value))}
+ onChange={(id) => id && onChange(moveBICondition(root, id, path))}
+ />
+ <LemonButton
+ size="xsmall"
+ disabledReason={path.length >= 8 ? 'Maximum group depth reached' : undefined}
+ onClick={() =>
+ update((node) => ({
+ ...node,
+ groups: [...node.groups, { operator: 'AND', filters: [], groups: [] }],
+ }))
+ }
+ >
+ Add group
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
+
+export function BIConditionGroups({
+ title,
+ group,
+ options,
+ onChange,
+}: {
+ title: string
+ group: BIConditionGroup | undefined
+ options: FilterOption[]
+ onChange: (group: BIConditionGroup) => void
+}): JSX.Element {
+ const [open, setOpen] = useState(false)
+ const normalized = normalizeBIConditionGroup(
+ group,
+ options.map((option) => option.value)
+ )
+ return (
+ <>
+ <LemonButton
+ size="xsmall"
+ disabledReason={!options.length ? 'Add filters first' : undefined}
+ onClick={() => setOpen(true)}
+ >
+ AND / OR groups
+ </LemonButton>
+ <LemonModal
+ title={title}
+ isOpen={open}
+ onClose={() => setOpen(false)}
+ width={560}
+ footer={
+ <LemonButton type="primary" onClick={() => setOpen(false)}>
+ Done
+ </LemonButton>
+ }
+ >
+ <p className="text-secondary">
+ 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} />
+ </LemonModal>
+ </>
+ )
+}
diff --git a/products/business_intelligence/frontend/components/BIFiltersCard.tsx b/products/business_intelligence/frontend/components/BIFiltersCard.tsx
index 1ea8c254867c..2b596de71017 100644
--- a/products/business_intelligence/frontend/components/BIFiltersCard.tsx
+++ b/products/business_intelligence/frontend/components/BIFiltersCard.tsx
@@ -8,12 +8,15 @@ import { BIFilterPill } from 'products/business_intelligence/frontend/components
import { BIShelfCard } from 'products/business_intelligence/frontend/components/BIShelfCard'
import { BIShelfDropTarget } from 'products/business_intelligence/frontend/components/BIShelfDropTarget'
+import { getBIFieldPillLabel, getBIFilterSummary } from '../biEditorTypes'
+import { BIConditionGroups } from './BIConditionGroups'
+
export function BIFiltersCard(): JSX.Element {
const { config } = useValues(biEditorLogic)
- const { addBlankFieldToShelf } = useActions(biEditorLogic)
+ const { addBlankFieldToShelf, setFilterGroup } = useActions(biEditorLogic)
return (
- <BIShelfCard title="Filters">
+ <BIShelfCard title="Row filters">
<BIShelfDropTarget shelf="filters" className="flex min-h-6 flex-col gap-0.5">
{config.filters.length > 0 ? (
config.filters.map((filter, index) => <BIFilterPill key={filter.field.id} index={index} />)
@@ -31,6 +34,15 @@ export function BIFiltersCard(): JSX.Element {
>
Add filter
</LemonButton>
+ <BIConditionGroups
+ title="Row filter groups"
+ group={config.rowFilterGroup}
+ options={config.filters.map((filter) => ({
+ value: filter.field.id,
+ label: `${getBIFieldPillLabel(filter.field)}: ${getBIFilterSummary(filter)}`,
+ }))}
+ onChange={(group) => setFilterGroup('row', group)}
+ />
</BIShelfCard>
)
}
diff --git a/products/business_intelligence/frontend/components/BIResultFiltersCard.tsx b/products/business_intelligence/frontend/components/BIResultFiltersCard.tsx
new file mode 100644
index 000000000000..4bcfb1956837
--- /dev/null
+++ b/products/business_intelligence/frontend/components/BIResultFiltersCard.tsx
@@ -0,0 +1,137 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonCheckbox, LemonDropdown, LemonInput, LemonSelect } from '@posthog/lemon-ui'
+
+import { BIResultFilter } from '~/queries/schema/schema-business-intelligence'
+
+import { biEditorLogic } from '../biEditorLogic'
+import { getBIResultFilterValidationError, getBIValuePillLabel } from '../biEditorTypes'
+import { BIConditionGroups } from './BIConditionGroups'
+import { BIShelfCard } from './BIShelfCard'
+
+const OPERATORS: { value: BIResultFilter['operator']; label: string }[] = [
+ { value: 'greater_than', label: 'Greater than' },
+ { value: 'greater_than_or_equal', label: 'At least' },
+ { value: 'less_than', label: 'Less than' },
+ { value: 'less_than_or_equal', label: 'At most' },
+ { value: 'equals', label: 'Equals' },
+ { value: 'not_equals', label: 'Does not equal' },
+ { value: 'between', label: 'Between (inclusive)' },
+ { value: 'is_set', label: 'Is set' },
+ { value: 'is_not_set', label: 'Is not set' },
+]
+
+function ResultFilterEditor({ filter }: { filter: BIResultFilter }): JSX.Element {
+ const { config } = useValues(biEditorLogic)
+ const { updateResultFilter, removeResultFilter } = useActions(biEditorLogic)
+ const error = getBIResultFilterValidationError(config, filter)
+ return (
+ <div className="flex w-64 max-w-full flex-col gap-2 p-2">
+ <LemonCheckbox
+ label="Apply result filter"
+ labelClassName="text-xs"
+ checked={filter.enabled !== false}
+ onChange={(enabled) => updateResultFilter(filter.id, { enabled })}
+ />
+ <LemonSelect
+ fullWidth
+ size="small"
+ value={filter.measureIndex}
+ options={
+ config.values.length
+ ? config.values.map((value, index) => ({ value: index, label: getBIValuePillLabel(value) }))
+ : [{ value: 0, label: 'Count' }]
+ }
+ onChange={(measureIndex) => updateResultFilter(filter.id, { measureIndex })}
+ />
+ <LemonSelect
+ fullWidth
+ size="small"
+ value={filter.operator}
+ options={OPERATORS}
+ onChange={(operator) => updateResultFilter(filter.id, { operator })}
+ />
+ {!['is_set', 'is_not_set'].includes(filter.operator) && (
+ <LemonInput
+ size="small"
+ aria-label="Result filter value"
+ placeholder={filter.operator === 'between' ? 'Minimum' : 'Value'}
+ value={filter.value}
+ status={error ? 'danger' : 'default'}
+ onChange={(value) => updateResultFilter(filter.id, { value })}
+ />
+ )}
+ {filter.operator === 'between' && (
+ <LemonInput
+ size="small"
+ aria-label="Result filter maximum"
+ placeholder="Maximum"
+ value={filter.valueTo ?? ''}
+ status={error ? 'danger' : 'default'}
+ onChange={(valueTo) => updateResultFilter(filter.id, { valueTo })}
+ />
+ )}
+ {error && (
+ <span role="alert" className="text-xs text-danger">
+ {error}
+ </span>
+ )}
+ <LemonButton size="small" status="danger" onClick={() => removeResultFilter(filter.id)}>
+ Remove filter
+ </LemonButton>
+ </div>
+ )
+}
+
+export function BIResultFiltersCard(): JSX.Element {
+ const { config } = useValues(biEditorLogic)
+ const { addResultFilter, setFilterGroup } = useActions(biEditorLogic)
+ const label = (filter: BIResultFilter): string =>
+ `${config.values[filter.measureIndex] ? getBIValuePillLabel(config.values[filter.measureIndex]) : 'Count'} ${OPERATORS.find((operator) => operator.value === filter.operator)?.label.toLowerCase()} ${filter.value}${filter.operator === 'between' ? ` and ${filter.valueTo ?? ''}` : ''}`
+ return (
+ <BIShelfCard title="Result filters">
+ <p className="mb-1 text-xs text-secondary">Filter measures after aggregation and table calculations.</p>
+ <div className="flex min-w-0 flex-col gap-1">
+ {config.resultFilters?.map((filter) => (
+ <LemonDropdown
+ key={filter.id}
+ closeOnClickInside={false}
+ placement="right-start"
+ overlay={<ResultFilterEditor filter={filter} />}
+ >
+ <LemonButton
+ size="xsmall"
+ fullWidth
+ status={getBIResultFilterValidationError(config, filter) ? 'danger' : undefined}
+ tooltip={label(filter)}
+ data-attr="bi-result-filter"
+ >
+ <span className="min-w-0 truncate">
+ {filter.enabled === false ? 'Off · ' : ''}
+ {label(filter)}
+ </span>
+ </LemonButton>
+ </LemonDropdown>
+ ))}
+ </div>
+ <LemonButton
+ size="xsmall"
+ disabledReason={!config.source ? 'Select a data source first' : undefined}
+ onClick={addResultFilter}
+ data-attr="bi-add-result-filter"
+ >
+ Add result filter
+ </LemonButton>
+ <BIConditionGroups
+ title="Result filter groups"
+ group={config.resultFilterGroup}
+ options={(config.resultFilters ?? []).map((filter) => ({ value: filter.id, label: label(filter) }))}
+ onChange={(group) => setFilterGroup('result', group)}
+ />
+ {!!config.resultFilters?.length &&
+ (config.totals?.rows || config.totals?.columns || config.totals?.subtotals) && (
+ <p className="text-xs text-secondary">Totals still include all groups matching the row filters.</p>
+ )}
+ </BIShelfCard>
+ )
+}
diff --git a/products/business_intelligence/manifest.tsx b/products/business_intelligence/manifest.tsx
index bf57a0a4903a..5dd8a213396d 100644
--- a/products/business_intelligence/manifest.tsx
+++ b/products/business_intelligence/manifest.tsx
@@ -7,6 +7,12 @@ import { ProductManifest } from '~/types'
export const manifest: ProductManifest = {
name: 'Business intelligence',
scenes: {
+ BusinessIntelligenceHome: {
+ name: 'Worksheets',
+ import: () => import('./frontend/BIWorksheetsScene'),
+ projectBased: true,
+ iconType: 'business_intelligence',
+ },
BusinessIntelligence: {
name: 'Business intelligence',
import: () => import('./frontend/BusinessIntelligenceScene'),
@@ -18,10 +24,14 @@ export const manifest: ProductManifest = {
},
},
routes: {
- '/bi': ['BusinessIntelligence', 'businessIntelligence'],
+ '/bi': ['BusinessIntelligenceHome', 'businessIntelligence'],
+ '/bi/new': ['BusinessIntelligence', 'businessIntelligenceNew'],
+ '/bi/:insightShortId': ['BusinessIntelligence', 'businessIntelligenceWorksheet'],
},
redirects: {},
urls: {
+ businessIntelligenceNew: (): string => '/bi/new',
+ businessIntelligenceWorksheet: (insightShortId: string): string => `/bi/${encodeURIComponent(insightShortId)}`,
businessIntelligence: ({
insightShortId,
viewId,
@@ -47,8 +57,25 @@ export const manifest: ProductManifest = {
return `/bi${query ? `?${query}` : ''}${hash}`
},
},
- fileSystemTypes: {},
- treeItemsNew: [],
+ fileSystemTypes: {
+ 'insight/bi': {
+ name: 'Worksheet',
+ iconType: 'business_intelligence',
+ href: (ref: string) => urls.businessIntelligenceWorksheet(ref),
+ listHref: () => urls.businessIntelligence(),
+ filterKey: 'insight',
+ },
+ },
+ treeItemsNew: [
+ {
+ path: 'Worksheet',
+ type: 'insight',
+ iconType: 'business_intelligence',
+ href: `${urls.businessIntelligenceNew()}#q=`,
+ flag: FEATURE_FLAGS.SQL_EDITOR_BI_MODE,
+ sceneKeys: ['BusinessIntelligence', 'BusinessIntelligenceHome'],
+ },
+ ],
treeItemsProducts: [
{
path: 'Business intelligence',
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index c809f704d4a7..123fb056c70a 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9439,6 +9439,43 @@ export const BIQueryLimitApi = {
Number50000: 50000,
} as const
+export type Operator1Api = (typeof Operator1Api)[keyof typeof Operator1Api]
+
+export const Operator1Api = {
+ And: 'AND',
+ Or: 'OR',
+} as const
+
+export interface BIConditionGroupApi {
+ filters: string[]
+ groups: BIConditionGroupApi[]
+ operator: Operator1Api
+}
+
+export type Operator2Api = (typeof Operator2Api)[keyof typeof Operator2Api]
+
+export const Operator2Api = {
+ Equals: 'equals',
+ NotEquals: 'not_equals',
+ GreaterThan: 'greater_than',
+ LessThan: 'less_than',
+ GreaterThanOrEqual: 'greater_than_or_equal',
+ LessThanOrEqual: 'less_than_or_equal',
+ Between: 'between',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+} as const
+
+export interface BIResultFilterApi {
+ enabled?: boolean | null
+ id: string
+ /** @minimum 0 */
+ measureIndex: number
+ operator: Operator2Api
+ value: string
+ valueTo?: string | null
+}
+
export type BISortDirectionApi = (typeof BISortDirectionApi)[keyof typeof BISortDirectionApi]
export const BISortDirectionApi = {
@@ -9516,6 +9553,9 @@ export interface BIConfigApi {
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
limit: BIQueryLimitApi
+ resultFilterGroup?: BIConditionGroupApi | null
+ resultFilters?: BIResultFilterApi[] | null
+ rowFilterGroup?: BIConditionGroupApi | null
rows: BIFieldApi[]
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISortApi | null
diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.py
index 56cad49553ff..e03898b060de 100644
--- a/products/product_analytics/backend/models/insight.py
+++ b/products/product_analytics/backend/models/insight.py
@@ -267,7 +267,9 @@ class Insight(Taggable, RootTeamMixin, FileSystemSyncMixin, models.Model):
type="insight", # sync with APIScopeObject in scopes.py
ref=self.short_id,
name=self.name or self.derived_name or "Untitled",
- href=f"/insights/{self.short_id}",
+ href=f"/bi/{self.short_id}"
+ if (self.query or {}).get("kind") == "BIVisualizationNode"
+ else f"/insights/{self.short_id}",
meta={
"created_at": str(self.created_at),
"created_by": self.created_by_id,
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 12378797badd..e3f6b13723d1 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -1726,8 +1726,29 @@ Background calculation can be tracked using the `query_status` response field.""
),
OpenApiParameter(
name="insight",
- enum=["TRENDS", "FUNNELS", "RETENTION", "PATHS", "JOURNEYS", "STICKINESS", "LIFECYCLE", "JSON", "SQL"],
- description="Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.",
+ enum=[
+ "TRENDS",
+ "FUNNELS",
+ "RETENTION",
+ "PATHS",
+ "JOURNEYS",
+ "STICKINESS",
+ "LIFECYCLE",
+ "JSON",
+ "SQL",
+ "BI",
+ ],
+ description="Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries; `BI` matches editable worksheets.",
+ ),
+ OpenApiParameter(
+ name="exclude_bi",
+ type=OpenApiTypes.BOOL,
+ description="Exclude Business intelligence worksheets from the insight list.",
+ ),
+ OpenApiParameter(
+ name="order",
+ type=OpenApiTypes.STR,
+ description="Sort by an insight field, with a leading minus for descending order. Supports last_modified_at and last_viewed_at.",
),
OpenApiParameter(
name="date_from",
@@ -2084,6 +2105,9 @@ class InsightViewSet(
queryset = queryset.filter(created_by=request.user)
elif key == "favorited":
queryset = queryset.filter(Q(favorited=True))
+ elif key == "exclude_bi":
+ if str_to_bool(request.GET["exclude_bi"]):
+ queryset = queryset.exclude(query__kind="BIVisualizationNode")
elif key == "hide_feature_flag_insights":
if str_to_bool(request.GET["hide_feature_flag_insights"]):
from posthog.helpers.dashboard_templates import feature_flag_generated_insight_q
@@ -2109,7 +2133,9 @@ class InsightViewSet(
"STICKINESS": schema.NodeKind.STICKINESS_QUERY,
"LIFECYCLE": schema.NodeKind.LIFECYCLE_QUERY,
}
- if insight == "JSON":
+ if insight == "BI":
+ queryset = queryset.filter(query__kind="BIVisualizationNode")
+ elif insight == "JSON":
queryset = queryset.filter(query__isnull=False)
queryset = queryset.exclude(query__kind__in=WRAPPER_NODE_KINDS, query__source__kind="HogQLQuery")
queryset = queryset.exclude(
diff --git a/products/product_analytics/backend/tests/api/test_bi_worksheets.py b/products/product_analytics/backend/tests/api/test_bi_worksheets.py
new file mode 100644
index 000000000000..ec85c0c8abda
--- /dev/null
+++ b/products/product_analytics/backend/tests/api/test_bi_worksheets.py
@@ -0,0 +1,30 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.product_analytics.backend.models.insight import Insight
+
+
+class TestBIWorksheetLists(APIBaseTest):
+ @parameterized.expand(
+ [
+ ({"insight": "BI"}, ["Worksheet"]),
+ ({"exclude_bi": "true"}, ["Trend"]),
+ ({"exclude_bi": "false"}, ["Trend", "Worksheet"]),
+ ]
+ )
+ def test_separates_worksheets_without_exposing_other_projects(
+ self, filters: dict[str, str], names: list[str]
+ ) -> None:
+ query = {"kind": "BIVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}}
+ Insight.objects.create(team=self.team, name="Worksheet", saved=True, query=query)
+ Insight.objects.create(team=self.team, name="Trend", saved=True)
+ other_team = Team.objects.create(organization=self.organization)
+ Insight.objects.create(team=other_team, name="Other project", saved=True, query=query)
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/insights/", {"basic": "true", "saved": "true", **filters}
+ )
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(sorted(item["name"] for item in response.json()["results"]), names)
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 7e6c64ca7429..747d6426a592 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8366,6 +8366,43 @@ export const BIQueryLimitApi = {
Number50000: 50000,
} as const
+export type Operator1Api = (typeof Operator1Api)[keyof typeof Operator1Api]
+
+export const Operator1Api = {
+ And: 'AND',
+ Or: 'OR',
+} as const
+
+export interface BIConditionGroupApi {
+ filters: string[]
+ groups: BIConditionGroupApi[]
+ operator: Operator1Api
+}
+
+export type Operator2Api = (typeof Operator2Api)[keyof typeof Operator2Api]
+
+export const Operator2Api = {
+ Equals: 'equals',
+ NotEquals: 'not_equals',
+ GreaterThan: 'greater_than',
+ LessThan: 'less_than',
+ GreaterThanOrEqual: 'greater_than_or_equal',
+ LessThanOrEqual: 'less_than_or_equal',
+ Between: 'between',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+} as const
+
+export interface BIResultFilterApi {
+ enabled?: boolean | null
+ id: string
+ /** @minimum 0 */
+ measureIndex: number
+ operator: Operator2Api
+ value: string
+ valueTo?: string | null
+}
+
export type BISortDirectionApi = (typeof BISortDirectionApi)[keyof typeof BISortDirectionApi]
export const BISortDirectionApi = {
@@ -8443,6 +8480,9 @@ export interface BIConfigApi {
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
limit: BIQueryLimitApi
+ resultFilterGroup?: BIConditionGroupApi | null
+ resultFilters?: BIResultFilterApi[] | null
+ rowFilterGroup?: BIConditionGroupApi | null
rows: BIFieldApi[]
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISortApi | null
@@ -9344,6 +9384,10 @@ export type InsightsListParams = {
* Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.
*/
date_to?: string
+ /**
+ * Exclude Business intelligence worksheets from the insight list.
+ */
+ exclude_bi?: boolean
/**
* Include this parameter (any value) to restrict results to insights marked as favorited.
*/
@@ -9354,7 +9398,7 @@ export type InsightsListParams = {
*/
include_dashboards?: boolean
/**
- * Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.
+ * Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries; `BI` matches editable worksheets.
*/
insight?: InsightsListInsight
/**
@@ -9373,6 +9417,10 @@ export type InsightsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Sort by an insight field, with a leading minus for descending order. Supports last_modified_at and last_viewed_at.
+ */
+ order?: string
/**
*
* Whether to refresh the retrieved insights, how aggressively, and if sync or async:
@@ -9414,6 +9462,7 @@ export const InsightsListFormat = {
export type InsightsListInsight = (typeof InsightsListInsight)[keyof typeof InsightsListInsight]
export const InsightsListInsight = {
+ Bi: 'BI',
Funnels: 'FUNNELS',
Journeys: 'JOURNEYS',
Json: 'JSON',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 15af28acba46..2b9051fd41fd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10718,6 +10718,45 @@ export namespace Schemas {
Number50000: 50000,
} as const;
+ export type Operator1 = typeof Operator1[keyof typeof Operator1];
+
+
+ export const Operator1 = {
+ And: 'AND',
+ Or: 'OR',
+ } as const;
+
+ export interface BIConditionGroup {
+ filters: string[];
+ groups: BIConditionGroup[];
+ operator: Operator1;
+ }
+
+ export type Operator2 = typeof Operator2[keyof typeof Operator2];
+
+
+ export const Operator2 = {
+ Equals: 'equals',
+ NotEquals: 'not_equals',
+ GreaterThan: 'greater_than',
+ LessThan: 'less_than',
+ GreaterThanOrEqual: 'greater_than_or_equal',
+ LessThanOrEqual: 'less_than_or_equal',
+ Between: 'between',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+ } as const;
+
+ export interface BIResultFilter {
+ enabled?: boolean | null;
+ id: string;
+ /** @minimum 0 */
+ measureIndex: number;
+ operator: Operator2;
+ value: string;
+ valueTo?: string | null;
+ }
+
export type BISortDirection = typeof BISortDirection[keyof typeof BISortDirection];
@@ -10798,6 +10837,9 @@ export namespace Schemas {
dateRange?: DateRange | null;
filters: BIFilter[];
limit: BIQueryLimit;
+ resultFilterGroup?: BIConditionGroup | null;
+ resultFilters?: BIResultFilter[] | null;
+ rowFilterGroup?: BIConditionGroup | null;
rows: BIField[];
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISort | null;
@@ -121419,6 +121461,10 @@ export namespace Schemas {
* Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.
*/
date_to?: string;
+ /**
+ * Exclude Business intelligence worksheets from the insight list.
+ */
+ exclude_bi?: boolean;
/**
* Include this parameter (any value) to restrict results to insights marked as favorited.
*/
@@ -121429,7 +121475,7 @@ export namespace Schemas {
*/
include_dashboards?: boolean;
/**
- * Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.
+ * Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries; `BI` matches editable worksheets.
*/
insight?: InsightsListInsight;
/**
@@ -121448,6 +121494,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Sort by an insight field, with a leading minus for descending order. Supports last_modified_at and last_viewed_at.
+ */
+ order?: string;
/**
*
* Whether to refresh the retrieved insights, how aggressively, and if sync or async:
@@ -121491,6 +121541,7 @@ export namespace Schemas {
export const InsightsListInsight = {
+ Bi: 'BI',
Funnels: 'FUNNELS',
Journeys: 'JOURNEYS',
Json: 'JSON',
diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.ts
index 1692f0bef227..025d1acebd3a 100644
--- a/services/mcp/src/generated/product_analytics/api.ts
+++ b/services/mcp/src/generated/product_analytics/api.ts
@@ -96,6 +96,7 @@ export const InsightsListQueryParams = () => zod.object({
.string()
.optional()
.describe('Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.'),
+ exclude_bi: zod.boolean().optional().describe('Exclude Business intelligence worksheets from the insight list.'),
favorited: zod
.boolean()
.optional()
@@ -108,10 +109,10 @@ export const InsightsListQueryParams = () => zod.object({
'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
),
insight: zod
- .enum(['FUNNELS', 'JOURNEYS', 'JSON', 'LIFECYCLE', 'PATHS', 'RETENTION', 'SQL', 'STICKINESS', 'TRENDS'])
+ .enum(['BI', 'FUNNELS', 'JOURNEYS', 'JSON', 'LIFECYCLE', 'PATHS', 'RETENTION', 'SQL', 'STICKINESS', 'TRENDS'])
.optional()
.describe(
- 'Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.'
+ 'Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries; `BI` matches editable worksheets.'
),
last_viewed_date_from: zod
.string()
@@ -123,6 +124,12 @@ export const InsightsListQueryParams = () => zod.object({
.describe('Filter by `last_viewed_at < last_viewed_date_to`. Accepts absolute or relative dates.'),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
+ order: zod
+ .string()
+ .optional()
+ .describe(
+ 'Sort by an insight field, with a leading minus for descending order. Supports last_modified_at and last_viewed_at.'
+ ),
refresh: zod
.enum([
'async',
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index a8f04e81a340..d3ba6047c92b 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -568,6 +568,7 @@ const insightsList = (): ToolBase<
dashboards: params.dashboards,
date_from: params.date_from,
date_to: params.date_to,
+ exclude_bi: params.exclude_bi,
favorited: params.favorited,
include_dashboards: params.include_dashboards,
insight: params.insight,
@@ -575,6 +576,7 @@ const insightsList = (): ToolBase<
last_viewed_date_to: params.last_viewed_date_to,
limit: params.limit,
offset: params.offset,
+ order: params.order,
saved: params.saved,
search: params.search,
short_id: params.short_id,
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 5de924d120b3..145534e5b09c 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -304,6 +304,16 @@
"params": [],
"scope": "project"
},
+ "businessIntelligenceNew": {
+ "template": "/bi/new",
+ "params": [],
+ "scope": "project"
+ },
+ "businessIntelligenceWorksheet": {
+ "template": "/bi/{insightShortId}",
+ "params": ["insightShortId"],
+ "scope": "project"
+ },
"businessKnowledge": {
"template": "/business-knowledge",
"params": [],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index 40e83b3af93b..9a14e64fd5de 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/scout-trials\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/scout-trials\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/verify_email\n/views\n/views/new\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
index bc920940fbaa..19165b186ab5 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
@@ -25,6 +25,10 @@
"description": "Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.",
"type": "string"
},
+ "exclude_bi": {
+ "description": "Exclude Business intelligence worksheets from the insight list.",
+ "type": "boolean"
+ },
"favorited": {
"description": "Include this parameter (any value) to restrict results to insights marked as favorited.",
"type": "boolean"
@@ -34,8 +38,19 @@
"type": "boolean"
},
"insight": {
- "description": "Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.",
- "enum": ["FUNNELS", "JOURNEYS", "JSON", "LIFECYCLE", "PATHS", "RETENTION", "SQL", "STICKINESS", "TRENDS"],
+ "description": "Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries; `BI` matches editable worksheets.",
+ "enum": [
+ "BI",
+ "FUNNELS",
+ "JOURNEYS",
+ "JSON",
+ "LIFECYCLE",
+ "PATHS",
+ "RETENTION",
+ "SQL",
+ "STICKINESS",
+ "TRENDS"
+ ],
"type": "string"
},
"last_viewed_date_from": {
@@ -54,6 +69,10 @@
"description": "The initial index from which to return the results.",
"type": "number"
},
+ "order": {
+ "description": "Sort by an insight field, with a leading minus for descending order. Supports last_modified_at and last_viewed_at.",
+ "type": "string"
+ },
"saved": {
"description": "When truthy, restricts results to insights that are saved (or attached to a visible dashboard). When falsy, only unsaved insights.",
"type": "boolean"