diff --git a/.changeset/35992-dashboard-filter-arity.md b/.changeset/35992-dashboard-filter-arity.md new file mode 100644 index 00000000000..250fec10374 --- /dev/null +++ b/.changeset/35992-dashboard-filter-arity.md @@ -0,0 +1,22 @@ +--- +'@object-ui/types': patch +'@object-ui/core': patch +'@object-ui/data-objectstack': patch +'@object-ui/plugin-dashboard': patch +--- + +fix(dashboard): a global filter bound to a field holding several values is sent as `$contains`, not `=` / `$in` + +Clause-②: yes (widening) +Metadata-protocol: none + +A dashboard `select` / `lookup` global filter bound to a field that holds several values (`multiple: true` on a select, lookup or user field, or a `multiselect` / `checkboxes` / `tags` field) used to be sent as `field = value`, or `$in` for several values. The server refuses both on such a field: the data query answers `400 INVALID_FILTER`, and the dataset query answers `200` with a count of 0, so the dashboard showed no data. The filter is now sent as `{ field: { $contains: value } }`, and several chosen values as `$or` over one `$contains` each, which the server answers with the matching rows. Single-value fields keep `=` / `$in`. + +To know whether the bound field holds several values, the dashboard reads the field's definition before it sends the widget's query: + +- `@object-ui/types`: `DataSource` has a new optional member, `getDataset(name, { callerPackage })`. It reads a dataset definition and resolves `null` when no such dataset is served; a failed read rejects. +- `@object-ui/data-objectstack`: `ObjectStackAdapter.getDataset` reads `GET /api/v1/meta/dataset/:name`, sending the reader's package as `callerPackage`, and caches the answer like the adapter's other metadata reads. +- `@object-ui/core`: `buildWidgetScopedFilter` takes an optional fifth argument, the operators each bound field takes when it is stored as a JSON column, and lowers a `select` / `lookup` filter on such a field to `$contains`. `boundMemberFilterNames` names the active `select` / `lookup` filters that bind a widget. +- `@object-ui/plugin-dashboard`: `DashboardRenderer` reads a dataset-bound widget's base object through `getDataset`, and a `provider: 'object'` widget's own object, through `getObjectSchema`. While that read is in flight, a widget that a `select` / `lookup` filter with a value binds draws a skeleton and sends no query. The operators come from `jsonColumnFilterOperators`, the helper the list quick filter and the filter builder use. + +A data source without `getDataset`, or a dataset the server does not serve, keeps the `=` / `$in` lowering, and the dashboard logs a console warning that names the filter. diff --git a/content/docs/frontend/data-source.mdx b/content/docs/frontend/data-source.mdx index f17cf41da09..a26b416c349 100644 --- a/content/docs/frontend/data-source.mdx +++ b/content/docs/frontend/data-source.mdx @@ -214,6 +214,8 @@ await (dataSource.batchMutationEvents ? dataSource.batchMutationEvents(write) : `listMetadataItems(type)` lists one metadata registry type as `{ name, label }` headers, for the `position-ref` / `permission-ref` field widgets (see the [Fields guide](/docs/frontend/fields)). An empty array means the registry has no item of that type, so a failed load must **reject**, never resolve `[]`. +`getDataset(name, { callerPackage })` reads a semantic-layer dataset definition (`GET /api/v1/meta/dataset/:name`). A dashboard reads it to learn a dataset-bound widget's base object, so a filter on a field holding several values is sent as `$contains` instead of `=` / `$in`. It resolves `null` when no such dataset is served, and a failed read must **reject**. The member is optional: without it, the dashboard sends `=` / `$in` and warns in the console, naming the filter. + ### Cross-object atomic writes (`batchTransaction`) Master-detail saves (a parent record plus its child line items) go through diff --git a/ui/packages/core/src/index.ts b/ui/packages/core/src/index.ts index 867ff827211..57e46ddd063 100644 --- a/ui/packages/core/src/index.ts +++ b/ui/packages/core/src/index.ts @@ -244,6 +244,8 @@ export { dashboardFilterVariableDefs, buildFilterCondition, buildWidgetScopedFilter, + boundMemberFilterNames, + type DashboardFilterJsonColumnOperators, } from './utils/dashboard-filters.js'; export * from './utils/merge-filters.js'; export * from './utils/compare-to.js'; diff --git a/ui/packages/core/src/utils/__tests__/dashboard-filters.multiValue-35992.test.ts b/ui/packages/core/src/utils/__tests__/dashboard-filters.multiValue-35992.test.ts new file mode 100644 index 00000000000..57b5513e7e4 --- /dev/null +++ b/ui/packages/core/src/utils/__tests__/dashboard-filters.multiValue-35992.test.ts @@ -0,0 +1,142 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35992 — a `select` / `lookup` dashboard filter bound to a field + * holding several values is lowered to `$contains`, one member per condition + * and `$or` for any of several, never `=` / `$in` (refused by the server on + * such a field). + * + * This file pins the pure lowering in `buildWidgetScopedFilter` with an + * operator answer handed in, as the renderer hands it in. The answer's own + * source, `jsonColumnFilterOperators` over a real field definition, and the + * rendered dashboard are pinned in `@object-ui/plugin-dashboard` + * (`filterFieldFacts.multiValue-35992.test.ts`, + * `DashboardRenderer.multiValueFilter-35992.test.tsx`). + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { + boundMemberFilterNames, + buildWidgetScopedFilter, + resolveDashboardFilterDefs, + type DashboardFilterJsonColumnOperators, +} from '../dashboard-filters'; + +afterEach(() => vi.restoreAllMocks()); + +/** The answer for a field holding several values, as the shared helper gives it. */ +const MULTI = ['contains', 'not_contains', 'is_empty', 'is_not_empty'] as const; +/** The answer for a structured JSON field: empty checks only. */ +const STRUCTURED = ['is_empty', 'is_not_empty'] as const; + +const operators: DashboardFilterJsonColumnOperators = (field) => + field === 'labels' || field === 'team_members' ? MULTI : field === 'address' ? STRUCTURED : undefined; + +const defs = resolveDashboardFilterDefs({ + globalFilters: [ + { name: 'label', field: 'labels', type: 'select', options: [{ value: 'frontend', label: 'Frontend' }] }, + { name: 'member', field: 'team_members', type: 'lookup' }, + { name: 'status', field: 'status', type: 'select' }, + { name: 'search', field: 'name', type: 'text' }, + ], +}); + +const widget = { id: 'w1' }; + +describe('buildWidgetScopedFilter: member filter on a field holding several values (objectstack#35992)', () => { + it('lowers one selected member to a single $contains', () => { + expect(buildWidgetScopedFilter(widget, defs, { label: 'frontend' }, undefined, operators)).toEqual({ + labels: { $contains: 'frontend' }, + }); + }); + + it('lowers several members (any of them) to $or over one $contains each', () => { + expect(buildWidgetScopedFilter(widget, defs, { label: ['frontend', 'qa'] }, undefined, operators)).toEqual({ + $or: [{ labels: { $contains: 'frontend' } }, { labels: { $contains: 'qa' } }], + }); + }); + + it('lowers a one-member list to a single $contains, not a one-arm $or', () => { + expect(buildWidgetScopedFilter(widget, defs, { label: ['frontend'] }, undefined, operators)).toEqual({ + labels: { $contains: 'frontend' }, + }); + }); + + it('lowers a lookup filter on a multi-value lookup / user field the same way', () => { + expect(buildWidgetScopedFilter(widget, defs, { member: 'usr_1' }, undefined, operators)).toEqual({ + team_members: { $contains: 'usr_1' }, + }); + expect(buildWidgetScopedFilter(widget, defs, { member: ['usr_1', 'usr_2'] }, undefined, operators)).toEqual({ + $or: [{ team_members: { $contains: 'usr_1' } }, { team_members: { $contains: 'usr_2' } }], + }); + }); + + it('follows an explicit filterBindings target to the field it names', () => { + const bound = { id: 'w2', filterBindings: { status: 'labels' } }; + expect(buildWidgetScopedFilter(bound, defs, { status: 'frontend' }, undefined, operators)).toEqual({ + labels: { $contains: 'frontend' }, + }); + }); + + it('leaves a single-value field on = / $in', () => { + expect(buildWidgetScopedFilter(widget, defs, { status: 'open' }, undefined, operators)).toEqual({ status: 'open' }); + expect(buildWidgetScopedFilter(widget, defs, { status: ['open', 'won'] }, undefined, operators)).toEqual({ + status: { $in: ['open', 'won'] }, + }); + }); + + it('leaves a text filter on its $contains, whatever the field', () => { + expect(buildWidgetScopedFilter(widget, defs, { search: 'acme' }, undefined, operators)).toEqual({ + name: { $contains: 'acme' }, + }); + }); + + it('ANDs a multi-value clause with the other active filters', () => { + expect( + buildWidgetScopedFilter(widget, defs, { label: ['frontend', 'qa'], status: 'open' }, undefined, operators), + ).toEqual({ + $and: [{ $or: [{ labels: { $contains: 'frontend' } }, { labels: { $contains: 'qa' } }] }, { status: 'open' }], + }); + }); + + it('keeps = / $in when no operator answer is given (field definitions not known)', () => { + expect(buildWidgetScopedFilter(widget, defs, { label: 'frontend' })).toEqual({ labels: 'frontend' }); + expect(buildWidgetScopedFilter(widget, defs, { label: ['frontend', 'qa'] })).toEqual({ + labels: { $in: ['frontend', 'qa'] }, + }); + }); + + it('keeps = / $in for a member filter on a structured JSON field (no contains), explicit binding included', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const structured = resolveDashboardFilterDefs({ + globalFilters: [{ name: 'where', field: 'address', type: 'select' }], + }); + expect(buildWidgetScopedFilter(widget, structured, { where: 'x' }, undefined, operators)).toEqual({ address: 'x' }); + expect( + buildWidgetScopedFilter({ id: 'w4', filterBindings: { where: 'address' } }, structured, { where: ['x', 'y'] }, undefined, operators), + ).toEqual({ address: { $in: ['x', 'y'] } }); + expect(warn).not.toHaveBeenCalled(); + }); +}); + +describe('boundMemberFilterNames (objectstack#35992)', () => { + it('names the active select / lookup filters that bind the widget', () => { + expect(boundMemberFilterNames(widget, defs, { label: 'frontend', member: 'usr_1', search: 'acme' })).toEqual([ + 'label', + 'member', + ]); + }); + + it('leaves out empty values and widgets that opt out', () => { + expect(boundMemberFilterNames(widget, defs, { label: '', member: [] })).toEqual([]); + expect(boundMemberFilterNames({ id: 'w3', filterBindings: { label: false } }, defs, { label: 'frontend' })).toEqual( + [], + ); + }); +}); diff --git a/ui/packages/core/src/utils/dashboard-filters.ts b/ui/packages/core/src/utils/dashboard-filters.ts index be1d7b3632f..e7919638f3d 100644 --- a/ui/packages/core/src/utils/dashboard-filters.ts +++ b/ui/packages/core/src/utils/dashboard-filters.ts @@ -692,6 +692,66 @@ export function buildFilterCondition( return value; } +/** + * The operators one bound field takes when it is stored as a JSON column, or + * `undefined` for every other field (and for a field whose definition is not + * known). The renderer answers it with `jsonColumnFilterOperators` from + * `@object-ui/components`, the one helper every filter surface reads, over the + * field definitions of the widget's object: this module does not restate that + * operator table, and `@object-ui/core` cannot import the components package. + */ +export type DashboardFilterJsonColumnOperators = (field: string) => readonly string[] | undefined; + +/** A filter whose value names members (`select` / `lookup`): `=` or `$in` today. */ +function isMemberFilter(def: DashboardFilterDef): boolean { + return def.type === 'select' || def.type === 'lookup'; +} + +/** + * Lower a `select` / `lookup` filter bound to a field stored as a JSON column. + * + * A field holding several values takes `contains` (`$contains`, ONE member per + * condition) and the empty checks; `=` and `$in` are refused. So one selected + * member is `{ field: { $contains: member } }`, and several (any of them) are + * `$or` over one `$contains` each. + * + * Only a field that takes `contains` reaches here. A field stored as a JSON + * column without it (a structured value such as `json` or `address`, empty + * checks only) holds no members, so the caller keeps the `=` / `$in` lowering + * for it, as before. + */ +function buildJsonColumnMemberClause( + field: string, + value: unknown, +): Record | undefined { + const members = (Array.isArray(value) ? value : [value]).filter( + (m) => m !== undefined && m !== null && m !== '', + ); + if (members.length === 0) return undefined; + if (members.length === 1) return { [field]: { $contains: members[0] } }; + return { $or: members.map((m) => ({ [field]: { $contains: m } })) }; +} + +/** + * The names of the `select` / `lookup` filters that hold a value AND bind this + * widget — the filters whose lowering depends on the bound field's definition + * (see `jsonColumnOperators` on {@link buildWidgetScopedFilter}). Empty when + * no such filter applies, so a renderer that waits for the definition before + * querying waits only when the answer can change the query. + */ +export function boundMemberFilterNames( + widget: Pick, + defs: DashboardFilterDef[], + values: Record, +): string[] { + const names: string[] = []; + for (const def of defs) { + if (!isMemberFilter(def) || isEmptyValue(def, values[def.name])) continue; + if (resolveBoundField(widget, def)) names.push(def.name); + } + return names; +} + /** * Resolve which of the widget's fields a filter binds to. * Returns `undefined` when the widget is not bound to this filter. @@ -727,12 +787,21 @@ function resolveBoundField( * field, so a typo surfaces as a visible (fixable) empty widget rather than * being silently dropped. Callers omit `knownFields` when metadata is not * (yet) available, preserving the previous behaviour. + * + * `jsonColumnOperators` answers, per bound field, the operators the field + * takes when it is stored as a JSON column (a field holding several values, + * `multiple: true` or a `multiselect`-like type). A `select` / `lookup` filter + * bound to such a field is lowered by {@link buildJsonColumnMemberClause} + * instead of to `=` / `$in`, which the server refuses there. Callers omit it + * when the field definitions are not known, which keeps the `=` / `$in` + * lowering of {@link buildFilterCondition}. */ export function buildWidgetScopedFilter( widget: Pick, defs: DashboardFilterDef[], values: Record, knownFields?: ReadonlySet, + jsonColumnOperators?: DashboardFilterJsonColumnOperators, ): Record | undefined { const conditions: Record[] = []; @@ -752,6 +821,11 @@ export function buildWidgetScopedFilter( } continue; } + if (isMemberFilter(def) && jsonColumnOperators?.(field)?.includes('contains')) { + const clause = buildJsonColumnMemberClause(field, value); + if (clause) conditions.push(clause); + continue; + } const condition = buildFilterCondition(def, value); if (condition === undefined) continue; conditions.push({ [field]: condition }); diff --git a/ui/packages/data-objectstack/src/getDataset-35992.test.ts b/ui/packages/data-objectstack/src/getDataset-35992.test.ts new file mode 100644 index 00000000000..a4304594452 --- /dev/null +++ b/ui/packages/data-objectstack/src/getDataset-35992.test.ts @@ -0,0 +1,92 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * `ObjectStackAdapter.getDataset` — the dataset definition a dashboard reads to + * learn a dataset-bound widget's base object, so a filter on a field holding + * several values is lowered to `$contains` (objectstack#35992). + * + * `null` means "no such dataset" and a failure rejects, so the dashboard can + * tell the two apart. Every case goes through the real `ObjectStackClient` + * over a stubbed `fetch`, so the client's envelope unwrap and error raise are + * part of what is measured. + */ +import { describe, it, expect, vi } from 'vitest'; +import { ObjectStackAdapter } from './index'; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +let seq = 0; + +/** A fresh base URL per adapter, so the shared discovery cache cannot carry over. */ +function makeAdapter(meta: (url: string) => Response) { + const baseUrl = `http://dataset-def-35992-${++seq}.local`; + const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.endsWith('/api/v1/discovery')) return json(200, { success: true, data: {} }); + return meta(url); + }); + return { adapter: new ObjectStackAdapter({ baseUrl, fetch: fetchImpl }), fetchImpl }; +} + +const metaUrls = (fetchImpl: ReturnType['fetchImpl']) => + fetchImpl.mock.calls.map(([u]) => String(u)).filter((u) => u.includes('/api/v1/meta/')); + +const DATASET = { name: 'project_metrics', label: 'Project Metrics', object: 'showcase_project' }; + +describe('ObjectStackAdapter.getDataset (objectstack#35992)', () => { + it('reads GET /api/v1/meta/dataset/:name and answers the item', async () => { + const { adapter, fetchImpl } = makeAdapter(() => + json(200, { success: true, data: { type: 'dataset', name: 'project_metrics', item: DATASET } }), + ); + await expect(adapter.getDataset('project_metrics')).resolves.toMatchObject({ object: 'showcase_project' }); + expect(metaUrls(fetchImpl)).toEqual([expect.stringMatching(/\/api\/v1\/meta\/dataset\/project_metrics$/)]); + }); + + it("sends the reader's package as callerPackage", async () => { + const { adapter, fetchImpl } = makeAdapter(() => + json(200, { success: true, data: { type: 'dataset', name: 'project_metrics', item: DATASET } }), + ); + await adapter.getDataset('project_metrics', { callerPackage: 'com.example.showcase' }); + expect(metaUrls(fetchImpl)).toEqual([ + expect.stringMatching(/\/api\/v1\/meta\/dataset\/project_metrics\?callerPackage=com\.example\.showcase$/), + ]); + }); + + it('answers null for an envelope with no item (no such dataset)', async () => { + const { adapter } = makeAdapter(() => json(200, { success: true, data: { type: 'dataset', name: 'nope' } })); + await expect(adapter.getDataset('nope')).resolves.toBeNull(); + }); + + it('answers null for a 404', async () => { + const { adapter } = makeAdapter(() => + json(404, { success: false, error: { code: 'RESOURCE_NOT_FOUND', message: 'not found' } }), + ); + await expect(adapter.getDataset('nope')).resolves.toBeNull(); + }); + + it('REJECTS a failed read instead of answering "no such dataset"', async () => { + const { adapter } = makeAdapter(() => + json(500, { success: false, error: { code: 'INTERNAL_ERROR', message: 'registry offline' } }), + ); + await expect(adapter.getDataset('project_metrics')).rejects.toMatchObject({ + httpStatus: 500, + code: 'INTERNAL_ERROR', + }); + }); + + it('reads one definition once per name and reader package', async () => { + const { adapter, fetchImpl } = makeAdapter(() => + json(200, { success: true, data: { type: 'dataset', name: 'project_metrics', item: DATASET } }), + ); + await adapter.getDataset('project_metrics'); + await adapter.getDataset('project_metrics'); + expect(metaUrls(fetchImpl)).toHaveLength(1); + }); +}); diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index ee2a635bd5d..b1ea4112d69 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -8,7 +8,7 @@ import { ObjectStackClient, type QueryOptions as ObjectStackQueryOptions } from '@objectstack/client'; import type { DroppedFieldsEvent, EngineAggregateOptions } from '@objectstack/spec/data'; -import type { ListViewGroupHeaderRow } from '@objectstack/spec/ui'; +import type { Dataset, ListViewGroupHeaderRow } from '@objectstack/spec/ui'; // objectui#11013 — a VALUE import: the keys `listViews` carries off a stored // ViewItem record are the spec's own record of the console's round-trip keys, // read off the pin rather than hand-listed (see `VIEW_ITEM_ROUND_TRIP_KEYS`). @@ -7323,6 +7323,42 @@ export class ObjectStackAdapter implements DataSource { } } + /** + * Get a semantic-layer dataset definition (`DataSource.getDataset`). + * + * Reads `GET /api/v1/meta/dataset/:name` through the client's + * `meta.getItem`, with the reader's package as `callerPackage` when the + * caller names one (ADR-0150 D3), so the name resolves the way the + * dataset query that follows resolves it. + * + * No such dataset is `null`, in both answers a server gives for it: the + * envelope with no `item` ({@link metaEnvelopeCarriesItem}) and the `404` + * ({@link is404Error}). Every other failure rejects, unlike {@link getPage}: + * the dashboard reports a definition it could not read, and a swallowed + * failure would read as "no dataset". + * + * Cached per name and reader package; `invalidateCache` / `clearCache` + * drop it like every other metadata read here. + */ + async getDataset(datasetName: string, options?: { callerPackage?: string }): Promise { + await this.connect(); + const callerPackage = options?.callerPackage; + const cacheKey = `dataset:${datasetName}${callerPackage ? `@${callerPackage}` : ''}`; + return this.metadataCache.get(cacheKey, async () => { + try { + const envelope: unknown = await this.client.meta.getItem( + 'dataset', + datasetName, + callerPackage ? { callerPackage } : undefined, + ); + return metaEnvelopeCarriesItem(envelope) ? ((envelope as { item: Dataset }).item) : null; + } catch (error: unknown) { + if (is404Error(error)) return null; + throw error; + } + }); + } + /** * Update (upsert) a dashboard definition. * diff --git a/ui/packages/plugin-dashboard/README.md b/ui/packages/plugin-dashboard/README.md index 8de493b6a2c..2967d256b45 100644 --- a/ui/packages/plugin-dashboard/README.md +++ b/ui/packages/plugin-dashboard/README.md @@ -493,6 +493,16 @@ Notes: query time, so widgets resolve them exactly like hand-authored filters. - Dataset-bound widgets receive the merged filter through the dataset query's `runtimeFilter`. +- A `select` / `lookup` filter bound to a field that holds several values + (`multiple: true`, or a `multiselect` / `checkboxes` / `tags` field) is sent + as `$contains`, one member per condition and `$or` for any of several, + because the server refuses `=` / `$in` on such a field. The dashboard reads + the field's definition first: a dataset-bound widget's base object through + the data source's optional `getDataset`, a `provider: 'object'` widget's own + object, each through `getObjectSchema`. The widget's query waits for that + answer. When the definition cannot be read (a data source without + `getDataset`, a dataset the server does not serve), the filter is sent as + `=` / `$in` and a console warning names it. - Filter values are also readable in widget expressions as `page.` (e.g. `page.region`), since they are hosted as dashboard variables. - `optionsFrom` resolves distinct option values server-side (a dataset diff --git a/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx b/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx index e2fd2b3bef8..f55f05727ef 100644 --- a/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx +++ b/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx @@ -15,13 +15,14 @@ import { resolveDashboardFilterDefs, dashboardFilterVariableDefs, buildWidgetScopedFilter, + boundMemberFilterNames, mergeFilters, toDomProps, chartCategoryKey, chartMeasureKey, chartConfigPresentation, } from '@object-ui/core'; -import { cn, Card, CardHeader, CardTitle, CardContent, Button, getLazyIcon, Empty, EmptyTitle, EmptyDescription } from '@object-ui/components'; +import { cn, Card, CardHeader, CardTitle, CardContent, Button, getLazyIcon, Empty, EmptyTitle, EmptyDescription, ChartSkeleton } from '@object-ui/components'; import { forwardRef, useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo, Fragment } from 'react'; import type { HTMLAttributes } from 'react'; import { Lock, RefreshCw } from 'lucide-react'; @@ -49,6 +50,7 @@ import type { DashboardChartRenderSchema } from './chartRenderHandoff'; import { useDashboardAutoRefresh, type DashboardAutoRefresh } from './useDashboardAutoRefresh'; import { DashboardFilterBar } from './DashboardFilterBar'; import { DatasetQueryCoalescerContext, useDatasetQueryCoalescer } from './datasetQueryBatch'; +import { filterFieldSource, jsonColumnOperatorsFor, useFilterFieldFacts, warnFilterLoweredWithoutFacts, type FilterFieldSource } from './filterFieldFacts'; /** * One `header.actions[]` entry, as the node's declaration types it: the spec's @@ -422,6 +424,20 @@ const DashboardRendererInner = forwardRef def.type === 'select' || def.type === 'lookup')) { + const entries: DashboardWidgetSlotEntry[] = schema.widgets ?? []; + for (const entry of entries) { + const source = isSlotComponentEntry(entry) ? undefined : filterFieldSource(entry); + if (source) filterFieldSources.push(source); + } + } + const filterFieldFactsFor = useFilterFieldFacts(dataSource, filterFieldSources, dashboardPackageId); // ── i18n: convention-based label resolution for dashboard / widget / // action text. The dashboard name (`schema.name`) keys all lookups; when @@ -1074,8 +1090,22 @@ const DashboardRendererInner = forwardRef 0 ? filterFieldFactsFor(fieldSource) : undefined; + if (fieldSource && fieldFacts?.status === 'unavailable') { + for (const name of memberFilters) warnFilterLoweredWithoutFacts(name, fieldSource, fieldFacts.reason); + } + const holdForFieldFacts = fieldFacts?.status === 'pending'; const scopedFilter = widgetArm && filterDefs.length > 0 - ? buildWidgetScopedFilter(widgetArm, filterDefs, filterValues) + ? buildWidgetScopedFilter(widgetArm, filterDefs, filterValues, undefined, jsonColumnOperatorsFor(fieldFacts)) : undefined; const componentSchema = ((): SchemaRendererProps['schema'] => { // No cast (objectui#11466): `getComponentSchema` returns @@ -1183,7 +1213,11 @@ const DashboardRendererInner = forwardRef
- {datasetWidget + {holdForFieldFacts + ?
+ +
+ : datasetWidget ? { + resetFilterFieldFactsWarnings(); + // Best-effort metadata probes are not what these cases are about. + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => ({}), text: async () => '{}' }))); +}); +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + cleanup(); +}); + +/** The fixture object: one multi-value select, one multi-value user, one single-value select. */ +const PROJECT_SCHEMA = { + name: 'project', + fields: { + name: { type: 'text', label: 'Name' }, + labels: { + type: 'multiselect', + label: 'Labels', + options: [ + { value: 'frontend', label: 'Frontend' }, + { value: 'qa', label: 'QA' }, + ], + }, + team_members: { type: 'user', label: 'Team Members', multiple: true }, + status: { type: 'select', label: 'Status' }, + }, +}; + +/** The fixture dashboard: a global filter on `labels`, read by a dataset-bound widget. */ +const fixtureDashboard = ( + defaultValue: string | undefined, + extra: Partial = {}, +): DashboardComponentSchema => ({ + type: 'dashboard', + globalFilters: [ + { + name: 'label', + field: 'labels', + type: 'select', + options: [ + { value: 'frontend', label: 'Frontend' }, + { value: 'qa', label: 'QA' }, + ], + ...(defaultValue === undefined ? {} : { defaultValue }), + }, + ], + widgets: [{ id: 'w1', type: 'bar', dataset: 'project_metrics', values: ['project_count'] }], + ...extra, +}); + +const makeQueryDataset = () => + vi.fn(async (_dataset: string, _selection: unknown) => ({ rows: [{ project_count: 2 }], fields: [] })); + +const runtimeFilters = (queryDataset: ReturnType, dataset: string): unknown[] => + queryDataset.mock.calls + .filter((c) => c[0] === dataset) + .map((c) => (c[1] as { runtimeFilter?: unknown })?.runtimeFilter); + +const makeSource = (overrides: Record = {}) => ({ + queryDataset: makeQueryDataset(), + getDataset: vi.fn(async (name: string) => + name === 'project_metrics' ? { name, label: 'Project Metrics', object: 'project' } : null, + ), + getObjectSchema: vi.fn(async (object: string) => (object === 'project' ? PROJECT_SCHEMA : null)), + ...overrides, +}); + +describe('DashboardRenderer: a global filter bound to a multi-value field (objectstack#35992)', () => { + it('sends $contains for the selected member, never = on the multi-value field', async () => { + const source = makeSource(); + render(); + + await waitFor(() => + expect(runtimeFilters(source.queryDataset, 'project_metrics')).toContainEqual({ + labels: { $contains: 'frontend' }, + }), + ); + // Held until the definition arrived: no query ever carried the refused `=`. + expect(runtimeFilters(source.queryDataset, 'project_metrics')).not.toContainEqual({ labels: 'frontend' }); + expect(source.getDataset).toHaveBeenCalledWith('project_metrics', undefined); + expect(source.getObjectSchema).toHaveBeenCalledWith('project'); + }); + + it('holds the widget query, drawing a skeleton, until the field definition arrives', async () => { + let answerDataset!: (value: unknown) => void; + const source = makeSource({ + getDataset: vi.fn(() => new Promise((resolve) => { answerDataset = resolve; })), + }); + render(); + + expect(await screen.findByTestId('dashboard-widget-filter-pending')).toBeInTheDocument(); + expect(source.queryDataset).not.toHaveBeenCalled(); + + await act(async () => { + answerDataset({ name: 'project_metrics', label: 'Project Metrics', object: 'project' }); + }); + await waitFor(() => + expect(runtimeFilters(source.queryDataset, 'project_metrics')).toEqual([{ labels: { $contains: 'frontend' } }]), + ); + expect(screen.queryByTestId('dashboard-widget-filter-pending')).not.toBeInTheDocument(); + }); + + it('lowers a lookup filter on a multi-value user field to $contains', async () => { + const source = makeSource(); + const schema = fixtureDashboard(undefined, { + globalFilters: [{ name: 'member', field: 'team_members', type: 'lookup', defaultValue: 'usr_1' }], + }); + render(); + await waitFor(() => + expect(runtimeFilters(source.queryDataset, 'project_metrics')).toEqual([{ team_members: { $contains: 'usr_1' } }]), + ); + }); + + it('holds nothing while the filter has no value', async () => { + const source = makeSource({ getDataset: vi.fn(() => new Promise(() => {})) }); + render(); + await waitFor(() => expect(runtimeFilters(source.queryDataset, 'project_metrics')).toEqual([undefined])); + expect(screen.queryByTestId('dashboard-widget-filter-pending')).not.toBeInTheDocument(); + }); + + it('keeps a single-value field on =', async () => { + const source = makeSource(); + const schema = fixtureDashboard(undefined, { + globalFilters: [ + { name: 'state', field: 'status', type: 'select', options: [{ value: 'open', label: 'Open' }], defaultValue: 'open' }, + ], + }); + render(); + await waitFor(() => expect(runtimeFilters(source.queryDataset, 'project_metrics')).toContainEqual({ status: 'open' })); + }); + + it('a data source without getDataset keeps = and warns, naming the filter', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const source = makeSource({ getDataset: undefined }); + render(); + + await waitFor(() => + expect(runtimeFilters(source.queryDataset, 'project_metrics')).toContainEqual({ labels: 'frontend' }), + ); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('"label"')); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain('getDataset'); + expect(lines[0]).toContain('"project_metrics"'); + expect(source.getObjectSchema).not.toHaveBeenCalled(); + }); + + it('a dataset the server does not serve keeps = and warns, naming the filter', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const source = makeSource({ getDataset: vi.fn(async () => null) }); + render(); + + await waitFor(() => + expect(runtimeFilters(source.queryDataset, 'project_metrics')).toContainEqual({ labels: 'frontend' }), + ); + expect(warn.mock.calls.map((c) => String(c[0])).some((l) => l.includes('"label"'))).toBe(true); + }); + + it('a provider: object table lowers the same filter against its own object', async () => { + const find = vi.fn(async (_object: string, _query?: unknown) => ({ data: [{ id: '1', name: 'Apollo' }], total: 1 })); + const source = { ...makeSource(), find, findOne: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() }; + const schema = fixtureDashboard('frontend', { + widgets: [ + { + id: 't1', + type: 'table', + options: { data: { provider: 'object', object: 'project' }, columns: [{ accessorKey: 'name', header: 'Name' }] }, + }, + ], + }); + render(); + + await waitFor(() => + expect(find.mock.calls.map((c) => (c[1] as { $filter?: unknown })?.$filter)).toContainEqual({ + labels: { $contains: 'frontend' }, + }), + ); + expect(find.mock.calls.map((c) => (c[1] as { $filter?: unknown })?.$filter)).not.toContainEqual({ labels: 'frontend' }); + expect(source.getDataset).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/__tests__/filterFieldFacts.multiValue-35992.test.ts b/ui/packages/plugin-dashboard/src/__tests__/filterFieldFacts.multiValue-35992.test.ts new file mode 100644 index 00000000000..d711e69a4be --- /dev/null +++ b/ui/packages/plugin-dashboard/src/__tests__/filterFieldFacts.multiValue-35992.test.ts @@ -0,0 +1,105 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35992 — the operator answer the dashboard hands + * `buildWidgetScopedFilter`, read off a field DEFINITION through + * `jsonColumnFilterOperators` (the helper the list quick filter and the filter + * builder read), and the source a widget's definition comes from. + */ + +import { describe, it, expect } from 'vitest'; +import { buildWidgetScopedFilter, resolveDashboardFilterDefs } from '@object-ui/core'; +import { filterFieldSource, jsonColumnOperatorsFor, type FilterFieldFacts } from '../filterFieldFacts'; + +const facts: FilterFieldFacts = { + status: 'ready', + object: 'project', + fields: { + labels: { type: 'multiselect' }, + tags_select: { type: 'select', multiple: true }, + account_refs: { type: 'lookup', multiple: true }, + team_members: { type: 'user', multiple: true }, + status: { type: 'select' }, + owner: { type: 'lookup' }, + }, +}; + +const defs = resolveDashboardFilterDefs({ + globalFilters: [ + { name: 'f', field: 'labels', type: 'select' }, + ], +}); + +/** Lower the one filter `f`, bound to `field`, with the facts above. */ +const lower = (field: string, value: unknown, type: 'select' | 'lookup' = 'select') => + buildWidgetScopedFilter( + { id: 'w', filterBindings: { f: field } }, + type === 'select' ? defs : resolveDashboardFilterDefs({ globalFilters: [{ name: 'f', field, type }] }), + { f: value }, + undefined, + jsonColumnOperatorsFor(facts), + ); + +describe('jsonColumnOperatorsFor + buildWidgetScopedFilter (objectstack#35992)', () => { + it('a multi-value select (multiselect, or select with multiple: true) takes $contains', () => { + expect(lower('labels', 'frontend')).toEqual({ labels: { $contains: 'frontend' } }); + expect(lower('tags_select', ['a', 'b'])).toEqual({ + $or: [{ tags_select: { $contains: 'a' } }, { tags_select: { $contains: 'b' } }], + }); + }); + + it('a multi-value lookup / user field takes $contains', () => { + expect(lower('account_refs', 'acc_1', 'lookup')).toEqual({ account_refs: { $contains: 'acc_1' } }); + expect(lower('team_members', ['usr_1', 'usr_2'], 'lookup')).toEqual({ + $or: [{ team_members: { $contains: 'usr_1' } }, { team_members: { $contains: 'usr_2' } }], + }); + }); + + it('a single-value field is unchanged: = for one value, $in for several', () => { + expect(lower('status', 'open')).toEqual({ status: 'open' }); + expect(lower('owner', ['usr_1', 'usr_2'], 'lookup')).toEqual({ owner: { $in: ['usr_1', 'usr_2'] } }); + }); + + it('a field the object does not declare keeps = / $in', () => { + expect(lower('account.region', 'EMEA')).toEqual({ 'account.region': 'EMEA' }); + }); + + it('facts that are pending or unavailable give no answer', () => { + expect(jsonColumnOperatorsFor({ status: 'pending' })).toBeUndefined(); + expect(jsonColumnOperatorsFor({ status: 'unavailable', reason: 'x' })).toBeUndefined(); + expect(jsonColumnOperatorsFor(undefined)).toBeUndefined(); + }); +}); + +describe('filterFieldSource (objectstack#35992)', () => { + it('a dataset-bound widget resolves through its dataset', () => { + expect(filterFieldSource({ type: 'bar', dataset: 'project_metrics' })).toEqual({ + key: 'dataset:project_metrics', + kind: 'dataset', + name: 'project_metrics', + }); + }); + + it('a provider: object widget names its object, under data or options.data', () => { + expect(filterFieldSource({ type: 'bar', data: { provider: 'object', object: 'project' } })).toEqual({ + key: 'object:project', + kind: 'object', + name: 'project', + }); + expect(filterFieldSource({ type: 'table', options: { data: { provider: 'object', object: 'task' } } })).toEqual({ + key: 'object:task', + kind: 'object', + name: 'task', + }); + }); + + it('a widget with inline rows has no source', () => { + expect(filterFieldSource({ type: 'bar', options: { data: [{ name: 'a', value: 1 }] } })).toBeUndefined(); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/filterFieldFacts.ts b/ui/packages/plugin-dashboard/src/filterFieldFacts.ts new file mode 100644 index 00000000000..558c82351fa --- /dev/null +++ b/ui/packages/plugin-dashboard/src/filterFieldFacts.ts @@ -0,0 +1,233 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The field definitions a dashboard filter is lowered against. + * + * A `select` / `lookup` dashboard filter bound to a field holding several + * values (`multiple: true`, `multiselect`, …) must be sent as `$contains` per + * member, never `=` / `$in`, which the server refuses on such a field + * (`buildWidgetScopedFilter` in `@object-ui/core`). Whether the bound field is + * one is a fact of the field's DEFINITION, so the dashboard reads it: + * + * - a dataset-bound widget (ADR-0021) names a dataset; its base object is + * `Dataset.object`, read through the optional `DataSource.getDataset`; + * - a `provider: 'object'` widget names its object itself. + * + * The object's fields then come from `DataSource.getObjectSchema`, and the + * operators a field takes from `jsonColumnFilterOperators`, the one helper + * the list quick filter and the filter builder read as well. + * + * When the definition cannot be read, the filter keeps the `=` / `$in` + * lowering and the dashboard says so once per filter and source with a + * console warning, never silently. + */ + +import { useEffect, useState } from 'react'; +import type { DataSource } from '@object-ui/types'; +import type { DashboardFilterJsonColumnOperators } from '@object-ui/core'; +import { jsonColumnFilterOperators, type FilterFieldStorageFacts } from '@object-ui/components'; +import { isObjectProvider } from './utils'; + +/** Where a widget's object comes from: a dataset to resolve, or the object itself. */ +export interface FilterFieldSource { + /** Stable key: `dataset:NAME` or `object:NAME`. */ + key: string; + kind: 'dataset' | 'object'; + name: string; +} + +/** What the dashboard knows about one source's field definitions. */ +export type FilterFieldFacts = + | { status: 'pending' } + | { status: 'ready'; object: string; fields: Readonly> } + | { status: 'unavailable'; reason: string }; + +/** + * The object source of one widget arm, or `undefined` for a widget with no + * query to scope (inline rows, a component node). + * + * The `provider: 'object'` read is the renderer's own (`widget.data` or + * `options.data`), so the two cannot name different objects. + */ +export function filterFieldSource(widget: unknown): FilterFieldSource | undefined { + if (!widget || typeof widget !== 'object') return undefined; + const w = widget as { dataset?: unknown; data?: unknown; options?: { data?: unknown } }; + if (typeof w.dataset === 'string' && w.dataset) { + return { key: `dataset:${w.dataset}`, kind: 'dataset', name: w.dataset }; + } + const data = w.data || w.options?.data; + if (isObjectProvider(data) && typeof data.object === 'string' && data.object) { + return { key: `object:${data.object}`, kind: 'object', name: data.object }; + } + return undefined; +} + +/** The storage facts of every field an object schema declares. */ +function readFieldFacts(objectSchema: unknown): Record { + const fields = (objectSchema as { fields?: unknown } | null | undefined)?.fields; + const out: Record = {}; + if (Array.isArray(fields)) { + for (const f of fields) { + const name = (f as { name?: unknown })?.name; + if (typeof name === 'string' && name) out[name] = storageFacts(f); + } + } else if (fields && typeof fields === 'object') { + for (const [name, f] of Object.entries(fields as Record)) out[name] = storageFacts(f); + } + return out; +} + +function storageFacts(field: unknown): FilterFieldStorageFacts { + const f = (field ?? {}) as { type?: unknown; multiple?: unknown }; + return { + ...(typeof f.type === 'string' ? { type: f.type } : {}), + ...(f.multiple === true ? { multiple: true } : {}), + }; +} + +function describeError(error: unknown): string { + if (error instanceof Error && error.message) return error.message; + return String(error); +} + +async function resolveFacts( + dataSource: DataSource | undefined, + source: FilterFieldSource, + callerPackage: string | undefined, +): Promise { + let object = source.name; + if (source.kind === 'dataset') { + if (typeof dataSource?.getDataset !== 'function') { + return { status: 'unavailable', reason: 'the data source cannot read a dataset definition (no getDataset)' }; + } + let dataset: Awaited>>; + try { + dataset = await dataSource.getDataset(source.name, callerPackage ? { callerPackage } : undefined); + } catch (error) { + return { status: 'unavailable', reason: `reading dataset "${source.name}" failed: ${describeError(error)}` }; + } + if (!dataset || typeof dataset.object !== 'string' || !dataset.object) { + return { status: 'unavailable', reason: `no dataset "${source.name}" is served` }; + } + object = dataset.object; + } + if (typeof dataSource?.getObjectSchema !== 'function') { + return { status: 'unavailable', reason: 'the data source cannot read an object definition (no getObjectSchema)' }; + } + try { + const schema = await dataSource.getObjectSchema(object); + return { status: 'ready', object, fields: readFieldFacts(schema) }; + } catch (error) { + return { status: 'unavailable', reason: `reading object "${object}" failed: ${describeError(error)}` }; + } +} + +/** + * Why a source's definition can never be read from this data source, decided + * without asking it; `undefined` when it can be asked. + */ +function unreadableReason(dataSource: DataSource | undefined, source: FilterFieldSource): string | undefined { + if (source.kind === 'dataset' && typeof dataSource?.getDataset !== 'function') { + return 'the data source cannot read a dataset definition (no getDataset)'; + } + if (typeof dataSource?.getObjectSchema !== 'function') { + return 'the data source cannot read an object definition (no getObjectSchema)'; + } + return undefined; +} + +function factsKey(callerPackage: string | undefined, sourceKey: string): string { + return `${callerPackage ?? ''}\n${sourceKey}`; +} + +/** + * Read the field definitions behind every source in `sources`, once per + * source and reader package, and answer them through the returned lookup. A + * source the data source cannot be asked about answers `unavailable` at once; + * one asked and not yet answered reads `pending`. + * + * The effect is keyed on the sources' KEYS joined to one string, never on an + * array identity (`ui/AGENTS.md` #10), so a re-render with the same widgets + * asks nothing again. + */ +export function useFilterFieldFacts( + dataSource: DataSource | undefined, + sources: readonly FilterFieldSource[], + callerPackage: string | undefined, +): (source: FilterFieldSource) => FilterFieldFacts { + const [answers, setAnswers] = useState>(() => new Map()); + const signature = Array.from(new Set(sources.map((s) => s.key))).sort().join('\n'); + + useEffect(() => { + if (!signature) return; + let cancelled = false; + for (const key of signature.split('\n')) { + const kind = key.startsWith('dataset:') ? 'dataset' : 'object'; + const source: FilterFieldSource = { key, kind, name: key.slice(kind.length + 1) }; + if (unreadableReason(dataSource, source)) continue; + void resolveFacts(dataSource, source, callerPackage).then((answer) => { + if (cancelled) return; + setAnswers((prev) => new Map(prev).set(factsKey(callerPackage, key), answer)); + }); + } + return () => { + cancelled = true; + }; + }, [dataSource, signature, callerPackage]); + + return (source) => { + const reason = unreadableReason(dataSource, source); + if (reason) return { status: 'unavailable', reason }; + return answers.get(factsKey(callerPackage, source.key)) ?? PENDING; + }; +} + +const PENDING: FilterFieldFacts = { status: 'pending' }; + +/** + * The per-field operator answer `buildWidgetScopedFilter` takes, for facts + * that are ready; `undefined` otherwise (the `=` / `$in` lowering stays). + */ +export function jsonColumnOperatorsFor( + facts: FilterFieldFacts | undefined, +): DashboardFilterJsonColumnOperators | undefined { + if (facts?.status !== 'ready') return undefined; + return (field) => (Object.prototype.hasOwnProperty.call(facts.fields, field) + ? jsonColumnFilterOperators(facts.fields[field]) + : undefined); +} + +/** + * Warn-once memo for filters lowered without their field definition, keyed by + * filter, source and reason: the renderer reaches this on every render. + */ +const warnedUnavailable = new Set(); + +/** Reset the warn-once memo. Exported for tests. */ +export function resetFilterFieldFactsWarnings(): void { + warnedUnavailable.clear(); +} + +/** + * Say, once, that `filterName` was lowered to `=` / `$in` without the bound + * field's definition, naming the source and why it could not be read: on a + * field holding several values the server refuses that query or answers it + * with no rows. + */ +export function warnFilterLoweredWithoutFacts(filterName: string, source: FilterFieldSource, reason: string): void { + const memo = `${filterName}\n${source.key}\n${reason}`; + if (warnedUnavailable.has(memo)) return; + warnedUnavailable.add(memo); + if (typeof console === 'undefined') return; + console.warn( + `[dashboard-filters] filter "${filterName}" on ${source.kind} "${source.name}" is sent as = / $in ` + + `without the bound field's definition: ${reason}. If that field holds several values ` + + `(multiple: true, multiselect), the server refuses the query or answers it with no rows.`, + ); +} diff --git a/ui/packages/types/src/data.ts b/ui/packages/types/src/data.ts index bc42e5b3c82..68dc157e34b 100644 --- a/ui/packages/types/src/data.ts +++ b/ui/packages/types/src/data.ts @@ -31,7 +31,7 @@ import type { } from '@objectstack/spec/api'; import type { EngineAggregateOptions, FilterArray } from '@objectstack/spec/data'; import type { ValidationError } from '@objectstack/spec/kernel'; -import type { ListViewGroupHeaderRow } from '@objectstack/spec/ui'; +import type { Dataset, ListViewGroupHeaderRow } from '@objectstack/spec/ui'; export type { ImportJobStatus, ImportWriteMode, ValidationError }; @@ -891,6 +891,31 @@ export interface DataSource { */ getPage?(pageId: string): Promise; + /** + * Get a semantic-layer dataset definition by name (ADR-0021), the document + * `GET /api/v1/meta/dataset/:name` serves. + * + * A dataset-bound dashboard widget learns its base object (`Dataset.object`) + * only from here before its first query: the dashboard filter bar reads the + * object's field definitions to decide how a filter on a field holding + * several values (`multiple: true`, `multiselect`, …) is lowered, since the + * server refuses `=` / `$in` on such a field. + * + * `options.callerPackage` is the READER's package (ADR-0150 D3), the one the + * dataset query names: the dataset name resolves from it. + * + * Resolves `null` when no dataset of that name is served. A failure + * (transport, permission, an ambiguous name) REJECTS, so a caller can tell + * "no such dataset" from "could not read it". + * + * Optional: an adapter without it leaves the dashboard lowering filters + * without the field definition, which the dashboard reports per filter. + * + * @param datasetName - Dataset name (what a widget's `dataset` stores) + * @throws on transport, permission or envelope failure — do NOT resolve `null` + */ + getDataset?(datasetName: string, options?: { callerPackage?: string }): Promise; + /** * Upload a single file to a resource. * Optional — only supported by data sources with file storage integration.