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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .changeset/35992-dashboard-filter-arity.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions content/docs/frontend/data-source.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions ui/packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Original file line number Diff line number Diff line change
@@ -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(
[],
);
});
});
74 changes: 74 additions & 0 deletions ui/packages/core/src/utils/dashboard-filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | 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<DashboardWidgetSchema, 'id' | 'filterBindings'>,
defs: DashboardFilterDef[],
values: Record<string, unknown>,
): 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.
Expand Down Expand Up @@ -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<DashboardWidgetSchema, 'id' | 'filterBindings'>,
defs: DashboardFilterDef[],
values: Record<string, unknown>,
knownFields?: ReadonlySet<string>,
jsonColumnOperators?: DashboardFilterJsonColumnOperators,
): Record<string, unknown> | undefined {
const conditions: Record<string, unknown>[] = [];

Expand All @@ -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 });
Expand Down
92 changes: 92 additions & 0 deletions ui/packages/data-objectstack/src/getDataset-35992.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof makeAdapter>['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);
});
});
Loading
Loading