Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit 8bfc001

Browse files
fix(plugin-dashboard): an object-metric with a structured groupBy and a rule-list filter draws its number (objectui#11526) (#11535)
Fixes #11526 Clause-②: no ## What this changes An authored `object-metric` whose `aggregate.groupBy` is the structured node (`{ field, dateGranularity }`) and whose `filter` is the bag's rule list (`ViewFilterRule[]`, as `ObjectMetricPropsSchema` in `@objectstack/spec/ui` declares it) passes both authoring faces (`safeValidateSchema`, which `objectui validate` runs, and `StrictAnyComponentSchema`; the pin asserts both, beside the block's own arm `ObjectMetricBlockSchema`), and on `ObjectStackAdapter` it drew `UnloweredAggregateWhereError` instead of its number. `ObjectMetricWidget` now lowers the rule list for the spec-shape aggregate query only, in a new module function `specShapeWhere` in `packages/plugin-dashboard/src/ObjectMetricWidget.tsx`. Files: - `packages/plugin-dashboard/src/ObjectMetricWidget.tsx`: `specShapeWhere`, called at the one spec-shape call site in `computeOne`. - `packages/plugin-dashboard/src/__tests__/ObjectMetricWidget.ruleFilterSpecShape-11526.test.tsx`: the pins. - `.changeset/11526-object-metric-rule-filter-spec-shape.md`: `@object-ui/plugin-dashboard` patch. No `@object-ui/core` edit, no adapter edit, no exported type moves (so `Clause-②: no` holds). ## The lowering, named - **What the legacy aggregate wire applies** (string or absent `groupBy`, the control that draws the number): `lowerAnalyticsFilterForWire` in `packages/data-objectstack/src/index.ts`. It runs `translateFilterArray` (rule list to filter AST, same file) and then `parseFilterAST` from `@objectstack/spec/data` (filter AST to `FilterCondition`). Both adapter functions are module-private. - **Why it is not imported or re-exported.** `@object-ui/data-objectstack` depends on `@object-ui/core`, so a re-export from core would be a dependency cycle. `plugin-dashboard` does not depend on the adapter package and reads any `DataSource` (AGENTS.md #1). Moving the translator into core would be a logic move in a package this claim does not cover. The brief's re-export fallback is therefore not available; see Acceptance notes. - **What the widget uses instead:** the same two stages, from where they are public. Stage 1 is `toFilterNode` (`packages/core/src/utils/filter-converter.ts`, exported from `@object-ui/core`). It is core's sink for a `ViewFilterRule[]`, and `object-grid` lowers its own rule-list `filter` through it (via `toFilterNodeSafely`). Stage 2 is `parseFilterAST`, the call the adapter makes. No conversion is written in the widget. The `isFilterAST` gate between them hands an array that is not a filter on unparsed, because `parseFilterAST` answers `undefined` for it, which would post an unfiltered aggregate. Handed on, the adapter's refusal answers it. - **One-time measurement (not a standing pin), real adapter, fetch stubbed, `@objectstack/spec` 17.5.0.** I compared `parseFilterAST(toFilterNode(rules))` with the `where` the legacy wire posts for the same rules. They are byte-equal for each operator in `VIEW_FILTER_OPERATORS` (20 at this spec version), for a two-rule list (`$and`), and for the legacy alias `eq`. Where a rule is refused, both paths refuse. An array comparand on `equals` and an empty `icontains` comparand are refused by both, with different error classes: the adapter's `UnlowerableAnalyticsFilterError` / `MalformedFilterError`, and core's `FilterOperatorError`. A scalar on `in` is refused by `parseFilterAST` on both paths. Nothing in this repo re-derives this equality, and the docblock says so. ## Reverse verification and ablation One-time proofs, run from the committed fix (`b60869195`). The probe that drives a real `ObjectStackAdapter` lived in the worktree only during these runs and is not in this PR. **Prediction, written before the runs:** BASE and the ablation are both red on the pin's four lowering rows (structured groupBy plus rules; multi-rule count; every operator; empty list) and green on the boundary row and the two controls. With the real adapter, the structured groupBy plus rules document draws the refusal, and both controls draw 42. | leg | new pin | real adapter: structured groupBy, rule list | real adapter: string groupBy, rule list | real adapter: structured groupBy, record filter | | --- | --- | --- | --- | --- | | BASE (`ObjectMetricWidget.tsx` at `58d1f5f4b`) | 4 failed, 3 passed | draws "aggregate('opportunity'): the spec-shape branch received a `where` array that is not a filter ..."; nothing posted | 42; analytics `where` `{"stage":"won"}` | 42; spec-shape `where` `{"stage":"won"}` | | ablation (`specShapeWhere(filterForRun)` replaced by `filterForRun`) | 4 failed, 3 passed | draws the same refusal; nothing posted | 42 | 42 | | fix (`b60869195`) | 7 passed | 42; spec-shape `where` `{"stage":"won"}`, the same bytes the legacy wire posts | 42 | 42 | Observed matches predicted. The empty-list row's BASE red is a change in the posted body (`where: []` becomes no `where`), not the card's defect. The platform engine reads `where: []` as no filter (objectstack's `engine-filter-array-lowering.test.ts`, the row 'an empty array is "no filter", exactly as before'). Landing and restore evidence: - **Ablation** (objectstack's `scripts/ablation-replace.mjs`): anchor count went from 1 to 0, and the blob went from `041e0f5d` to `42c7914d`. Restore gave blob equal to HEAD `041e0f5d` with `git diff HEAD` empty. - **BASE leg:** restored with `git checkout HEAD --` on the absolute path. Blob equality with HEAD and an empty `git diff HEAD` were checked by the leg script, which carries a `trap` restore. - **No build/dist leg:** the pin imports the widget by relative path, and `@object-ui/*` resolve to `src` through the vitest alias. ## Tests and gates The final head is `fea8ccb0e`. From `b60869195` to `fea8ccb0e`, only comment lines changed (a docblock correction and a test comment). | at | command | verdict | | --- | --- | --- | | `fea8ccb0e` | `pnpm exec vitest run` on the new pin, `objectMetricStructuredGroupBy-8613`, `ObjectMetricWidget.drillRoutedToSharedDrawer-8970`, `ObjectMetricWidget.compareTo`, `objectMetricQueryMembers-8071`, and `data-objectstack`'s `aggregate-spec-shape-where` | Test Files 6 passed (6), Tests 59 passed (59) | | `fea8ccb0e` | `pnpm --filter @object-ui/plugin-dashboard type-check` (`tsc --noEmit` and `tsc -p tsconfig.test.json`; the new pin is in the test program per `--listFiles`) | exit 0 | | `fea8ccb0e` | `pnpm check:control-bytes` / `check:new-line-citations` / `node scripts/check-changeset-presence.mjs` / `changeset:check` / `check:changeset-claims` / `check:pending-changeset-literals` | OK / 0 new citation(s) / 1 changeset for 1 released package / OK / OK / OK | | `fea8ccb0e` | eslint, narrowed (below) | 2 files, 0 errors | | `b60869195` | `pnpm exec vitest run packages/plugin-dashboard/` | Test Files 163 passed (163), Tests 1554 passed, 6 skipped (1560) | | `b60869195` | the 33 tests outside `plugin-dashboard` that name `ObjectMetricWidget`, `object-metric` or `objectAggregateSpecQuery` (`git grep -l`, `apps/console` and `packages/core` included), plus `aggregate-spec-shape-where` | Test Files 34 passed (34), Tests 2193 passed (2193) | | `b60869195` | `pnpm turbo run build --filter='./packages/*'`, then `pnpm --filter @object-ui/console build` (the Bundle Analysis type program) | 39 of 39 tasks successful; exit 0 | | `b60869195` | `check:phantom-deps`, `check:spec-symbols`, `check:test-path-roots`, `check:vi-mock-specifiers` / `-inherit` / `-override-shape`, `check:unused-deps`, `check:component-surface-parity`, `check:handler-key-reads`, `check:unreferenced-sources` | exit 0 each | | | `node scripts/check-governed-queue-guard.mjs --test` (the 3 paths) | NOT GOVERNED | ESLint narrowing, as a measurement: 1. **Population:** `eslint.config.js` lints `**/*.{ts,tsx}` with `tseslint.configs.recommended` and sets no parser `project`, so linting is not type-aware. 2. **Count:** `--format json` lists 2 files. `ObjectMetricWidget.tsx` has 0 errors and 11 warnings, and its BASE blob linted the same way also has 0 errors and 11 warnings, from the same two rules. The new pin has 0 errors and 0 warnings. 3. **Invariance:** with no type-aware rules, and no `fs` read in any `eslint-rules/*.js` (grep returns 0 matches; the same pattern hits `scripts/check-control-bytes.mjs`, the positive control), this diff cannot move a verdict on an untouched file. Repo-wide lint is CI's. - Patch round 1 (head `e37c484be`, at the seat's request): both authoring faces measured and pinned. The card's document, the showcase-shaped document and all 20 per-operator documents pass `ObjectMetricBlockSchema`, `safeValidateSchema` (the tolerant face `objectui validate` runs) and `StrictAnyComponentSchema`. The probe's controls show each face can refuse: an unknown `properties` key is refused by all three, and an unknown node-level key is refused by the strict face only. The changeset and the pin comment now say "passes both authoring faces" instead of "the strict face". The pin passes 7 of 7, `plugin-dashboard` type-check is green, and there is no source change. ## Acceptance notes - **The legacy wire is untouched.** The control pins the raw rule list on the legacy bag; the adapter lowers that wire. - **The drill drawer is unchanged.** It still receives `resolvedFilter`, and the 8970 pin is green. objectui#11506's drill path is not touched. - **`UnloweredAggregateWhereError` and its check are untouched.** The refusal of a caller that skips the lowering is pinned by `data-objectstack`'s `aggregate-spec-shape-where.test.ts` ("throws UnloweredAggregateWhereError instead of posting a rule array"). The ablation above shows the refusal coming back end to end once the lowering call is removed. That file also pins the other half of the seam: "a FilterCondition OBJECT is not an array, and this gate leaves it alone". - **The committed pin uses a recording adapter, not the real one.** `plugin-dashboard` does not declare `@object-ui/data-objectstack`, and declaring it (a `package.json` and lockfile edit) is outside this claim's file surface. The pin therefore asserts the posted `where` is a `FilterCondition` (`FilterConditionSchema` from `@objectstack/spec/data`). The adapter's acceptance of that shape is pinned on the adapter's side, as above. - **The brief's mechanism assumption 2 was falsified.** The legacy wire's lowering lives in the adapter package, and a re-export from core is a cycle. The route changed to the two public stages, per the ruling's intent: lower at the producer, no hand-written conversion, the refusal stays, and the bag is not narrowed. - **Observation, not filed:** this repo has two rule-list translators, `translateFilterArray` (adapter-private) and `toFilterNode` (core). They agreed after `parseFilterAST` across the declared vocabulary in the measurement above, and on refused rules they differ only in error class. No defect was measured. Carrier: none. - **Not measured:** `object-chart` makes the same spec-shape call. Its declared `filter` is a `FilterArray` or a record (`ObjectChartSchema.filter`), not a rule list, so this card's dialect does not reach it. --- _Generated by [Claude Code](https://claude.ai/code/session_01YLg8XqWGJ785fwQ5v4pH37)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c73cdb5 commit 8bfc001

3 files changed

Lines changed: 347 additions & 3 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
---
2+
'@object-ui/plugin-dashboard': patch
3+
---
4+
5+
fix(plugin-dashboard): an `object-metric` with a structured `groupBy` and a rule-list `filter` draws its number
6+
7+
An authored node such as
8+
9+
```ts
10+
{
11+
type: 'object-metric',
12+
properties: {
13+
objectName: 'opportunity',
14+
aggregate: { field: 'amount', function: 'sum', groupBy: { field: 'close_date', dateGranularity: 'month' } },
15+
filter: [{ field: 'stage', operator: 'equals', value: 'won' }],
16+
},
17+
}
18+
```
19+
20+
passes both authoring faces (`safeValidateSchema`, which `objectui validate` runs, and
21+
`StrictAnyComponentSchema`), and on `ObjectStackAdapter` it drew the adapter's refusal
22+
("the spec-shape branch received a `where` array that is not a filter") instead of its number
23+
(objectui#11526).
24+
25+
A structured `groupBy` sends the tile down the spec-shape aggregate query (objectui#8613), and
26+
`ObjectMetricWidget` passed the bag's `filter`, a `ViewFilterRule[]`, into that query's `where`
27+
as written. The adapter posts that `where` verbatim and refuses a rule list there with
28+
`UnloweredAggregateWhereError` (objectui#6825), so the query was never sent. The same rule list
29+
with a string `groupBy` drew its number, because the legacy aggregate bag carries it as
30+
`filter` and the adapter lowers that key itself.
31+
32+
The tile now lowers the rule list before it builds the spec-shape query: `toFilterNode` from
33+
`@object-ui/core` turns it into filter AST, and `parseFilterAST` from `@objectstack/spec/data`
34+
turns that into the `FilterCondition` that `QuerySchema.where` declares. These are the same two
35+
stages the adapter applies to the rule list on the legacy bag, where its own translator is
36+
private to `@object-ui/data-objectstack`. An array that is neither a rule list nor filter AST is
37+
passed on unparsed, so the adapter still refuses it rather than receiving no filter and
38+
aggregating every row.
39+
40+
What does not move:
41+
42+
- a string or absent `groupBy`: the legacy bag still carries the rule list as `filter`, and the
43+
adapter lowers it as before;
44+
- a flat record filter (`{ stage: 'won' }`): it is already a `FilterCondition` and still travels
45+
verbatim as `where`;
46+
- the drill-down drawer: it still receives the tile's resolved filter, unchanged;
47+
- `UnloweredAggregateWhereError`: the adapter still refuses an unlowered rule list from any
48+
caller that skips the lowering.
49+
50+
One posted body changes without changing its answer: an empty rule list on the spec-shape query
51+
now sends no `where`. It used to send `where: []`, which the platform engine reads as no filter.

‎packages/plugin-dashboard/src/ObjectMetricWidget.tsx‎

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import React, { useState, useEffect, useContext, useCallback, useMemo } from 'react';
1010
import { SchemaRendererContext, useFilterScope, useDataInvalidation } from '@object-ui/react';
11-
import { isDrillEnabled, resolveDrillTitle, isStructuredGroupBy, objectAggregateSpecQuery } from '@object-ui/core';
11+
import { isDrillEnabled, resolveDrillTitle, isStructuredGroupBy, objectAggregateSpecQuery, toFilterNode } from '@object-ui/core';
1212
import type { I18nLabel, ObjectChartSchema, ObjectMetricDrillDownConfig } from '@object-ui/types';
1313
import {
1414
useLocalization,
@@ -18,7 +18,7 @@ import {
1818
pickLocalized,
1919
} from '@object-ui/i18n';
2020
import { formatCurrency, formatPercent, percentCellScale } from '@object-ui/fields';
21-
import { resolveFieldScale } from '@objectstack/spec/data';
21+
import { isFilterAST, parseFilterAST, resolveFieldScale } from '@objectstack/spec/data';
2222
import { MetricWidget, metricPatternDecimals } from './MetricWidget';
2323
import { DrillDownDrawer } from './DrillDownDrawer';
2424
import {
@@ -105,6 +105,54 @@ function ownFractionDigits(value: number): number {
105105
return Math.min(Math.max(fraction - (exponent ? Number(exponent) : 0), 0), 20);
106106
}
107107

108+
/**
109+
* The spec-shape query's `where`, lowered from the tile's filter
110+
* (objectui#11526).
111+
*
112+
* The authored bag's `filter` is a `ViewFilterRule[]`: `ObjectMetricPropsSchema`
113+
* in `@objectstack/spec/ui` declares it so. The two wires take it differently:
114+
*
115+
* - the legacy bag carries it raw as `filter`, and `ObjectStackAdapter`
116+
* lowers it there (`lowerAnalyticsFilterForWire`: the rule list becomes
117+
* filter AST through `translateFilterArray`, then a `FilterCondition`
118+
* through `parseFilterAST`);
119+
* - the spec-shape query posts `where` VERBATIM, and the adapter refuses a
120+
* rule list there with `UnloweredAggregateWhereError` (objectui#6825,
121+
* ruling A: refuse, never lower). The producer lowers it.
122+
*
123+
* The adapter's lowering is module-private to `@object-ui/data-objectstack`,
124+
* which this plugin does not depend on (it reads any `DataSource`), and
125+
* `@object-ui/core` cannot re-export it: the adapter package depends on core.
126+
* So the same two stages are taken from where they are public. `toFilterNode`
127+
* is core's sink for a `ViewFilterRule[]` (the one `object-grid` lowers its own
128+
* rule-list `filter` through, via `toFilterNodeSafely`), and `parseFilterAST`
129+
* is the spec's single sink, the call the adapter makes. The result is the
130+
* `FilterCondition` that `QuerySchema.where` declares; the pin
131+
* `ObjectMetricWidget.ruleFilterSpecShape-11526` checks that every operator the
132+
* spec's rule vocabulary declares lowers to one. That it equals the legacy
133+
* wire's `where` was measured once, on objectui#11526's pull request, against
134+
* the real adapter; nothing in this repo re-derives that equality.
135+
*
136+
* Three inputs keep what they had:
137+
*
138+
* - a NON-array filter is already a `FilterCondition` (the flat record form),
139+
* so it is returned untouched;
140+
* - an EMPTY array lowers to `undefined`, so no `where` is posted, as the
141+
* legacy wire posts none;
142+
* - an array the lowering could not turn into a filter (`isFilterAST` says
143+
* no) is returned unparsed. `parseFilterAST` answers `undefined` for such
144+
* an array, which would post an UNFILTERED aggregate under a filtered
145+
* question; handed on, it meets the adapter's refusal and nothing is sent.
146+
*
147+
* A rule either sink refuses throws here, and `fetchMetric` shows it as the
148+
* tile's error.
149+
*/
150+
function specShapeWhere(filter: unknown): unknown {
151+
if (!Array.isArray(filter)) return filter;
152+
const node = toFilterNode(filter);
153+
return node !== undefined && isFilterAST(node) ? parseFilterAST(node) : node;
154+
}
155+
108156
/**
109157
* ObjectMetricWidget — Data-bound metric widget.
110158
*
@@ -419,8 +467,13 @@ export const ObjectMetricWidget: React.FC<ObjectMetricWidgetProps> = ({
419467
// measure is projected under `chartMeasureKey`'s alias — the raw `field`,
420468
// or the literal `'count'` for a fieldless count — and both are limbs the
421469
// two chains already try (`row[field]`, `r.count`).
470+
//
471+
// The filter is lowered for the spec-shape query only (`specShapeWhere`,
472+
// objectui#11526): its `where` is posted verbatim, while the legacy bag's
473+
// `filter` is lowered by the adapter. The drill drawer below still gets
474+
// `resolvedFilter` as it was.
422475
const results = isStructuredGroupBy(groupBy)
423-
? await ds.aggregate(objectName, objectAggregateSpecQuery(aggregate, groupBy, filterForRun))
476+
? await ds.aggregate(objectName, objectAggregateSpecQuery(aggregate, groupBy, specShapeWhere(filterForRun)))
424477
: await ds.aggregate(objectName, {
425478
field: aggregate.field,
426479
function: aggregate.function,
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectui#11526 — an authored `object-metric` whose `aggregate.groupBy` is
5+
* the structured node and whose `filter` is the bag's rule list draws its
6+
* number.
7+
*
8+
* The bag's `filter` is a `ViewFilterRule[]` (`ObjectMetricPropsSchema` in
9+
* `@objectstack/spec/ui`). A structured `groupBy` sends the tile down the
10+
* spec-shape query (objectui#8613), whose `where` `ObjectStackAdapter` posts
11+
* verbatim and refuses as a rule list with `UnloweredAggregateWhereError`
12+
* (objectui#6825, ruling A). So before this card the tile drew that refusal,
13+
* while the same rule list on the legacy bag (a string `groupBy`) drew the
14+
* number, because the adapter lowers the legacy bag's `filter` itself.
15+
*
16+
* The fix lowers the rule list in the producer, for the spec-shape query only
17+
* (`specShapeWhere` in `ObjectMetricWidget`). The oracle is the POSTED bag:
18+
* `where` must be a `FilterCondition`, the dialect `QuerySchema.where`
19+
* declares and the adapter's gate passes untouched. That half of the seam is
20+
* pinned in `data-objectstack`'s `aggregate-spec-shape-where.test.ts` ("a
21+
* FilterCondition OBJECT is not an array, and this gate leaves it alone"), and
22+
* the refusal this card keeps is pinned there too ("throws
23+
* UnloweredAggregateWhereError instead of posting a rule array").
24+
*
25+
* The controls are load-bearing: the legacy bag still carries the rule list
26+
* RAW (the adapter lowers that wire), and a flat record filter still travels
27+
* verbatim on the spec-shape query.
28+
*/
29+
30+
import { describe, it, expect, vi, afterEach } from 'vitest';
31+
import { render, screen, cleanup, waitFor } from '@testing-library/react';
32+
import { SchemaRenderer, SchemaRendererProvider } from '@object-ui/react';
33+
import { ObjectMetricBlockSchema, StrictAnyComponentSchema, safeValidateSchema } from '@object-ui/types/zod';
34+
import { FilterConditionSchema } from '@objectstack/spec/data';
35+
import { VIEW_FILTER_OPERATORS } from '@objectstack/spec/ui';
36+
// Registers `object-metric` at MODULE scope, never inside a hook —
37+
// object-ui/no-dynamic-import-in-test-hook.
38+
import '../index';
39+
40+
afterEach(cleanup);
41+
42+
type Params = Record<string, unknown>;
43+
44+
/** An adapter that can aggregate, recording every call's options bag. */
45+
const aggregatingAdapter = (rows: Record<string, unknown>[]) => ({
46+
aggregate: vi.fn(async (_object: string, _params: Params) => rows),
47+
find: vi.fn(async (_object: string, _params: Params) => ({ data: [] as unknown[] })),
48+
});
49+
50+
/**
51+
* The authored node, in the `properties` form. The card's document, the
52+
* showcase-shaped one and each per-operator document are checked on the
53+
* block's own arm (`ObjectMetricBlockSchema`) and on both authoring faces:
54+
* `safeValidateSchema` (the tolerant `AnyComponentSchema`, which
55+
* `objectui validate` runs) and `StrictAnyComponentSchema`.
56+
*/
57+
const node = (properties: Record<string, unknown>) => ({ type: 'object-metric', properties });
58+
59+
const mount = (schema: Record<string, unknown>, adapter: unknown) =>
60+
render(
61+
<SchemaRendererProvider dataSource={adapter as never}>
62+
<SchemaRenderer schema={schema as never} />
63+
</SchemaRendererProvider>,
64+
);
65+
66+
/** The options bag of the first `aggregate()` call. */
67+
const bagOf = (adapter: ReturnType<typeof aggregatingAdapter>): Params =>
68+
adapter.aggregate.mock.calls[0][1];
69+
70+
/** The date-bucketing node, in the spelling `ChartGroupBySchema` admits. */
71+
const MONTHLY = { field: 'close_date', dateGranularity: 'month' };
72+
73+
/** The card's rule list. */
74+
const WON = [{ field: 'stage', operator: 'equals', value: 'won' }];
75+
76+
describe('object-metric — a structured `groupBy` with a rule-list `filter` draws its number (objectui#11526)', () => {
77+
it('posts the rule list lowered to a FilterCondition as `where`, and draws the number', async () => {
78+
// The card's document, as authored. Both authoring faces accept it, which
79+
// is what makes the refusal a defect rather than an authoring error.
80+
const doc = node({
81+
label: 'Won',
82+
objectName: 'opportunity',
83+
aggregate: { field: 'amount', function: 'sum', groupBy: MONTHLY },
84+
filter: WON,
85+
});
86+
expect(ObjectMetricBlockSchema.safeParse(doc).success).toBe(true);
87+
expect(safeValidateSchema(doc).success).toBe(true);
88+
expect(StrictAnyComponentSchema.safeParse(doc).success).toBe(true);
89+
90+
const adapter = aggregatingAdapter([{ close_date: '2026-01', amount: 42 }]);
91+
mount(doc, adapter);
92+
93+
expect(await screen.findByText('42')).toBeTruthy();
94+
expect(adapter.aggregate.mock.calls[0][0]).toBe('opportunity');
95+
// The WHOLE bag, so a key added to or dropped from the call is red either way.
96+
expect(bagOf(adapter)).toEqual({
97+
groupBy: [MONTHLY],
98+
aggregations: [{ function: 'sum', alias: 'amount', field: 'amount' }],
99+
where: { stage: 'won' },
100+
});
101+
expect(Array.isArray(bagOf(adapter).where)).toBe(false);
102+
expect(FilterConditionSchema.safeParse(bagOf(adapter).where).success).toBe(true);
103+
});
104+
105+
it('lowers a multi-rule list to one condition, on the count shape the showcase tiles author', async () => {
106+
// `app-showcase`'s My Work tiles count by `id` under a rule list; this is
107+
// its Open Tasks tile with a structured `groupBy` and a second rule added.
108+
// A count is summed across the buckets under the `count` alias.
109+
const doc = node({
110+
label: 'Open Tasks',
111+
objectName: 'showcase_task',
112+
aggregate: { field: 'id', function: 'count', groupBy: { field: 'created_at', dateGranularity: 'month' } },
113+
filter: [
114+
{ field: 'status', operator: 'not_equals', value: 'done' },
115+
{ field: 'priority', operator: 'in', value: ['high', 'urgent'] },
116+
],
117+
});
118+
expect(ObjectMetricBlockSchema.safeParse(doc).success).toBe(true);
119+
expect(safeValidateSchema(doc).success).toBe(true);
120+
expect(StrictAnyComponentSchema.safeParse(doc).success).toBe(true);
121+
122+
const adapter = aggregatingAdapter([
123+
{ created_at: '2026-01', count: 3 },
124+
{ created_at: '2026-02', count: 4 },
125+
]);
126+
mount(doc, adapter);
127+
128+
expect(await screen.findByText('7')).toBeTruthy();
129+
expect(bagOf(adapter).where).toEqual({
130+
$and: [{ status: { $ne: 'done' } }, { priority: { $in: ['high', 'urgent'] } }],
131+
});
132+
});
133+
134+
it('lowers every operator the spec`s rule vocabulary declares to a FilterCondition', async () => {
135+
// Read off the spec at run time, so an operator it adds is covered here
136+
// without an edit. A comparand is supplied where the operator takes one.
137+
const comparand: Record<string, unknown> = {
138+
in: ['a', 'b'],
139+
not_in: ['a', 'b'],
140+
between: [1, 9],
141+
greater_than: 5,
142+
less_than: 5,
143+
greater_than_or_equal: 5,
144+
less_than_or_equal: 5,
145+
before: '2026-01-01',
146+
after: '2026-01-01',
147+
};
148+
const valueless = new Set(['is_empty', 'is_not_empty', 'is_null', 'is_not_null']);
149+
expect(VIEW_FILTER_OPERATORS.length).toBeGreaterThan(0);
150+
151+
for (const operator of VIEW_FILTER_OPERATORS) {
152+
const rule: Record<string, unknown> = { field: 'f', operator };
153+
if (!valueless.has(operator)) rule.value = comparand[operator] ?? 'x';
154+
const doc = node({
155+
objectName: 'deal',
156+
aggregate: { field: 'amount', function: 'sum', groupBy: MONTHLY },
157+
filter: [rule],
158+
});
159+
expect(ObjectMetricBlockSchema.safeParse(doc).success, operator).toBe(true);
160+
expect(safeValidateSchema(doc).success, operator).toBe(true);
161+
expect(StrictAnyComponentSchema.safeParse(doc).success, operator).toBe(true);
162+
163+
const adapter = aggregatingAdapter([{ close_date: '2026-01', amount: 1 }]);
164+
mount(doc, adapter);
165+
await waitFor(() => expect(adapter.aggregate).toHaveBeenCalled());
166+
const where = bagOf(adapter).where;
167+
expect(Array.isArray(where), operator).toBe(false);
168+
expect(where, operator).toBeDefined();
169+
expect(FilterConditionSchema.safeParse(where).success, operator).toBe(true);
170+
cleanup();
171+
}
172+
});
173+
174+
it('an EMPTY rule list posts no filter, as the legacy wire posts none', async () => {
175+
const adapter = aggregatingAdapter([{ close_date: '2026-01', amount: 5 }]);
176+
mount(
177+
node({ objectName: 'deal', aggregate: { field: 'amount', function: 'sum', groupBy: MONTHLY }, filter: [] }),
178+
adapter,
179+
);
180+
181+
await waitFor(() => expect(adapter.aggregate).toHaveBeenCalled());
182+
expect(bagOf(adapter).where).toBeUndefined();
183+
});
184+
185+
it('BOUNDARY — an array the lowering cannot read is handed on, never dropped to "no filter"', async () => {
186+
// A record condition wrapped in an array is neither a rule list nor
187+
// filter AST. `parseFilterAST` answers `undefined` for it, which as
188+
// `where` would aggregate EVERY row under a filtered question. It is
189+
// handed on unparsed, so the adapter's refusal answers it instead.
190+
const unreadable = [{ stage: 'won' }];
191+
const adapter = aggregatingAdapter([{ close_date: '2026-01', amount: 5 }]);
192+
mount(
193+
node({ objectName: 'deal', aggregate: { field: 'amount', function: 'sum', groupBy: MONTHLY }, filter: unreadable }),
194+
adapter,
195+
);
196+
197+
await waitFor(() => expect(adapter.aggregate).toHaveBeenCalled());
198+
expect(bagOf(adapter).where).toEqual(unreadable);
199+
});
200+
});
201+
202+
describe('object-metric — the shapes that must NOT move (objectui#11526 controls)', () => {
203+
it('CONTROL — a string `groupBy` still carries the rule list RAW on the legacy bag', async () => {
204+
// The adapter lowers this wire's `filter` itself, so the producer leaves it
205+
// alone. A producer that lowered it here too would be a second lowering.
206+
const doc = node({
207+
label: 'Won',
208+
objectName: 'opportunity',
209+
aggregate: { field: 'amount', function: 'sum', groupBy: 'stage' },
210+
filter: WON,
211+
});
212+
const adapter = aggregatingAdapter([{ amount_sum: 42 }]);
213+
mount(doc, adapter);
214+
215+
expect(await screen.findByText('42')).toBeTruthy();
216+
expect(bagOf(adapter)).toEqual({
217+
field: 'amount',
218+
function: 'sum',
219+
groupBy: 'stage',
220+
filter: WON,
221+
});
222+
});
223+
224+
it('CONTROL — a flat record filter still travels verbatim on the spec-shape query', async () => {
225+
const record = { stage: 'won' };
226+
const adapter = aggregatingAdapter([{ close_date: '2026-01', amount: 42 }]);
227+
mount(
228+
node({
229+
label: 'Won',
230+
objectName: 'opportunity',
231+
aggregate: { field: 'amount', function: 'sum', groupBy: MONTHLY },
232+
filter: record,
233+
}),
234+
adapter,
235+
);
236+
237+
expect(await screen.findByText('42')).toBeTruthy();
238+
expect(bagOf(adapter).where).toEqual(record);
239+
});
240+
});

0 commit comments

Comments
 (0)