From 775d80eed8ce39de777567a54a4ccdc174adb1c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:17:43 +0000 Subject: [PATCH 1/4] wip(console): the report builder's filter under the data source Claude-Session: https://claude.ai/code/session_01JQwxbXeiNLk9jGd2XxhBfz Co-authored-by: Claude --- .../app-shell/src/views/ReportBuilderHost.tsx | 44 ++++++++ .../app-shell/src/views/ReportView.tsx | 14 ++- .../inspectors/FilterConditionField.tsx | 53 +++++++-- .../app-shell/src/views/reportFilterFields.ts | 105 ++++++++++++++++++ ui/packages/i18n/src/locales/ar.ts | 4 + ui/packages/i18n/src/locales/de.ts | 4 + ui/packages/i18n/src/locales/en.ts | 4 + ui/packages/i18n/src/locales/es.ts | 4 + ui/packages/i18n/src/locales/fr.ts | 4 + ui/packages/i18n/src/locales/ja.ts | 4 + ui/packages/i18n/src/locales/ko.ts | 4 + ui/packages/i18n/src/locales/pt-BR.ts | 4 + ui/packages/i18n/src/locales/ru.ts | 4 + ui/packages/i18n/src/locales/zh-Hans.ts | 4 + ui/packages/i18n/src/locales/zh-Hant.ts | 4 + ui/packages/plugin-list/src/index.tsx | 5 + .../__tests__/reportBuilder-36374.test.tsx | 87 +++++++++++++++ .../src/builder/ReportBuilder.tsx | 14 ++- .../src/builder/reportBuilderModel.ts | 6 +- 19 files changed, 355 insertions(+), 17 deletions(-) create mode 100644 ui/packages/app-shell/src/views/reportFilterFields.ts diff --git a/ui/packages/app-shell/src/views/ReportBuilderHost.tsx b/ui/packages/app-shell/src/views/ReportBuilderHost.tsx index d6dd2bee3ca..05a181041a2 100644 --- a/ui/packages/app-shell/src/views/ReportBuilderHost.tsx +++ b/ui/packages/app-shell/src/views/ReportBuilderHost.tsx @@ -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'; @@ -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 () => { @@ -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 ? ( + + ) : undefined + } onSave={handleSave} onDiscard={() => setDraft(initial)} onClose={onClose} diff --git a/ui/packages/app-shell/src/views/ReportView.tsx b/ui/packages/app-shell/src/views/ReportView.tsx index 6b280680db0..b3be4ed4865 100644 --- a/ui/packages/app-shell/src/views/ReportView.tsx +++ b/ui/packages/app-shell/src/views/ReportView.tsx @@ -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 @@ -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 | 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; } diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FilterConditionField.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FilterConditionField.tsx index 4eae47b219c..1929680c4fa 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FilterConditionField.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FilterConditionField.tsx @@ -10,7 +10,7 @@ */ import * as React from 'react'; -import { ChevronDown } from 'lucide-react'; +import { ChevronDown, Plus } from 'lucide-react'; import { Button, FilterBuilder, Label, Popover, PopoverContent, PopoverTrigger } from '@object-ui/components'; import { conditionToGroup, groupToCondition, isClearedGroup, type BuilderGroup, type FilterCondition } from './datasetFilterCondition.js'; import { t, tFormat, type SupportedLocale } from '../i18n.js'; @@ -29,8 +29,9 @@ function withSlots(template: string, slots: Record): Re * (nested / `$or` / multi-op) degrade to a "edit in Source" note rather than being * silently rewritten. See {@link conditionToGroup} / {@link groupToCondition}. */ -export function FilterConditionField({ label, help, value, onCommit, fields, disabled, locale, advancedNote, noFieldsNote, testId }: { - label: string; +export function FilterConditionField({ label, help, value, onCommit, fields, disabled, locale, advancedNote, noFieldsNote, addLabel, testId }: { + /** The caption above the field; a host that captions it itself leaves it out. */ + label?: string; help?: string; value: FilterCondition | undefined; onCommit: (fc: FilterCondition | undefined) => void; @@ -51,6 +52,13 @@ export function FilterConditionField({ label, help, value, onCommit, fields, dis advancedNote?: React.ReactNode; /** What the popover says when there are no fields to filter on. */ noFieldsNote?: string; + /** + * While the filter is empty, the trigger is a small 「+ {addLabel}」 link + * instead of the full-width "Add filter" box — the report builder's + * 「+ 筛选」 under its data source (objectstack#36645). A filter with rows + * keeps the box, which counts them. + */ + addLabel?: string; /** `data-testid` on the field's wrapper. */ testId?: string; }) { @@ -87,7 +95,7 @@ export function FilterConditionField({ label, help, value, onCommit, fields, dis }; return (
- + {label ? : null} {!representable ? (

{advancedNote ?? withSlots(t('engine.inspector.dataset.filterAdvanced', locale), { @@ -97,14 +105,35 @@ export function FilterConditionField({ label, help, value, onCommit, fields, dis ) : ( - + {addLabel && !count ? ( + + ) : ( + + )} {fields.length === 0 ? ( diff --git a/ui/packages/app-shell/src/views/reportFilterFields.ts b/ui/packages/app-shell/src/views/reportFilterFields.ts new file mode 100644 index 00000000000..f367fae72de --- /dev/null +++ b/ui/packages/app-shell/src/views/reportFilterFields.ts @@ -0,0 +1,105 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The fields the report builder's 「+ Filter」 offers (objectstack#36645). + * + * A report's `runtimeFilter` is keyed by fields of its dataset's OBJECT — the + * dataset door lowers it onto that object's columns, not onto the dataset's + * dimensions (`dataset-filter-field-binding.ts` in `service-analytics`). So + * the list is the object's own fields, read from the console's data source as + * a list's Filter panel reads them, and mapped by that panel's one mapping + * (`conditionCandidatesOf`): the same translated labels, the same option + * pickers for a select, the same record picker for a lookup. + * + * Two narrowings on top of that mapping, both because the builder writes + * through the console's `FilterCondition` bridge (`datasetFilterCondition`), + * not through the list's own filter dialect: + * + * - a field the object marks `hidden: true` is not offered, as the list's + * Filter panel does not offer it; + * - a `record`-mode amount's currency pairing (`currencyField`) is dropped: the + * pairing writes a second, companion condition the bridge reads back as a + * row of its own, so the amount is offered as the dataset designer offers + * it — a plain number. + * + * Only the base object's fields: a relationship path (`account.region`) is + * out of reach of this first cut, as it is of the dataset designer's filters. + * + * @module + */ + +import * as React from 'react'; +import type { DataSource } from '@object-ui/types'; +import { useObjectLabel } from '@object-ui/i18n'; +import { conditionCandidatesOf, conditionOptionsOf, type ConditionCandidateField } from '@object-ui/plugin-list'; + +/** One field the report filter may name. */ +export type ReportFilterField = Omit; + +/** + * The filterable fields of an object definition, as the console serves it + * (`fields` keyed by name). Pure — the labels are resolved by the caller's + * resolvers, so a test hands in identity ones. + */ +export function reportFilterFields( + def: { fields?: Record } | null | undefined, + label: (field: string, fallback: string) => string, + options: (field: string, raw: unknown) => ConditionCandidateField['options'], +): ReportFilterField[] { + const defs = def?.fields; + if (!defs || typeof defs !== 'object' || Array.isArray(defs)) return []; + const shown: Record = {}; + for (const [name, field] of Object.entries(defs)) { + if (!field || typeof field !== 'object') continue; + if ((field as { hidden?: unknown }).hidden === true) continue; + shown[name] = field; + } + return conditionCandidatesOf(shown, label, options).map(({ currencyField: _paired, ...field }) => field); +} + +/** + * Read `object`'s definition through the data source and answer its + * filterable fields. `loading` while the read is in flight; an object the + * source cannot serve answers no fields, which the filter says in its popover. + */ +export function useReportFilterFields( + object: string | undefined, + dataSource: DataSource | undefined, +): { fields: ReportFilterField[]; loading: boolean } { + const { fieldLabel, translateOptions } = useObjectLabel(); + const [read, setRead] = React.useState<{ object: string; def: { fields?: Record } | null } | null>(null); + + React.useEffect(() => { + if (!object || !dataSource || typeof dataSource.getObjectSchema !== 'function') return; + let cancelled = false; + dataSource + .getObjectSchema(object) + .then((def: unknown) => { + if (!cancelled) setRead({ object, def: def && typeof def === 'object' ? (def as { fields?: Record }) : null }); + }) + .catch(() => { + if (!cancelled) setRead({ object, def: null }); + }); + return () => { + cancelled = true; + }; + }, [object, dataSource]); + + const def = object && read?.object === object ? read.def : undefined; + const fields = React.useMemo( + () => + object && def + ? reportFilterFields( + def, + (field, fallback) => fieldLabel(object, field, fallback), + (field, raw) => { + const list = conditionOptionsOf(raw); + return list ? translateOptions(object, field, list) : undefined; + }, + ) + : [], + [object, def, fieldLabel, translateOptions], + ); + const canRead = !!dataSource && typeof dataSource.getObjectSchema === 'function'; + return { fields, loading: !!object && canRead && def === undefined }; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index dadee092e52..2af295b03c2 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -4440,6 +4440,10 @@ const ar = { placeholder: "اختر مصدر بيانات", loading: "جارٍ تحميل مصادر البيانات…", none: "لا توجد مصادر بيانات بعد", + addFilter: "تصفية", + filterAdvanced: "لا يمكن تغيير عامل التصفية هذا هنا. يبقى كما تم حفظه.", + filterLoading: "جارٍ تحميل الحقول…", + filterNoFields: "لا يحتوي مصدر البيانات هذا على حقول للتصفية.", }, measure: { label: "المقياس", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 937e9e96f75..9455e20a983 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4082,6 +4082,10 @@ const de = { placeholder: "Datenquelle wählen", loading: "Datenquellen werden geladen…", none: "Noch keine Datenquellen", + addFilter: "Filter", + filterAdvanced: "Dieser Filter kann hier nicht geändert werden. Er bleibt so, wie er gespeichert wurde.", + filterLoading: "Felder werden geladen…", + filterNoFields: "Diese Datenquelle hat keine Felder zum Filtern.", }, measure: { label: "Kennzahl", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 41934b72b7a..4621dddd946 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2207,6 +2207,10 @@ const en = { placeholder: 'Choose a data source', loading: 'Loading data sources…', none: 'No data sources yet', + addFilter: 'Filter', + filterAdvanced: 'This filter cannot be changed here. It is kept as saved.', + filterLoading: 'Loading fields…', + filterNoFields: 'This data source has no fields to filter on.', }, measure: { label: 'Measure', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index af8de32d7ec..8c735a8c93e 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4172,6 +4172,10 @@ const es = { placeholder: "Elige un origen de datos", loading: "Cargando orígenes de datos…", none: "Aún no hay orígenes de datos", + addFilter: "Filtro", + filterAdvanced: "Este filtro no se puede cambiar aquí. Se conserva tal como se guardó.", + filterLoading: "Cargando campos…", + filterNoFields: "Este origen de datos no tiene campos para filtrar.", }, measure: { label: "Medida", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 4f7ee4f0cf9..1ecdff63fb5 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4168,6 +4168,10 @@ const fr = { placeholder: "Choisir une source de données", loading: "Chargement des sources de données…", none: "Aucune source de données pour l’instant", + addFilter: "Filtre", + filterAdvanced: "Ce filtre ne peut pas être modifié ici. Il est conservé tel qu’il a été enregistré.", + filterLoading: "Chargement des champs…", + filterNoFields: "Cette source de données n’a aucun champ à filtrer.", }, measure: { label: "Mesure", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index e40dccd1dc8..337a200a6ce 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4084,6 +4084,10 @@ const ja = { placeholder: "データソースを選択", loading: "データソースを読み込み中…", none: "データソースがまだありません", + addFilter: "フィルター", + filterAdvanced: "このフィルターはここでは変更できません。保存されたまま残ります。", + filterLoading: "フィールドを読み込み中…", + filterNoFields: "このデータソースには絞り込めるフィールドがありません。", }, measure: { label: "指標", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 31da75274af..6c8973c9ebb 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4081,6 +4081,10 @@ const ko = { placeholder: "데이터 소스 선택", loading: "데이터 소스를 불러오는 중…", none: "아직 데이터 소스가 없습니다", + addFilter: "필터", + filterAdvanced: "이 필터는 여기에서 변경할 수 없습니다. 저장된 그대로 유지됩니다.", + filterLoading: "필드를 불러오는 중…", + filterNoFields: "이 데이터 소스에는 필터링할 필드가 없습니다.", }, measure: { label: "지표", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index ecc9f0ee6e1..d9d15b41907 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4167,6 +4167,10 @@ const pt = { placeholder: "Escolha uma fonte de dados", loading: "Carregando fontes de dados…", none: "Ainda não há fontes de dados", + addFilter: "Filtro", + filterAdvanced: "Este filtro não pode ser alterado aqui. Ele é mantido como foi salvo.", + filterLoading: "Carregando campos…", + filterNoFields: "Esta fonte de dados não tem campos para filtrar.", }, measure: { label: "Medida", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 21a26bae268..69230b7e3a1 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4271,6 +4271,10 @@ const ru = { placeholder: "Выберите источник данных", loading: "Загрузка источников данных…", none: "Источников данных пока нет", + addFilter: "Фильтр", + filterAdvanced: "Этот фильтр нельзя изменить здесь. Он сохраняется в том виде, в каком был сохранён.", + filterLoading: "Загрузка полей…", + filterNoFields: "В этом источнике данных нет полей для фильтрации.", }, measure: { label: "Показатель", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index c6fbdc36957..08d7ce2e333 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1847,6 +1847,10 @@ const zh = { placeholder: '选一个数据来源', loading: '正在读取数据来源…', none: '还没有数据来源', + addFilter: '筛选', + filterAdvanced: '这个筛选条件不能在这里修改,会按保存时的样子保留。', + filterLoading: '正在读取字段…', + filterNoFields: '这个数据来源没有可以筛选的字段。', }, measure: { label: '指标', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index cff81f25653..3488cfa6037 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1847,6 +1847,10 @@ const zhHant = { placeholder: '選一個數據來源', loading: '正在讀取資料來源…', none: '還沒有資料來源', + addFilter: '篩選', + filterAdvanced: '這個篩選條件不能在這裡修改,會按儲存時的樣子保留。', + filterLoading: '正在讀取欄位…', + filterNoFields: '這個資料來源沒有可以篩選的欄位。', }, measure: { label: '指標', diff --git a/ui/packages/plugin-list/src/index.tsx b/ui/packages/plugin-list/src/index.tsx index 72232d502c8..cfef887ce86 100644 --- a/ui/packages/plugin-list/src/index.tsx +++ b/ui/packages/plugin-list/src/index.tsx @@ -28,6 +28,11 @@ export { PhonePanelSheet, useListPhonePanels, PHONE_CHIP, PHONE_CHIP_ACTIVE } fr export type { PhonePanelSheetProps, ListPhonePanels } from './phone/PhoneListPanels'; export type { UserFiltersProps, UserFiltersHandle } from './UserFilters'; export { normalizeFilterCondition, normalizeFilters } from './ListView'; +// objectstack#36645 — the one mapping from an object definition's fields to the +// Filter picker's field list, so the report builder's 「+ Filter」 offers the +// same fields, labels and value pickers as a list's Filter panel. +export { conditionCandidatesOf, conditionOptionsOf } from './ListView'; +export type { ConditionCandidateField } from './ListView'; // The provider-less fallback table, exported so objectui#4401's mirror gate can // compare it against the `en` pack from a package that depends on both. export { LIST_DEFAULT_TRANSLATIONS } from './ListView'; diff --git a/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx b/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx index 41f3a5ac58f..df2c4a10c5a 100644 --- a/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/reportBuilder-36374.test.tsx @@ -313,3 +313,90 @@ describe('the computed values fold (objectstack#36374)', () => { expect(screen.queryByTestId('dataset-report-computed-values-toggle')).toBeNull(); }); }); + +describe('the report filter under the data source (objectstack#36645)', () => { + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + const box = (value = '') => ({ value, onChange: () => {} }); + + /** + * The builder with a host filter control: a button that sets the report's + * `runtimeFilter` and one that clears it, standing in for the console's + * filter editor (the real one is `ReportBuilderHost.filter-36645`'s subject). + */ + function FilterHarness({ initial, dataSource }: { initial: ReportDraft; dataSource?: unknown }) { + const [report, setReport] = React.useState(initial); + const setFilter = (fc: Record | undefined) => + setReport((r) => { + const next = { ...r }; + if (fc) next.runtimeFilter = fc; + else delete next.runtimeFilter; + return next; + }); + return ( + <> + {}} + onDiscard={() => setReport(initial)} + onClose={() => {}} + dataSource={dataSource} + filter={ + <> + + + + } + /> +

{JSON.stringify(report)}
+ + ); + } + + const current = () => JSON.parse(screen.getByTestId('report-json').textContent ?? '{}'); + + it('draws the host filter under the data source, and only once a data source is bound', () => { + const { unmount } = render(); + expect(screen.queryByTestId('report-builder-filter')).toBeNull(); + unmount(); + render(); + const slot = screen.getByTestId('report-builder-filter'); + // Under the data source: inside that section, after its picker. + const source = screen.getByTestId('report-builder-source'); + expect(source).toContainElement(slot); + expect(screen.getByTestId('report-builder-source-trigger').compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + }); + + it('a filter added redraws the preview at once with it; removing it redraws without', async () => { + ComponentRegistry.register('chart', () =>
); + const queryDataset = vi.fn(async (_dataset: string, _selection: Record) => ({ rows: [{ stage: 'Won', total_amount: 10 }], fields: [] })); + render(); + await waitFor(() => expect(queryDataset).toHaveBeenCalled()); + expect(queryDataset.mock.calls.at(-1)?.[1]).not.toHaveProperty('runtimeFilter'); + + fireEvent.click(screen.getByTestId('host-filter-won')); + expect(current().runtimeFilter).toEqual({ stage: { $eq: 'won' } }); + await waitFor(() => expect(queryDataset.mock.calls.at(-1)?.[1]).toHaveProperty('runtimeFilter', { stage: { $eq: 'won' } })); + expectSpecValid(current()); + + fireEvent.click(screen.getByTestId('host-filter-clear')); + expect(current()).not.toHaveProperty('runtimeFilter'); + await waitFor(() => expect(queryDataset.mock.calls.at(-1)?.[1]).not.toHaveProperty('runtimeFilter')); + }); + + it('switching the data source drops the filter: its fields are the old dataset object\'s', () => { + const next = pickDataset({ ...EXISTING, runtimeFilter: { stage: { $eq: 'won' } } }, 'other', MEMBERS); + expect(next).not.toHaveProperty('runtimeFilter'); + // Picking the data source already bound is no switch: the filter stays. + const same = pickDataset({ ...EXISTING, runtimeFilter: { stage: { $eq: 'won' } } }, 'pipeline', MEMBERS); + expect(same.runtimeFilter).toEqual({ stage: { $eq: 'won' } }); + }); +}); diff --git a/ui/packages/plugin-report/src/builder/ReportBuilder.tsx b/ui/packages/plugin-report/src/builder/ReportBuilder.tsx index b0d1b21418d..2862d63e179 100644 --- a/ui/packages/plugin-report/src/builder/ReportBuilder.tsx +++ b/ui/packages/plugin-report/src/builder/ReportBuilder.tsx @@ -5,7 +5,8 @@ * (objectstack#36374, board 49 figure 3). * * Left: the report drawn live. Right: five settings, top to bottom — report - * type, data source, measure, grouping, chart. There is no "Generate" button: + * type, data source (with 「+ Filter」 under it, objectstack#36645), measure, + * grouping, chart. There is no "Generate" button: * every pick rewrites the report document (`reportBuilderModel.ts`) and the * preview draws it again. Picking a data source draws a number at once (the * dataset's count measure, no grouping). While a required piece is missing the @@ -89,6 +90,15 @@ export interface ReportBuilderProps { membersLoading?: boolean; /** A line the host could not read the catalog or the members with. */ catalogError?: string; + /** + * The report filter under the data source (「+ Filter」, objectstack#36645): + * the report's `runtimeFilter` on the bound dataset. Host-controlled like + * the name box — the filterable fields are the dataset object's, and the + * filter's conversion to and from the spec's `FilterCondition` is the + * console's one shared bridge, so neither is read in this package. Drawn + * only while a data source is bound; absent, the builder offers no filter. + */ + filter?: React.ReactNode; /** Save: resolves once the host has written (or refused) the report. */ onSave: () => void | Promise; /** Discard: put the report back as it was when the builder opened. */ @@ -144,6 +154,7 @@ export function ReportBuilder({ members, membersLoading, catalogError, + filter, onSave, onDiscard, onClose, @@ -346,6 +357,7 @@ export function ReportBuilder({ {catalogError ?

{catalogError}

: null} + {dataset && filter ?
{filter}
: null}
diff --git a/ui/packages/plugin-report/src/builder/reportBuilderModel.ts b/ui/packages/plugin-report/src/builder/reportBuilderModel.ts index 37df5b95903..59a99b5863d 100644 --- a/ui/packages/plugin-report/src/builder/reportBuilderModel.ts +++ b/ui/packages/plugin-report/src/builder/reportBuilderModel.ts @@ -20,7 +20,11 @@ * measure, `seriesBy` = the second layer where the chart can split. The * 「表格」 choice is `chart.type: 'table'`, which the renderer draws as the * report's own table and no duplicate chart (`planReportChart`); - * - the period chip is `dateRange` with a date dimension the report groups by. + * - the period chip is `dateRange` with a date dimension the report groups by; + * - the filter under the data source is `runtimeFilter` (objectstack#36645), + * keyed by fields of the dataset's object. The host draws and writes it (see + * `ReportBuilderProps.filter`); this module only clears it when the data + * source changes, since the old dataset's fields mean nothing on the new one. * * No function here reads the network: the host hands in the dataset catalog * and the bound dataset's members, so the builder is drawable in a test and in From 147645de4f569edebdbe7835eb5cc10ab806cc67 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:25:38 +0000 Subject: [PATCH 2/4] wip: tests and changeset for the report builder filter Claude-Session: https://claude.ai/code/session_01JQwxbXeiNLk9jGd2XxhBfz Co-authored-by: Claude --- .changeset/36645-report-builder-filter.md | 14 ++ .../ReportBuilderHost.filter-36645.test.tsx | 144 ++++++++++++++++++ .../ReportView.saveRefusal-11583.test.tsx | 14 +- 3 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 .changeset/36645-report-builder-filter.md create mode 100644 ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx diff --git a/.changeset/36645-report-builder-filter.md b/.changeset/36645-report-builder-filter.md new file mode 100644 index 00000000000..a980ccdaadb --- /dev/null +++ b/.changeset/36645-report-builder-filter.md @@ -0,0 +1,14 @@ +--- +'@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. +- **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. diff --git a/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx b/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx new file mode 100644 index 00000000000..065e87d06de --- /dev/null +++ b/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx @@ -0,0 +1,144 @@ +// 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 = { + 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' }, + }, +}; + +const REPORT = { + name: 'deals', + label: 'Deals', + type: 'summary', + dataset: 'pipeline', + values: ['deal_count'], + chart: { type: 'metric', xAxis: '', yAxis: 'deal_count' }, +}; + +function mount(initial: Record) { + ComponentRegistry.register('chart', () =>
); + const onSave = vi.fn(async (_report: Record) => true); + const dataSource = { + getObjectSchema: vi.fn(async () => OBJECT_DEF), + queryDataset: vi.fn(async (_dataset: string, _selection: Record) => ({ rows: [{ deal_count: 3 }], fields: [] })), + }; + render( {}} 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 ones, with no currency pairing', () => { + const fields = reportFilterFields(OBJECT_DEF, (_f, fallback) => fallback, (_f, raw) => (Array.isArray(raw) ? raw : undefined)); + expect(fields.map((f) => f.value)).toEqual(['name', 'stage', 'amount', 'account']); + 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); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx b/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx index 86301efaa77..ee1d0defbcf 100644 --- a/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx +++ b/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx @@ -327,10 +327,20 @@ 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); + }); }); From ba6792906cef46be53570f5847e1dfb87d5d153e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:47:43 +0000 Subject: [PATCH 3/4] feat(console): offer business fields first in the report filter Claude-Session: https://claude.ai/code/session_01JQwxbXeiNLk9jGd2XxhBfz Co-authored-by: Claude --- .../views/ReportBuilderHost.filter-36645.test.tsx | 7 +++++++ .../app-shell/src/views/reportFilterFields.ts | 14 +++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx b/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx index 065e87d06de..02e4c21ba00 100644 --- a/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx +++ b/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx @@ -86,6 +86,13 @@ describe('the report filter fields (objectstack#36645)', () => { it('are the object\'s own fields, minus the hidden ones, with no currency pairing', () => { const fields = reportFilterFields(OBJECT_DEF, (_f, fallback) => fallback, (_f, raw) => (Array.isArray(raw) ? raw : undefined)); 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'); diff --git a/ui/packages/app-shell/src/views/reportFilterFields.ts b/ui/packages/app-shell/src/views/reportFilterFields.ts index f367fae72de..ca6081357fc 100644 --- a/ui/packages/app-shell/src/views/reportFilterFields.ts +++ b/ui/packages/app-shell/src/views/reportFilterFields.ts @@ -11,6 +11,12 @@ * (`conditionCandidatesOf`): the same translated labels, the same option * pickers for a select, the same record picker for a lookup. * + * The list's Filter panel also sets the ORDER, and so does this: the business + * fields first, then the system ones (`isSystemManagedField` — created by, + * modified at, owner …), each in the definition's order. "Add filter" seeds + * its row on the first field, so a new condition starts on a business field + * rather than on 「Created by」. + * * Two narrowings on top of that mapping, both because the builder writes * through the console's `FilterCondition` bridge (`datasetFilterCondition`), * not through the list's own filter dialect: @@ -29,7 +35,7 @@ */ import * as React from 'react'; -import type { DataSource } from '@object-ui/types'; +import { isSystemManagedField, type DataSource } from '@object-ui/types'; import { useObjectLabel } from '@object-ui/i18n'; import { conditionCandidatesOf, conditionOptionsOf, type ConditionCandidateField } from '@object-ui/plugin-list'; @@ -48,12 +54,14 @@ export function reportFilterFields( ): ReportFilterField[] { const defs = def?.fields; if (!defs || typeof defs !== 'object' || Array.isArray(defs)) return []; - const shown: Record = {}; + const business: Array<[string, unknown]> = []; + const system: Array<[string, unknown]> = []; for (const [name, field] of Object.entries(defs)) { if (!field || typeof field !== 'object') continue; if ((field as { hidden?: unknown }).hidden === true) continue; - shown[name] = field; + (isSystemManagedField(name, field as { system?: boolean }) ? system : business).push([name, field]); } + const shown: Record = Object.fromEntries([...business, ...system]); return conditionCandidatesOf(shown, label, options).map(({ currencyField: _paired, ...field }) => field); } From bdf493b77bb873bddad2f487b8ab7a3e58984eca Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 13:42:14 +0000 Subject: [PATCH 4/4] fix(console): keep $and-with-siblings filters out of the builder; offer no formula fields The shared filter bridge read only the $and rows of a filter that also has other top-level keys and called it editable, so the report builder (and the dataset designer) opened it where the next edit would drop the siblings. It now needs $and to be the only key, and a logical operator in a field slot is not a row. The report filter no longer offers virtual (formula) fields, which the dataset door refuses. Claude-Session: https://claude.ai/code/session_01JQwxbXeiNLk9jGd2XxhBfz Co-authored-by: Claude --- .changeset/36645-report-builder-filter.md | 2 ++ .../ReportBuilderHost.filter-36645.test.tsx | 15 +++++++++++++- .../ReportView.saveRefusal-11583.test.tsx | 5 +++++ .../inspectors/datasetFilterCondition.test.ts | 20 +++++++++++++++++++ .../inspectors/datasetFilterCondition.ts | 10 ++++++++++ .../app-shell/src/views/reportFilterFields.ts | 8 ++++++++ 6 files changed, 59 insertions(+), 1 deletion(-) diff --git a/.changeset/36645-report-builder-filter.md b/.changeset/36645-report-builder-filter.md index a980ccdaadb..dc843facda2 100644 --- a/.changeset/36645-report-builder-filter.md +++ b/.changeset/36645-report-builder-filter.md @@ -11,4 +11,6 @@ Clause-②: yes (widening) — a new optional `filter` slot on `ReportBuilder` ( 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. diff --git a/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx b/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx index 02e4c21ba00..c8361f50432 100644 --- a/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx +++ b/ui/packages/app-shell/src/views/ReportBuilderHost.filter-36645.test.tsx @@ -48,6 +48,7 @@ const OBJECT_DEF = { 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' }, }, }; @@ -83,8 +84,9 @@ afterEach(() => { }); describe('the report filter fields (objectstack#36645)', () => { - it('are the object\'s own fields, minus the hidden ones, with no currency pairing', () => { + 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( @@ -148,4 +150,15 @@ describe('「+ Filter」 under the report builder\'s data source (objectstack#36 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); + }); }); diff --git a/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx b/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx index ee1d0defbcf..12f344d07b9 100644 --- a/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx +++ b/ui/packages/app-shell/src/views/ReportView.saveRefusal-11583.test.tsx @@ -342,5 +342,10 @@ describe('which reports open in the builder (objectstack#36374, opensInBuilder)' 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); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.test.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.test.ts index 17fa129b3c2..957f6ba5b71 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.test.ts @@ -106,4 +106,24 @@ describe('datasetFilterCondition', () => { expect(conditionToGroup({ amount: { $gt: 1, $lt: 9 } }).representable).toBe(false); expect(conditionToGroup({ $and: [{ $or: [{ a: { $eq: 1 } }] }] }).representable).toBe(false); }); + + it('`$and` is the group only when it is the only key: siblings send the filter to the source editor (objectstack#36645)', () => { + // The spec's FilterCondition is a field record intersected with optional + // `$and` / `$or` / `$not`, so these are valid. Read as just their `$and` + // rows, the next commit of any row would drop the siblings. + for (const stored of [ + { $and: [{ stage: { $eq: 'won' } }], amount: { $gt: 5 } }, + { $and: [{ stage: { $eq: 'won' } }], $not: { stage: { $eq: 'lost' } } }, + { $and: { stage: { $eq: 'won' } } }, + { $not: { stage: { $eq: 'lost' } } }, + { $not: { $eq: 'lost' } }, + ]) { + expect(conditionToGroup(stored as never).representable, JSON.stringify(stored)).toBe(false); + } + // CONTROL: a lone `$and` still opens as its rows and writes back as it was. + const lone = { $and: [{ stage: { $eq: 'won' } }, { amount: { $gt: 5 } }] }; + const read = conditionToGroup(lone); + expect(read.representable).toBe(true); + expect(groupToCondition(read.group)).toEqual(lone); + }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.ts index 2ef8e759a4f..d6dd8e422d6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetFilterCondition.ts @@ -402,6 +402,14 @@ export function conditionToGroup( if (cond == null) return { group: empty, representable: true }; if (typeof cond !== 'object' || Array.isArray(cond)) return { group: empty, representable: false }; if ('$or' in cond) return { group: empty, representable: false }; + // `$and` is the whole group only when it is the ONLY key. The spec's shape is + // a field record intersected with optional `$and` / `$or` / `$not`, so + // `{ $and: [...], amount: {...} }` and `{ $and: [...], $not: {...} }` are + // valid — and reading only the `$and` rows would open them as editable and + // let the next commit of any row drop the siblings (objectstack#36645). + if ('$and' in cond && (Object.keys(cond).length !== 1 || !Array.isArray((cond as Record).$and))) { + return { group: empty, representable: false }; + } const list: FilterCondition[] = Array.isArray((cond as any).$and) ? (cond as any).$and : [cond]; const conditions: BuilderCondition[] = []; @@ -412,6 +420,8 @@ export function conditionToGroup( const keys = Object.keys(c); if (keys.length !== 1) return { group: empty, representable: false }; const field = keys[0]; + // A logical operator in the field slot (`$not`, …) is not a row. + if (field.startsWith('$')) return { group: empty, representable: false }; const v = (c as any)[field]; let row: BuilderCondition; if (v && typeof v === 'object' && !Array.isArray(v)) { diff --git a/ui/packages/app-shell/src/views/reportFilterFields.ts b/ui/packages/app-shell/src/views/reportFilterFields.ts index ca6081357fc..f0065126bda 100644 --- a/ui/packages/app-shell/src/views/reportFilterFields.ts +++ b/ui/packages/app-shell/src/views/reportFilterFields.ts @@ -23,6 +23,8 @@ * * - a field the object marks `hidden: true` is not offered, as the list's * Filter panel does not offer it; + * - a virtual field (`isVirtualSearchField`: a formula, no column) is not + * offered — the dataset door refuses a filter on one (400 INVALID_FIELD); * - a `record`-mode amount's currency pairing (`currencyField`) is dropped: the * pairing writes a second, companion condition the bridge reads back as a * row of its own, so the amount is offered as the dataset designer offers @@ -35,6 +37,7 @@ */ import * as React from 'react'; +import { isVirtualSearchField, type SearchFieldMeta } from '@objectstack/spec/data'; import { isSystemManagedField, type DataSource } from '@object-ui/types'; import { useObjectLabel } from '@object-ui/i18n'; import { conditionCandidatesOf, conditionOptionsOf, type ConditionCandidateField } from '@object-ui/plugin-list'; @@ -59,6 +62,11 @@ export function reportFilterFields( for (const [name, field] of Object.entries(defs)) { if (!field || typeof field !== 'object') continue; if ((field as { hidden?: unknown }).hidden === true) continue; + // A virtual field (a formula, no column) is refused by the dataset door + // with 400 INVALID_FIELD, so offering it would let a report be saved that + // fails for every viewer. The spec's own predicate, as the list's + // grouping uses it. + if (isVirtualSearchField(field as SearchFieldMeta)) continue; (isSystemManagedField(name, field as { system?: boolean }) ? system : business).push([name, field]); } const shown: Record = Object.fromEntries([...business, ...system]);