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 reusable hierarchies and next-level drill-down (#115588)

Marius Andra4dacfe167279
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 368aeaa62034..f73120b80d35 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -76,6 +76,8 @@ The **Marks** card offers table calculations per measure: percent of total, runn
Pivot tables display every measure beneath nested column headers. Expand or collapse a row or column header to move between hierarchy levels. Collapsed values are reaggregated from source rows, including averages and distinct counts. **Subtotals** also shows the intermediate aggregates while expanded. Row and column grand totals retain their separate controls, and total cells keep drill-down scoped to the visible dimensions. Expansion is local to the view; the worksheet's shelves and settings remain unchanged. Tracking records hierarchy expansion with axis and depth, and adds missing-date and full-window settings to the existing worksheet events.
+**Hierarchies** in the data pane names an ordered set of dimensions, such as Country → State → City. Create a hierarchy with 2–10 levels, then start it on rows or columns. Selecting a result offers **Drill to** the next level in a new worksheet, retaining filters for the selected parent values, the date range, and measures. Leaf values and levels already on a shelf do not offer another drill action; nested pivot expansion remains available for those shelves. Definitions stay with the saved worksheet and survive **Clear sheet**. **Import from worksheet** copies a hierarchy from an accessible saved worksheet using the same table and connection. The copy is independent: edits do not change the source worksheet or create global fields. Deleting a local calculated field removes its uses from hierarchy levels, dropping definitions with fewer than two remaining levels.
+
The **Analysis** card ranks **Top N** categories by a selected measure across the full current date range. **Include "Other"** combines the remaining source rows and re-aggregates them, including averages and distinct counts. Removing the ranking measure turns Top N off. Previous-period comparisons use the current period's category selection. Tables offer a grand total; pivot tables offer row and column grand totals. Both support hierarchy subtotals when an axis has multiple dimensions. Totals re-aggregate source rows; table-calculation cells remain blank on total rows. Summary rows can occupy at most half the result limit, reserving room for detail cells. The BI visualization requests an extra row to determine whether more results exist, then removes it before building tables and charts. Saved SQL and exports retain the worksheet's configured limit. A notice appears only when the response confirms more results beyond that limit, which also applies across comparison periods. Cached results and execution caps may prevent the extra row from being returned.
Each measure's **Format and display** dialog sets its label, currency, decimal precision, abbreviation, percentage format, and suffix. Percentage formatting expects fractional values (0.25 displays as 25%); percent-of-total and percent-change calculations produce that scale automatically. Formats persist in saved insights and apply to charts, tables, and pivot cells. Bar, line, and area charts support a separate series style and left/right axis for each measure. **Combine line + bar** assigns two measures to separate axes with bar and line styles.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 137fbb11a55c..36c4bd6d07c1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9971,17 +9971,17 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
hash: v1.k794b7964.69c71d482b1b19aa18a81b5ba0fc0bb038d8f3bdc9bdb0a7286c9addb4893dc2.LjgKhmcTELX-Cd50ZnnKmKLTGxv3AH0cD5BfLrBKfQ8
scenes-app-data-warehouse-sql-editor--bi-category-groups--dark:
- hash: v1.k794b7964.4862f067a79916c1bc7631cc581155719af255322b0d08285364e70d53b70d31.Y5LRP10StWiZcr-NqzWFC4UPVlr9HZn-V4mYhtyzBhg
+ hash: v1.k794b7964.db5febe752a0c601218161bf584e79b0d77bbbbd12966f8fe961a959c267ee1e.4ZiKbWINQmisbWlQVD6yBgyd5gJ4MOVfe8zokw_Tb0Y
scenes-app-data-warehouse-sql-editor--bi-category-groups--light:
- hash: v1.k794b7964.62b584942db83429d5384454db46559325a38aae7461fe858dca39d924c19b0c.bjTFL_dJv0ZVEJPu7g47thm4JpPkUi92CbW2jdQVksU
+ hash: v1.k794b7964.04625f1c9605316762dff7bd3e46f7b76802083005c8d09a22cd06608c682869.CSZ-F3iT7ug-a7AZjlgN8XSVME0fqP0GicbdBrzoMVM
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
hash: v1.k794b7964.2e8dbc1f0bb7bb1dcf836c5d4707c424d0141f0028125a4cb8d7c21090ccc431.5GXasdCC9-YudIAt1e1OtBh5E_I7A-AUg9hKCwbXQcA
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
hash: v1.k794b7964.04dd9cdc2ab2406095e54ac83367eb03e934d8077ffc7b91cbcc91c6353464f8.3qw_aAJ3Q9irvPSh21Es3dt_dfn8bAvwujrBfwiCJR0
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.b5b95871212596a43997b44286c217f1da94aaa8e13366b56ff98e9549040cc3.HqBVXoKkdHSEAU9IEyXRcTjcs4bubpYrtK1yJAa8e-M
+ hash: v1.k794b7964.2c3737b6e5d890efb0669574b681a782c986675ac3df6604be3172b54f7fa1f2.pN-fC2R_SkEl27zDFzyqPErFCM1q7KfMxaZWr_joTAc
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.653dba05f6a4fc4a6a89a75e7bd1fa711b0a4d55aac4c7f9d88a67629a42e9e6.wTdD8tsecGW5H2Ar2A3Fy5wneuEDttDOxW0Yi3NGWQc
+ hash: v1.k794b7964.459f184b6ec5bdd3cf9b4e9b7ddacda0463e8ae9ac490073d560f1ce0a51e2fe.BPnn_AzPAIFkpnsA015JwfMExsyL9o80wl-nMAnfgME
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
hash: v1.k794b7964.a1acb6f3170a9596f63792895642e0ed3b586a9f08c38439462711cabba2a246.y22PV6f4Ujxe7EbYAlaLmH0En029zIxy87yjmI6NKE8
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
@@ -10006,10 +10006,14 @@ snapshots:
hash: v1.k794b7964.6309ca3f3ecb88032969e856079e14cda460aa306a5172863693ff8a95ea011c.dIXWRHfmipDgezW97RK0MYne72aosXhe0o1S_uXrt_w
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
hash: v1.k794b7964.d60ca4f154f5b6aa7dfe97f5907d32aeb07d408ef2ccfdd9b86bd8880c17ba6b.m2J3D-2Zw-ub5S6SSZk2MFZf3rAXWA6146N6UMKx2Xo
+ scenes-app-data-warehouse-sql-editor--bi-named-hierarchy--dark:
+ hash: v1.k794b7964.e6f61be03177c256f1bb5dd7a4b5d79cee68d160cc0f989393e93a380cb17cb0.I6dU4AaYdoS1IJpK0NHhf4PY9n_vu8Fh1ZeDfhqYrZY
+ scenes-app-data-warehouse-sql-editor--bi-named-hierarchy--light:
+ hash: v1.k794b7964.dc0afaa3d657c1d8a0e9b67fb1fd33456dd609953cafa443523c4f199eb3fdc9.siBkKwoFyxSMYhoa_pWeSnxWi4P6_zKPVocTkH14Vow
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--dark:
- hash: v1.k794b7964.4532221938c1106707fc5f0c0b5d3d46190a3fe1aa308c8c171e4a388740c1dc.UFEB1zCEm5S6DQuqCv3qzsDKUwXT-Q4r1NRsdjuOiDw
+ hash: v1.k794b7964.ce7f9b0758d844ef7e601584ccf4e00bd56e11fc4e3a99d79a41a11e2f4bbc25.o-zb8OLX9Kvxf9mxobVialeZLI6s6H2J-fKiC2Oxokg
scenes-app-data-warehouse-sql-editor--bi-numeric-bins--light:
- hash: v1.k794b7964.e657e5340fa1f9cc5e47629bf17ea1bed6e13a8c7a97da216c55695be518f999.x1iI2nub4uOCHgHIXDykRlEWgr1sLn9d8vUeGjm_8ps
+ hash: v1.k794b7964.9b234c135dad525901107f80bc445c7b89af51a3c134f9150dc10d046431843f.hph6byvyMOb86wmhGzrpDsK1Kcfnu2zaxnAlwQTP8ls
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
hash: v1.k794b7964.2df94a5485dcafae44f3d5809fc628beaa922709115b7054e7efb718586d45bc.egZdKfplib4AJI3CBOZujqfjklXOm8uHI9Lmf0u98Ps
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
@@ -10023,9 +10027,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
hash: v1.k794b7964.36f528a219125afe7c4b3560c23186d45ccd168c425b71dc7b3aa3ad4eceb75f.DkHc1_D-S2BUrITOk9Pq6PrjOe1PWiBq13riygF45jU
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.b9e08999b9e7fa195b3049a27590f7b26d00f32ed21abbc03083dcf5be095fa9.uIKlPLFSpiY_QsB1ywcr0HpTU4lYG4Wv7X9d8z9WgK0
+ hash: v1.k794b7964.5a454caf96f701bd143857fdb0409b81d61d85478b12c8dd30ec1e24c1f6b797.RL289SkBaWUNGq6w-uAkne1J9mJtwp7YsUydHRnZXnc
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.f0c45d8ef51292e34cffbfd727f8b3f0a01656288add9fda1c21329d3ab58552.pcHNenr182WYRP2IV1_lySz3HYGcTJ_4bhjs2fi5FFc
+ hash: v1.k794b7964.dbf24706c9ab3988200c93b62361d03dca1542bd10c8427b4775d618f55424a5.AOB9fkh4lFm5dTHRVptioJtCTAVPdVxoFj6jvE1zdqo
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.06df092616d217a4ebdaf0f5f35015c05fe63f5bc1e9b9c39dcdf6594293c0e3.D8zEjaefT5868HRYC8F6GkfsuMMlcxSxekM5z-VoXyM
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 452cba91332d..5dde400bab2c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6184,6 +6184,13 @@
},
"type": "array"
},
+ "hierarchies": {
+ "description": "Named dimension sequences saved with the worksheet; imports are independent copies.",
+ "items": {
+ "$ref": "#/definitions/BIHierarchy"
+ },
+ "type": "array"
+ },
"limit": {
"$ref": "#/definitions/BIQueryLimit"
},
@@ -6354,6 +6361,26 @@
],
"type": "string"
},
+ "BIHierarchy": {
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "levels": {
+ "description": "Ordered from the broadest dimension to the most detailed.",
+ "items": {
+ "$ref": "#/definitions/BIField"
+ },
+ "type": "array"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "name", "levels"],
+ "type": "object"
+ },
"BILocalFieldDefinition": {
"anyOf": [
{
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index a82ec36a5cbc..2c3a2d3d2845 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -77,6 +77,13 @@ export interface BICategoryGroup {
values: string[]
}
+export interface BIHierarchy {
+ id: string
+ name: string
+ /** Ordered from the broadest dimension to the most detailed. */
+ levels: BIField[]
+}
+
export interface BIValue {
field: BIField
/** Measures in older worksheets belong to rows. */
@@ -134,6 +141,8 @@ export interface BIConfig {
source: BIDataSource | null
/** Reusable expressions owned by this worksheet only. */
localFields?: BIField[]
+ /** Named dimension sequences saved with the worksheet; imports are independent copies. */
+ hierarchies?: BIHierarchy[]
colorBy?: string | null
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIField | null
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 7548cb7cccf9..cdba5f4c1395 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -23,7 +23,7 @@ import {
import type { DataWarehouseSavedQuery, InsightShortId } from '~/types'
import { AccessControlLevel, AccessControlResourceType, ChartDisplayType } from '~/types'
-import { buildBIQuery } from 'products/business_intelligence/frontend/biEditorTypes'
+import { buildBIQuery, getBIResultDimensions } from 'products/business_intelligence/frontend/biEditorTypes'
import { biSceneLogic } from 'products/business_intelligence/frontend/biSceneLogic'
import { expect, userEvent } from 'storybook/test'
@@ -1412,6 +1412,112 @@ export const BIPivotTotals: Story = {
},
}
+const BI_GEOGRAPHY_FIELDS: BIField[] = ['Country', 'State', 'City'].map((name) => ({
+ ...biEventsField(name, 'string'),
+ expression: `properties.${name.toLowerCase()}`,
+}))
+const BI_HIERARCHY_CONFIG: BIConfig = {
+ ...BI_WORKSHEET_CONFIG,
+ chartType: ChartDisplayType.ActionsTable,
+ rows: [BI_GEOGRAPHY_FIELDS[0]],
+ columns: [],
+ filters: [],
+ hierarchies: [{ id: 'geography', name: 'Geography', levels: BI_GEOGRAPHY_FIELDS }],
+}
+const BI_HIERARCHY_WORKSHEET = {
+ ...buildBIQuery(BI_HIERARCHY_CONFIG)!.node,
+ kind: NodeKind.BIVisualizationNode,
+ config: BI_HIERARCHY_CONFIG,
+}
+
+export const BINamedHierarchy: Story = {
+ ...BITableAnalysis,
+ parameters: {
+ ...BITableAnalysis.parameters,
+ pageUrl: `${urls.businessIntelligence()}#q=${encodeURIComponent(JSON.stringify(BI_HIERARCHY_WORKSHEET))}`,
+ testOptions: { ...BITableAnalysis.parameters?.testOptions, includeNavigationInSnapshot: true },
+ msw: {
+ mocks: {
+ ...BIModeWorksheet.parameters?.msw.mocks,
+ get: {
+ ...BIModeWorksheet.parameters?.msw.mocks.get,
+ '/api/projects/:team_id/insights/': {
+ results: [
+ {
+ id: 910,
+ short_id: 'exampleGeo',
+ name: 'Example geography',
+ query: BI_HIERARCHY_WORKSHEET,
+ },
+ ],
+ next: null,
+ count: 1,
+ },
+ '/api/projects/:team_id/insights/910/': {
+ id: 910,
+ short_id: 'exampleGeo',
+ name: 'Example geography',
+ query: BI_HIERARCHY_WORKSHEET,
+ },
+ },
+ post: {
+ ...BIModeWorksheet.parameters?.msw.mocks.post,
+ '/api/environments/:team_id/query/DatabaseSchemaQuery/': {
+ tables: {
+ events: {
+ id: 'events',
+ name: 'events',
+ type: 'posthog',
+ fields: {
+ ...BI_EVENTS_FIELDS,
+ ...Object.fromEntries(
+ BI_GEOGRAPHY_FIELDS.map((field) => [
+ field.name,
+ {
+ name: field.name,
+ hogql_value: field.expression,
+ type: field.type,
+ schema_valid: true,
+ },
+ ])
+ ),
+ },
+ },
+ },
+ },
+ '/api/environments/:team_id/query/HogQLQuery/': async ({ request }: MockResolverInfo) => {
+ const { query } = (await request.json()) as { query: { query: string } }
+ const level =
+ BI_GEOGRAPHY_FIELDS.find((field) =>
+ query.query.split('FROM')[0].includes(field.expression)
+ ) ?? BI_GEOGRAPHY_FIELDS[0]
+ const column = getBIResultDimensions({ ...BI_HIERARCHY_CONFIG, rows: [level] })[0].column
+ return [
+ 200,
+ {
+ columns: [column, 'sum_revenue'],
+ types: [
+ [column, 'String'],
+ ['sum_revenue', 'Float64'],
+ ],
+ results: [[`Example ${level.name.toLowerCase()}`, 120]],
+ hasMore: false,
+ },
+ ]
+ },
+ },
+ },
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByRole('button', { name: /^Run$/ }))
+ await userEvent.click(await canvas.findByText('120', { exact: true }))
+ await waitFor(() => expect(within(document.body).getByRole('link', { name: 'Drill to State' })).toBeVisible())
+ await stabilizeQueryElapsedTime()
+ },
+}
+
export const BICategoryGroups: Story = {
...BIModeWorksheet,
parameters: {
diff --git a/posthog/schema.py b/posthog/schema.py
index 164d5f8144be..127aef6e41cf 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5154,6 +5154,15 @@ class BIFilter(BaseModel):
values: list[str] | None = None
+class BIHierarchy(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ id: str
+ levels: list[BIField] = Field(..., description="Ordered from the broadest dimension to the most detailed.")
+ name: str
+
+
class BIResultFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -11370,6 +11379,10 @@ class BIConfig(BaseModel):
)
dateRange: DateRange | None = None
filters: list[BIFilter]
+ hierarchies: list[BIHierarchy] | None = Field(
+ default=None,
+ description=("Named dimension sequences saved with the worksheet; imports are independent copies."),
+ )
limit: BIQueryLimit
localFields: list[BIField] | None = Field(
default=None, description="Reusable expressions owned by this worksheet only."
diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsx
index 2e62d79a969c..24dd86ea61d1 100644
--- a/products/business_intelligence/frontend/BIDrilldownModal.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx
@@ -11,7 +11,7 @@ import { BIDrilldownProps, biDrilldownLogic } from './biDrilldownLogic'
import { captureBIWorksheetAction } from './biEditorAnalytics'
export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldownProps }): JSX.Element {
- const { selection, queries, showRows } = useValues(biDrilldownLogic(props))
+ const { selection, queries, showRows, hierarchyDrills } = useValues(biDrilldownLogic(props))
const { close, viewRows } = useActions(biDrilldownLogic(props))
return (
<LemonModal title="Explore this result" isOpen={!!selection} onClose={close} width={showRows ? '90vw' : 520}>
@@ -31,6 +31,17 @@ export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldow
</ul>
) : null}
<div className="flex flex-wrap gap-2">
+ {hierarchyDrills.map(({ hierarchy, next, worksheet }) => (
+ <LemonButton
+ key={hierarchy.id}
+ type="primary"
+ to={`${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(worksheet))}`}
+ onClick={close}
+ tooltip={`${hierarchy.name}: opens a new worksheet filtered to this selection`}
+ >
+ Drill to {next.name}
+ </LemonButton>
+ ))}
<LemonButton
type="primary"
onClick={() => {
diff --git a/products/business_intelligence/frontend/BIHierarchyImportModal.tsx b/products/business_intelligence/frontend/BIHierarchyImportModal.tsx
new file mode 100644
index 000000000000..5320d7c1db51
--- /dev/null
+++ b/products/business_intelligence/frontend/BIHierarchyImportModal.tsx
@@ -0,0 +1,125 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonInput, LemonModal, Spinner } from '@posthog/lemon-ui'
+
+import { biHierarchyLogic } from './biHierarchyLogic'
+
+export function BIHierarchyImportModal({ tabId }: { tabId: string }): JSX.Element {
+ const logic = biHierarchyLogic({ tabId })
+ const {
+ importOpen,
+ search,
+ page,
+ worksheets,
+ worksheetsLoading,
+ hierarchySource,
+ hierarchySourceLoading,
+ importHierarchies,
+ importError,
+ config,
+ selectedWorksheetId,
+ } = useValues(logic)
+ const { closeImport, setSearch, setPage, loadHierarchySource, importHierarchy, retryImport } = useActions(logic)
+ return (
+ <LemonModal isOpen={importOpen} onClose={closeImport} title="Import a hierarchy" width={600}>
+ <div className="flex flex-col gap-3">
+ <p className="m-0 text-secondary">
+ Copy a named hierarchy from a saved worksheet using the same data source.
+ </p>
+ <LemonInput
+ type="search"
+ aria-label="Search worksheets for hierarchies"
+ placeholder="Search saved worksheets"
+ value={search}
+ onChange={setSearch}
+ />
+ {importError ? (
+ <LemonBanner type="error">
+ Couldn't load worksheets or hierarchies.{' '}
+ <LemonButton
+ size="xsmall"
+ onClick={retryImport}
+ loading={worksheetsLoading || hierarchySourceLoading}
+ >
+ Retry
+ </LemonButton>
+ </LemonBanner>
+ ) : null}
+ {worksheetsLoading ? (
+ <Spinner />
+ ) : worksheets?.results.length ? (
+ <div className="max-h-60 overflow-y-auto">
+ {worksheets.results.map((worksheet) => (
+ <LemonButton
+ key={worksheet.id}
+ fullWidth
+ size="small"
+ active={hierarchySource?.id === worksheet.id}
+ loading={hierarchySourceLoading && selectedWorksheetId === worksheet.id}
+ disabledReason={hierarchySourceLoading ? 'Loading hierarchy definitions' : undefined}
+ onClick={() => loadHierarchySource(worksheet.id)}
+ >
+ <span className="truncate">
+ {worksheet.name || worksheet.derived_name || 'Untitled worksheet'}
+ </span>
+ </LemonButton>
+ ))}
+ </div>
+ ) : !importError ? (
+ <p className="m-0 text-secondary">No saved worksheets found.</p>
+ ) : null}
+ <div className="flex gap-2">
+ <LemonButton
+ size="small"
+ disabledReason={page === 0 || worksheetsLoading ? 'No previous page available' : undefined}
+ onClick={() => setPage(page - 1)}
+ >
+ Previous
+ </LemonButton>
+ <LemonButton
+ size="small"
+ disabledReason={!worksheets?.next || worksheetsLoading ? 'No next page available' : undefined}
+ onClick={() => setPage(page + 1)}
+ >
+ Next
+ </LemonButton>
+ </div>
+ {hierarchySourceLoading ? (
+ <Spinner />
+ ) : hierarchySource ? (
+ <div className="border-t pt-3 space-y-2">
+ {importHierarchies.length ? (
+ importHierarchies.map((hierarchy) => (
+ <LemonButton
+ key={hierarchy.id}
+ fullWidth
+ type="secondary"
+ onClick={() => importHierarchy(hierarchy.id)}
+ disabledReason={
+ hierarchy.levels.some(
+ (field) =>
+ field.source.table !== config.source?.table ||
+ (field.source.connectionId ?? null) !==
+ (config.source?.connectionId ?? null)
+ )
+ ? 'This hierarchy uses a different data source'
+ : undefined
+ }
+ >
+ <span className="min-w-0 text-left">
+ <span className="block truncate">{hierarchy.name}</span>
+ <span className="block text-xs font-normal break-words">
+ {hierarchy.levels.map((field) => field.name).join(' → ')}
+ </span>
+ </span>
+ </LemonButton>
+ ))
+ ) : (
+ <p className="m-0 text-secondary">This worksheet has no named hierarchies.</p>
+ )}
+ </div>
+ ) : null}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIHierarchyModal.tsx b/products/business_intelligence/frontend/BIHierarchyModal.tsx
new file mode 100644
index 000000000000..f7a6e647a9da
--- /dev/null
+++ b/products/business_intelligence/frontend/BIHierarchyModal.tsx
@@ -0,0 +1,95 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronDown, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonModal, LemonSelect } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { hierarchyFieldKey } from './biHierarchies'
+import { biHierarchyLogic } from './biHierarchyLogic'
+
+export function BIHierarchyModal({ tabId }: { tabId: string }): JSX.Element | null {
+ const { draft, availableFields, draftError } = useValues(biHierarchyLogic({ tabId }))
+ const { setDraft, saveHierarchy, moveLevel, removeLevel, addLevel } = useActions(biHierarchyLogic({ tabId }))
+ if (!draft) {
+ return null
+ }
+ return (
+ <LemonModal
+ isOpen
+ title="Named hierarchy"
+ onClose={() => setDraft(null)}
+ width={560}
+ footer={
+ <LemonButton type="primary" onClick={saveHierarchy} disabledReason={draftError}>
+ Save hierarchy
+ </LemonButton>
+ }
+ >
+ <div className="flex flex-col gap-3">
+ <p className="m-0 text-secondary">
+ Order dimensions from broadest to most detailed. Save the worksheet to reuse this hierarchy in other
+ worksheets.
+ </p>
+ <LemonField.Pure label="Name">
+ <LemonInput
+ aria-label="Hierarchy name"
+ value={draft.name}
+ onChange={(name) => setDraft({ ...draft, name })}
+ placeholder="For example, Geography"
+ />
+ </LemonField.Pure>
+ <ol className="m-0 pl-5 space-y-2">
+ {draft.levels.map((field, index) => (
+ <li key={hierarchyFieldKey(field)}>
+ <div className="flex min-w-0 items-center gap-1">
+ <span className="min-w-0 flex-1 truncate" title={field.name}>
+ {field.name}
+ </span>
+ <LemonButton
+ icon={<IconChevronDown className="rotate-180" />}
+ size="xsmall"
+ aria-label={`Move ${field.name} up`}
+ disabledReason={index === 0 ? 'Already the first level' : undefined}
+ onClick={() => moveLevel(index, -1)}
+ />
+ <LemonButton
+ icon={<IconChevronDown />}
+ size="xsmall"
+ aria-label={`Move ${field.name} down`}
+ disabledReason={
+ index === draft.levels.length - 1 ? 'Already the last level' : undefined
+ }
+ onClick={() => moveLevel(index, 1)}
+ />
+ <LemonButton
+ icon={<IconTrash />}
+ size="xsmall"
+ aria-label={`Remove ${field.name} level`}
+ onClick={() => removeLevel(index)}
+ />
+ </div>
+ </li>
+ ))}
+ </ol>
+ <LemonSelect
+ aria-label="Add hierarchy level"
+ placeholder="Add a level"
+ value={null}
+ disabledReason={draft.levels.length >= 10 ? 'A hierarchy can have up to 10 levels' : undefined}
+ options={availableFields.map((field) => ({ value: field.id, label: field.name }))}
+ onChange={(id) => {
+ if (id) {
+ addLevel(id)
+ }
+ }}
+ fullWidth
+ />
+ <p className="m-0 text-xs text-secondary">
+ Deleting or editing a hierarchy leaves fields already on shelves unchanged. Imported hierarchies are
+ independent copies.
+ </p>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIHierarchySection.tsx b/products/business_intelligence/frontend/BIHierarchySection.tsx
new file mode 100644
index 000000000000..489582b04f6c
--- /dev/null
+++ b/products/business_intelligence/frontend/BIHierarchySection.tsx
@@ -0,0 +1,79 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEllipsis, IconPlus } from '@posthog/icons'
+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
+
+import { biEditorLogic } from './biEditorLogic'
+import { hierarchyError } from './biHierarchies'
+import { BIHierarchyImportModal } from './BIHierarchyImportModal'
+import { biHierarchyLogic } from './biHierarchyLogic'
+import { BIHierarchyModal } from './BIHierarchyModal'
+
+export function BIHierarchySection({ tabId }: { tabId: string }): JSX.Element {
+ const { config, dataPaneSearch } = useValues(biEditorLogic({ tabId }))
+ const { removeHierarchy } = useActions(biEditorLogic({ tabId }))
+ const { editHierarchy, openImport, startHierarchy } = useActions(biHierarchyLogic({ tabId }))
+ return (
+ <div className="px-1 py-2">
+ <div className="flex items-center justify-between gap-1">
+ <span className="text-xs font-semibold text-secondary">Hierarchies</span>
+ <LemonMenu
+ items={[
+ { label: 'Create hierarchy', onClick: () => editHierarchy() },
+ { label: 'Import from worksheet', onClick: openImport },
+ ]}
+ >
+ <LemonButton size="xsmall" icon={<IconPlus />} aria-label="Add hierarchy" />
+ </LemonMenu>
+ </div>
+ {(config.hierarchies ?? [])
+ .filter((hierarchy) =>
+ [hierarchy.name, ...hierarchy.levels.map((level) => level.name)].some((name) =>
+ name.toLowerCase().includes(dataPaneSearch.toLowerCase())
+ )
+ )
+ .map((hierarchy) => (
+ <div key={hierarchy.id} className="flex min-w-0 items-center gap-1">
+ <LemonButton
+ size="xsmall"
+ className="min-w-0 flex-1"
+ tooltip={hierarchy.levels.map((level) => level.name).join(' → ')}
+ aria-label={hierarchy.name}
+ disabledReason={hierarchyError(hierarchy, config)}
+ onClick={() => startHierarchy(hierarchy.id, 'rows')}
+ >
+ <span className="truncate">{hierarchy.name}</span>
+ </LemonButton>
+ <LemonMenu
+ items={[
+ {
+ label: 'Start on rows',
+ disabledReason: hierarchyError(hierarchy, config),
+ onClick: () => startHierarchy(hierarchy.id, 'rows'),
+ },
+ {
+ label: 'Start on columns',
+ disabledReason: hierarchyError(hierarchy, config),
+ onClick: () => startHierarchy(hierarchy.id, 'columns'),
+ },
+ { label: 'Edit hierarchy', onClick: () => editHierarchy(hierarchy) },
+ {
+ label: 'Delete hierarchy',
+ status: 'danger',
+ onClick: () => removeHierarchy(hierarchy.id),
+ },
+ ]}
+ >
+ <LemonButton
+ icon={<IconEllipsis />}
+ size="xsmall"
+ aria-label={`Options for hierarchy ${hierarchy.name}`}
+ />
+ </LemonMenu>
+ </div>
+ ))}
+ <BIHierarchyModal tabId={tabId} />
+ <BIHierarchyImportModal tabId={tabId} />
+ </div>
+ )
+}
diff --git a/products/business_intelligence/frontend/biDrilldownLogic.ts b/products/business_intelligence/frontend/biDrilldownLogic.ts
index 926343eed24b..f81db042ba7e 100644
--- a/products/business_intelligence/frontend/biDrilldownLogic.ts
+++ b/products/business_intelligence/frontend/biDrilldownLogic.ts
@@ -4,6 +4,7 @@ import { VisualizationNode, NodeKind, DashboardFilter, HogQLVariable } from '~/q
import { BIDrillSelection, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'
import { captureBIWorksheetAction } from './biEditorAnalytics'
+import { getBIHierarchyDrills, BIHierarchyDrill } from './biHierarchies'
export interface BIDrilldownProps {
key: string
@@ -14,6 +15,7 @@ export interface BIDrilldownProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biDrilldownLogicValues {
+ hierarchyDrills: BIHierarchyDrill[]
queries: ReturnType<typeof getBIDrillQueries>
query: VisualizationNode
record: Record<string, unknown> | null
@@ -38,6 +40,7 @@ export interface biDrilldownLogicActions {
export interface biDrilldownLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ hierarchyDrills: (selection: BIDrillSelection | null, query: VisualizationNode) => BIHierarchyDrill[]
query: (arg: any, arg2: any, arg3: any) => VisualizationNode
selection: (record: Record<string, unknown> | null, query: VisualizationNode) => BIDrillSelection | null
queries: (selection: BIDrillSelection | null, query: VisualizationNode) => ReturnType<typeof getBIDrillQueries>
@@ -67,6 +70,11 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
showRows: [false, { inspect: () => false, viewRows: () => true, close: () => false }],
}),
selectors({
+ hierarchyDrills: [
+ (s) => [s.selection, s.query],
+ (selection: BIDrillSelection | null, query: VisualizationNode): BIHierarchyDrill[] =>
+ selection && query.kind === NodeKind.BIVisualizationNode ? getBIHierarchyDrills(query, selection) : [],
+ ],
query: [
() => [
(_, props) => props.query,
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index cb177ad04e3d..ad4375ca1fcf 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -20,6 +20,7 @@ import {
BISort,
BIConditionGroup,
BIResultFilter,
+ BIHierarchy,
} from '~/queries/schema/schema-business-intelligence'
import { CompareFilter, DatabaseSchemaTable, DateRange } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
@@ -93,6 +94,7 @@ function setDataSourceInConfig(config: BIConfig, source: BIDataSource): BIConfig
...config,
source,
localFields: undefined,
+ hierarchies: undefined,
colorBy: undefined,
comparisonPeriod: undefined,
rows: [],
@@ -472,6 +474,9 @@ export interface biEditorLogicActions {
index: number
shelf: BIShelf
}
+ removeHierarchy: (id: string) => {
+ id: string
+ }
removeLocalField: (fieldId: string) => {
fieldId: string
}
@@ -668,6 +673,9 @@ export interface biEditorLogicActions {
draft: BICalculatedMeasureDraft
fieldId: string
}
+ upsertHierarchy: (hierarchy: BIHierarchy) => {
+ hierarchy: BIHierarchy
+ }
upsertLocalField: (field: BIField) => {
field: BIField
}
@@ -740,6 +748,8 @@ export const biEditorLogic = kea<biEditorLogicType>([
setLocalFieldDraft: (field: BIField | null) => ({ field }),
saveLocalField: true,
upsertLocalField: (field: BIField) => ({ field }),
+ upsertHierarchy: (hierarchy: BIHierarchy) => ({ hierarchy }),
+ removeHierarchy: (id: string) => ({ id }),
setFilterGroup: (scope: 'row' | 'result', group: BIConditionGroup) => ({ scope, group }),
addResultFilter: () => ({ id: uuid() }),
updateResultFilter: (id: string, update: Partial<BIResultFilter>) => ({ id, update }),
@@ -902,6 +912,14 @@ export const biEditorLogic = kea<biEditorLogicType>([
freshBIConfig(),
{
upsertLocalField: (config, { field }) => upsertBILocalField(config, field),
+ upsertHierarchy: (config, { hierarchy }) => ({
+ ...config,
+ hierarchies: [...(config.hierarchies ?? []).filter((item) => item.id !== hierarchy.id), hierarchy],
+ }),
+ removeHierarchy: (config, { id }) => ({
+ ...config,
+ hierarchies: config.hierarchies?.filter((item) => item.id !== id),
+ }),
upsertCalculatedMeasure: (config, { draft, fieldId }) => {
if (!config.source) {
return config
@@ -961,6 +979,12 @@ export const biEditorLogic = kea<biEditorLogicType>([
...next,
rows: next.rows.filter((field) => !matches(field)),
columns: next.columns.filter((field) => !matches(field)),
+ hierarchies: next.hierarchies
+ ?.map((hierarchy) => ({
+ ...hierarchy,
+ levels: hierarchy.levels.filter((field) => !matches(field)),
+ }))
+ .filter((hierarchy) => hierarchy.levels.length >= 2),
filters: next.filters.filter((filter) => !matches(filter.field)),
dateField: next.dateField && matches(next.dateField) ? undefined : next.dateField,
})
@@ -1183,6 +1207,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
...freshBIConfig(),
source: config.source,
localFields: getBILocalFields(config),
+ hierarchies: config.hierarchies,
dateField: config.dateField,
dateRange: config.dateRange,
}),
@@ -1431,6 +1456,8 @@ export const biEditorLogic = kea<biEditorLogicType>([
setCompareFilter: () => actions.runAfterChange(),
setMissingDates: () => actions.runAfterChange(),
setDateField: () => actions.runAfterChange(),
+ upsertHierarchy: () => actions.runAfterChange(),
+ removeHierarchy: () => actions.runAfterChange(),
setDataSource: () => {
captureBIWorksheetAction('source_selected', values.config)
actions.runAfterChange()
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 9225ab70fea3..46c1a36b23cd 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -525,6 +525,22 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
}
const candidate = decodedConfig as Partial<BIConfig>
+ if (
+ candidate.hierarchies !== undefined &&
+ (!Array.isArray(candidate.hierarchies) ||
+ candidate.hierarchies.some(
+ (hierarchy) =>
+ !hierarchy ||
+ typeof hierarchy.id !== 'string' ||
+ typeof hierarchy.name !== 'string' ||
+ !Array.isArray(hierarchy.levels) ||
+ hierarchy.levels.length < 2 ||
+ hierarchy.levels.length > 10 ||
+ hierarchy.levels.some((field) => !parseBIFieldValue(field))
+ ))
+ ) {
+ return null
+ }
if (
candidate.localFields !== undefined &&
(!Array.isArray(candidate.localFields) || candidate.localFields.some((field) => !parseBIFieldValue(field)))
@@ -669,6 +685,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
source,
...(candidate.colorBy === null || typeof candidate.colorBy === 'string' ? { colorBy: candidate.colorBy } : {}),
...(candidate.localFields ? { localFields: candidate.localFields } : {}),
+ ...(candidate.hierarchies ? { hierarchies: candidate.hierarchies } : {}),
...(candidate.comparisonPeriod ? { comparisonPeriod: candidate.comparisonPeriod } : {}),
...(candidate.rowFilterGroup ? { rowFilterGroup: candidate.rowFilterGroup } : {}),
...(candidate.resultFilterGroup ? { resultFilterGroup: candidate.resultFilterGroup } : {}),
diff --git a/products/business_intelligence/frontend/biHierarchies.test.ts b/products/business_intelligence/frontend/biHierarchies.test.ts
new file mode 100644
index 000000000000..f0e057471447
--- /dev/null
+++ b/products/business_intelligence/frontend/biHierarchies.test.ts
@@ -0,0 +1,123 @@
+import { BIConfig, BIField, BIHierarchy, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { getBIDrillSelection } from './biDrilldown'
+import {
+ BIEditorView,
+ buildBIQuery,
+ DEFAULT_BI_CONFIG,
+ getBIResultDimensions,
+ parseBIEditorState,
+} from './biEditorTypes'
+import { getBIHierarchyDrills, hierarchyError } from './biHierarchies'
+
+const field = (name: string): BIField => ({
+ id: name,
+ name,
+ expression: `properties.${name}`,
+ type: 'string',
+ source: { table: 'events' },
+})
+const geography: BIHierarchy = { id: 'geography', name: 'Geography', levels: ['country', 'state', 'city'].map(field) }
+const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsTable,
+ rows: [field('country')],
+ values: [{ field: field('event'), aggregation: 'count' }],
+ hierarchies: [geography],
+}
+
+function worksheet(config: BIConfig): BIVisualizationNode {
+ return { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode, config }
+}
+
+it.each(['rows', 'columns'] as const)(
+ 'drills through successive %s levels while retaining parent filters and query context',
+ (shelf) => {
+ const node = worksheet({ ...config, rows: [], [shelf]: [field('country')] })
+ node.source.filters = { dateRange: { date_from: '-30d' }, filterTestAccounts: true }
+ node.source.variables = { test: { variableId: 'test', code_name: 'test', value: 'example' } }
+ const dimension = getBIResultDimensions(node.config)[0]
+ const selection = getBIDrillSelection(node.config, { [dimension.column]: "Example's country" })
+ const [drill] = getBIHierarchyDrills(node, selection)
+ expect(drill.next.name).toBe('state')
+ expect(drill.worksheet.config[shelf]).toEqual([{ ...field('state'), id: 'country' }])
+ expect(drill.worksheet.source.query).toContain("properties.country = 'Example\\'s country'")
+ expect(drill.worksheet.source.filters).toEqual(node.source.filters)
+ expect(drill.worksheet.source.variables).toEqual(node.source.variables)
+ const nextDimension = getBIResultDimensions(drill.worksheet.config)[0]
+ const [city] = getBIHierarchyDrills(
+ drill.worksheet,
+ getBIDrillSelection(drill.worksheet.config, { [nextDimension.column]: null })
+ )
+ expect(city.next.name).toBe('city')
+ expect(city.worksheet.source.query).toContain('properties.state IS NULL')
+ expect(city.worksheet.source.query).toContain("properties.country = 'Example\\'s country'")
+ expect(parseBIEditorState(BIEditorView.BI, city.worksheet.config)?.config.hierarchies).toEqual([geography])
+ }
+)
+
+it('preserves OR filter semantics, other dimensions, and measure calculations', () => {
+ const market = field('market')
+ const channel = field('channel')
+ const node = worksheet({
+ ...config,
+ columns: [channel],
+ filters: [{ field: market, operator: 'equals', value: 'example' }],
+ rowFilterGroup: { operator: 'OR', filters: [market.id], groups: [] },
+ values: [{ ...config.values[0], tableCalculation: { type: 'percent_of_total' } }],
+ topN: { fieldId: 'country', count: 5, measureIndex: 0, includeOther: false },
+ })
+ const [dimension] = getBIResultDimensions(node.config)
+ const [drill] = getBIHierarchyDrills(node, getBIDrillSelection(node.config, { [dimension.column]: 'Example' }))
+ expect(drill.worksheet.config.columns).toEqual([channel])
+ expect(drill.worksheet.config.values).toEqual(node.config.values)
+ expect(drill.worksheet.config.rowFilterGroup?.operator).toBe('AND')
+ expect(drill.worksheet.config.rowFilterGroup?.groups[0].operator).toBe('OR')
+ expect(drill.worksheet.config.topN).toBeUndefined()
+})
+
+it('does not offer another level for grand totals, leaf fields, or a level already on a shelf', () => {
+ for (const rows of [[field('city')], [field('country'), field('state')]]) {
+ const node = worksheet({ ...config, rows })
+ const [dimension] = getBIResultDimensions(node.config)
+ expect(getBIHierarchyDrills(node, getBIDrillSelection(node.config, { [dimension.column]: 'Example' }))).toEqual(
+ []
+ )
+ }
+ const node = worksheet(config)
+ expect(getBIHierarchyDrills(node, getBIDrillSelection(config, {}))).toEqual([])
+})
+
+it('rejects invalid definitions and malformed persisted levels', () => {
+ expect(hierarchyError({ ...geography, levels: [field('country'), field('country')] }, config)).toBeTruthy()
+ expect(
+ hierarchyError(
+ { ...geography, levels: [field('country'), { ...field('state'), source: { table: 'other' } }] },
+ config
+ )
+ ).toBeTruthy()
+ expect(
+ hierarchyError(
+ {
+ ...geography,
+ levels: [
+ field('country'),
+ {
+ ...field('state'),
+ localDefinition: { kind: 'expression', expression: 'count()', aggregate: true },
+ },
+ ],
+ },
+ config
+ )
+ ).toBeTruthy()
+ expect(
+ parseBIEditorState(BIEditorView.BI, {
+ ...config,
+ hierarchies: [{ ...geography, levels: [null, field('state')] }],
+ })
+ ).toBeNull()
+})
diff --git a/products/business_intelligence/frontend/biHierarchies.ts b/products/business_intelligence/frontend/biHierarchies.ts
new file mode 100644
index 000000000000..eb9756c9ce1a
--- /dev/null
+++ b/products/business_intelligence/frontend/biHierarchies.ts
@@ -0,0 +1,97 @@
+import { BIConfig, BIField, BIHierarchy, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import { BIDrillSelection, getBIDrillQueries } from './biDrilldown'
+import { buildBIQuery } from './biEditorTypes'
+
+export function hierarchyFieldKey(field: BIField): string {
+ return JSON.stringify([
+ field.source.connectionId ?? null,
+ field.source.table,
+ field.expression.trim(),
+ field.dateBucket ?? null,
+ field.datePart ?? null,
+ ])
+}
+
+export function hierarchyError(hierarchy: BIHierarchy, config: BIConfig): string | undefined {
+ if (!hierarchy.name.trim()) {
+ return 'Enter a hierarchy name'
+ }
+ if (
+ config.hierarchies?.some(
+ (item) => item.id !== hierarchy.id && item.name.toLowerCase() === hierarchy.name.trim().toLowerCase()
+ )
+ ) {
+ return 'Choose a different hierarchy name'
+ }
+ if (hierarchy.levels.length < 2 || hierarchy.levels.length > 10) {
+ return 'Choose between 2 and 10 levels'
+ }
+ if (
+ hierarchy.levels.some(
+ (field) =>
+ !field.expression.trim() ||
+ field.source.table !== config.source?.table ||
+ (field.source.connectionId ?? null) !== (config.source?.connectionId ?? null) ||
+ (field.localDefinition?.kind === 'expression' && field.localDefinition.aggregate)
+ )
+ ) {
+ return 'Choose dimensions from this worksheet’s data source'
+ }
+ if (new Set(hierarchy.levels.map(hierarchyFieldKey)).size !== hierarchy.levels.length) {
+ return 'Use each level only once'
+ }
+}
+
+export interface BIHierarchyDrill {
+ hierarchy: BIHierarchy
+ next: BIField
+ worksheet: BIVisualizationNode
+}
+
+export function getBIHierarchyDrills(node: BIVisualizationNode, selection: BIDrillSelection): BIHierarchyDrill[] {
+ if (!node.config.hierarchies?.length) {
+ return []
+ }
+ const filtered = getBIDrillQueries(node, selection)?.worksheet
+ if (!filtered) {
+ return []
+ }
+ const selected = new Set(selection.filters.map((filter) => hierarchyFieldKey(filter.field)))
+ const dimensions = [...node.config.rows, ...node.config.columns]
+ return (node.config.hierarchies ?? []).flatMap((hierarchy): BIHierarchyDrill[] => {
+ if (hierarchyError(hierarchy, node.config)) {
+ return []
+ }
+ const index = hierarchy.levels.findLastIndex((field) => selected.has(hierarchyFieldKey(field)))
+ const current = hierarchy.levels[index]
+ const next = hierarchy.levels[index + 1]
+ const active = current && dimensions.find((field) => hierarchyFieldKey(field) === hierarchyFieldKey(current))
+ if (!active || !next || dimensions.some((field) => hierarchyFieldKey(field) === hierarchyFieldKey(next))) {
+ return []
+ }
+ const replace = (field: BIField): BIField => (field.id === active.id ? { ...next, id: active.id } : field)
+ const config: BIConfig = {
+ ...filtered.config,
+ rows: filtered.config.rows.map(replace),
+ columns: filtered.config.columns.map(replace),
+ }
+ const built = buildBIQuery(config)?.node
+ if (!built) {
+ return []
+ }
+ return [
+ {
+ hierarchy,
+ next,
+ worksheet: {
+ ...built,
+ kind: NodeKind.BIVisualizationNode,
+ config,
+ source: { ...built.source, filters: filtered.source.filters, variables: filtered.source.variables },
+ },
+ },
+ ]
+ })
+}
diff --git a/products/business_intelligence/frontend/biHierarchyLogic.test.ts b/products/business_intelligence/frontend/biHierarchyLogic.test.ts
new file mode 100644
index 000000000000..4f7758c69655
--- /dev/null
+++ b/products/business_intelligence/frontend/biHierarchyLogic.test.ts
@@ -0,0 +1,72 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { BIField } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { biEditorLogic } from './biEditorLogic'
+import { BIEditorView, DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { biHierarchyLogic } from './biHierarchyLogic'
+
+const levels: BIField[] = ['category', 'subcategory'].map((name) => ({
+ id: name,
+ name,
+ expression: `properties.${name}`,
+ type: 'string',
+ source: { table: 'events' },
+}))
+const sourceConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ hierarchies: [{ id: 'categories', name: 'Categories', levels }],
+}
+
+beforeEach(() => {
+ initKeaTests()
+ useMocks({
+ get: {
+ '/api/projects/:team_id/external_data_sources/connections/': [],
+ '/api/projects/:team_id/warehouse_saved_queries/': { results: [] },
+ '/api/projects/:team_id/insights/910/': {
+ id: 910,
+ query: { kind: NodeKind.BIVisualizationNode, config: sourceConfig },
+ },
+ '/api/projects/:team_id/insights/911/': [403, { detail: 'Access denied' }],
+ },
+ post: { '/api/environments/:team_id/query/': { tables: {} } },
+ })
+})
+
+it('imports an independent definition without changing the source or the current shelves', async () => {
+ const logic = biHierarchyLogic({ tabId: 'hierarchy-test' })
+ logic.mount()
+ const editor = biEditorLogic({ tabId: 'hierarchy-test' })
+ editor.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: { ...DEFAULT_BI_CONFIG, source: { table: 'events' }, rows: [levels[0]] },
+ })
+ await expectLogic(logic, () => logic.actions.loadHierarchySource(910)).toFinishAllListeners()
+ expect(logic.values.importHierarchies).toEqual(sourceConfig.hierarchies)
+ logic.actions.importHierarchy('categories')
+ expect(logic.values.draft?.id).not.toBe('categories')
+ expect(logic.values.draft?.levels[0].id).not.toBe('category')
+ logic.actions.moveLevel(1, -1)
+ logic.actions.saveHierarchy()
+ expect(editor.values.config.hierarchies?.[0].levels.map((field) => field.name)).toEqual(['subcategory', 'category'])
+ expect(editor.values.config.rows).toEqual([levels[0]])
+ expect(logic.values.importHierarchies[0].levels.map((field) => field.name)).toEqual(['category', 'subcategory'])
+ logic.unmount()
+})
+
+it('clears a previously loaded definition when the next worksheet cannot be accessed', async () => {
+ const logic = biHierarchyLogic({ tabId: 'hierarchy-test' })
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.loadHierarchySource(910)).toFinishAllListeners()
+ expect(logic.values.importHierarchies).toHaveLength(1)
+ await expectLogic(logic, () => logic.actions.loadHierarchySource(911)).toFinishAllListeners()
+ expect(logic.values.importHierarchies).toEqual([])
+ expect(logic.values.importError).toBeTruthy()
+ expect(logic.values.hierarchySourceLoading).toBe(false)
+ logic.unmount()
+})
diff --git a/products/business_intelligence/frontend/biHierarchyLogic.ts b/products/business_intelligence/frontend/biHierarchyLogic.ts
new file mode 100644
index 000000000000..aba1282be359
--- /dev/null
+++ b/products/business_intelligence/frontend/biHierarchyLogic.ts
@@ -0,0 +1,331 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { uuid } from 'lib/utils/dom'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { BIField, BIHierarchy } from '~/queries/schema/schema-business-intelligence'
+import { isBIVisualizationNode } from '~/queries/utils'
+
+import { insightsList, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
+
+import type { BIConfig } from '../../../frontend/src/queries/schema/schema-business-intelligence'
+import type { InsightApi, PaginatedInsightListApi } from '../../product_analytics/frontend/generated/api.schemas'
+import { biEditorLogic } from './biEditorLogic'
+import { BIEditorView, parseBIEditorState } from './biEditorTypes'
+import type { BIDataPaneFields } from './biEditorTypes'
+import { hierarchyError, hierarchyFieldKey } from './biHierarchies'
+
+export interface BIHierarchyProps {
+ tabId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biHierarchyLogicValues {
+ config: BIConfig // biEditorLogic
+ dataPaneFields: BIDataPaneFields // biEditorLogic
+ currentTeamId: number | null // teamLogic
+ availableFields: BIField[]
+ draft: BIHierarchy | null
+ draftError: string | undefined
+ fields: BIField[]
+ hierarchySource: Awaited<ReturnType<typeof insightsRetrieve>> | null
+ hierarchySourceLoading: boolean
+ importError: string | null
+ importHierarchies: BIHierarchy[]
+ importOpen: boolean
+ page: number
+ search: string
+ selectedWorksheetId: number | string | null
+ 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 biHierarchyLogicActions {
+ addFieldToShelf: (
+ field: BIField,
+ shelf: import('./biEditorTypes').BIShelf
+ ) => {
+ field: BIField
+ shelf: import('./biEditorTypes').BIShelf
+ } // biEditorLogic
+ upsertHierarchy: (hierarchy: BIHierarchy) => {
+ hierarchy: BIHierarchy
+ } // biEditorLogic
+ addLevel: (fieldId: string) => {
+ fieldId: string
+ }
+ closeImport: () => {
+ value: true
+ }
+ editHierarchy: (hierarchy?: BIHierarchy) => {
+ hierarchy: BIHierarchy | undefined
+ }
+ importHierarchy: (id: string) => {
+ id: string
+ }
+ loadHierarchySource: (id: number | string) => number | string
+ loadHierarchySourceFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadHierarchySourceSuccess: (
+ hierarchySource: InsightApi | null,
+ payload?: number | string
+ ) => {
+ hierarchySource: InsightApi | null
+ payload?: number | string
+ }
+ loadWorksheets: (_: void) => void
+ loadWorksheetsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadWorksheetsSuccess: (
+ worksheets: PaginatedInsightListApi,
+ payload?: void
+ ) => {
+ worksheets: PaginatedInsightListApi
+ payload?: void
+ }
+ moveLevel: (
+ index: number,
+ offset: 1 | -1
+ ) => {
+ index: number
+ offset: 1 | -1
+ }
+ openImport: () => {
+ value: true
+ }
+ removeLevel: (index: number) => {
+ index: number
+ }
+ retryImport: () => {
+ value: true
+ }
+ saveHierarchy: () => {
+ value: true
+ }
+ setDraft: (draft: BIHierarchy | null) => {
+ draft: BIHierarchy | null
+ }
+ setPage: (page: number) => {
+ page: number
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+ startHierarchy: (
+ id: string,
+ shelf: 'columns' | 'rows'
+ ) => {
+ id: string
+ shelf: 'columns' | 'rows'
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biHierarchyLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ fields: (dataPaneFields: BIDataPaneFields) => BIField[]
+ availableFields: (fields: BIField[], draft: BIHierarchy | null) => BIField[]
+ draftError: (draft: BIHierarchy | null, config: BIConfig) => string | undefined
+ importHierarchies: (hierarchySource: InsightApi | null) => BIHierarchy[]
+ }
+}
+
+export type biHierarchyLogicType = MakeLogicType<
+ biHierarchyLogicValues,
+ biHierarchyLogicActions,
+ BIHierarchyProps,
+ biHierarchyLogicMeta
+>
+
+export const biHierarchyLogic = kea<biHierarchyLogicType>([
+ props({} as BIHierarchyProps),
+ key((props) => props.tabId),
+ path((key) => ['products', 'business_intelligence', 'biHierarchyLogic', key]),
+ connect((props: BIHierarchyProps) => ({
+ values: [biEditorLogic(props), ['config', 'dataPaneFields'], teamLogic, ['currentTeamId']],
+ actions: [biEditorLogic(props), ['upsertHierarchy', 'addFieldToShelf']],
+ })),
+ actions({
+ editHierarchy: (hierarchy?: BIHierarchy) => ({ hierarchy }),
+ setDraft: (draft: BIHierarchy | null) => ({ draft }),
+ saveHierarchy: true,
+ openImport: true,
+ closeImport: true,
+ setSearch: (search: string) => ({ search }),
+ setPage: (page: number) => ({ page }),
+ importHierarchy: (id: string) => ({ id }),
+ addLevel: (fieldId: string) => ({ fieldId }),
+ removeLevel: (index: number) => ({ index }),
+ moveLevel: (index: number, offset: -1 | 1) => ({ index, offset }),
+ startHierarchy: (id: string, shelf: 'rows' | 'columns') => ({ id, shelf }),
+ retryImport: true,
+ }),
+ reducers({
+ selectedWorksheetId: [
+ null as number | string | null,
+ {
+ loadHierarchySource: (_, id) => id,
+ loadWorksheets: () => null,
+ },
+ ],
+ hierarchySource: [
+ null as Awaited<ReturnType<typeof insightsRetrieve>> | null,
+ {
+ openImport: () => null,
+ loadHierarchySource: () => null,
+ loadWorksheets: () => null,
+ },
+ ],
+ draft: [
+ null as BIHierarchy | null,
+ {
+ editHierarchy: (_, { hierarchy }) => hierarchy ?? { id: uuid(), name: '', levels: [] },
+ setDraft: (_, { draft }) => draft,
+ upsertHierarchy: () => null,
+ removeLevel: (draft, { index }) =>
+ draft ? { ...draft, levels: draft.levels.filter((_, i) => i !== index) } : draft,
+ moveLevel: (draft, { index, offset }) => {
+ if (!draft || index + offset < 0 || index + offset >= draft.levels.length) {
+ return draft
+ }
+ const levels = [...draft.levels]
+ ;[levels[index], levels[index + offset]] = [levels[index + offset], levels[index]]
+ return { ...draft, levels }
+ },
+ },
+ ],
+ importOpen: [false, { openImport: () => true, closeImport: () => false, editHierarchy: () => false }],
+ search: ['', { setSearch: (_, { search }) => search, openImport: () => '' }],
+ page: [0, { setPage: (_, { page }) => page, setSearch: () => 0, openImport: () => 0 }],
+ importError: [
+ null as string | null,
+ {
+ openImport: () => null,
+ loadWorksheets: () => null,
+ loadWorksheetsFailure: (_, { error }) => error,
+ loadHierarchySource: () => null,
+ loadHierarchySourceFailure: (_, { 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: 20,
+ offset: values.page * 20,
+ search: values.search.trim() || undefined,
+ })
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ hierarchySource: [
+ null as Awaited<ReturnType<typeof insightsRetrieve>> | null,
+ {
+ loadHierarchySource: async (id: number | string, breakpoint) => {
+ const response = await insightsRetrieve(String(values.currentTeamId), id)
+ breakpoint()
+ return values.selectedWorksheetId === id ? response : null
+ },
+ },
+ ],
+ })),
+ selectors({
+ fields: [
+ (s) => [s.dataPaneFields],
+ (fields: BIDataPaneFields): BIField[] =>
+ [...fields.dimensions, ...fields.measures].filter(
+ (field) => !(field.localDefinition?.kind === 'expression' && field.localDefinition.aggregate)
+ ),
+ ],
+ availableFields: [
+ (s) => [s.fields, s.draft],
+ (fields: BIField[], draft: BIHierarchy | null): BIField[] =>
+ fields.filter(
+ (field) => !draft?.levels.some((level) => hierarchyFieldKey(level) === hierarchyFieldKey(field))
+ ),
+ ],
+ draftError: [
+ (s) => [s.draft, s.config],
+ (draft: BIHierarchy | null, config: BIConfig): string | undefined =>
+ draft ? hierarchyError(draft, config) : 'Create a hierarchy',
+ ],
+ importHierarchies: [
+ (s) => [s.hierarchySource],
+ (source: InsightApi | null): BIHierarchy[] => {
+ const query: unknown = source?.query
+ return query && isBIVisualizationNode(query)
+ ? (parseBIEditorState(BIEditorView.BI, query.config)?.config.hierarchies ?? [])
+ : []
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ retryImport: () => {
+ if (values.selectedWorksheetId !== null) {
+ actions.loadHierarchySource(values.selectedWorksheetId)
+ } else {
+ actions.loadWorksheets()
+ }
+ },
+ addLevel: ({ fieldId }) => {
+ const field = values.availableFields.find((field) => field.id === fieldId)
+ if (values.draft && field && values.draft.levels.length < 10) {
+ actions.setDraft({ ...values.draft, levels: [...values.draft.levels, field] })
+ }
+ },
+ startHierarchy: ({ id, shelf }) => {
+ const hierarchy = values.config.hierarchies?.find((item) => item.id === id)
+ if (hierarchy && !hierarchyError(hierarchy, values.config)) {
+ const field = hierarchy.levels[0]
+ actions.addFieldToShelf(
+ {
+ ...field,
+ id: uuid(),
+ localFieldId: field.localFieldId ?? (field.localDefinition ? field.id : undefined),
+ },
+ shelf
+ )
+ }
+ },
+ saveHierarchy: () => {
+ if (values.draft && !values.draftError) {
+ actions.upsertHierarchy({ ...values.draft, name: values.draft.name.trim() })
+ }
+ },
+ openImport: () => actions.loadWorksheets(),
+ setSearch: () => actions.loadWorksheets(),
+ setPage: () => actions.loadWorksheets(),
+ importHierarchy: ({ id }) => {
+ const hierarchy = values.importHierarchies.find((item) => item.id === id)
+ if (hierarchy) {
+ actions.editHierarchy({
+ ...hierarchy,
+ id: uuid(),
+ levels: hierarchy.levels.map((field) => ({ ...field, id: uuid(), localFieldId: undefined })),
+ })
+ }
+ },
+ })),
+])
diff --git a/products/business_intelligence/frontend/biLocalFields.ts b/products/business_intelligence/frontend/biLocalFields.ts
index f27df09d07fc..6e09f5624b83 100644
--- a/products/business_intelligence/frontend/biLocalFields.ts
+++ b/products/business_intelligence/frontend/biLocalFields.ts
@@ -83,6 +83,7 @@ export function upsertBILocalField(config: BIConfig, field: BIField): BIConfig {
localFields: [...(config.localFields ?? []).filter((current) => current.id !== field.id), field],
rows: config.rows.map(replace),
columns: config.columns.map(replace),
+ hierarchies: config.hierarchies?.map((hierarchy) => ({ ...hierarchy, levels: hierarchy.levels.map(replace) })),
values: config.values.map((value) => ({
...value,
field: replace(value.field),
diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.ts
index e1cdbb25916f..5ea0a1a79b9a 100644
--- a/products/business_intelligence/frontend/biSceneLogic.test.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts
@@ -225,7 +225,8 @@ describe('biSceneLogic', () => {
})
it('saves the wrapper and reopens the insight without a draft or SQL editor', async () => {
- const node = worksheet()
+ const hierarchy = { id: 'event-time', name: 'Event timeline', levels: [eventField, timestampField] }
+ const node = worksheet({ ...config, hierarchies: [hierarchy] })
node.chartSettings!.yAxis![0].settings = { formatting: { prefix: '$', suffix: '' } }
node.chartSettings!.goalLines = [{ label: 'Average', value: 0, calculation: 'mean', scope: 'series' }]
logic.actions.restoreWorksheet(node)
@@ -242,7 +243,7 @@ describe('biSceneLogic', () => {
logic = biSceneLogic({ tabId: 'reopened' })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.worksheet.config).toEqual(config)
+ expect(logic.values.worksheet.config).toEqual({ ...config, hierarchies: [hierarchy] })
expect(logic.values.worksheet.chartSettings?.yAxis?.[0].settings?.formatting?.prefix).toBe('$')
expect(logic.values.worksheet.chartSettings?.goalLines).toEqual(node.chartSettings!.goalLines)
expect(logic.values.hasUnsavedChanges).toBe(false)
@@ -514,7 +515,14 @@ describe('biSceneLogic', () => {
name: 'Category',
expression: 'lower(event)',
}
- logic.actions.restoreWorksheet(worksheet({ ...config, source, localFields: [localField] }))
+ const hierarchy = {
+ id: 'category-event',
+ name: 'Category events',
+ levels: [localField, { ...eventField, source }],
+ }
+ logic.actions.restoreWorksheet(
+ worksheet({ ...config, source, localFields: [localField], hierarchies: [hierarchy] })
+ )
logic.actions.recordWorksheet()
const data = dataNodeLogic({
key: logic.values.dataNodeKey,
@@ -530,6 +538,7 @@ describe('biSceneLogic', () => {
expect(logic.values.config).toMatchObject({
source,
localFields: [localField],
+ hierarchies: [hierarchy],
rows: [],
columns: [],
values: [],
diff --git a/products/business_intelligence/frontend/components/BIDataPane.tsx b/products/business_intelligence/frontend/components/BIDataPane.tsx
index 460a6fbcf0bc..c2d659c5ecfb 100644
--- a/products/business_intelligence/frontend/components/BIDataPane.tsx
+++ b/products/business_intelligence/frontend/components/BIDataPane.tsx
@@ -7,6 +7,7 @@ import { BIConnections } from 'products/business_intelligence/frontend/BIConnect
import { BIDataPaneSection } from 'products/business_intelligence/frontend/BIDataPaneSection'
import { BIDataSourcePicker } from 'products/business_intelligence/frontend/BIDataSourcePicker'
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
+import { BIHierarchySection } from 'products/business_intelligence/frontend/BIHierarchySection'
import { BIConnectionSelector } from './BIConnectionSelector'
@@ -87,6 +88,7 @@ export function BIDataPane({ tabId }: { tabId: string }): JSX.Element {
/>
</>
)}
+ {config.source && !dataPaneFieldsError ? <BIHierarchySection tabId={tabId} /> : null}
{config.source && !dataPaneFieldsError ? <BIConnections /> : null}
</div>
<div className="border-t p-2">
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index ab47d473bb6a..4101a0f34242 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9559,6 +9559,13 @@ export interface BIFilterApi {
values?: string[] | null
}
+export interface BIHierarchyApi {
+ id: string
+ /** Ordered from the broadest dimension to the most detailed. */
+ levels: BIFieldApi[]
+ name: string
+}
+
export type BIQueryLimitApi = (typeof BIQueryLimitApi)[keyof typeof BIQueryLimitApi]
export const BIQueryLimitApi = {
@@ -9702,6 +9709,8 @@ export interface BIConfigApi {
dateField?: BIFieldApi | null
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
+ /** Named dimension sequences saved with the worksheet; imports are independent copies. */
+ hierarchies?: BIHierarchyApi[] | null
limit: BIQueryLimitApi
/** Reusable expressions owned by this worksheet only. */
localFields?: BIFieldApi[] | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 95ec6fa92c8a..7da2ac073a8c 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8423,6 +8423,13 @@ export interface BIFilterApi {
values?: string[] | null
}
+export interface BIHierarchyApi {
+ id: string
+ /** Ordered from the broadest dimension to the most detailed. */
+ levels: BIFieldApi[]
+ name: string
+}
+
export type BIQueryLimitApi = (typeof BIQueryLimitApi)[keyof typeof BIQueryLimitApi]
export const BIQueryLimitApi = {
@@ -8566,6 +8573,8 @@ export interface BIConfigApi {
dateField?: BIFieldApi | null
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
+ /** Named dimension sequences saved with the worksheet; imports are independent copies. */
+ hierarchies?: BIHierarchyApi[] | null
limit: BIQueryLimitApi
/** Reusable expressions owned by this worksheet only. */
localFields?: BIFieldApi[] | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 58cd26ed800f..ee9acb2f8691 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10867,6 +10867,13 @@ export namespace Schemas {
values?: string[] | null;
}
+ export interface BIHierarchy {
+ id: string;
+ /** Ordered from the broadest dimension to the most detailed. */
+ levels: BIField[];
+ name: string;
+ }
+
export type BIQueryLimit = typeof BIQueryLimit[keyof typeof BIQueryLimit];
@@ -11018,6 +11025,8 @@ export namespace Schemas {
dateField?: BIField | null;
dateRange?: DateRange | null;
filters: BIFilter[];
+ /** Named dimension sequences saved with the worksheet; imports are independent copies. */
+ hierarchies?: BIHierarchy[] | null;
limit: BIQueryLimit;
/** Reusable expressions owned by this worksheet only. */
localFields?: BIField[] | null;