: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(bi): add source preview and member alias editors (#117499)
Marius Andra4f19f7debeb0
diff --git a/products/business_intelligence/frontend/BIMemberAliasesModal.test.tsx b/products/business_intelligence/frontend/BIMemberAliasesModal.test.tsxnew file mode 100644index 000000000000..981522b207ef--- /dev/null+++ b/products/business_intelligence/frontend/BIMemberAliasesModal.test.tsx@@ -0,0 +1,59 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'++import * as queryRunner from '~/queries/query'+import { BIField } from '~/queries/schema/schema-business-intelligence'+import { initKeaTests } from '~/test/init'++import { biMemberAliasesLogic } from './biMemberAliasesLogic'+import { BIMemberAliasesModal } from './BIMemberAliasesModal'++describe('member alias editor', () => {+ beforeEach(() => initKeaTests())+ afterEach(() => {+ cleanup()+ jest.restoreAllMocks()+ })++ it('bounds rendered inputs and keeps edits stable across pages and saved-alias search', async () => {+ jest.spyOn(queryRunner, 'performQuery').mockResolvedValue({ results: [] } as never)+ const props = { tabId: 'alias-pagination-test' }+ const logic = biMemberAliasesLogic(props)+ logic.mount()+ const field: BIField = {+ id: 'region',+ name: 'Region',+ expression: 'region',+ type: 'string',+ source: { table: 'example_orders' },+ }+ logic.actions.edit(+ field,+ Array.from({ length: 101 }, (_, i) => ({ value: `value-${i}`, label: `Label ${i}` }))+ )+ render(<BIMemberAliasesModal {...props} />)+ await waitFor(() => expect(screen.getAllByLabelText(/^Alias for /)).toHaveLength(50))+ const first = screen.getByLabelText('Alias for value-0')+ fireEvent.change(first, { target: { value: 'Updated first' } })+ expect(screen.getByLabelText('Alias for value-0')).toHaveValue('Updated first')+ fireEvent.click(screen.getByLabelText('Next page'))+ expect(screen.queryByLabelText('Alias for value-0')).not.toBeInTheDocument()+ expect(screen.getAllByLabelText(/^Alias for /)).toHaveLength(50)+ fireEvent.click(screen.getByLabelText('Previous page'))+ expect(screen.getByLabelText('Alias for value-0')).toHaveValue('Updated first')+ fireEvent.change(screen.getByLabelText('Search member values and aliases'), { target: { value: 'Label 100' } })+ expect(await screen.findByLabelText('Alias for value-100')).toHaveValue('Label 100')+ expect(screen.getAllByLabelText(/^Alias for /)).toHaveLength(1)+ const matchingInput = screen.getByLabelText('Alias for value-100')+ matchingInput.focus()+ fireEvent.change(matchingInput, { target: { value: '' } })+ expect(screen.getByLabelText('Alias for value-100')).toBe(matchingInput)+ expect(matchingInput).toHaveFocus()+ fireEvent.change(matchingInput, { target: { value: 'Replacement label' } })+ expect(matchingInput).toHaveValue('Replacement label')+ expect(logic.values.draft).toHaveLength(101)+ expect(logic.values.draft[0]).toEqual({ value: 'value-0', label: 'Updated first' })+ logic.unmount()+ })+})diff --git a/products/business_intelligence/frontend/BIMemberAliasesModal.tsx b/products/business_intelligence/frontend/BIMemberAliasesModal.tsxnew file mode 100644index 000000000000..147c2852da11--- /dev/null+++ b/products/business_intelligence/frontend/BIMemberAliasesModal.tsx@@ -0,0 +1,98 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonInput, LemonModal, LemonTable } from '@posthog/lemon-ui'++import { biFilterValuesLogic } from './biFilterValuesLogic'+import { biMemberAliasesLogic } from './biMemberAliasesLogic'++export function BIMemberAliasesModal({ tabId }: { tabId: string }): JSX.Element {+ const logic = biMemberAliasesLogic({ tabId })+ const { field, draft, draftByValue, savedLabels, query } = useValues(logic)+ const { close, setAlias, save } = useActions(logic)+ const valuesLogic = biFilterValuesLogic({ query, active: !!field })+ const { options, optionsLoading, optionsError, hasMore, search } = useValues(valuesLogic)+ const { setSearch, loadMore, loadOptions } = useActions(valuesLogic)+ const members = [...new Set([null, ...(options ?? []), ...draft.map((alias) => alias.value)])].filter(+ (value) =>+ !search ||+ String(value ?? '(no value)')+ .toLowerCase()+ .includes(search.toLowerCase()) ||+ savedLabels.get(value)?.toLowerCase().includes(search.toLowerCase())+ )+ return (+ <LemonModal+ title={`Display aliases: ${field?.name ?? ''}`}+ isOpen={!!field}+ onClose={close}+ width={680}+ footer={+ <>+ <LemonButton onClick={close}>Cancel</LemonButton>+ <LemonButton type="primary" onClick={save}>+ Save aliases+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-3">+ <p>+ Aliases change display labels only. Filtering, sorting, selections, SQL, and data exports use the+ original values. Different values may share a label and stay separate.+ </p>+ <LemonInput+ type="search"+ value={search}+ onChange={setSearch}+ placeholder="Search values or saved aliases"+ aria-label="Search member values and aliases"+ />+ {optionsError && (+ <div role="alert">+ Could not load values. Saved aliases can still be edited.{' '}+ <LemonButton onClick={() => loadOptions()} loading={optionsLoading}>+ Retry+ </LemonButton>+ </div>+ )}+ <LemonTable+ key={search}+ pagination={{ pageSize: 50 }}+ size="small"+ loading={optionsLoading}+ dataSource={members.map((value) => ({ value }))}+ rowKey={(row) => JSON.stringify(row.value)}+ columns={[+ {+ title: 'Original value',+ key: 'value',+ render: (_, { value }) =>+ value === null ? '(no value)' : value === '' ? '(empty string)' : value,+ },+ {+ title: 'Display alias',+ key: 'alias',+ render: (_, { value }) => (+ <LemonInput+ value={draftByValue.get(value) ?? ''}+ onChange={(label) => setAlias(value, label)}+ placeholder="Original value"+ aria-label={`Alias for ${value ?? '(no value)'}`}+ maxLength={200}+ />+ ),+ },+ ]}+ />+ {hasMore && (+ <LemonButton onClick={loadMore} loading={optionsLoading}>+ Load more values+ </LemonButton>+ )}+ <p className="text-xs text-secondary">+ Clear an alias to restore the original value. Changes apply only after Save aliases.+ </p>+ </div>+ </LemonModal>+ )+}diff --git a/products/business_intelligence/frontend/BISourcePreviewModal.tsx b/products/business_intelligence/frontend/BISourcePreviewModal.tsxnew file mode 100644index 000000000000..8c05570a72a9--- /dev/null+++ b/products/business_intelligence/frontend/BISourcePreviewModal.tsx@@ -0,0 +1,85 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonModal, LemonSelect } from '@posthog/lemon-ui'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'+import { Query } from '~/queries/Query/Query'+import { NodeKind } from '~/queries/schema/schema-general'++import { biSourcePreviewLogic } from './biSourcePreviewLogic'++export function BISourcePreviewModal({ tabId }: { tabId: string }): JSX.Element | null {+ const { worksheet, filtered, limit, query } = useValues(biSourcePreviewLogic({ tabId }))+ const { close, setFiltered, loadMore } = useActions(biSourcePreviewLogic({ tabId }))+ const insightProps = { dashboardItemId: `new-SQL-bi-source-preview-${tabId}` as const }+ const { response, responseLoading } = useValues(+ dataNodeLogic({+ key: insightVizDataNodeKey(insightProps),+ query: query?.source ?? { kind: NodeKind.HogQLQuery, query: '' },+ autoLoad: !!query,+ })+ )+ if (!worksheet) {+ return null+ }+ const rowCount =+ response && 'results' in response && Array.isArray(response.results) ? response.results.length : null+ return (+ <LemonModal title={`Source data: ${worksheet.config.source?.table ?? ''}`} isOpen onClose={close} width="90vw">+ <div className="flex flex-col gap-3">+ <LemonSelect+ value={filtered}+ options={[+ { value: false, label: 'All source rows' },+ { value: true, label: 'Matching worksheet row and date filters' },+ ]}+ onChange={setFiltered}+ disabledReason={responseLoading ? 'Loading source rows' : undefined}+ data-attr="bi-source-preview-scope"+ />+ <p className="m-0 text-secondary">+ Sample of up to <span translate="no">{limit.toLocaleString()}</span> unaggregated rows. Repeated IDs+ are separate records. A sample does not establish uniqueness. Result filters and table calculations+ do not apply.+ </p>+ {response && 'types' in response && Array.isArray(response.types) && (+ <details className="text-xs">+ <summary className="cursor-pointer">Column names and types</summary>+ <dl className="mt-2 flex flex-wrap gap-x-4 gap-y-1">+ {response.types.map(([name, type]) => (+ <div key={name} className="flex gap-1">+ <dt className="font-semibold">{name}:</dt>+ <dd className="m-0 text-secondary">{type}</dd>+ </div>+ ))}+ </dl>+ </details>+ )}+ {query ? (+ <Query query={query} context={{ insightProps }} readOnly embedded />+ ) : (+ <LemonBanner type="warning">+ Check the source and row filters before viewing this sample.+ </LemonBanner>+ )}+ <LemonButton+ onClick={loadMore}+ loading={responseLoading}+ disabledReason={+ !query+ ? 'Choose a valid source and filters'+ : limit >= 10000+ ? 'Maximum sample size reached'+ : rowCount !== null && rowCount < limit+ ? 'All matching rows are shown'+ : undefined+ }+ data-attr="bi-source-preview-more"+ >+ Load a larger sample+ </LemonButton>+ </div>+ </LemonModal>+ )+}diff --git a/products/business_intelligence/frontend/biMemberAliasesLogic.ts b/products/business_intelligence/frontend/biMemberAliasesLogic.tsnew file mode 100644index 000000000000..4c6914887108--- /dev/null+++ b/products/business_intelligence/frontend/biMemberAliasesLogic.ts@@ -0,0 +1,153 @@+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { BIField, BIConfig, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'+import { HogQLQuery } from '~/queries/schema/schema-general'++import { biEditorLogic } from './biEditorLogic'+import { BIEditorView, buildBIFilterOptionsQuery } from './biEditorTypes'+import { biMemberFieldKey } from './biMemberAliases'+import { biSceneLogic } from './biSceneLogic'++interface BIMemberAliasesProps {+ tabId: string+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface biMemberAliasesLogicValues {+ draft: {+ label: string+ value: string | null+ }[]+ draftByValue: Map<string | null, string>+ field: BIField | null+ query: HogQLQuery | null+ savedLabels: Map<string | null, string>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface biMemberAliasesLogicActions {+ close: () => {+ value: true+ }+ edit: (+ field: BIField,+ aliases: {+ label: string+ value: string | null+ }[]+ ) => {+ aliases: {+ label: string+ value: string | null+ }[]+ field: BIField+ }+ save: () => {+ value: true+ }+ setAlias: (+ value: string | null,+ label: string+ ) => {+ label: string+ value: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface biMemberAliasesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ draftByValue: (+ draft: {+ label: string+ value: string | null+ }[]+ ) => Map<string | null, string>+ query: (field: BIField | null, config: BIConfig, worksheet: BIVisualizationNode) => HogQLQuery | null+ }+}++export type biMemberAliasesLogicType = MakeLogicType<+ biMemberAliasesLogicValues,+ biMemberAliasesLogicActions,+ BIMemberAliasesProps,+ biMemberAliasesLogicMeta+>+export const biMemberAliasesLogic = kea<biMemberAliasesLogicType>([+ props({} as BIMemberAliasesProps),+ key(({ tabId }) => tabId),+ path((key) => ['products', 'business_intelligence', 'biMemberAliasesLogic', key]),+ actions({+ edit: (field: BIField, aliases: { value: string | null; label: string }[]) => ({ field, aliases }),+ setAlias: (value: string | null, label: string) => ({ value, label }),+ close: true,+ save: true,+ }),+ reducers({+ field: [null as BIField | null, { edit: (_, { field }) => field, close: () => null }],+ savedLabels: [+ new Map<string | null, string>(),+ { edit: (_, { aliases }) => new Map(aliases.map(({ value, label }) => [value, label])) },+ ],+ draft: [+ [] as { value: string | null; label: string }[],+ {+ edit: (_, { aliases }) => aliases,+ setAlias: (draft, { value, label }) =>+ draft.some((alias) => alias.value === value)+ ? draft.map((alias) => (alias.value === value ? { value, label } : alias))+ : [...draft, { value, label }],+ },+ ],+ }),+ selectors(({ props }) => ({+ draftByValue: [+ (s) => [s.draft],+ (+ draft: {+ label: string+ value: string | null+ }[]+ ): Map<string | null, string> => new Map(draft.map(({ value, label }) => [value, label])),+ ],+ query: [+ (s) => [s.field, biEditorLogic(props).selectors.config, biSceneLogic(props).selectors.worksheet],+ (field: BIField | null, config: BIConfig, worksheet: BIVisualizationNode): HogQLQuery | null => {+ const query = field+ ? buildBIFilterOptionsQuery(+ { ...config, filters: [{ field, operator: 'in', value: '' }], rowFilterGroup: undefined },+ 0+ )+ : null+ return query ? { ...query, variables: worksheet.source.variables } : null+ },+ ],+ })),+ listeners(({ props, values, actions }) => ({+ save: () => {+ if (!values.field) {+ return+ }+ const editor = biEditorLogic(props)+ const field = values.field+ const aliases = values.draft+ .filter((alias) => alias.label.trim())+ .map((alias) => ({ ...alias, label: alias.label.trim() }))+ editor.actions.restoreState({+ editorView: BIEditorView.BI,+ config: {+ ...editor.values.config,+ memberAliases: [+ ...(editor.values.config.memberAliases ?? []).filter(+ (entry) => biMemberFieldKey(entry.field) !== biMemberFieldKey(field)+ ),+ ...(aliases.length ? [{ field, aliases }] : []),+ ],+ },+ })+ biSceneLogic(props).actions.recordWorksheet()+ editor.actions.runAfterChange()+ actions.close()+ },+ })),+])diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.tsindex d11501ab6a41..d69b75b363a0 100644--- a/products/business_intelligence/frontend/biSceneLogic.test.ts+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts@@ -7,6 +7,7 @@ import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'import { BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'import { DatabaseSchemaQuery, HogQLFilters, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'@@ -17,7 +18,9 @@ import { claimConnectionScope, releaseConnectionScope } from 'products/data_wareimport { BI_EDITOR_EVENTS } from './biEditorAnalytics'import { biEditorLogic } from './biEditorLogic'import { BIEditorView, buildBIQuery } from './biEditorTypes'+import { biMemberAliasesLogic } from './biMemberAliasesLogic'import { biSceneLogic } from './biSceneLogic'+import { biSourcePreviewLogic } from './biSourcePreviewLogic'const eventField: BIField = {id: 'event',@@ -374,6 +377,24 @@ describe('biSceneLogic', () => {await expectLogic(logic).toFinishAllListeners()})+ it('cancels only the source preview query when its modal closes', () => {+ const preview = biSourcePreviewLogic({ tabId: 'preview-cancel' })+ preview.mount()+ const data = dataNodeLogic({+ key: insightVizDataNodeKey({ dashboardItemId: 'new-SQL-bi-source-preview-preview-cancel' }),+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },+ autoLoad: false,+ })+ data.mount()+ const cancel = jest.spyOn(data.actions, 'cancelQuery')+ preview.actions.open(worksheet(config))+ preview.actions.close()+ expect(cancel).toHaveBeenCalledTimes(1)+ expect(preview.values.worksheet).toBeNull()+ data.unmount()+ preview.unmount()+ })+it('tracks the first successful chart once, without counting empty results or reruns', async () => {const capture = jest.spyOn(posthog, 'capture').mockImplementation()logic.actions.restoreWorksheet(worksheet())@@ -527,6 +548,37 @@ describe('biSceneLogic', () => {expect(logic.values.hasUnsavedChanges).toBe(false)})+ it('saves member aliases as drafts, keeps raw query semantics, and preserves them through undo and Clear sheet', async () => {+ await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()+ editor.actions.setAutoUpdate(false)+ const aliases = biMemberAliasesLogic({ tabId: 'bi-test' })+ const unmount = aliases.mount()+ const query = logic.values.worksheet.source.query+ aliases.actions.edit(eventField, [])+ aliases.actions.setAlias('example_a', 'Same label')+ aliases.actions.close()+ expect(editor.values.config.memberAliases).toBeUndefined()+ aliases.actions.edit(eventField, [])+ aliases.actions.setAlias('example_a', 'Same label')+ aliases.actions.setAlias('example_b', 'Same label')+ aliases.actions.save()+ expect(editor.values.config.memberAliases?.[0].aliases).toHaveLength(2)+ expect(logic.values.worksheet.source.query).toBe(query)+ logic.actions.undo()+ expect(editor.values.config.memberAliases).toBeUndefined()+ logic.actions.redo()+ expect(editor.values.config.memberAliases?.[0].aliases).toHaveLength(2)+ await expectLogic(logic, () => logic.actions.saveInsight()).toFinishAllListeners()+ expect(stored.query.config.memberAliases?.[0].aliases).toHaveLength(2)+ editor.actions.resetConfig()+ expect(editor.values.config.memberAliases?.[0].aliases).toHaveLength(2)+ aliases.actions.edit(eventField, editor.values.config.memberAliases![0].aliases)+ aliases.actions.setAlias('example_a', ' ')+ aliases.actions.save()+ expect(editor.values.config.memberAliases?.[0].aliases).toEqual([{ value: 'example_b', label: 'Same label' }])+ unmount()+ })+it('runs the restored worksheet when auto update is enabled', async () => {await expectLogic(logic, () => logic.actions.loadInsight(stored.short_id)).toFinishAllListeners()await expectLogic(editor, () => editor.actions.setAutoUpdate(true)).toFinishAllListeners()diff --git a/products/business_intelligence/frontend/biSourcePreviewLogic.ts b/products/business_intelligence/frontend/biSourcePreviewLogic.tsnew file mode 100644index 000000000000..1c14f0fdb655--- /dev/null+++ b/products/business_intelligence/frontend/biSourcePreviewLogic.ts@@ -0,0 +1,86 @@+import { LogicWrapper, MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'+import { DataVisualizationNode } from '~/queries/schema/schema-general'++import { buildBISourcePreview } from './biSourcePreview'++interface BISourcePreviewProps {+ tabId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface biSourcePreviewLogicValues {+ filtered: boolean+ limit: number+ query: DataVisualizationNode | null+ worksheet: BIVisualizationNode | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface biSourcePreviewLogicActions {+ close: () => {+ value: true+ }+ loadMore: () => {+ value: true+ }+ open: (worksheet: BIVisualizationNode) => {+ worksheet: BIVisualizationNode+ }+ setFiltered: (filtered: boolean) => {+ filtered: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface biSourcePreviewLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ query: (worksheet: BIVisualizationNode | null, filtered: boolean, limit: number) => DataVisualizationNode | null+ }+}++export type biSourcePreviewLogicType = MakeLogicType<+ biSourcePreviewLogicValues,+ biSourcePreviewLogicActions,+ BISourcePreviewProps,+ biSourcePreviewLogicMeta+>++export const biSourcePreviewLogic: LogicWrapper<biSourcePreviewLogicType> = kea<biSourcePreviewLogicType>([+ props({} as BISourcePreviewProps),+ key(({ tabId }) => tabId),+ path((key) => ['products', 'business_intelligence', 'biSourcePreviewLogic', key]),+ actions({+ open: (worksheet: BIVisualizationNode) => ({ worksheet }),+ close: true,+ setFiltered: (filtered: boolean) => ({ filtered }),+ loadMore: true,+ }),+ reducers({+ worksheet: [null as BIVisualizationNode | null, { open: (_, { worksheet }) => worksheet, close: () => null }],+ filtered: [false, { open: () => false, setFiltered: (_, { filtered }) => filtered }],+ limit: [+ 1000,+ { open: () => 1000, setFiltered: () => 1000, loadMore: (limit) => Math.min(limit + 1000, 10000) },+ ],+ }),+ listeners(({ props }) => ({+ close: () =>+ dataNodeLogic+ .findMounted({+ key: insightVizDataNodeKey({ dashboardItemId: `new-SQL-bi-source-preview-${props.tabId}` }),+ })+ ?.actions.cancelQuery(),+ })),+ selectors({+ query: [+ (s) => [s.worksheet, s.filtered, s.limit],+ (worksheet: BIVisualizationNode | null, filtered: boolean, limit: number): DataVisualizationNode | null =>+ worksheet ? buildBISourcePreview(worksheet, filtered, limit) : null,+ ],+ }),+])