Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/36645-report-builder-filter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@object-ui/plugin-report': patch
'@object-ui/app-shell': patch
'@object-ui/plugin-list': patch
'@object-ui/i18n': patch
---

feat(console): the report builder adds 「+ Filter」 under the data source — a report filter on the bound dataset, drawn into the preview at once and kept on Save

Clause-②: yes (widening) — a new optional `filter` slot on `ReportBuilder` (`@object-ui/plugin-report`), two exports from `@object-ui/plugin-list` (`conditionCandidatesOf`, `conditionOptionsOf`, and the `ConditionCandidateField` type), and four new `@object-ui/i18n` keys (`report.builder.source.addFilter`, `filterAdvanced`, `filterLoading`, `filterNoFields`) in all 11 locales; no spec, schema or server change
Metadata-protocol: none

- **The filter** (`@object-ui/app-shell`): under the data source, 「+ Filter」 opens the same condition editor the dataset designer uses, over the fields of the dataset's object (their translated labels, a select's options, a lookup's record picker; hidden fields are not offered). Each condition is written into the report's `runtimeFilter`, the preview redraws with it at once, and Save keeps it; removing the last condition removes the key. Switching the data source clears the filter.
- **The fields offered** leave out virtual (formula) fields: the dataset door refuses a filter on one, so a report filtered on it could be saved and then fail for every viewer.
- **A filter with `$and` beside other conditions** (`{ $and: [...], amount: {...} }`, or with `$not`) is no longer read as editable rows by the shared filter bridge, so neither the report builder nor the dataset designer opens it where the next edit would drop the conditions beside the `$and`; it keeps the panel / source editor, unchanged.
- **Which reports open in the builder:** a dataset report with a saved filter now opens in the builder when its filter is one the builder can edit (field conditions joined by AND); a filter it cannot edit (an OR, a nested group, two operators on one field) keeps the report inspector panel, as before. A filter that turns out not to be editable once the fields are read is shown as kept and saved unchanged.
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#36645 (item 1) — 「+ Filter」 under the report builder's data
* source: the console host draws the report's `runtimeFilter` with the shared
* `FilterConditionField` over the dataset OBJECT's fields, writes each edit
* into the report it hands to Save, and drops the key when the last condition
* goes.
*
* Real subjects: `ReportBuilderHost`, the real `ReportBuilder`, the real
* `FilterConditionField` and `FilterBuilder`, and `reportFilterFields`. Fakes:
* the metadata client (the dataset catalog) and the data source (the object
* definition and the preview's query).
*/

import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ComponentRegistry } from '@object-ui/core';

const DATASET_DOC = vi.hoisted(() => ({
name: 'pipeline',
label: 'Pipeline',
object: 'opportunity',
dimensions: [{ name: 'stage', label: 'Stage', type: 'select', field: 'stage' }],
measures: [{ name: 'deal_count', label: 'Deals', aggregate: 'count' }],
}));

const client = vi.hoisted(() => {
const c: Record<string, any> = {
list: vi.fn(async () => [DATASET_DOC]),
get: vi.fn(async () => DATASET_DOC),
};
c.withPreviewDrafts = () => c;
return c;
});
vi.mock('./metadata-admin/useMetadata.js', () => ({ useMetadataClient: () => client }));

import { ReportBuilderHost } from './ReportBuilderHost';
import { reportFilterFields } from './reportFilterFields';

const OBJECT_DEF = {
name: 'opportunity',
fields: {
name: { type: 'text', label: 'Name' },
stage: { type: 'select', label: 'Stage', options: [{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }] },
amount: { type: 'currency', label: 'Amount', currencyConfig: { mode: 'record', currencyField: 'currency' } },
organization_id: { type: 'lookup', label: 'Organization', reference: 'sys_organization', hidden: true },
account: { type: 'lookup', label: 'Account', reference: 'account' },
weighted: { type: 'formula', label: 'Weighted', expression: 'amount * 0.5' },
},
};

const REPORT = {
name: 'deals',
label: 'Deals',
type: 'summary',
dataset: 'pipeline',
values: ['deal_count'],
chart: { type: 'metric', xAxis: '', yAxis: 'deal_count' },
};

function mount(initial: Record<string, unknown>) {
ComponentRegistry.register('chart', () => <div data-testid="chart-stub" />);
const onSave = vi.fn(async (_report: Record<string, unknown>) => true);
const dataSource = {
getObjectSchema: vi.fn(async () => OBJECT_DEF),
queryDataset: vi.fn(async (_dataset: string, _selection: Record<string, unknown>) => ({ rows: [{ deal_count: 3 }], fields: [] })),
};
render(<ReportBuilderHost initial={initial} onSave={onSave} onClose={() => {}} dataSource={dataSource as never} />);
return { onSave, dataSource };
}

const save = async () => {
await act(async () => {
fireEvent.click(screen.getByTestId('report-builder-save'));
});
};

afterEach(() => {
cleanup();
vi.clearAllMocks();
});

describe('the report filter fields (objectstack#36645)', () => {
it('are the object\'s own fields, minus the hidden and the virtual ones, with no currency pairing', () => {
const fields = reportFilterFields(OBJECT_DEF, (_f, fallback) => fallback, (_f, raw) => (Array.isArray(raw) ? raw : undefined));
// `weighted` is a formula: the dataset door refuses a filter on it (400 INVALID_FIELD).
expect(fields.map((f) => f.value)).toEqual(['name', 'stage', 'amount', 'account']);
// Business fields first, system fields after, as the list's Filter panel orders them.
const withSystem = reportFilterFields(
{ fields: { created_by: { type: 'lookup', label: 'Created by', system: true }, ...OBJECT_DEF.fields } },
(_f, fallback) => fallback,
() => undefined,
);
expect(withSystem.map((f) => f.value)).toEqual(['name', 'stage', 'amount', 'account', 'created_by']);
expect(fields.find((f) => f.value === 'stage')?.options).toEqual([{ value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }]);
expect(fields.find((f) => f.value === 'account')?.referenceTo).toBe('account');
expect(fields.find((f) => f.value === 'amount')).not.toHaveProperty('currencyField');
expect(reportFilterFields(null, (_f, d) => d, () => undefined)).toEqual([]);
});
});

describe('「+ Filter」 under the report builder\'s data source (objectstack#36645)', () => {
it('reads the dataset object\'s definition, and offers 「+ Filter」 while the report has none', async () => {
const { dataSource } = mount(REPORT);
const add = await screen.findByTestId('report-builder-filter-field-add');
expect(add).toHaveTextContent('Filter');
await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalledWith('opportunity'));
});

it('a condition added is saved as the report\'s runtimeFilter, and the preview redraws with it', async () => {
const { onSave, dataSource } = mount(REPORT);
await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalled());
fireEvent.click(await screen.findByTestId('report-builder-filter-field-add'));
// The popover's builder: one row, seeded on the first field (`name`, text).
fireEvent.click(await screen.findByText('Add filter'));
const value = await screen.findByPlaceholderText('Value');
fireEvent.change(value, { target: { value: 'Acme' } });
// The trigger now counts the condition.
await waitFor(() => expect(screen.getByTestId('report-builder-filter-field-trigger')).toHaveTextContent('1 condition'));
await waitFor(() =>
expect(dataSource.queryDataset.mock.calls.at(-1)?.[1]).toHaveProperty('runtimeFilter', { name: { $eq: 'Acme' } }),
);
await save();
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave.mock.calls[0][0].runtimeFilter).toEqual({ name: { $eq: 'Acme' } });
});

it('an existing filter opens counted; editing it saves the edit, and clearing it saves no runtimeFilter at all', async () => {
const { onSave } = mount({ ...REPORT, runtimeFilter: { name: { $eq: 'Acme' } } });
const trigger = await screen.findByTestId('report-builder-filter-field-trigger');
expect(trigger).toHaveTextContent('1 condition');
fireEvent.click(trigger);
fireEvent.change(await screen.findByDisplayValue('Acme'), { target: { value: 'Contoso' } });
await save();
expect(onSave.mock.calls.at(-1)?.[0].runtimeFilter).toEqual({ name: { $eq: 'Contoso' } });

fireEvent.click(screen.getByText('Clear all'));
await waitFor(() => expect(screen.getByTestId('report-builder-filter-field-add')).toBeInTheDocument());
await save();
expect(onSave.mock.calls.at(-1)?.[0]).not.toHaveProperty('runtimeFilter');
});

it('a filter the builder cannot hold is kept as saved and says so', async () => {
const odd = { name: { $gt: 1, $lt: 9 } };
const { onSave } = mount({ ...REPORT, runtimeFilter: odd });
expect(await screen.findByText('This filter cannot be changed here. It is kept as saved.')).toBeInTheDocument();
await save();
expect(onSave.mock.calls.at(-1)?.[0].runtimeFilter).toEqual(odd);
});

it('a filter holdable by shape but not by its field\'s type is kept as saved, once the fields are read', async () => {
// One operator on one field (so the report opens here), but `name` is text
// and its dropdown has no 「greater than」.
const byType = { name: { $gt: 'M' } };
const { onSave, dataSource } = mount({ ...REPORT, runtimeFilter: byType });
await waitFor(() => expect(dataSource.getObjectSchema).toHaveBeenCalledWith('opportunity'));
expect(await screen.findByText('This filter cannot be changed here. It is kept as saved.')).toBeInTheDocument();
await save();
expect(onSave.mock.calls.at(-1)?.[0].runtimeFilter).toEqual(byType);
});
});
44 changes: 44 additions & 0 deletions ui/packages/app-shell/src/views/ReportBuilderHost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,22 @@
* #36481). Writing the report is the caller's: `onSave` resolves `true` when
* the report was saved, and the builder closes only then.
*
* It also draws the report filter under the data source (「+ Filter」,
* objectstack#36645): the report's `runtimeFilter`, edited with the console's
* one `FilterCondition` editor (`FilterConditionField`, the dataset
* designer's) over the dataset object's fields (`useReportFilterFields`).
*
* @module
*/

import * as React from 'react';
import { ReportBuilder, type ReportDraft, type DatasetDrillArgs } from '@object-ui/plugin-report';
import type { DataSource } from '@object-ui/types';
import { useSafeTranslate } from '@object-ui/i18n';
import { useDatasetCatalog, useDatasetSemantics } from './metadata-admin/previews/useDatasetCatalog.js';
import { FilterConditionField } from './metadata-admin/inspectors/FilterConditionField.js';
import type { FilterCondition } from './metadata-admin/inspectors/datasetFilterCondition.js';
import { useReportFilterFields } from './reportFilterFields.js';
import { shownLabel, writtenLabel, servedLabelNote, useLabelLanguage } from './metadata-admin/inspectors/servedLabel.js';
import { tFormat, useMetadataLocale } from './metadata-admin/i18n.js';
import type { ServedReportText } from './studio-design/servedReportText.js';
Expand Down Expand Up @@ -66,6 +75,23 @@ export function ReportBuilderHost({ initial, servedText, onSave, onClose, banner
[dataset, semantics.loading, semantics.measures, semantics.dimensions],
);

const tt = useSafeTranslate();
const object = catalog.datasets.find((d) => d.name === dataset)?.object;
const filterFields = useReportFilterFields(object, dataSource);
const runtimeFilter =
draft.runtimeFilter && typeof draft.runtimeFilter === 'object' && !Array.isArray(draft.runtimeFilter)
? (draft.runtimeFilter as FilterCondition)
: undefined;
// The last row removed (or Clear all) commits `undefined`: the key goes, so
// a report with no filter is stored without one rather than with `{}`.
const commitFilter = (fc: FilterCondition | undefined) =>
setDraft((d) => {
const next: ReportDraft = { ...d };
if (fc === undefined) delete next.runtimeFilter;
else next.runtimeFilter = fc;
return next;
});

const dirty = React.useMemo(() => JSON.stringify(draft) !== JSON.stringify(initial), [draft, initial]);

const handleSave = React.useCallback(async () => {
Expand Down Expand Up @@ -101,6 +127,24 @@ export function ReportBuilderHost({ initial, servedText, onSave, onClose, banner
members={members}
membersLoading={!!dataset && semantics.loading}
catalogError={catalog.error ?? semantics.error ?? undefined}
filter={
dataset ? (
<FilterConditionField
value={runtimeFilter}
onCommit={commitFilter}
fields={filterFields.fields}
locale={locale}
addLabel={tt('report.builder.source.addFilter', 'Filter')}
advancedNote={tt('report.builder.source.filterAdvanced', 'This filter cannot be changed here. It is kept as saved.')}
noFieldsNote={
filterFields.loading
? tt('report.builder.source.filterLoading', 'Loading fields…')
: tt('report.builder.source.filterNoFields', 'This data source has no fields to filter on.')
}
testId="report-builder-filter-field"
/>
) : undefined
}
onSave={handleSave}
onDiscard={() => setDraft(initial)}
onClose={onClose}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,10 +327,25 @@ describe('which reports open in the builder (objectstack#36374, opensInBuilder)'
expect(opensInBuilder(null)).toBe(false);
});

it('a dataset report the builder has no setting for keeps the panel: a cross-tab, a saved filter, several values', () => {
it('a dataset report the builder has no setting for keeps the panel: a cross-tab, several values', () => {
expect(opensInBuilder({ ...DATASET_REPORT, columns: ['owner'] })).toBe(false);
expect(opensInBuilder({ ...DATASET_REPORT, columns: [] })).toBe(true);
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { stage: 'won' } })).toBe(false);
expect(opensInBuilder({ ...DATASET_REPORT, values: ['a', 'b'] })).toBe(false);
});

it('a saved filter opens in the builder when its 「+ Filter」 can hold it, and keeps the panel when not (objectstack#36645)', () => {
// The rows the builder's filter edits: implicit equality, an operator map, a flat `$and`.
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { stage: 'won' } })).toBe(true);
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { amount: { $gt: 100 } } })).toBe(true);
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { $and: [{ stage: 'won' }, { amount: { $gte: 5 } }] } })).toBe(true);
// Shapes it cannot hold stay in the panel, which edits them as written.
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { $or: [{ stage: 'won' }, { stage: 'lost' }] } })).toBe(false);
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { amount: { $gt: 1, $lt: 9 } } })).toBe(false);
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { $and: [{ $or: [{ stage: 'won' }] }] } })).toBe(false);
// `$and` beside other top-level keys is a valid spec shape the builder
// would narrow to the `$and` rows on the next edit: it keeps the panel.
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { $and: [{ stage: 'won' }], amount: { $gt: 5 } } as never })).toBe(false);
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { $and: [{ stage: 'won' }], $not: { stage: 'lost' } } as never })).toBe(false);
expect(opensInBuilder({ ...DATASET_REPORT, runtimeFilter: { $not: { stage: 'lost' } } as never })).toBe(false);
});
});
14 changes: 11 additions & 3 deletions ui/packages/app-shell/src/views/ReportView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
servedReportTextOf,
type ServedReportText,
} from './studio-design/servedReportText.js';
import { conditionToGroup, type FilterCondition } from './metadata-admin/inspectors/datasetFilterCondition.js';

/**
* The report keys whose text the server translates where it serves the report
Expand Down Expand Up @@ -74,16 +75,23 @@ export function previewWithServedText(
* (several datasets, one per block) and a pre-dataset report (`objectName`,
* `dataSource` or inline `data`) keep the report inspector panel, which edits
* every shape the spec allows; so does a dataset report the builder has no
* setting for (a cross-tab, a saved filter, several values).
* setting for (a cross-tab, several values, or a saved filter its 「+ Filter」
* cannot hold — an `$or`, a nested group, an operator it does not offer).
* A saved filter it CAN hold opens in the builder (objectstack#36645).
*/
export function opensInBuilder(report: Record<string, unknown> | null | undefined): boolean {
if (!report) return false;
if (report.type === 'joined') return false;
if (report.objectName !== undefined || report.dataSource !== undefined || report.data !== undefined) return false;
// Shapes the builder has no setting for keep the panel, which edits them: a
// cross-tab (`columns`), a saved filter (`runtimeFilter`) and several values.
// cross-tab (`columns`), several values, and a saved filter (`runtimeFilter`)
// the builder's filter cannot hold. The question is the filter editor's own
// read-back (`conditionToGroup`), asked without the field list: its shape
// alone decides here, and an operator the field's type does not offer is
// kept as saved in the builder, not rewritten (objectstack#36645).
const filled = (v: unknown) => Array.isArray(v) ? v.length > 0 : v !== undefined && v !== null;
if (filled(report.columns) || filled(report.runtimeFilter)) return false;
if (filled(report.columns)) return false;
if (filled(report.runtimeFilter) && !conditionToGroup(report.runtimeFilter as FilterCondition).representable) return false;
if (Array.isArray(report.values) && report.values.length > 1) return false;
return true;
}
Expand Down
Loading
Loading