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): extend worksheet comparisons and local fields (#113455)

Marius Andrac1924b5b3d13
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 929bb5532f9c..1b27a4ef734d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6495,9 +6495,9 @@ snapshots:
products-business-intelligence-pivot-table--multiple-measures-and-hierarchies--light:
hash: v1.k794b7964.f3a5839e83ddc9921b021426487c0f0db66fe969bc1369dd799c98bd83c91c19.e4TqncN8iN7TmyLw5M8lgUEjfSjD2LgrVykUPu1Ws48
products-business-intelligence-worksheets--worksheets--dark:
- hash: v1.k794b7964.07d353f8f721fee4df50f532e578c185cb89a6e61838a84828b5d6aa8d074933.Vug8TcMYcUt4yrU-GMl8VkVhxa2sYMsjdHIOs3XbW6Q
+ hash: v1.k794b7964.3998501a45652d1982a4ae8217c905e0482c6979a4f54642cbc8739d991730ef.x5TzvSg7zyGoyTdnBYKHG__tv6ytXrmifpxCAgkyItg
products-business-intelligence-worksheets--worksheets--light:
- hash: v1.k794b7964.e90e46bb924e56d9c070a598383f0921ea8228a4c0e496f5c74f48786f573f20.YO56ekCK2pncH_qlfkRjVVKdEKYu0mNRGsaCMxFCBu4
+ hash: v1.k794b7964.4555ec007faf662eec95759dfa8eb37393e76e45a88cda912ba99ce6c8b219d6.dvKnhFxE9Rs1ruwCF0EWXB0x2rromI5oC_n3pjq2Grc
products-dashboards--dashboard-states--dark:
hash: v1.k794b7964.cc591635f83447f7bcfb802062302b8b1bbcd51826110b12fa0f68d4830dcfd3.CIgt_KxCyQRgbn7DPF4MDXc5JBlSxbaCPS0Snyx3cRs
products-dashboards--dashboard-states--light:
@@ -9738,6 +9738,10 @@ snapshots:
hash: v1.k794b7964.1c26a867126bd8f979d25b607a2b97f8ca6c6247af3277a01f3743b70ee79906.2WumIrqVnmCHOdKoSFlfOweHTj1x0mY2uixo5g-bBkE
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
hash: v1.k794b7964.e372f1acdc4460bd92df4c1d47b1995013566643ede9a4df193fd8519656a31e.0FqHLQiwr1QawwbcwZjh4O5bP0W_DEgWWXRX8etSTUU
+ scenes-app-data-warehouse-sql-editor--bi-category-groups--dark:
+ hash: v1.k794b7964.66ec45051a096c59a68b697692b10bb086a3ac739c25015e7cf0282e7c7053ad.DEBjzrYLSC2paBtr6HfGr8R8sGjsyokzXe2A_NozrHA
+ scenes-app-data-warehouse-sql-editor--bi-category-groups--light:
+ hash: v1.k794b7964.69f108b72473d757b7a8ce8f8465160e7d09d195d307037bc3e16f885051890d.hAmrrJ3QY4XcTBG0XB55k2ENtaQBeDGWgAaaWl0V7v8
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
hash: v1.k794b7964.09a8bc2f32bdc11358e8e2e47e8ee27f24c6c685013360f6d1cfa4c1d5b5936f.U-vRC09hHiNsoVqmtEHHk3J22eBn-fsFz_LD87tZX1Q
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
@@ -9770,6 +9774,10 @@ snapshots:
hash: v1.k794b7964.ba547f3a41ec2e8b517142f1a6549848e39ce50da6245a8185117128424b5fc6.mto7EGXrYQwr6BBCyPfkDZS_fYGuYIb_k6KbIkShjQY
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
hash: v1.k794b7964.f17b0a24d40667261252cd224fc879c6303e143cdb46582ea0c3d58516a96508.B3zMdPmNMyvPT29AsSlyzi2TOsGlD40QZz4jThEmkXY
+ scenes-app-data-warehouse-sql-editor--bi-numeric-bins--dark:
+ hash: v1.k794b7964.49ccf73c1eaefe539b3eb14172f6fc20577693ecfd0b2fc969b7c8a33f344b6c.2RAKqVztCf6GQ2MXlOgaP_AHgjJYJHlBtB4RW9JzmBM
+ scenes-app-data-warehouse-sql-editor--bi-numeric-bins--light:
+ hash: v1.k794b7964.57aea5873020e95f2201bf79c5c715c398b6411ff7893c30e24b0f09c472fe22.K__odgjET4LULBxnyhf9KIxhIBpCF3sStZEx5bxjuC0
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
hash: v1.k794b7964.bf9cdbe93cab7bf8f2cc7bc226082cea7dbc69cffb6496ce7b991b18d42fa682.8qoSKEAsOEoHEg8AbdLRi1olkEjewJKyZgqoQLvIEes
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 0c370d58b275..12a071655bc3 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6143,6 +6143,22 @@
"enum": ["count", "count_distinct", "sum", "average", "minimum", "maximum", "custom"],
"type": "string"
},
+ "BICategoryGroup": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "values": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["name", "values"],
+ "type": "object"
+ },
"BIConditionGroup": {
"additionalProperties": false,
"properties": {
@@ -6181,6 +6197,11 @@
"compareFilter": {
"$ref": "#/definitions/CompareFilter"
},
+ "comparisonPeriod": {
+ "description": "Explore only the comparison window, using dateRange as its reference window.",
+ "enum": ["previous", null],
+ "type": ["string", "null"]
+ },
"dateField": {
"anyOf": [
{
@@ -6204,6 +6225,13 @@
"limit": {
"$ref": "#/definitions/BIQueryLimit"
},
+ "localFields": {
+ "description": "Reusable expressions owned by this worksheet only.",
+ "items": {
+ "$ref": "#/definitions/BIField"
+ },
+ "type": "array"
+ },
"missingDates": {
"description": "Fill missing date buckets before table calculations. Unset preserves observed points only.",
"enum": ["gap", "zero"],
@@ -6293,6 +6321,9 @@
"id": {
"type": "string"
},
+ "localDefinition": {
+ "$ref": "#/definitions/BILocalFieldDefinition"
+ },
"name": {
"type": "string"
},
@@ -6354,6 +6385,53 @@
],
"type": "string"
},
+ "BILocalFieldDefinition": {
+ "anyOf": [
+ {
+ "additionalProperties": false,
+ "properties": {
+ "expression": {
+ "type": "string"
+ },
+ "groups": {
+ "items": {
+ "$ref": "#/definitions/BICategoryGroup"
+ },
+ "type": "array"
+ },
+ "kind": {
+ "const": "groups",
+ "type": "string"
+ },
+ "other": {
+ "type": "string"
+ }
+ },
+ "required": ["kind", "expression", "groups", "other"],
+ "type": "object"
+ },
+ {
+ "additionalProperties": false,
+ "properties": {
+ "expression": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "bins",
+ "type": "string"
+ },
+ "origin": {
+ "type": "number"
+ },
+ "width": {
+ "type": "number"
+ }
+ },
+ "required": ["kind", "expression", "width", "origin"],
+ "type": "object"
+ }
+ ]
+ },
"BIQueryLimit": {
"enum": [100, 1000, 10000, 50000],
"type": "number"
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index bad63be64787..1e090d594d5f 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -62,6 +62,16 @@ export interface BIField {
type: DatabaseSerializedFieldType
source: BIDataSource
dateBucket?: BIDateBucket
+ localDefinition?: BILocalFieldDefinition
+}
+
+export type BILocalFieldDefinition =
+ | { kind: 'groups'; expression: string; groups: BICategoryGroup[]; other: string }
+ | { kind: 'bins'; expression: string; width: number; origin: number }
+
+export interface BICategoryGroup {
+ name: string
+ values: string[]
}
export interface BIValue {
@@ -117,10 +127,14 @@ export interface BIFilter {
export interface BIConfig {
source: BIDataSource | null
+ /** Reusable expressions owned by this worksheet only. */
+ localFields?: BIField[]
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIField | null
dateRange?: DateRange
compareFilter?: CompareFilter
+ /** Explore only the comparison window, using dateRange as its reference window. */
+ comparisonPeriod?: 'previous' | null
chartType: ChartDisplayType
rows: BIField[]
columns: BIField[]
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 9cda8c1c9697..0d1ab106bf7d 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -161,6 +161,8 @@ const meta: Meta = {
mswDecorator({
get: {
'/api/environments/:team_id/external_data_sources/wizard': () => [200, AVAILABLE_SOURCES],
+ '/api/:scope/:team_id/external_data_sources/connections/': [],
+ '/api/:scope/:team_id/external_data_sources/direct_connection_options/': [],
},
post: {
'/api/environments/:team_id/query/:kind': async ({ request }) => {
@@ -1390,3 +1392,29 @@ export const BIPivotTotals: Story = {
},
},
}
+
+export const BICategoryGroups: Story = {
+ ...BIModeWorksheet,
+ parameters: {
+ ...BIModeWorksheet.parameters,
+ testOptions: { waitForSelector: '[data-attr="bi-local-field-modal"]', viewport: { width: 1050, height: 900 } },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByLabelText('Options for event', {}, { timeout: 15000 }))
+ const body = within(canvasElement.ownerDocument.body)
+ await userEvent.click(await body.findByText('Group categories', { exact: true }))
+ await userEvent.type(await body.findByLabelText('Group 1 name'), 'Purchases')
+ },
+}
+
+export const BINumericBins: Story = {
+ ...BIModeWorksheet,
+ parameters: { ...BICategoryGroups.parameters },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByLabelText('Options for revenue', {}, { timeout: 15000 }))
+ const body = within(canvasElement.ownerDocument.body)
+ await userEvent.click(await body.findByText('Create numeric bins', { exact: true }))
+ },
+}
diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.py
index b6fb6f0bf0a3..8ee93a2f0d2e 100644
--- a/posthog/hogql/filters.py
+++ b/posthog/hogql/filters.py
@@ -225,6 +225,10 @@ class ReplaceFilters(CloningVisitor):
return node
def visit_placeholder(self, node):
+ if node.chain in (["filters", "previous", "dateRange", "from"], ["filters", "previous", "dateRange", "to"]):
+ return self._comparison_visitor().visit_placeholder(
+ ast.Placeholder(expr=ast.Field(chain=["filters", "dateRange", node.chain[-1]]))
+ )
if node.chain == ["filters", "previous"]:
return self._comparison_visitor().visit_placeholder(ast.Placeholder(expr=ast.Field(chain=["filters"])))
# The column-bound form {filters(expr AS key, ...)}: the query author maps each filter key
diff --git a/posthog/hogql/printer/postgres_functions.py b/posthog/hogql/printer/postgres_functions.py
index a3424a629eb7..5b2ed39f6871 100644
--- a/posthog/hogql/printer/postgres_functions.py
+++ b/posthog/hogql/printer/postgres_functions.py
@@ -73,6 +73,15 @@ def _handle_to_last_day_of_month(args: list[str]) -> str:
return f"CAST((DATE_TRUNC('month', {args[0]}) + INTERVAL '1 month' - INTERVAL '1 day') AS DATE)"
+def _handle_position_case_insensitive_utf8(args: list[str]) -> str:
+ haystack, needle = f"LOWER({args[0]})", f"LOWER({args[1]})"
+ if len(args) == 2:
+ return f"STRPOS({haystack}, {needle})"
+ start = f"GREATEST(1, {args[2]})"
+ position = f"STRPOS(SUBSTRING({haystack} FROM {start}), {needle})"
+ return f"CASE WHEN {position} = 0 THEN 0 ELSE {position} + {start} - 1 END"
+
+
def _handle_today(args: list[str]) -> str:
return "CURRENT_DATE"
@@ -211,6 +220,7 @@ def _handle_log2(args: list[str]) -> str:
# PostgresPrinter._visit_to_start_of_call() and inline sub-hour code
# in visit_call(), which intercept before this dict is consulted.
POSTGRES_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {
+ "positionCaseInsensitiveUTF8": _handle_position_case_insensitive_utf8,
# Type conversions
"toDate": _make_cast_handler("DATE"),
"toDateTime": _make_cast_handler("TIMESTAMP"),
diff --git a/posthog/hogql/printer/test/test_postgres_printer.py b/posthog/hogql/printer/test/test_postgres_printer.py
index c3f5c901e4d8..3dd76fd70edd 100644
--- a/posthog/hogql/printer/test/test_postgres_printer.py
+++ b/posthog/hogql/printer/test/test_postgres_printer.py
@@ -914,6 +914,11 @@ class TestPostgresPrinter(BaseTest):
("startsWith", "startsWith('hello', 'he')", "starts_with(%(hogql_val_0)s, %(hogql_val_1)s)"),
("rand", "rand()", "random()"),
("generateSeries", "generateSeries(1, 10, 1)", "generate_series(1, 10, 1)"),
+ (
+ "positionCaseInsensitiveUTF8",
+ "positionCaseInsensitiveUTF8('Account', 'COUNT')",
+ "STRPOS(LOWER(%(hogql_val_0)s), LOWER(%(hogql_val_1)s))",
+ ),
# Type conversions
("toDate", "toDate('2024-01-01')", "CAST(%(hogql_val_0)s AS DATE)"),
("toDateTime", "toDateTime('2024-01-01')", "CAST(%(hogql_val_0)s AS TIMESTAMP)"),
diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.py
index 4eaf179afe21..9ff2b784eb5d 100644
--- a/posthog/hogql/test/test_filters.py
+++ b/posthog/hogql/test/test_filters.py
@@ -1,3 +1,4 @@
+from datetime import datetime
from typing import Any, Optional
import time_machine
@@ -87,6 +88,19 @@ class TestFilters(BaseTest):
with self.assertRaisesMessage(QueryError, "Select a"):
replace_filters(query, None, self.team)
+ def test_comparison_window_bounds_use_the_same_range_as_previous_rows(self) -> None:
+ filters = HogQLFilters(dateRange=DateRange(date_from="2026-01-08", date_to="2026-01-14"))
+ query = replace_filters(
+ parse_select("SELECT {filters.previous.dateRange.from}, {filters.previous.dateRange.to}"),
+ filters,
+ self.team,
+ )
+ assert isinstance(query, ast.SelectQuery)
+ for expression, expected in zip(query.select, ["2026-01-01", "2026-01-08"], strict=True):
+ assert isinstance(expression, ast.Constant)
+ assert isinstance(expression.value, datetime)
+ assert expression.value.strftime("%Y-%m-%d") == expected
+
def _parse_expr(self, expr: str, placeholders: Optional[dict[str, Any]] = None):
return clear_locations(parse_expr(expr, placeholders=placeholders))
diff --git a/posthog/schema.py b/posthog/schema.py
index 520cf8340deb..858dee640c4c 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -75,6 +75,7 @@ from posthog.schema_enums import (
ChartDisplayType as ChartDisplayType,
ColorMode as ColorMode,
Compare as Compare,
+ ComparisonPeriod as ComparisonPeriod,
ConversionRateInputType as ConversionRateInputType,
CoreEventCategory as CoreEventCategory,
CorrelationType as CorrelationType,
@@ -948,6 +949,14 @@ class AssistantUpdateEvent(BaseModel):
tool_call_id: str
+class BICategoryGroup(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ name: str
+ values: list[str]
+
+
class BIConditionGroup(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -965,6 +974,26 @@ class BIDataSource(BaseModel):
table: str
+class BILocalFieldDefinition1(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ expression: str
+ groups: list[BICategoryGroup]
+ kind: Literal["groups"] = "groups"
+ other: str
+
+
+class BILocalFieldDefinition2(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ expression: str
+ kind: Literal["bins"] = "bins"
+ origin: float
+ width: float
+
+
class BITotals(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -5006,6 +5035,7 @@ class BIField(BaseModel):
dateBucket: BIDateBucket | None = None
expression: str
id: str
+ localDefinition: BILocalFieldDefinition1 | BILocalFieldDefinition2 | None = None
name: str
source: BIDataSource
type: DatabaseSerializedFieldType
@@ -11141,6 +11171,10 @@ class BIConfig(BaseModel):
chartType: ChartDisplayType
columns: list[BIField]
compareFilter: CompareFilter | None = None
+ comparisonPeriod: ComparisonPeriod | None = Field(
+ default=None,
+ description=("Explore only the comparison window, using dateRange as its reference window."),
+ )
dateField: BIField | None = Field(
default=None,
description="Column that receives the worksheet and dashboard date range.",
@@ -11148,6 +11182,9 @@ class BIConfig(BaseModel):
dateRange: DateRange | None = None
filters: list[BIFilter]
limit: BIQueryLimit
+ localFields: list[BIField] | None = Field(
+ default=None, description="Reusable expressions owned by this worksheet only."
+ )
missingDates: MissingDates | None = Field(
default=None,
description=("Fill missing date buckets before table calculations. Unset preserves observed points only."),
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 6c96c8297c51..db460270e181 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -635,6 +635,11 @@ class Operator1(StrEnum):
OR_ = "OR"
+class ComparisonPeriod(Enum):
+ PREVIOUS = "previous"
+ NONE_TYPE_NONE = None
+
+
class MissingDates(StrEnum):
GAP = "gap"
ZERO = "zero"
diff --git a/products/business_intelligence/frontend/BIDataPaneField.tsx b/products/business_intelligence/frontend/BIDataPaneField.tsx
index b845d5a306e7..95fc000128c1 100644
--- a/products/business_intelligence/frontend/BIDataPaneField.tsx
+++ b/products/business_intelligence/frontend/BIDataPaneField.tsx
@@ -1,6 +1,7 @@
import { useActions } from 'kea'
-import { IconCalendar } from '@posthog/icons'
+import { IconCalendar, IconEllipsis } from '@posthog/icons'
+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
@@ -11,6 +12,7 @@ import {
BI_FIELD_DRAG_MIME_TYPE,
getBIDropTarget,
serializeBIField,
+ isNumericBIField,
} from 'products/business_intelligence/frontend/biEditorTypes'
function FieldTypeGlyph({ field, measure }: { field: BIField; measure: boolean }): JSX.Element {
@@ -47,35 +49,65 @@ export function BIDataPaneField({
measure: boolean
path?: string[]
}): JSX.Element {
- const { addFieldToShelf } = useActions(biEditorLogic)
+ const { addFieldToShelf, editLocalField } = useActions(biEditorLogic)
const addField = (field: BIField): void => {
const target = getBIDropTarget(field, 'rows')
addFieldToShelf(target.field, target.shelf)
}
return (
- <button
- key={field.id}
- type="button"
- draggable
- title={field.name}
- className={cn(
- 'flex h-6 w-full min-w-0 cursor-grab items-center gap-1 rounded px-1 text-left text-xs hover:bg-fill-highlight-100',
- 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent'
+ <div className="flex min-w-0 items-center group/bi-field">
+ <button
+ key={field.id}
+ type="button"
+ draggable
+ title={field.name}
+ className={cn(
+ 'flex h-6 w-full min-w-0 cursor-grab items-center gap-1 rounded px-1 text-left text-xs hover:bg-fill-highlight-100',
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent'
+ )}
+ onDragStart={(event) => {
+ event.dataTransfer.effectAllowed = 'copy'
+ event.dataTransfer.setData(BI_FIELD_DRAG_MIME_TYPE, serializeBIField(field))
+ }}
+ onDoubleClick={() => addField(field)}
+ onClick={(event) => {
+ if (event.detail === 0) {
+ addField(field)
+ }
+ }}
+ data-attr={measure ? 'bi-editor-data-pane-measure' : 'bi-editor-data-pane-dimension'}
+ >
+ <FieldTypeGlyph field={field} measure={measure} />
+ <span className="truncate">
+ {path.length ? field.name.slice(path.join('.').length + 1) : field.name}
+ </span>
+ </button>
+ {(field.localDefinition || isNumericBIField(field) || ['string', 'boolean'].includes(field.type)) && (
+ <LemonMenu
+ items={
+ field.localDefinition
+ ? [
+ {
+ label: 'Edit local definition',
+ onClick: () => editLocalField(field, field.localDefinition!.kind),
+ },
+ ]
+ : [
+ { label: 'Group categories', onClick: () => editLocalField(field, 'groups') },
+ ...(isNumericBIField(field)
+ ? [{ label: 'Create numeric bins', onClick: () => editLocalField(field, 'bins') }]
+ : []),
+ ]
+ }
+ >
+ <LemonButton
+ size="xxsmall"
+ icon={<IconEllipsis />}
+ aria-label={`Options for ${field.name}`}
+ className="shrink-0 opacity-0 group-hover/bi-field:opacity-100 focus:opacity-100"
+ />
+ </LemonMenu>
)}
- onDragStart={(event) => {
- event.dataTransfer.effectAllowed = 'copy'
- event.dataTransfer.setData(BI_FIELD_DRAG_MIME_TYPE, serializeBIField(field))
- }}
- onDoubleClick={() => addField(field)}
- onClick={(event) => {
- if (event.detail === 0) {
- addField(field)
- }
- }}
- data-attr={measure ? 'bi-editor-data-pane-measure' : 'bi-editor-data-pane-dimension'}
- >
- <FieldTypeGlyph field={field} measure={measure} />
- <span className="truncate">{path.length ? field.name.slice(path.join('.').length + 1) : field.name}</span>
- </button>
+ </div>
)
}
diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsx
index ed01ce13ddb0..2e62d79a969c 100644
--- a/products/business_intelligence/frontend/BIDrilldownModal.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx
@@ -41,14 +41,12 @@ export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldow
}}
to={
queries.worksheet
- ? `${urls.businessIntelligence()}#q=${encodeURIComponent(JSON.stringify(queries.worksheet))}`
+ ? `${urls.businessIntelligenceNew()}#q=${encodeURIComponent(JSON.stringify(queries.worksheet))}`
: undefined
}
disabledReason={
!queries.worksheet
- ? selection?.previous
- ? 'Open comparison-period rows below to explore their original dates'
- : 'Maximum filter group depth reached. View the underlying rows instead.'
+ ? '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 7a6d2949bdb1..c8223d9b6b30 100644
--- a/products/business_intelligence/frontend/BIEditor.tsx
+++ b/products/business_intelligence/frontend/BIEditor.tsx
@@ -21,6 +21,7 @@ import { BIShowMe } from 'products/business_intelligence/frontend/components/BIS
import { BIToolbar } from 'products/business_intelligence/frontend/components/BIToolbar'
import { BIAnalysisControls } from './BIAnalysisControls'
+import { BILocalFieldModal } from './BILocalFieldModal'
import { BIMeasureSettingsModal } from './BIMeasureSettingsModal'
import { BIResultFiltersCard } from './components/BIResultFiltersCard'
@@ -71,6 +72,7 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
>
<BIToolbar />
<BICalculatedMeasureModal />
+ <BILocalFieldModal />
<BIMeasureSettingsModal />
<div className="flex min-h-0 flex-1">
<div
diff --git a/products/business_intelligence/frontend/BIFilterValueInput.tsx b/products/business_intelligence/frontend/BIFilterValueInput.tsx
index ae47c5ca59eb..f805330a1e8a 100644
--- a/products/business_intelligence/frontend/BIFilterValueInput.tsx
+++ b/products/business_intelligence/frontend/BIFilterValueInput.tsx
@@ -19,9 +19,13 @@ export function BIFilterValueInput({ index }: { index: number }): JSX.Element |
const { setFilterValue, updateFilter } = useActions(biEditorLogic)
const filter = config.filters[index]
const [focused, setFocused] = useState(false)
- const valuesLogic = biFilterValuesLogic({ query: buildBIFilterOptionsQuery(config, index), active: focused })
- const { options, optionsLoading, optionsError } = useValues(valuesLogic)
- const { loadOptions } = useActions(valuesLogic)
+ const valuesLogic = biFilterValuesLogic({
+ query: buildBIFilterOptionsQuery(config, index),
+ active: focused,
+ config,
+ })
+ const { options, optionsLoading, optionsError, hasMore } = useValues(valuesLogic)
+ const { loadOptions, setSearch, loadMore } = useActions(valuesLogic)
if (!filter || ['last_7_days', 'is_set', 'is_not_set', 'custom'].includes(filter.operator)) {
return null
}
@@ -38,6 +42,8 @@ export function BIFilterValueInput({ index }: { index: number }): JSX.Element |
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onChange={(values) => updateFilter(index, { values })}
+ onInputChange={setSearch}
+ disableFiltering
placeholder={filter.operator === 'in' ? 'All values' : 'No excluded values'}
title={`Values for ${filter.field.name}`}
allowCustomValues
@@ -60,8 +66,10 @@ export function BIFilterValueInput({ index }: { index: number }): JSX.Element |
Retry
</LemonButton>
</div>
- ) : options?.length === 100 ? (
- <span className="text-xs text-tertiary">Showing 100 suggestions. Type to add another value.</span>
+ ) : hasMore ? (
+ <LemonButton size="xsmall" onClick={loadMore} loading={optionsLoading}>
+ Load more values
+ </LemonButton>
) : null}
</div>
)
diff --git a/products/business_intelligence/frontend/BILocalFieldModal.tsx b/products/business_intelligence/frontend/BILocalFieldModal.tsx
new file mode 100644
index 000000000000..fbe5e0f505e3
--- /dev/null
+++ b/products/business_intelligence/frontend/BILocalFieldModal.tsx
@@ -0,0 +1,195 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInput, LemonInputSelect, LemonModal } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { biEditorLogic } from './biEditorLogic'
+import { buildBIFilterOptionsQuery } from './biEditorTypes'
+import { biFilterValuesLogic } from './biFilterValuesLogic'
+import { localFieldError } from './biLocalFields'
+
+export function BILocalFieldModal(): JSX.Element | null {
+ const { localFieldDraft: draft, config } = useValues(biEditorLogic)
+ const { setLocalFieldDraft, saveLocalField } = useActions(biEditorLogic)
+ const definition = draft?.localDefinition
+ const sourceField =
+ draft && definition ? { ...draft, localDefinition: undefined, expression: definition.expression } : null
+ const valuesLogic = biFilterValuesLogic({
+ query: sourceField
+ ? buildBIFilterOptionsQuery(
+ { ...config, filters: [...config.filters, { field: sourceField, operator: 'in', value: '' }] },
+ config.filters.length
+ )
+ : null,
+ active: definition?.kind === 'groups',
+ config,
+ })
+ const { options, optionsLoading, hasMore, optionsError } = useValues(valuesLogic)
+ const { setSearch, loadMore, loadOptions } = useActions(valuesLogic)
+ if (!draft || !definition) {
+ return null
+ }
+ const error = !draft.name.trim() ? 'Enter a name' : localFieldError(definition)
+ return (
+ <LemonModal
+ isOpen
+ data-attr="bi-local-field-modal"
+ onClose={() => setLocalFieldDraft(null)}
+ title={definition.kind === 'bins' ? 'Numeric bins' : 'Category groups'}
+ footer={
+ <LemonButton type="primary" onClick={saveLocalField} disabledReason={error}>
+ Save local field
+ </LemonButton>
+ }
+ >
+ <div className="flex flex-col gap-3">
+ <p className="m-0 text-secondary">
+ This definition stays in this worksheet. Drag the new field from Dimensions onto a shelf to use it.
+ </p>
+ <LemonField.Pure label="Name">
+ <LemonInput
+ aria-label="Local field name"
+ value={draft.name}
+ onChange={(name) => setLocalFieldDraft({ ...draft, name })}
+ />
+ </LemonField.Pure>
+ <p className="m-0 text-xs text-secondary break-words">
+ Source: <code>{definition.expression}</code>
+ </p>
+ {definition.kind === 'bins' ? (
+ <>
+ <LemonField.Pure label="Bin width">
+ <LemonInput
+ type="number"
+ aria-label="Bin width"
+ value={definition.width}
+ onChange={(width) =>
+ setLocalFieldDraft({
+ ...draft,
+ localDefinition: { ...definition, width: width ?? 0 },
+ })
+ }
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Starting point">
+ <LemonInput
+ type="number"
+ aria-label="Starting point"
+ value={definition.origin}
+ onChange={(origin) =>
+ setLocalFieldDraft({
+ ...draft,
+ localDefinition: { ...definition, origin: origin ?? 0 },
+ })
+ }
+ />
+ </LemonField.Pure>
+ <p className="m-0 text-xs">
+ Each bin is labeled by its lower bound, includes that bound, and excludes the next one.
+ Missing values stay missing.
+ </p>
+ </>
+ ) : (
+ <>
+ {definition.groups.map((group, index) => (
+ <div key={index} className="flex flex-col gap-2 rounded border p-2">
+ <LemonInput
+ aria-label={`Group ${index + 1} name`}
+ placeholder="Group name"
+ value={group.name}
+ onChange={(name) =>
+ setLocalFieldDraft({
+ ...draft,
+ localDefinition: {
+ ...definition,
+ groups: definition.groups.map((current, i) =>
+ i === index ? { ...current, name } : current
+ ),
+ },
+ })
+ }
+ />
+ <LemonInputSelect
+ mode="multiple"
+ value={group.values}
+ options={(options ?? []).map((value) => ({
+ key: value,
+ label: value || '(empty string)',
+ }))}
+ loading={optionsLoading}
+ onInputChange={setSearch}
+ disableFiltering
+ allowCustomValues
+ disableCommaSplitting
+ onChange={(values) =>
+ setLocalFieldDraft({
+ ...draft,
+ localDefinition: {
+ ...definition,
+ groups: definition.groups.map((current, i) =>
+ i === index ? { ...current, values } : current
+ ),
+ },
+ })
+ }
+ placeholder="Search or enter values"
+ />
+ <LemonButton
+ size="xsmall"
+ status="danger"
+ onClick={() =>
+ setLocalFieldDraft({
+ ...draft,
+ localDefinition: {
+ ...definition,
+ groups: definition.groups.filter((_, i) => i !== index),
+ },
+ })
+ }
+ >
+ Remove group
+ </LemonButton>
+ </div>
+ ))}
+ {optionsError && (
+ <LemonButton size="xsmall" onClick={() => loadOptions()} loading={optionsLoading}>
+ Retry loading values
+ </LemonButton>
+ )}
+ {hasMore && (
+ <LemonButton size="xsmall" loading={optionsLoading} onClick={loadMore}>
+ Load more values
+ </LemonButton>
+ )}
+ <LemonButton
+ size="small"
+ onClick={() =>
+ setLocalFieldDraft({
+ ...draft,
+ localDefinition: {
+ ...definition,
+ groups: [...definition.groups, { name: '', values: [] }],
+ },
+ })
+ }
+ >
+ Add group
+ </LemonButton>
+ <LemonField.Pure label="Other values">
+ <LemonInput
+ value={definition.other}
+ onChange={(other) =>
+ setLocalFieldDraft({ ...draft, localDefinition: { ...definition, other } })
+ }
+ />
+ </LemonField.Pure>
+ <p className="m-0 text-xs text-secondary">
+ Unlisted values use this label. Missing values stay missing.
+ </p>
+ </>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIStarters.tsx b/products/business_intelligence/frontend/BIStarters.tsx
new file mode 100644
index 000000000000..06f5950835ba
--- /dev/null
+++ b/products/business_intelligence/frontend/BIStarters.tsx
@@ -0,0 +1,57 @@
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { BIConfig, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { captureBIWorksheetAction } from './biEditorAnalytics'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+export function starterWorksheetUrl(config: BIConfig): string {
+ const built = buildBIQuery(config)!
+ const worksheet: BIVisualizationNode = { ...built.node, kind: NodeKind.BIVisualizationNode, config }
+ return `${urls.businessIntelligenceNew()}?starter=1#q=${encodeURIComponent(JSON.stringify(worksheet))}`
+}
+
+const EVENTS_CONFIG: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ dateRange: { date_from: '-7d' },
+ chartType: ChartDisplayType.ActionsLineGraph,
+ rows: [
+ {
+ id: 'starter:timestamp',
+ name: 'timestamp',
+ expression: 'timestamp',
+ source: { table: 'events' },
+ type: 'datetime',
+ dateBucket: 'day',
+ },
+ ],
+}
+
+export function BIStarters(): JSX.Element {
+ return (
+ <section className="flex flex-col gap-2" aria-label="Worksheet starting points">
+ <h3 className="m-0">Start with a question</h3>
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ to={starterWorksheetUrl(EVENTS_CONFIG)}
+ onClick={() =>
+ captureBIWorksheetAction('starter_selected', EVENTS_CONFIG, { starter_kind: 'events' })
+ }
+ >
+ Events per day · Last 7 days
+ </LemonButton>
+ </div>
+ <p className="m-0 text-xs text-secondary">
+ Choose a starting point, check its definition, then Run. Save your worksheet to return to it or add it
+ to a dashboard.
+ </p>
+ </section>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIWorksheetsScene.tsx b/products/business_intelligence/frontend/BIWorksheetsScene.tsx
index a3c576fe21c5..745a8d8c9f1f 100644
--- a/products/business_intelligence/frontend/BIWorksheetsScene.tsx
+++ b/products/business_intelligence/frontend/BIWorksheetsScene.tsx
@@ -13,6 +13,7 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { BIStarters } from './BIStarters'
import { biWorksheetsLogic } from './biWorksheetsLogic'
export const scene: SceneExport = { component: BIWorksheetsScene, logic: biWorksheetsLogic }
@@ -36,6 +37,7 @@ export function BIWorksheetsScene(): JSX.Element {
</LemonButton>
}
/>
+ <BIStarters />
<div className="flex flex-wrap items-center gap-2">
<LemonInput type="search" placeholder="Search worksheets" value={search} onChange={setSearch} />
<LemonSegmentedButton
diff --git a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
index 195b800269b4..591858348aff 100644
--- a/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
+++ b/products/business_intelligence/frontend/BusinessIntelligenceScene.tsx
@@ -43,6 +43,7 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
canUndo,
canRedo,
copyDisabledReason,
+ worksheet,
} = useValues(logic)
const {
setName,
@@ -173,7 +174,9 @@ export function BusinessIntelligenceScene({ tabId = 'bi-default' }: { tabId?: st
/>
) : (
<div className="flex flex-1 items-center justify-center p-4 text-secondary">
- Select a table and add fields to build your worksheet.
+ {worksheet.config.source
+ ? 'Press Run to see the results of this worksheet.'
+ : 'Select a table and add fields to build your worksheet.'}
</div>
)}
</BIEditor>
diff --git a/products/business_intelligence/frontend/biAnalysis.test.ts b/products/business_intelligence/frontend/biAnalysis.test.ts
index 7cf2765da423..830acab889fc 100644
--- a/products/business_intelligence/frontend/biAnalysis.test.ts
+++ b/products/business_intelligence/frontend/biAnalysis.test.ts
@@ -20,6 +20,42 @@ const config: BIConfig = {
}
describe('BI analysis queries', () => {
+ it.each(['gap', 'zero'] as const)(
+ 'fills %s dates on direct connections before calculating windows',
+ (missingDates) => {
+ const source = { table: 'orders', connectionId: 'connection' }
+ const date = { ...field('created_at', 'datetime'), source, dateBucket: 'day' as const }
+ const worksheet: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source,
+ dateField: date,
+ rows: [date],
+ columns: [{ ...field('region'), source }],
+ values: [
+ {
+ field: { ...field('amount', 'float'), source },
+ aggregation: 'sum',
+ tableCalculation: { type: 'moving_average', window: 3 },
+ },
+ ],
+ chartType: ChartDisplayType.ActionsTable,
+ missingDates,
+ dateRange: { date_from: '2026-01-01', date_to: '2026-01-03' },
+ }
+ const query = buildBIQuery(worksheet)!.query
+ expect(query).not.toContain('WITH FILL')
+ expect(query).toContain('bi_dates CROSS JOIN bi_series LEFT JOIN bi_observed')
+ expect(query).toContain('bi_observed.bi_column_region IS NULL AND bi_series.bi_column_region IS NULL')
+ expect(query).toContain(
+ `if(bi_observed.bi_present = 1, toFloat(bi_observed.sum_amount), ${missingDates === 'zero' ? '0' : 'NULL'})`
+ )
+ expect(query).toContain('< {filters.dateRange.to}')
+ expect(query).toContain('FROM bi_current_filled')
+ expect(
+ buildBIQuery({ ...worksheet, dateRange: { date_from: '1800-01-01', date_to: '2026-01-01' } })!.query
+ ).not.toContain('bi_digits')
+ }
+ )
it.each(['gap', 'zero'] as const)(
'fills %s date buckets separately in each period before window calculations',
(missingDates) => {
diff --git a/products/business_intelligence/frontend/biAnalysis.ts b/products/business_intelligence/frontend/biAnalysis.ts
index 5955c115af4d..95d388434ca1 100644
--- a/products/business_intelligence/frontend/biAnalysis.ts
+++ b/products/business_intelligence/frontend/biAnalysis.ts
@@ -2,7 +2,7 @@ import { BIConfig, BIField, BITableCalculation, BIValue } from '~/queries/schema
import { escapeHogQLString, escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
import { ChartDisplayType } from '~/types'
-import { biComparisonCategory } from './biComparison'
+import { biComparisonSeries } from './biComparison'
import { limitBIComparisonQuery } from './biComparisonLimit'
import { buildBIFilledPeriod, getBIMissingDatesDisabledReason } from './biTimeSeries'
@@ -275,9 +275,13 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
dimensions.find((dimension) => ['date', 'datetime'].includes(dimension.field.type)) ??
input.columns[0] ??
input.rows[0]
- const breakdown = dimensions.find((dimension) => dimension !== xDimension)
select.push(
- `${breakdown ? `concat(bi_period, ' · ', ${biComparisonCategory(displayed[dimensions.indexOf(breakdown)])})` : 'bi_period'} AS bi_comparison`
+ `${biComparisonSeries(
+ 'bi_period',
+ dimensions
+ .filter((dimension) => dimension !== xDimension)
+ .map((dimension) => displayed[dimensions.indexOf(dimension)])
+ )} AS bi_comparison`
)
}
let order = input.orderBy
diff --git a/products/business_intelligence/frontend/biComparison.ts b/products/business_intelligence/frontend/biComparison.ts
index b290ea72ea87..d559ab99541c 100644
--- a/products/business_intelligence/frontend/biComparison.ts
+++ b/products/business_intelligence/frontend/biComparison.ts
@@ -8,16 +8,45 @@ export const BI_COMPARISON_EMPTY_LABEL = '(empty)'
export function biComparisonCategory(expression: string): string {
const empty = escapeHogQLString(BI_COMPARISON_EMPTY_LABEL)
- return `if(${expression} IS NULL, ${empty}, if(startsWith(toString(${expression}), ${empty}), concat(toString(${expression}), ' (category)'), toString(${expression})))`
+ return `if(${expression} IS NULL, ${empty}, if(substring(toString(${expression}), 1, ${BI_COMPARISON_EMPTY_LABEL.length}) = ${empty}, concat(toString(${expression}), ' (category)'), toString(${expression})))`
+}
+
+export function decodeBIComparisonCategory(category: string): string | null {
+ return category === BI_COMPARISON_EMPTY_LABEL
+ ? null
+ : category.startsWith(BI_COMPARISON_EMPTY_LABEL) && category.endsWith(' (category)')
+ ? category.slice(0, -11)
+ : category
+}
+
+export function decodeBIComparisonSeries(category: string): (string | null)[] {
+ return category
+ .split(' · ')
+ .map((part) =>
+ decodeBIComparisonCategory(
+ part.replace(/\\(\\|s)/g, (_, escaped: string) => (escaped === 's' ? ' · ' : '\\'))
+ )
+ )
+}
+
+export function biComparisonSeries(period: string, dimensions: string[]): string {
+ if (!dimensions.length) {
+ return period
+ }
+ const category =
+ dimensions.length === 1
+ ? biComparisonCategory(dimensions[0])
+ : `concat(${dimensions.map((dimension) => `replaceAll(replaceAll(${biComparisonCategory(dimension)}, ${escapeHogQLString('\\')}, ${escapeHogQLString('\\\\')}), ' · ', ${escapeHogQLString('\\s')})`).join(", ' · ', ")})`
+ return `concat(${period}, ' · ', ${category})`
}
export function getBIComparisonDisabledReason(config: BIConfig): string | undefined {
+ if (config.comparisonPeriod) {
+ return 'This worksheet explores the comparison window of its reference date range'
+ }
if (!getBIDateField(config) || !config.dateRange?.date_from || config.dateRange.date_from === 'all') {
return 'Select a date column and a bounded date range first'
}
- if (config.rows.length + config.columns.length > 2) {
- return 'Period comparisons support up to two dimensions'
- }
if (
![
ChartDisplayType.Auto,
diff --git a/products/business_intelligence/frontend/biDrilldown.test.ts b/products/business_intelligence/frontend/biDrilldown.test.ts
index 20503cf827e7..47020331177d 100644
--- a/products/business_intelligence/frontend/biDrilldown.test.ts
+++ b/products/business_intelligence/frontend/biDrilldown.test.ts
@@ -143,7 +143,31 @@ describe('BI drill-down', () => {
expect(queries.rows.source.query).toContain('{filters.previous}')
expect(queries.rows.source.query).toContain("toStartOfDay({filters.compareDate(timestamp)}) = '2026-06-01'")
expect(queries.rows.source.query).toContain("event = 'purchase · web'")
- expect(queries.worksheet).toBeNull()
+ expect(queries.worksheet?.config.comparisonPeriod).toBe('previous')
+ expect(queries.worksheet?.source.query).toContain('{filters.previous}')
+ expect(parseBIEditorState(BIEditorView.BI, queries.worksheet?.config)).not.toBeNull()
+ })
+
+ it('keeps every comparison breakdown, including nulls and separator text, in a filtered worksheet', () => {
+ const node = buildWorksheet({
+ ...config,
+ compareFilter: { compare: true },
+ columns: [field('event'), field('properties.country'), field('properties.browser')],
+ }).node
+ expect(node.source.query).toContain('replaceAll(replaceAll(')
+ const record = getBIChartRecord(
+ node,
+ 'bi_row_timestamp',
+ '2026-06-01',
+ 'Previous period · purchase\\sweb · (empty) · Firefox'
+ )
+ const selection = getBIDrillSelection(node.config, record)
+ const queries = getBIDrillQueries(node, selection)!
+ expect(selection.filters).toHaveLength(4)
+ expect(queries.worksheet?.source.query).toContain("event = 'purchase · web'")
+ expect(queries.worksheet?.source.query).toContain('properties.country IS NULL')
+ expect(queries.worksheet?.source.query).toContain("properties.browser = 'Firefox'")
+ expect(queries.worksheet?.source.query).not.toContain('UNION ALL')
})
it('selects the remainder with null-safe membership and removes the top N restriction', () => {
diff --git a/products/business_intelligence/frontend/biDrilldown.ts b/products/business_intelligence/frontend/biDrilldown.ts
index 27722fa7dad6..ff833b816d7c 100644
--- a/products/business_intelligence/frontend/biDrilldown.ts
+++ b/products/business_intelligence/frontend/biDrilldown.ts
@@ -11,7 +11,7 @@ import {
import { escapeHogQLString } from '~/queries/utils'
import { ChartDisplayType } from '~/types'
-import { BI_COMPARISON_EMPTY_LABEL, getBIComparisonDateExpression } from './biComparison'
+import { decodeBIComparisonCategory, decodeBIComparisonSeries, getBIComparisonDateExpression } from './biComparison'
import {
buildBIQuery,
buildBIRowsQuery,
@@ -171,15 +171,19 @@ export function getBIChartRecord(
}
if (config.compareFilter?.compare) {
record.bi_comparison = breakdown
- const dimension = getBIResultDimensions(config).find((dimension) => dimension.column !== xColumn)
- if (dimension && /^(Current|Previous|Comparison) period · /.test(breakdown)) {
+ const dimensions = getBIResultDimensions(config).filter((dimension) => dimension.column !== xColumn)
+ if (dimensions.length && /^(Current|Previous|Comparison) period · /.test(breakdown)) {
const category = breakdown.replace(/^(Current|Previous|Comparison) period · /, '')
- record[dimension.column] =
- category === BI_COMPARISON_EMPTY_LABEL
- ? null
- : category.startsWith(BI_COMPARISON_EMPTY_LABEL) && category.endsWith(' (category)')
- ? category.slice(0, -11)
- : category
+ if (dimensions.length > 1) {
+ const categories = decodeBIComparisonSeries(category)
+ if (categories.length === dimensions.length) {
+ dimensions.forEach((dimension, index) => {
+ record[dimension.column] = categories[index]
+ })
+ }
+ } else {
+ record[dimensions[0].column] = decodeBIComparisonCategory(category)
+ }
}
}
}
@@ -223,17 +227,18 @@ export function getBIDrillQueries(
}
: {}),
topN: undefined,
+ ...(selection.previous
+ ? { comparisonPeriod: 'previous' as const, compareFilter: { ...saved.compareFilter, compare: false } }
+ : {}),
}
- const source = buildBIRowsQuery(config, selection.previous)
+ const source = buildBIRowsQuery(config)
if (!source) {
return null
}
source.filters = { ...source.filters, ...node.source.filters }
source.variables = node.source.variables
const generated =
- selection.previous || (config.rowFilterGroup && !isBIConditionGroup(config.rowFilterGroup))
- ? null
- : buildBIQuery(config)?.node
+ 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 4723f9dacef8..cb14f49ee111 100644
--- a/products/business_intelligence/frontend/biEditorAnalytics.ts
+++ b/products/business_intelligence/frontend/biEditorAnalytics.ts
@@ -35,6 +35,8 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
config.filters.filter((filter) => filter.operator === 'custom').length
return {
+ local_group_count: config.localFields?.filter((field) => field.localDefinition?.kind === 'groups').length ?? 0,
+ local_bin_count: config.localFields?.filter((field) => field.localDefinition?.kind === 'bins').length ?? 0,
result_filter_count: config.resultFilters?.length ?? 0,
row_filter_group_count: filterGroupCount(config.rowFilterGroup),
result_filter_group_count: filterGroupCount(config.resultFilterGroup),
@@ -84,6 +86,10 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
}
export type BIWorksheetAction =
+ | 'starter_selected'
+ | 'filter_values_searched'
+ | 'filter_values_page_loaded'
+ | 'local_field_saved'
| 'undo'
| 'redo'
| 'copied'
@@ -111,6 +117,7 @@ export function captureBIWorksheetAction(
hierarchy_axis?: 'rows' | 'columns'
hierarchy_depth?: number
expanded?: boolean
+ starter_kind?: 'events'
} = {}
): void {
posthog.capture(BI_EDITOR_EVENTS.WORKSHEET_ACTION, {
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 48d43f38de36..e366d526c40a 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -50,6 +50,7 @@ import {
normalizeBIConfig,
} from 'products/business_intelligence/frontend/biEditorTypes'
+import { localFieldError, localFieldExpression, upsertBILocalField } from './biLocalFields'
import { matchesBIFieldSearch } from './biPropertyFields'
import { getBIDateField } from './biQueryFilters'
@@ -86,6 +87,8 @@ function setDataSourceInConfig(config: BIConfig, source: BIDataSource): BIConfig
return {
...config,
source,
+ localFields: undefined,
+ comparisonPeriod: undefined,
rows: [],
columns: [],
values: [],
@@ -306,6 +309,7 @@ export interface biEditorLogicValues {
filteredDataPaneFields: BIDataPaneFields
generatedQuery: BIQueryBuildResult | null
hoveredChartType: ChartDisplayType | null
+ localFieldDraft: BIField | null
selectableDataSources: BIDataSource[]
showMeOpen: boolean
sortOptions: BISortOption[]
@@ -354,6 +358,13 @@ export interface biEditorLogicActions {
editCalculatedMeasure: (index?: number | null) => {
index: number | null
}
+ editLocalField: (
+ field: BIField,
+ kind: 'bins' | 'groups'
+ ) => {
+ field: BIField
+ kind: 'bins' | 'groups'
+ }
editMeasureSettings: (index: number | null) => {
index: number | null
}
@@ -388,6 +399,9 @@ export interface biEditorLogicActions {
saveCalculatedMeasure: () => {
value: true
}
+ saveLocalField: () => {
+ value: true
+ }
setActiveDropShelf: (shelf: BIShelf | null) => {
shelf: BIShelf | null
}
@@ -477,6 +491,9 @@ export interface biEditorLogicActions {
setLimit: (limit: BIQueryLimit) => {
limit: BIQueryLimit
}
+ setLocalFieldDraft: (field: BIField | null) => {
+ field: BIField | null
+ }
setMissingDates: (missingDates: BIConfig['missingDates']) => {
missingDates: 'gap' | 'zero' | undefined
}
@@ -541,6 +558,9 @@ export interface biEditorLogicActions {
draft: BICalculatedMeasureDraft
fieldId: string
}
+ upsertLocalField: (field: BIField) => {
+ field: BIField
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -601,6 +621,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
actions: [databaseTableListLogic, ['hydrateTableFields', 'loadDatabaseSuccess']],
})),
actions({
+ editLocalField: (field: BIField, kind: 'groups' | 'bins') => ({ field, kind }),
+ setLocalFieldDraft: (field: BIField | null) => ({ field }),
+ saveLocalField: true,
+ upsertLocalField: (field: BIField) => ({ field }),
setFilterGroup: (scope: 'row' | 'result', group: BIConditionGroup) => ({ scope, group }),
addResultFilter: () => ({ id: uuid() }),
updateResultFilter: (id: string, update: Partial<BIResultFilter>) => ({ id, update }),
@@ -669,6 +693,10 @@ export const biEditorLogic = kea<biEditorLogicType>([
resetConfig: true,
}),
reducers(() => ({
+ localFieldDraft: [
+ null as BIField | null,
+ { setLocalFieldDraft: (_, { field }) => field, upsertLocalField: () => null, setDataSource: () => null },
+ ],
activeMeasureSettingsIndex: [null as number | null, { editMeasureSettings: (_, { index }) => index }],
calculatedMeasureDraft: [
null as BICalculatedMeasureDraft | null,
@@ -740,6 +768,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
config: [
freshBIConfig(),
{
+ upsertLocalField: (config, { field }) => upsertBILocalField(config, field),
upsertCalculatedMeasure: (config, { draft, fieldId }) => {
if (!config.source) {
return config
@@ -933,10 +962,19 @@ export const biEditorLogic = kea<biEditorLogicType>([
databaseConnectionId: string | null
): BIDataPaneFields =>
config.source && (config.source.connectionId ?? null) === databaseConnectionId
- ? getBIDataPaneFields(
- allTables.find((table) => table.name === config.source?.table),
- config.source
- )
+ ? {
+ ...getBIDataPaneFields(
+ allTables.find((table) => table.name === config.source?.table),
+ config.source
+ ),
+ dimensions: [
+ ...(config.localFields ?? []),
+ ...getBIDataPaneFields(
+ allTables.find((table) => table.name === config.source?.table),
+ config.source
+ ).dimensions,
+ ],
+ }
: { dimensions: [], measures: [] },
],
dataPaneFieldsLoading: [
@@ -979,6 +1017,37 @@ export const biEditorLogic = kea<biEditorLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ editLocalField: ({ field, kind }) =>
+ actions.setLocalFieldDraft(
+ field.localDefinition
+ ? field
+ : {
+ ...field,
+ id: `bi-local-${uuid()}`,
+ name: `${field.name} ${kind}`,
+ type: kind === 'bins' ? 'float' : 'string',
+ dateBucket: undefined,
+ localDefinition:
+ kind === 'bins'
+ ? { kind, expression: field.expression, width: 10, origin: 0 }
+ : {
+ kind,
+ expression: field.expression,
+ groups: [{ name: '', values: [] }],
+ other: 'Other',
+ },
+ }
+ ),
+ saveLocalField: () => {
+ const draft = values.localFieldDraft
+ if (draft?.name.trim() && draft.localDefinition && !localFieldError(draft.localDefinition)) {
+ actions.upsertLocalField({ ...draft, expression: localFieldExpression(draft.localDefinition) })
+ }
+ },
+ upsertLocalField: () => {
+ captureBIWorksheetAction('local_field_saved', values.config)
+ actions.runAfterChange()
+ },
editCalculatedMeasure: ({ index }) => {
if (!values.config.source) {
return
diff --git a/products/business_intelligence/frontend/biEditorTypes.test.ts b/products/business_intelligence/frontend/biEditorTypes.test.ts
index b952d0233d07..c80262776efb 100644
--- a/products/business_intelligence/frontend/biEditorTypes.test.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.test.ts
@@ -96,6 +96,9 @@ describe('BI editor query generation', () => {
expect(result.query).toContain('ORDER BY bi_comparison_sort DESC, bi_row_timestamp ASC')
expect(result.node.chartSettings?.seriesBreakdownColumn).toBe('bi_comparison')
expect(parseBIEditorState(BIEditorView.BI, config)?.config.compareFilter).toEqual(config.compareFilter)
+ expect(
+ parseBIEditorState(BIEditorView.BI, { ...config, comparisonPeriod: null })?.config.compareFilter
+ ).toEqual(config.compareFilter)
expect(buildBIQuery({ ...config, dateRange: { date_from: 'all' } })?.query).not.toContain('UNION ALL')
})
@@ -246,7 +249,7 @@ describe('BI editor query generation', () => {
kind: NodeKind.HogQLQuery,
connectionId: source.connectionId,
filters: { dateRange: { date_from: 'all' } },
- query: "SELECT DISTINCT toString(event) AS value\nFROM orders\nWHERE ({filters((null) AS 'timestamp', (event) AS 'event', (properties.revenue) AS 'revenue')}) AND (event IS NOT NULL) AND ((properties.revenue >= 10 AND properties.revenue <= 100))\nLIMIT 100",
+ query: "SELECT DISTINCT toString(event) AS value\nFROM orders\nWHERE ({filters((null) AS 'timestamp', (event) AS 'event', (properties.revenue) AS 'revenue')}) AND (event IS NOT NULL) AND ((properties.revenue >= 10 AND properties.revenue <= 100))",
})
config.filters.push({
field: { ...eventField, expression: '', name: '', source },
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 410f5e9e7b97..c99cf3b7141e 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -36,7 +36,7 @@ import {
isBIAnalysisConfig,
isBITableCalculation,
} from './biAnalysis'
-import { biComparisonCategory, getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
+import { biComparisonSeries, getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
import { limitBIComparisonQuery } from './biComparisonLimit'
import {
buildBIConditionExpression,
@@ -44,6 +44,7 @@ import {
isBIResultFilter,
normalizeBIConditionGroup,
} from './biFilterGroups'
+import { localFieldError } from './biLocalFields'
import { getBIMeasureSettings, isBIMeasureSettings, mergeBIMeasureSettings } from './biMeasureSettings'
import { getBIFiltersPlaceholder, getBIQueryFilters, normalizeBIDates } from './biQueryFilters'
@@ -146,6 +147,9 @@ export const DEFAULT_BI_CONFIG: BIConfig = {
export function normalizeBIConfig(config: BIConfig): BIConfig {
let normalized = normalizeBIDates(config)
+ if (normalized.comparisonPeriod) {
+ normalized = { ...normalized, compareFilter: { ...normalized.compareFilter, compare: false } }
+ }
if (normalized.compareFilter?.compare && getBIComparisonDisabledReason(normalized)) {
normalized = { ...normalized, compareFilter: { compare: false } }
}
@@ -256,6 +260,7 @@ const IDENTIFIER_FIELD_NAME_REGEX = /(^|_)(id|uuid)$/i
/** Numeric fields that are not identifiers aggregate by default, like measures in a BI tool. */
export function isBIMeasureField(field: BIField): boolean {
return (
+ !field.localDefinition &&
isNumericBIField(field) &&
defaultAggregationForField(field) !== 'count' &&
!IDENTIFIER_FIELD_NAME_REGEX.test(field.name.replace(/([a-z0-9])([A-Z])/g, '$1_$2'))
@@ -361,14 +366,18 @@ export function getBIChartFit(config: BIConfig, chartType: ChartDisplayType): BI
case ChartDisplayType.ActionsLineGraph:
case ChartDisplayType.ActionsAreaGraph:
return {
- fits: hasDateDimension && dimensionCount <= 2,
- requirement: '1 date, up to 1 more dimension, and any measures',
+ fits: hasDateDimension && (dimensionCount <= 2 || !!config.compareFilter?.compare),
+ requirement: config.compareFilter?.compare
+ ? '1 date, any breakdown dimensions, and measures'
+ : '1 date, up to 1 more dimension, and any measures',
}
case ChartDisplayType.ActionsBar:
case ChartDisplayType.ActionsStackedBar:
return {
- fits: dimensionCount >= 1 && dimensionCount <= 2,
- requirement: '1 or 2 dimensions, and any measures',
+ fits: dimensionCount >= 1 && (dimensionCount <= 2 || !!config.compareFilter?.compare),
+ requirement: config.compareFilter?.compare
+ ? 'Any dimensions and measures'
+ : '1 or 2 dimensions, and any measures',
}
case ChartDisplayType.ActionsPie:
case ChartDisplayType.ActionsDonut:
@@ -384,8 +393,10 @@ export function getBIChartFit(config: BIConfig, chartType: ChartDisplayType): BI
case ChartDisplayType.BoldNumber:
case ChartDisplayType.Metric:
return {
- fits: dimensionCount === 0 && config.values.length <= 1,
- requirement: 'no dimensions and up to 1 measure',
+ fits: !!config.compareFilter?.compare || (dimensionCount === 0 && config.values.length <= 1),
+ requirement: config.compareFilter?.compare
+ ? 'A comparison card for each dimension and measure'
+ : 'no dimensions and up to 1 measure',
}
default:
return { fits: true, requirement: '' }
@@ -426,6 +437,7 @@ function parseBIFieldValue(value: unknown): BIField | null {
const candidate = value as Partial<BIField>
if (
+ (candidate.localDefinition !== undefined && !!localFieldError(candidate.localDefinition)) ||
typeof candidate.id !== 'string' ||
typeof candidate.name !== 'string' ||
typeof candidate.expression !== 'string' ||
@@ -476,6 +488,15 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
}
const candidate = decodedConfig as Partial<BIConfig>
+ if (
+ candidate.localFields !== undefined &&
+ (!Array.isArray(candidate.localFields) || candidate.localFields.some((field) => !parseBIFieldValue(field)))
+ ) {
+ return null
+ }
+ if (candidate.comparisonPeriod != null && candidate.comparisonPeriod !== 'previous') {
+ return null
+ }
if (!isBIAnalysisConfig(candidate)) {
return null
}
@@ -607,6 +628,8 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
const config: BIConfig = {
source,
+ ...(candidate.localFields ? { localFields: candidate.localFields } : {}),
+ ...(candidate.comparisonPeriod ? { comparisonPeriod: candidate.comparisonPeriod } : {}),
...(candidate.rowFilterGroup ? { rowFilterGroup: candidate.rowFilterGroup } : {}),
...(candidate.resultFilterGroup ? { resultFilterGroup: candidate.resultFilterGroup } : {}),
...(candidate.resultFilters ? { resultFilters: candidate.resultFilters } : {}),
@@ -632,6 +655,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
...config.values.map((value) => value.field),
...config.filters.map((filter) => filter.field),
...(config.dateField ? [config.dateField] : []),
+ ...(config.localFields ?? []),
]
if (fields.length > 0 && (!source || fields.some((field) => !isBIFieldCompatible(source, field)))) {
@@ -941,7 +965,7 @@ export function buildBIFilterOptionsQuery(config: BIConfig, index: number): HogQ
kind: NodeKind.HogQLQuery,
connectionId: config.source.connectionId,
filters: getBIQueryFilters(config),
- query: `SELECT DISTINCT toString(${expression}) AS value\nFROM ${escapePropertyAsHogQLIdentifier(config.source.table)}\nWHERE ${[getBIFiltersPlaceholder(config), `${expression} IS NOT NULL`, ...conditions].map((condition) => `(${condition})`).join(' AND ')}\nLIMIT 100`,
+ query: `SELECT DISTINCT toString(${expression}) AS value\nFROM ${escapePropertyAsHogQLIdentifier(config.source.table)}\nWHERE ${[getBIFiltersPlaceholder(config), `${expression} IS NOT NULL`, ...conditions].map((condition) => `(${condition})`).join(' AND ')}`,
}
}
@@ -1304,10 +1328,6 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
? `${orderDimension.alias} ${orderByExpression?.endsWith(' ASC') ? 'ASC' : 'DESC'}`
: orderByExpression
const periodLabel = config.compareFilter?.compare_to ? 'Comparison period' : 'Previous period'
- const periodExpression = (label: string): string =>
- breakdownDimension
- ? `concat(${escapeHogQLString(label + ' · ')}, ${biComparisonCategory(fieldExpression(breakdownDimension.field))})`
- : escapeHogQLString(label)
const buildPeriod = (previous: boolean): string => {
const expressions = dimensions.map(({ field }) =>
fieldExpression(
@@ -1319,7 +1339,12 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
const select = [
...dimensions.map(({ alias }, index) => `${expressions[index]} AS ${alias}`),
...valueExpressions,
- `${periodExpression(previous ? periodLabel : 'Current period')} AS bi_comparison`,
+ `${biComparisonSeries(
+ escapeHogQLString(previous ? periodLabel : 'Current period'),
+ dimensions
+ .filter((dimension) => dimension !== xDimension)
+ .map((dimension) => expressions[dimensions.indexOf(dimension)])
+ )} AS bi_comparison`,
]
const placeholder = getBIFiltersPlaceholder(config)
return [
diff --git a/products/business_intelligence/frontend/biFilterValuesLogic.test.ts b/products/business_intelligence/frontend/biFilterValuesLogic.test.ts
index d88705093168..bd73bac5a3e2 100644
--- a/products/business_intelligence/frontend/biFilterValuesLogic.test.ts
+++ b/products/business_intelligence/frontend/biFilterValuesLogic.test.ts
@@ -1,7 +1,7 @@
import { expectLogic } from 'kea-test-utils'
import * as queryRunner from '~/queries/query'
-import { NodeKind } from '~/queries/schema/schema-general'
+import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { biFilterValuesLogic } from 'products/business_intelligence/frontend/biFilterValuesLogic'
@@ -9,6 +9,34 @@ import { biFilterValuesLogic } from 'products/business_intelligence/frontend/biF
describe('BI filter suggestions', () => {
beforeEach(() => initKeaTests())
+ it('paginates beyond 100 values, searches on the server, and resets pagination for a new search', async () => {
+ const performQuery = jest
+ .spyOn(queryRunner, 'performQuery')
+ .mockResolvedValueOnce({ results: Array.from({ length: 101 }, (_, index) => [`value ${index}`]) } as never)
+ .mockResolvedValueOnce({ results: [['value 100']] } as never)
+ .mockResolvedValueOnce({ results: [["O'Reilly"]] } as never)
+ const logic = biFilterValuesLogic({
+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT DISTINCT name AS value FROM accounts' },
+ active: true,
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadOptionsSuccess'])
+ expect(logic.values.options).toHaveLength(100)
+ expect(logic.values.hasMore).toBe(true)
+ await expectLogic(logic, () => logic.actions.loadMore()).toFinishAllListeners()
+ expect(logic.values.options).toHaveLength(101)
+ expect(logic.values.hasMore).toBe(false)
+ expect((performQuery.mock.calls[1][0] as HogQLQuery).query).toContain('OFFSET 100')
+ await expectLogic(logic, () => logic.actions.setSearch("O'Reilly")).toFinishAllListeners()
+ expect(logic.values.options).toEqual(["O'Reilly"])
+ expect((performQuery.mock.calls[2][0] as HogQLQuery).query).toContain(
+ "positionCaseInsensitiveUTF8(value, 'O\\'Reilly')"
+ )
+ expect((performQuery.mock.calls[2][0] as HogQLQuery).query).toContain('OFFSET 0')
+ logic.unmount()
+ performQuery.mockRestore()
+ })
+
it('loads a changed query while the input remains focused', async () => {
const query = { kind: NodeKind.HogQLQuery as const, query: 'SELECT DISTINCT event FROM events LIMIT 100' }
const performQuery = jest
diff --git a/products/business_intelligence/frontend/biFilterValuesLogic.ts b/products/business_intelligence/frontend/biFilterValuesLogic.ts
index 534d757823df..3d87b1f72d75 100644
--- a/products/business_intelligence/frontend/biFilterValuesLogic.ts
+++ b/products/business_intelligence/frontend/biFilterValuesLogic.ts
@@ -1,24 +1,65 @@
-import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, reducers } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+ selectors,
+} from 'kea'
import { loaders } from 'kea-loaders'
import { performQuery } from '~/queries/query'
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
import { HogQLQuery } from '~/queries/schema/schema-general'
+import { escapeHogQLString } from '~/queries/utils'
+
+import { captureBIWorksheetAction } from './biEditorAnalytics'
+
+const PAGE_SIZE = 100
+
+export function searchBIFilterValues(query: HogQLQuery, search: string, offset: number): HogQLQuery {
+ return {
+ ...query,
+ query: `SELECT value FROM (${query.query}) AS bi_filter_values WHERE positionCaseInsensitiveUTF8(value, ${escapeHogQLString(search)}) > 0 ORDER BY value ASC LIMIT ${PAGE_SIZE + 1} OFFSET ${offset}`,
+ }
+}
+
+interface BIFilterValuePage {
+ values: string[]
+ hasMore: boolean
+}
export interface BIFilterValuesLogicProps {
query: HogQLQuery | null
active?: boolean
+ config?: BIConfig
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biFilterValuesLogicValues {
+ hasMore: boolean
options: string[] | null
optionsError: string | null
optionsLoading: boolean
+ page: BIFilterValuePage | null
+ pageLoading: boolean
+ search: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biFilterValuesLogicActions {
- loadOptions: (_: void) => void
+ loadMore: () => {
+ value: true
+ }
+ loadOptions: (payload?: { append?: boolean; debounce?: boolean }) => {
+ append?: boolean
+ debounce?: boolean
+ }
loadOptionsFailure: (
error: string,
errorObject?: any
@@ -27,17 +68,31 @@ export interface biFilterValuesLogicActions {
errorObject?: any
}
loadOptionsSuccess: (
- options: string[],
- payload?: void
+ page: BIFilterValuePage,
+ payload?: {
+ append?: boolean
+ debounce?: boolean
+ }
) => {
- options: string[]
- payload?: void
+ page: BIFilterValuePage
+ payload?: {
+ append?: boolean
+ debounce?: boolean
+ }
+ }
+ setSearch: (search: string) => {
+ search: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biFilterValuesLogicMeta {
key: string
+ __keaTypeGenInternalSelectorTypes: {
+ options: (page: BIFilterValuePage | null) => string[] | null
+ hasMore: (page: BIFilterValuePage | null) => boolean
+ optionsLoading: (pageLoading: boolean) => boolean
+ }
}
export type biFilterValuesLogicType = MakeLogicType<
@@ -51,22 +106,46 @@ export const biFilterValuesLogic = kea<biFilterValuesLogicType>([
props({} as BIFilterValuesLogicProps),
key((props) => JSON.stringify(props.query)),
path((key) => ['products', 'business_intelligence', 'frontend', 'biFilterValuesLogic', key]),
- loaders(({ props }) => ({
- options: [
- null as string[] | null,
+ actions({ setSearch: (search: string) => ({ search }), loadMore: true }),
+ loaders(({ props, values }) => ({
+ page: [
+ null as BIFilterValuePage | null,
{
- loadOptions: async (_: void, breakpoint): Promise<string[]> => {
+ loadOptions: async (
+ payload: { append?: boolean; debounce?: boolean } = {},
+ breakpoint
+ ): Promise<BIFilterValuePage> => {
+ const { append = false, debounce = false } = payload
+ const search = values.search
+ const existing = append ? (values.page?.values ?? []) : []
+ if (debounce) {
+ await breakpoint(300)
+ }
if (!props.query) {
- return []
+ return { values: [], hasMore: false }
}
- const response = await performQuery(props.query)
+ const response = await performQuery(searchBIFilterValues(props.query, search, existing.length))
breakpoint()
- return response.results.map((row) => String(row[0])).sort()
+ if (props.config && (debounce || append)) {
+ captureBIWorksheetAction(
+ debounce ? 'filter_values_searched' : 'filter_values_page_loaded',
+ props.config,
+ {
+ result_count: Math.min(response.results.length, PAGE_SIZE),
+ }
+ )
+ }
+ return {
+ values: [...existing, ...response.results.slice(0, PAGE_SIZE).map((row) => String(row[0]))],
+ hasMore: response.results.length > PAGE_SIZE,
+ }
},
},
],
})),
reducers({
+ search: ['', { setSearch: (_, { search }) => search }],
+ page: { setSearch: () => null },
optionsError: [
null as string | null,
{
@@ -76,6 +155,19 @@ export const biFilterValuesLogic = kea<biFilterValuesLogicType>([
},
],
}),
+ selectors({
+ options: [(s) => [s.page], (page: BIFilterValuePage | null): string[] | null => page?.values ?? null],
+ hasMore: [(s) => [s.page], (page: BIFilterValuePage | null): boolean => page?.hasMore ?? false],
+ optionsLoading: [(s) => [s.pageLoading], (loading: boolean): boolean => loading],
+ }),
+ listeners(({ actions, values }) => ({
+ setSearch: () => actions.loadOptions({ debounce: true }),
+ loadMore: () => {
+ if (values.hasMore && !values.optionsLoading) {
+ actions.loadOptions({ append: true })
+ }
+ },
+ })),
afterMount(({ actions, props }) => {
if (props.active) {
actions.loadOptions()
diff --git a/products/business_intelligence/frontend/biLocalFields.test.ts b/products/business_intelligence/frontend/biLocalFields.test.ts
new file mode 100644
index 000000000000..fd9e440ecc3b
--- /dev/null
+++ b/products/business_intelligence/frontend/biLocalFields.test.ts
@@ -0,0 +1,60 @@
+import { BIField, BILocalFieldDefinition } from '~/queries/schema/schema-business-intelligence'
+
+import { BIEditorView, buildBIQuery, DEFAULT_BI_CONFIG, parseBIEditorState } from './biEditorTypes'
+import { localFieldError, localFieldExpression, upsertBILocalField } from './biLocalFields'
+
+it.each<BILocalFieldDefinition>([
+ {
+ kind: 'groups',
+ expression: 'properties.country',
+ groups: [{ name: "Europe's region", values: ['France', "Cote d'Ivoire"] }],
+ other: 'Rest',
+ },
+ { kind: 'bins', expression: 'properties.size', width: 10, origin: -5 },
+])('persists $kind locally and updates the expression on every shelf', (definition) => {
+ const field: BIField = {
+ id: 'local',
+ name: 'Region',
+ source: { table: 'events' },
+ type: definition.kind === 'bins' ? 'float' : 'string',
+ expression: 'old',
+ localDefinition: definition,
+ }
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ source: field.source,
+ rows: [field],
+ columns: [field],
+ values: [{ field, aggregation: 'count' as const }],
+ filters: [{ field, operator: 'is_set' as const, value: '' }],
+ }
+ const updated = upsertBILocalField(config, { ...field, expression: localFieldExpression(definition) })
+ const parsed = parseBIEditorState(BIEditorView.BI, updated)!.config
+ expect(parsed.localFields?.[0].localDefinition).toEqual(definition)
+ expect(
+ [parsed.rows[0], parsed.columns[0], parsed.values[0].field, parsed.filters[0].field].map(
+ (field) => field.expression
+ )
+ ).toEqual(Array(4).fill(localFieldExpression(definition)))
+ expect(buildBIQuery(parsed)?.query).not.toContain('old')
+ if (definition.kind === 'groups') {
+ expect(buildBIQuery(parsed)?.query).toContain("'Cote d\\'Ivoire'")
+ expect(buildBIQuery(parsed)?.query).toContain('IS NULL, NULL')
+ }
+})
+
+it.each([
+ { kind: 'bins', expression: 'size', width: 0, origin: 0 },
+ { kind: 'bins', expression: 'size', width: 10, origin: Infinity },
+ {
+ kind: 'groups',
+ expression: 'country',
+ groups: [
+ { name: 'A', values: ['US'] },
+ { name: 'B', values: ['US'] },
+ ],
+ other: 'Other',
+ },
+] as BILocalFieldDefinition[])('rejects invalid or ambiguous local definitions: %j', (definition) => {
+ expect(localFieldError(definition)).toBeTruthy()
+})
diff --git a/products/business_intelligence/frontend/biLocalFields.ts b/products/business_intelligence/frontend/biLocalFields.ts
new file mode 100644
index 000000000000..8f47ca5eb1a8
--- /dev/null
+++ b/products/business_intelligence/frontend/biLocalFields.ts
@@ -0,0 +1,72 @@
+import { BIConfig, BIField, BILocalFieldDefinition } from '~/queries/schema/schema-business-intelligence'
+import { escapeHogQLString } from '~/queries/utils'
+
+export function localFieldError(definition: BILocalFieldDefinition): string | undefined {
+ if (!definition || typeof definition.expression !== 'string' || !definition.expression.trim()) {
+ return 'Choose a source field'
+ }
+ if (definition.kind === 'bins') {
+ return Number.isFinite(definition.width) && definition.width > 0 && Number.isFinite(definition.origin)
+ ? undefined
+ : 'Use a positive bin width and a finite starting point'
+ }
+ if (
+ definition.kind !== 'groups' ||
+ !Array.isArray(definition.groups) ||
+ !definition.groups.length ||
+ definition.groups.length > 100 ||
+ typeof definition.other !== 'string' ||
+ !definition.other.trim()
+ ) {
+ return 'Add at least one group and a label for other values'
+ }
+ const used = new Set<string>()
+ const names = new Set<string>([definition.other])
+ for (const group of definition.groups) {
+ if (
+ !group ||
+ typeof group.name !== 'string' ||
+ !group.name.trim() ||
+ !Array.isArray(group.values) ||
+ !group.values.length ||
+ group.values.length > 10000 ||
+ !group.values.every((value) => typeof value === 'string')
+ ) {
+ return 'Give every group a name and at least one value'
+ }
+ if (names.has(group.name)) {
+ return 'Group names and the other-values label must be distinct'
+ }
+ names.add(group.name)
+ for (const value of group.values) {
+ if (used.has(value)) {
+ return 'Each value can belong to only one group'
+ }
+ used.add(value)
+ }
+ }
+}
+
+export function localFieldExpression(definition: BILocalFieldDefinition): string {
+ if (definition.kind === 'bins') {
+ return `(floor(((${definition.expression}) - ${definition.origin}) / ${definition.width}) * ${definition.width} + ${definition.origin})`
+ }
+ const expression = `(${definition.expression})`
+ const cases = definition.groups.flatMap((group) => [
+ `toString(${expression}) IN (${group.values.map(escapeHogQLString).join(', ')})`,
+ escapeHogQLString(group.name),
+ ])
+ return `if(${expression} IS NULL, NULL, multiIf(${[...cases, escapeHogQLString(definition.other)].join(', ')}))`
+}
+
+export function upsertBILocalField(config: BIConfig, field: BIField): BIConfig {
+ const replace = (current: BIField): BIField => (current.id === field.id ? field : current)
+ return {
+ ...config,
+ localFields: [...(config.localFields ?? []).filter((current) => current.id !== field.id), field],
+ rows: config.rows.map(replace),
+ columns: config.columns.map(replace),
+ values: config.values.map((value) => ({ ...value, field: replace(value.field) })),
+ filters: config.filters.map((filter) => ({ ...filter, field: replace(filter.field) })),
+ }
+}
diff --git a/products/business_intelligence/frontend/biQueryFilters.ts b/products/business_intelligence/frontend/biQueryFilters.ts
index 6c7e4afeab06..fb987275f2be 100644
--- a/products/business_intelligence/frontend/biQueryFilters.ts
+++ b/products/business_intelligence/frontend/biQueryFilters.ts
@@ -45,6 +45,11 @@ export function normalizeBIDates(config: BIConfig): BIConfig {
}
export function getBIFiltersPlaceholder(config: BIConfig): string {
+ const placeholder = buildBIFiltersPlaceholder(config)
+ return config.comparisonPeriod === 'previous' ? placeholder.replace('{filters', '{filters.previous') : placeholder
+}
+
+function buildBIFiltersPlaceholder(config: BIConfig): string {
const dateField = getBIDateField(config)
if (usesNativeBIFilters(config.source)) {
return dateField?.expression === NATIVE_DATE_FIELDS[config.source!.table]
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index ec52219c16b4..ac180401749c 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -743,6 +743,9 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
lemonToast.error('Could not restore the worksheet link.')
}
actions.restoreWorksheet(worksheet)
+ if (searchParams.starter) {
+ actions.setLastRunQuery(null)
+ }
actions.setName('Untitled worksheet')
actions.recordWorksheet(true)
},
diff --git a/products/business_intelligence/frontend/biTimeSeries.ts b/products/business_intelligence/frontend/biTimeSeries.ts
index 4b443265785f..de8427b3656b 100644
--- a/products/business_intelligence/frontend/biTimeSeries.ts
+++ b/products/business_intelligence/frontend/biTimeSeries.ts
@@ -1,3 +1,6 @@
+import { dayjs } from 'lib/dayjs'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
+
import { BIConfig, BIDateBucket } from '~/queries/schema/schema-business-intelligence'
import { escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
import { ChartDisplayType } from '~/types'
@@ -28,7 +31,11 @@ export function getBIMissingDatesDisabledReason(config: BIConfig): string | unde
return 'Use the date dimension as the date column and select a bounded date range'
}
if (config.source?.connectionId) {
- return 'Date filling is available for project and warehouse tables'
+ const from = dateStringToDayJs(config.dateRange.date_from)
+ const to = config.dateRange.date_to ? dateStringToDayJs(config.dateRange.date_to) : dayjs()
+ if (!from?.isValid() || !to?.isValid() || to.diff(from, dates[0].dateBucket) >= 49999) {
+ return 'Use fewer than 50,000 date buckets: shorten the range or choose a wider time bucket'
+ }
}
if (
![
@@ -57,8 +64,48 @@ export function buildBIFilledPeriod(
const date = dimensions.find(({ field }) => ['date', 'datetime'].includes(field.type))!
const bucket = date.field.dateBucket!
const start = BUCKET_START[bucket]
+ const dateRange = config.comparisonPeriod ? 'filters.previous.dateRange' : 'filters.dateRange'
const period = `bi_${previous ? 'previous' : 'current'}`
const measures = input.measures.map(({ alias }) => escapeRawPropertyAsHogQLIdentifier(alias))
+ if (config.source?.connectionId) {
+ const add: Record<BIDateBucket, string> = {
+ minute: 'addMinutes',
+ hour: 'addHours',
+ day: 'addDays',
+ week: 'addWeeks',
+ month: 'addMonths',
+ quarter: 'addQuarters',
+ year: 'addYears',
+ }
+ // A bounded decimal spine also runs on engines without generate_series (such as Redshift).
+ const digits = Array.from({ length: 10 }, (_, index) => `SELECT ${index} AS n`).join(' UNION ALL ')
+ const sequence = 'd0.n + 10 * d1.n + 100 * d2.n + 1000 * d3.n + 10000 * d4.n'
+ const others = dimensions.filter((dimension) => dimension !== date)
+ const groups = others.map(({ alias }) => alias)
+ const detail = totals ? ' WHERE bi_grouping = 0' : ''
+ const spine = `${add[bucket]}(${start}({${dateRange}.from}), ${sequence})`
+ const projection = dimensions.map(
+ ({ alias }) => `${alias === date.alias ? 'bi_dates' : 'bi_series'}.${alias} AS ${alias}`
+ )
+ const match = dimensions
+ .map(({ alias }) => {
+ const key = `${alias === date.alias ? 'bi_dates' : 'bi_series'}.${alias}`
+ return `(bi_observed.${alias} = ${key} OR (bi_observed.${alias} IS NULL AND ${key} IS NULL))`
+ })
+ .join(' AND ')
+ const filled = measures.map(
+ (alias) =>
+ `if(bi_observed.bi_present = 1, toFloat(bi_observed.${alias}), ${config.missingDates === 'zero' ? '0' : 'NULL'}) AS ${alias}`
+ )
+ const flags = totals ? ['0 AS bi_grouping', ...dimensions.map((_, index) => `0 AS bi_grouping_${index}`)] : []
+ const totalsSelect = [
+ ...dimensions.map(({ alias }) => alias),
+ ...measures,
+ 'bi_grouping',
+ ...dimensions.map((_, index) => `bi_grouping_${index}`),
+ ]
+ return `${period}_filled AS (WITH bi_digits AS (${digits}), bi_dates AS (SELECT ${spine} AS ${date.alias} FROM bi_digits AS d0 CROSS JOIN bi_digits AS d1 CROSS JOIN bi_digits AS d2 CROSS JOIN bi_digits AS d3 CROSS JOIN bi_digits AS d4 WHERE d4.n < 5 AND ${spine} < {${dateRange}.to}), bi_series AS (SELECT DISTINCT ${groups.length ? groups.join(', ') : '1 AS bi_series_key'} FROM ${period}${detail}), bi_observed AS (SELECT *, 1 AS bi_present FROM ${period}${detail}) SELECT ${[...projection, ...filled, ...flags].join(', ')} FROM bi_dates CROSS JOIN bi_series LEFT JOIN bi_observed ON ${match}${totals ? ` UNION ALL SELECT ${totalsSelect.join(', ')} FROM ${period} WHERE bi_grouping != 0` : ''})`
+ }
const select = [
...dimensions.map(({ alias }) => alias),
...measures.map((alias) => `toNullable(toFloat(${alias})) AS ${alias}`),
@@ -66,7 +113,7 @@ export function buildBIFilledPeriod(
].join(', ')
const order = [
...dimensions.filter((dimension) => dimension !== date).map(({ alias }) => `${alias} ASC`),
- `${date.alias} ASC WITH FILL FROM ${start}({filters.dateRange.from}) TO ${start}({filters.dateRange.to}) + INTERVAL 1 ${bucket.toUpperCase()} STEP INTERVAL 1 ${bucket.toUpperCase()}`,
+ `${date.alias} ASC WITH FILL FROM ${start}({${dateRange}.from}) TO {${dateRange}.to} STEP INTERVAL 1 ${bucket.toUpperCase()}`,
]
const interpolate =
config.missingDates === 'zero' ? ` INTERPOLATE (${measures.map((alias) => `${alias} AS 0`).join(', ')})` : ''
diff --git a/products/business_intelligence/frontend/components/BIToolbar.tsx b/products/business_intelligence/frontend/components/BIToolbar.tsx
index e280938c02ef..8ffce4840ba9 100644
--- a/products/business_intelligence/frontend/components/BIToolbar.tsx
+++ b/products/business_intelligence/frontend/components/BIToolbar.tsx
@@ -126,6 +126,9 @@ export function BIToolbar(): JSX.Element {
/>
<LemonDivider vertical />
<BIDateControls />
+ {config.comparisonPeriod && (
+ <span className="text-xs text-secondary">Comparison window of this reference range</span>
+ )}
<LemonDivider vertical />
<LemonButton
size="small"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 914ba7819ffa..371613e04396 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9368,6 +9368,25 @@ export const BIDateBucketApi = {
Year: 'year',
} as const
+export interface BICategoryGroupApi {
+ name: string
+ values: string[]
+}
+
+export interface BILocalFieldDefinition1Api {
+ expression: string
+ groups: BICategoryGroupApi[]
+ kind?: 'groups'
+ other: string
+}
+
+export interface BILocalFieldDefinition2Api {
+ expression: string
+ kind?: 'bins'
+ origin: number
+ width: number
+}
+
export interface BIDataSourceApi {
connectionId?: string | null
table: string
@@ -9399,11 +9418,18 @@ export interface BIFieldApi {
dateBucket?: BIDateBucketApi | null
expression: string
id: string
+ localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | null
name: string
source: BIDataSourceApi
type: DatabaseSerializedFieldTypeApi
}
+export type ComparisonPeriodApi = (typeof ComparisonPeriodApi)[keyof typeof ComparisonPeriodApi]
+
+export const ComparisonPeriodApi = {
+ Previous: 'previous',
+} as const
+
export type BIFilterOperatorApi = (typeof BIFilterOperatorApi)[keyof typeof BIFilterOperatorApi]
export const BIFilterOperatorApi = {
@@ -9558,11 +9584,15 @@ export interface BIConfigApi {
chartType: ChartDisplayTypeApi
columns: BIFieldApi[]
compareFilter?: CompareFilterApi | null
+ /** Explore only the comparison window, using dateRange as its reference window. */
+ comparisonPeriod?: ComparisonPeriodApi | null
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIFieldApi | null
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
limit: BIQueryLimitApi
+ /** Reusable expressions owned by this worksheet only. */
+ localFields?: BIFieldApi[] | null
/** Fill missing date buckets before table calculations. Unset preserves observed points only. */
missingDates?: MissingDatesApi | null
resultFilterGroup?: BIConditionGroupApi | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 1aeb59980cd5..772ac81e5a7b 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8295,6 +8295,25 @@ export const BIDateBucketApi = {
Year: 'year',
} as const
+export interface BICategoryGroupApi {
+ name: string
+ values: string[]
+}
+
+export interface BILocalFieldDefinition1Api {
+ expression: string
+ groups: BICategoryGroupApi[]
+ kind?: 'groups'
+ other: string
+}
+
+export interface BILocalFieldDefinition2Api {
+ expression: string
+ kind?: 'bins'
+ origin: number
+ width: number
+}
+
export interface BIDataSourceApi {
connectionId?: string | null
table: string
@@ -8326,11 +8345,18 @@ export interface BIFieldApi {
dateBucket?: BIDateBucketApi | null
expression: string
id: string
+ localDefinition?: BILocalFieldDefinition1Api | BILocalFieldDefinition2Api | null
name: string
source: BIDataSourceApi
type: DatabaseSerializedFieldTypeApi
}
+export type ComparisonPeriodApi = (typeof ComparisonPeriodApi)[keyof typeof ComparisonPeriodApi]
+
+export const ComparisonPeriodApi = {
+ Previous: 'previous',
+} as const
+
export type BIFilterOperatorApi = (typeof BIFilterOperatorApi)[keyof typeof BIFilterOperatorApi]
export const BIFilterOperatorApi = {
@@ -8485,11 +8511,15 @@ export interface BIConfigApi {
chartType: ChartDisplayTypeApi
columns: BIFieldApi[]
compareFilter?: CompareFilterApi | null
+ /** Explore only the comparison window, using dateRange as its reference window. */
+ comparisonPeriod?: ComparisonPeriodApi | null
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIFieldApi | null
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
limit: BIQueryLimitApi
+ /** Reusable expressions owned by this worksheet only. */
+ localFields?: BIFieldApi[] | null
/** Fill missing date buckets before table calculations. Unset preserves observed points only. */
missingDates?: MissingDatesApi | null
resultFilterGroup?: BIConditionGroupApi | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 67263af358ce..1c6c66c78e5e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10685,6 +10685,25 @@ export namespace Schemas {
Year: 'year',
} as const;
+ export interface BICategoryGroup {
+ name: string;
+ values: string[];
+ }
+
+ export interface BILocalFieldDefinition1 {
+ expression: string;
+ groups: BICategoryGroup[];
+ kind?: 'groups';
+ other: string;
+ }
+
+ export interface BILocalFieldDefinition2 {
+ expression: string;
+ kind?: 'bins';
+ origin: number;
+ width: number;
+ }
+
export interface BIDataSource {
connectionId?: string | null;
table: string;
@@ -10716,11 +10735,19 @@ export namespace Schemas {
dateBucket?: BIDateBucket | null;
expression: string;
id: string;
+ localDefinition?: BILocalFieldDefinition1 | BILocalFieldDefinition2 | null;
name: string;
source: BIDataSource;
type: DatabaseSerializedFieldType;
}
+ export type ComparisonPeriod = typeof ComparisonPeriod[keyof typeof ComparisonPeriod];
+
+
+ export const ComparisonPeriod = {
+ Previous: 'previous',
+ } as const;
+
export type BIFilterOperator = typeof BIFilterOperator[keyof typeof BIFilterOperator];
@@ -10883,11 +10910,15 @@ export namespace Schemas {
chartType: ChartDisplayType;
columns: BIField[];
compareFilter?: CompareFilter | null;
+ /** Explore only the comparison window, using dateRange as its reference window. */
+ comparisonPeriod?: ComparisonPeriod | null;
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIField | null;
dateRange?: DateRange | null;
filters: BIFilter[];
limit: BIQueryLimit;
+ /** Reusable expressions owned by this worksheet only. */
+ localFields?: BIField[] | null;
/** Fill missing date buckets before table calculations. Unset preserves observed points only. */
missingDates?: MissingDates | null;
resultFilterGroup?: BIConditionGroup | null;