Skip to content

Commit b57f778

Browse files
fix(plugin-grid): leave a raw aggregate over a record-mode quantity out of the whole-set footer and group headers (#36271)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XP3RHGWUG7UH3fNa4tBa9UC)_ Fixes #36082 Clause-②: no Metadata-protocol: none ## 维护者速读 - 列表和表格分页时,底部合计行不再把「按行单位的数量」(一行千克、一行磅)的求和、平均、最小、最大放进整表合计查询;该列只显示计数,其他列照常显示整个视图的合计。 - 属于「数量带单位」上线前的收尾:引擎已拒绝不按单位分组的这类求和,不做这一步,整条合计查询被拒,其他列会悄悄退回成本页合计。 - 出错的话,影响的只是表格底部和分组标题里的数字;可直接撤回本改动,不涉及数据。 - 无。 ## What changes One rule in `recordCurrencyAggregates.ts`, two readers: a raw `sum` / `avg` / `min` / `max` over a measure whose unit each record names itself needs the rows grouped by that unit's field. - `recordUnitField(def)` reads a `record`-mode quantity exactly as the engine door `recordUnitFieldOf` does (`packages/objectql/src/record-unit-aggregate-door.ts`): a `number` with `unitConfig.unitMode === 'record'` and a non-empty `unitField`. - `recordMeasureUnitField(def)` = the currency code field (`recordCurrencyField` from `@object-ui/i18n`, unchanged) or that unit field. - `requiredCurrencyGrouping` becomes `requiredAggregateGrouping` and `isMoneyAggregate` becomes `isMeasureAggregate` (module-internal, not in the package barrel); the aggregate set stays one constant. - Readers, all through that one helper: `wholeSetSummaryNodes` (the whole-set footer query leaves the node out), `honestGroupAggregations` (a group aggregate stands only when grouped by the unit field), `useScopedColumnSummary` (the footer cell draws nothing for it, as for a record-mode amount) and `offeredColumnSummaries` (the footer menu offers the count family only). - No engine, no `packages/spec` change. No new per-unit total. ## Tests - `recordCurrencyAggregates-27188.test.tsx`, new top-level describe for the quantity: footer draws no sum / avg / min / max and the count stands; fixed-mode and plain-number controls sum; the menu offers no aggregate; group aggregates stand grouped by `unit_code` and drop otherwise; the predicate's edges (empty `unitField`, non-`number` type). - `footerSummaryScope-12081.test.tsx`, new top-level describe (the double now refuses a record-mode quantity aggregate as the engine does): a view with a record-mode quantity `sum` beside a plain-number `sum` sends one query carrying only `count` and `sum_amount`, the plain column shows its whole-set figure, the quantity column shows nothing, zero refusals. Control: a `fixed`-mode quantity is asked and totals over the whole set. - Ablations (one per leg, each through `scripts/ablation-replace.mjs`, mutation landed and restore proven by blob hash): see Verification. ## Acceptance notes - Group headers at a shallower depth (out of scope, for the seat): `honestGroupAggregations` keeps a measure aggregate when the unit or code field is at ANY grouping level, and `useServerGrouping` asks each depth with the first `depth` grouping fields. Measured with the spec's `compileListViewGroupQuery`: grouping `region` then `unit_code` with a `sum` over `qty` compiles depth 1 to `groupBy: ["region"]` carrying `sum_qty`, which the engine's unit door (and the currency door, for a record-mode amount) refuses. This PR keeps the currency precedent's rule unchanged and applies it to quantities, as the card ordered. - The shared test files were extended instead of a new card-named file: the root rule puts a new pin for a component with a shared harness file into that file as a top-level describe. ## Verification Read first: 1. `ui/packages/plugin-grid/src/recordCurrencyAggregates.ts`: `recordUnitField` must match the engine door's reading. 2. `ui/packages/plugin-grid/src/useWholeSetSummary.ts`: the leave-out line in `wholeSetSummaryNodes`. 3. `ui/packages/plugin-grid/src/useColumnSummary.ts`: the footer skip and `offeredColumnSummaries`. Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-grid/src/__tests__/recordCurrencyAggregates-27188.test.tsx packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx` from the repo root; expect 42 passed. Readings (source tree at 9f56bc1; the test runs were taken at ae56a75, whose sources are byte-identical, the later commit adds only the changeset): <details><summary>Pin files and the plugin-grid suite</summary> - `vitest run` of the two pin files: Test Files 2 passed (2), Tests 42 passed (42). - `vitest run packages/plugin-grid/`: Test Files 300 passed (300), Tests 2657 passed (2657); lock VERDICT command-exit 0. - `pnpm --filter @object-ui/plugin-grid type-check` (tsc on src and on `tsconfig.test.json`, which lists both pin files): VERDICT command-exit 0. </details> <details><summary>Ablations, one per leg</summary> Each mutation through `scripts/ablation-replace.mjs` (anchor 1 to 0, blob changed), restored with blob equal to HEAD and an empty `git diff HEAD`. The subject resolves to `src` (relative imports), so no rebuild sits between mutation and run. - Shared predicate (`?? recordUnitField(def)` removed): 5 failed / 37 passed, exactly the five quantity pins; every currency pin and control stays green. A first attempt was refused by the tool (the replacement was a bare semicolon, whose count could not rise); it ran nothing and is not counted. - Whole-set leave-out (the `continue` in `wholeSetSummaryNodes` removed): 5 failed / 25 passed, the four record-currency pins and the quantity whole-set pin. - Footer cell skip disabled: 5 failed / 37 passed, the two footer pins (amount, quantity) and the three whole-set pins (two currency, one quantity): the left-out column falls back to a page sum over mixed units. - Footer menu (`offeredColumnSummaries`) disabled: 1 failed / 11 passed, the quantity menu pin. - Group filter (`honestGroupAggregations` keeps all): 2 failed / 10 passed, the currency and the quantity drop pins. </details> <details><summary>Local gate subset</summary> Derived by `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` (38 commands); all 38 exit 0. `pnpm --dir ui exec vitest run scripts/` queue-timed out twice on the shared verify lock (exit 99), then passed on the third attempt after the PR was opened: 172 files passed, 2 skipped; 5122 tests passed. `pnpm check:type-check-debt` first queue-timed out, then exit 0 on retry. Outside the list: `check-platform-checklist --changed-from origin/main` exit 0 (no anchored file), `pnpm --dir ui check:new-line-citations` 0 new. `overlap-check` VERDICT clean. </details> <!-- signed: repo:objectstack#4 · os-project-manager · session_01FEkQ5okniknzVVR3KTSVr1 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a6756a2 commit b57f778

7 files changed

Lines changed: 268 additions & 82 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@object-ui/plugin-grid': patch
3+
---
4+
5+
fix(plugin-grid): leave a raw aggregate over a record-mode quantity out of the whole-set footer and the group headers
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The engine refuses a `sum` / `avg` / `min` / `max` over a `number` field declaring `unitConfig: { unitMode: 'record', unitField }` unless the query groups by `unitField` (ADR-0158 U7 R1): quantities in different units do not add. The grid now treats such a quantity the way it treats a `record`-mode currency amount (ADR-0144 D6), through one rule:
11+
12+
- The whole-set footer query of a paged list or grid leaves that column's aggregate out, so the other summarised columns keep their whole-set figures instead of all falling back to the current page's.
13+
- The footer draws no `sum` / `avg` / `min` / `max` for that column, and its menu offers the count family only; the counts stand.
14+
- A group-header aggregate over it stands only when the grid is grouped by its `unitField`.
15+
16+
A `fixed`-mode quantity and a `number` with no `unitConfig` total as before.

‎ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx‎

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
* - ADR-0144 D6: a money aggregate over a `record`-mode amount is left out
4141
* of the whole-set query (the double refuses it as the engine does), so
4242
* the other columns keep their whole-set figures.
43+
* - ADR-0158 U7 R1: the same for a `record`-mode quantity.
4344
*/
4445
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
4546
import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react';
@@ -74,12 +75,13 @@ afterEach(() => {
7475
const OBJECT = 'plan_line';
7576
const PAGE = 25;
7677

77-
type Row = { id: string; name: string; stage: string; amount: number; note: string | null; closed_at: string; qty: number; currency_code: string; approved: boolean | null } & Record<string, unknown>;
78+
type Row = { id: string; name: string; stage: string; amount: number; note: string | null; closed_at: string; qty: number; currency_code: string; unit_code: string; approved: boolean | null } & Record<string, unknown>;
7879
/**
7980
* 300 rows; every fifth `note` is empty, every third row is `won`, and
8081
* `closed_at` is one day later per row, so the last row is the latest.
8182
* `currency_code` alternates USD / EUR, for the `record`-mode amount cases
82-
* (ADR-0144 D6); `qty` is a plain number beside it.
83+
* (ADR-0144 D6); `qty` is a plain number beside it. `unit_code` alternates
84+
* KGM / LBR, for the `record`-mode quantity cases (ADR-0158 U7 R1).
8385
*/
8486
const ROWS: Row[] = Array.from({ length: 300 }, (_, i) => ({
8587
id: `r${i}`,
@@ -90,6 +92,7 @@ const ROWS: Row[] = Array.from({ length: 300 }, (_, i) => ({
9092
closed_at: new Date(Date.UTC(2025, 0, 1, 9, 30) + i * 86_400_000).toISOString(),
9193
qty: (i % 7) + 1,
9294
currency_code: i % 2 === 0 ? 'USD' : 'EUR',
95+
unit_code: i % 2 === 0 ? 'KGM' : 'LBR',
9396
// objectstack#35702 — a boolean: every fourth unset, then true / false alternating (75 / 75 / 150).
9497
approved: i % 4 === 0 ? null : i % 2 === 0,
9598
}));
@@ -162,6 +165,14 @@ const recordPointerOf = (def: unknown): string | undefined => {
162165
return config?.currencyMode === 'record' && typeof config.currencyField === 'string' ? config.currencyField : undefined;
163166
};
164167

168+
/** A field def's `record`-mode unit pointer, as the engine's ADR-0158 U7 R1 door reads it. */
169+
const recordUnitOf = (def: unknown): string | undefined => {
170+
const { type, unitConfig } = (def ?? {}) as { type?: unknown; unitConfig?: { unitMode?: unknown; unitField?: unknown } };
171+
return type === 'number' && unitConfig?.unitMode === 'record' && typeof unitConfig.unitField === 'string' && unitConfig.unitField !== ''
172+
? unitConfig.unitField
173+
: undefined;
174+
};
175+
165176
function makeDataSource(opts: {
166177
door?: 'answers' | 'absent' | 'refuses' | 'no-row' | 'strings';
167178
/** The object definition's fields `getObjectSchema` answers (default `OBJECT_FIELDS`). */
@@ -195,10 +206,12 @@ function makeDataSource(opts: {
195206
if (door === 'refuses') throw Object.assign(new Error('refused'), { code: 'UNSUPPORTED_QUERY_PARAM' });
196207
const groupBy = query.groupBy ?? [];
197208
if (groupBy.length > 0) throw new Error('double: this suite asks no grouped query');
198-
// [ADR-0144 D6] The engine refuses a raw sum / avg / min / max over a
199-
// `record`-mode amount in an ungrouped query, and runs none of it.
209+
// [ADR-0144 D6, ADR-0158 U7 R1] The engine refuses a raw sum / avg /
210+
// min / max over a `record`-mode amount or quantity in an ungrouped
211+
// query, and runs none of it.
200212
const raw = (query.aggregations ?? []).filter((node) => ['sum', 'avg', 'min', 'max'].includes(node.function)
201-
&& node.field !== undefined && recordPointerOf(fields[node.field]) !== undefined);
213+
&& node.field !== undefined
214+
&& (recordPointerOf(fields[node.field]) ?? recordUnitOf(fields[node.field])) !== undefined);
202215
if (raw.length > 0) {
203216
refusals.push(...raw.map((node) => `${node.function}(${node.field})`));
204217
throw Object.assign(new Error('refused: a raw aggregate across currencies'), { code: 'INVALID_FIELD', status: 400 });
@@ -751,3 +764,48 @@ describe('a money aggregate over a `record`-mode amount is left out of the whole
751764
]);
752765
});
753766
});
767+
768+
describe('a raw aggregate over a `record`-mode quantity is left out of the whole-set query (ADR-0158 U7 R1)', () => {
769+
/** `qty` in each row's own unit, the code in the sibling `unit_code`; `amount` a plain number beside it. */
770+
const recordQty = (unitConfig: Record<string, unknown>) => ({
771+
...OBJECT_FIELDS,
772+
qty: { type: 'number', label: 'Qty', unitConfig },
773+
unit_code: { type: 'text', label: 'Unit' },
774+
});
775+
const RECORD_QTY = recordQty({ unitMode: 'record', unitField: 'unit_code' });
776+
const COLUMNS = [
777+
{ field: 'name', label: 'Name' },
778+
{ field: 'qty', label: 'Qty', type: 'number', summary: 'sum' },
779+
{ field: 'amount', label: 'Amount', type: 'number', summary: 'sum' },
780+
];
781+
const amountWhole = `Amount: Sum: ${fmt(sumOf(ROWS))}`;
782+
const qtyNodes = (ds: TestDataSource) => ds.queryGroupHeaders.mock.calls
783+
.flatMap(([, query]) => (query as AggregateQuery).aggregations ?? [])
784+
.filter((node) => node.field === 'qty');
785+
786+
it('the plain-number sum keeps its whole-set figure, and no refused request is sent', async () => {
787+
const ds = makeDataSource({ fields: RECORD_QTY });
788+
render(hostGrid(ds, { rows: ROWS, columns: COLUMNS }));
789+
790+
await waitFor(() => expect(footerText('amount')).toBe(amountWhole));
791+
// The record-mode quantity draws nothing: no whole-set figure, and no page sum over KGM and LBR.
792+
expect(footerText('qty')).toBeNull();
793+
expect(ds.refusals).toEqual([]);
794+
expect(qtyNodes(ds)).toEqual([]);
795+
expect(ds.queryGroupHeaders).toHaveBeenCalledTimes(1);
796+
expect((ds.queryGroupHeaders.mock.calls[0][1] as AggregateQuery).aggregations).toEqual([
797+
{ function: 'count', alias: 'count' },
798+
{ function: 'sum', field: 'amount', alias: 'sum_amount' },
799+
]);
800+
});
801+
802+
it('CONTROL: a fixed-mode quantity is asked and totals over the whole set', async () => {
803+
const ds = makeDataSource({ fields: recordQty({ unitMode: 'fixed', unit: 'KGM' }) });
804+
render(hostGrid(ds, { rows: ROWS, columns: COLUMNS }));
805+
806+
await waitFor(() => expect(footerText('qty')).toBe(`Qty: Sum: ${fmt(ROWS.reduce((a, r) => a + r.qty, 0))}`));
807+
expect(footerText('amount')).toBe(amountWhole);
808+
expect(ds.refusals).toEqual([]);
809+
expect(qtyNodes(ds)).toEqual([{ function: 'sum', field: 'qty', alias: 'sum_qty' }]);
810+
});
811+
});

‎ui/packages/plugin-grid/src/__tests__/recordCurrencyAggregates-27188.test.tsx‎

Lines changed: 71 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ import { describe, it, expect, afterEach } from 'vitest';
1717
import * as React from 'react';
1818
import { renderHook, cleanup } from '@testing-library/react';
1919
import { I18nProvider, LocalizationProvider } from '@object-ui/i18n';
20-
import { useColumnSummary } from '../useColumnSummary';
21-
import { honestGroupAggregations, requiredCurrencyGrouping } from '../recordCurrencyAggregates';
20+
import { useColumnSummary, offeredColumnSummaries } from '../useColumnSummary';
21+
import { honestGroupAggregations, requiredAggregateGrouping } from '../recordCurrencyAggregates';
2222

2323
afterEach(cleanup);
2424

@@ -76,8 +76,74 @@ describe('group-header aggregations over a record-mode amount', () => {
7676
});
7777

7878
it('only a money aggregate over a record-mode amount needs the code grouping', () => {
79-
expect(requiredCurrencyGrouping('amount', 'sum', META)).toBe('currency_code');
80-
expect(requiredCurrencyGrouping('amount', 'count_distinct', META)).toBeUndefined();
81-
expect(requiredCurrencyGrouping('amount_home', 'sum', META)).toBeUndefined();
79+
expect(requiredAggregateGrouping('amount', 'sum', META)).toBe('currency_code');
80+
expect(requiredAggregateGrouping('amount', 'count_distinct', META)).toBeUndefined();
81+
expect(requiredAggregateGrouping('amount_home', 'sum', META)).toBeUndefined();
82+
});
83+
});
84+
85+
/**
86+
* ADR-0158 U7 R1, the same rule over a quantity: a `number` declaring
87+
* `unitConfig: { unitMode: 'record', unitField }` holds a quantity in each
88+
* row's own unit, so a sum / avg / min / max over it stands only inside one
89+
* unit. The engine refuses one unless grouped by `unitField`; a `fixed`-mode
90+
* quantity and a number with no `unitConfig` total as before.
91+
*/
92+
describe('a record-mode quantity: footer and group headers (ADR-0158 U7 R1)', () => {
93+
const UNIT_META: NonNullable<Parameters<typeof useColumnSummary>[2]> = {
94+
qty: { type: 'number', unitConfig: { unitMode: 'record', unitField: 'unit_code' } },
95+
qty_kg: { type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } },
96+
weight: { type: 'number' },
97+
unit_code: { type: 'text' },
98+
};
99+
const UNIT_ROWS = [
100+
{ qty: 10, qty_kg: 10, weight: 3, unit_code: 'KGM' },
101+
{ qty: 10, qty_kg: 5, weight: 4, unit_code: 'LBR' },
102+
];
103+
const unitFooter = (field: string, summary: string): string | undefined => {
104+
const columns: any[] = [{ field, summary }];
105+
const { result } = renderHook(() => useColumnSummary(columns, UNIT_ROWS, UNIT_META), { wrapper: Providers });
106+
return result.current.summaries.get(field)?.label;
107+
};
108+
109+
it('the footer draws no sum / avg / min / max — 10 KGM and 10 LBR are not 20; a count stands', () => {
110+
for (const s of ['sum', 'avg', 'min', 'max']) expect(unitFooter('qty', s)).toBeUndefined();
111+
expect(unitFooter('qty', 'count')).toBe('Count: 2');
112+
});
113+
114+
it('CONTROL: a fixed-mode quantity and a plain number sum as before', () => {
115+
expect(unitFooter('qty_kg', 'sum')).toBe('Sum: 15');
116+
expect(unitFooter('weight', 'sum')).toBe('Sum: 7');
117+
});
118+
119+
it('the footer menu offers the count family only, as for a record-mode amount', () => {
120+
const offered = offeredColumnSummaries(UNIT_META.qty);
121+
for (const s of ['sum', 'avg', 'min', 'max'] as const) expect(offered).not.toContain(s);
122+
expect(offered).toContain('count_filled');
123+
expect(offeredColumnSummaries(UNIT_META.qty_kg)).toContain('sum');
124+
});
125+
126+
const UNIT_AGGS = [
127+
{ field: 'qty', type: 'sum' as const },
128+
{ field: 'qty', type: 'count' as const },
129+
{ field: 'weight', type: 'sum' as const },
130+
{ field: 'qty_kg', type: 'max' as const },
131+
];
132+
133+
it('a group-header aggregate over it stands when the grid is grouped by its unit field', () => {
134+
expect(honestGroupAggregations(UNIT_AGGS, UNIT_META, ['unit_code'])).toBe(UNIT_AGGS);
135+
});
136+
137+
it('it is dropped when grouped by anything else; the counts, the fixed-mode and the plain aggregates stand', () => {
138+
expect(honestGroupAggregations(UNIT_AGGS, UNIT_META, ['region'])).toEqual([UNIT_AGGS[1], UNIT_AGGS[2], UNIT_AGGS[3]]);
139+
});
140+
141+
it('the unit field is read as the engine reads it: a `number` in record mode with a non-empty unitField', () => {
142+
expect(requiredAggregateGrouping('qty', 'avg', UNIT_META)).toBe('unit_code');
143+
expect(requiredAggregateGrouping('qty', 'count_distinct', UNIT_META)).toBeUndefined();
144+
expect(requiredAggregateGrouping('qty_kg', 'sum', UNIT_META)).toBeUndefined();
145+
expect(requiredAggregateGrouping('weight', 'sum', UNIT_META)).toBeUndefined();
146+
expect(requiredAggregateGrouping('q', 'sum', { q: { type: 'number', unitConfig: { unitMode: 'record', unitField: '' } } })).toBeUndefined();
147+
expect(requiredAggregateGrouping('q', 'sum', { q: { type: 'text', unitConfig: { unitMode: 'record', unitField: 'unit_code' } } })).toBeUndefined();
82148
});
83149
});

‎ui/packages/plugin-grid/src/objectGridGrouping.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -291,15 +291,16 @@ export function useObjectGridGrouping({
291291
}
292292
}, [groupRowQueryKey]);
293293
const groupReloadKey = `${refreshKey}:${invalidationNonce}`;
294-
// [ADR-0144 D6] A money aggregate over a `record`-mode amount stands only in
295-
// groups bucketed by that amount's code field; elsewhere it would add
296-
// amounts in different currencies, so it is dropped before either the
297-
// server or the client bucketing computes it. Keyed on what it reads, so a
294+
// [ADR-0144 D6, ADR-0158 U7 R1] A measure aggregate over a `record`-mode
295+
// amount or quantity stands only in groups bucketed by its code or unit
296+
// field; elsewhere it would add amounts in different currencies or
297+
// quantities in different units, so it is dropped before either the server
298+
// or the client bucketing computes it. Keyed on what it reads, so a
298299
// host that rebuilds `schema` every render does not re-key the header query.
299300
// [objectstack#32119] Per aggregated field whose cell paints a date-family
300301
// face, that face, resolved as the group headings' faces are: a `min` /
301302
// `max` over it is a time, drawn as the cell draws it, and a `sum` / `avg`
302-
// over it is no figure at all, so it is dropped here with the money
303+
// over it is no figure at all, so it is dropped here with the measure
303304
// aggregates, before either path computes it or the server is asked.
304305
const groupAggregationKey = JSON.stringify({
305306
aggregations: schema.aggregations ?? null,

‎ui/packages/plugin-grid/src/recordCurrencyAggregates.ts‎

Lines changed: 63 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,57 +7,94 @@
77
*/
88

99
/**
10-
* ADR-0144 D6 on the grid: a raw money aggregate over a `record`-mode amount
11-
* is honest only inside one currency. A group bucketed by the amount's code
12-
* field holds one currency, so its `sum` / `avg` / `min` / `max` stand; any
13-
* other set of rows mixes currencies, and adding 100 USD to 100 EUR answers a
14-
* number that is no amount at all. Consolidated totals belong to the home
15-
* field, an ordinary `dynamic` amount that totals unchanged.
10+
* One rule on the grid for a measure whose unit each record names itself: a
11+
* raw aggregate over it is honest only inside one unit, so it needs the rows
12+
* grouped by the field holding that unit. Two measures read the rule:
1613
*
17-
* The counts are currency-free and always stand.
14+
* - ADR-0144 D6, a `record`-mode amount (`currencyConfig.currencyMode:
15+
* 'record'`): the unit is the currency code in its `currencyField`.
16+
* Adding 100 USD to 100 EUR answers a number that is no amount at all.
17+
* Consolidated totals belong to the home field, an ordinary `dynamic`
18+
* amount that totals unchanged.
19+
* - ADR-0158 U7 R1, a `record`-mode quantity (a `number` declaring
20+
* `unitConfig: { unitMode: 'record', unitField }`): the unit is the code
21+
* in its `unitField`. 10 KGM and 10 LBR summed to 20. The engine refuses
22+
* such an aggregate unless the query groups by `unitField`
23+
* (`record-unit-aggregate-door.ts` in `@objectstack/objectql`), and this
24+
* module reads the field exactly as that door's `recordUnitFieldOf` does.
25+
*
26+
* A group bucketed by that field holds one unit, so its `sum` / `avg` /
27+
* `min` / `max` stand; any other set of rows mixes units. The counts are
28+
* unit-free and always stand.
1829
*/
1930
import { recordCurrencyField } from '@object-ui/i18n';
2031
import type { GroupAggregationConfig } from './useGroupedData';
2132

22-
const MONEY_AGGREGATES = new Set(['sum', 'avg', 'min', 'max']);
33+
/** The aggregates that read the measure itself: ADR-0144 Open item 10, ADR-0158 Open item 12. */
34+
const MEASURE_AGGREGATES = new Set(['sum', 'avg', 'min', 'max']);
2335

24-
/** Whether `type` aggregates the amounts themselves (not a count of rows). */
25-
export function isMoneyAggregate(type: string): boolean {
26-
return MONEY_AGGREGATES.has(type);
36+
/** Whether `type` aggregates the measure itself (not a count of rows). */
37+
export function isMeasureAggregate(type: string): boolean {
38+
return MEASURE_AGGREGATES.has(type);
2739
}
2840

29-
/** Any object field def; only its `currencyConfig` is read. */
30-
type CurrencyFieldLike = object | null | undefined;
41+
/** Any object field def; only its `type`, `currencyConfig` and `unitConfig` are read. */
42+
type MeasureFieldLike = object | null | undefined;
43+
44+
/**
45+
* [ADR-0158 U7 R1] The unit field of a `record`-mode quantity, or
46+
* `undefined`: a `number` field declaring `unitConfig: { unitMode: 'record',
47+
* unitField }` with a non-empty `unitField`, the reading the engine's
48+
* aggregate door makes. A `fixed`-mode quantity has one unit for every row,
49+
* and a number with no `unitConfig` has none to mix.
50+
*/
51+
export function recordUnitField(def: unknown): string | undefined {
52+
if (def === null || typeof def !== 'object') return undefined;
53+
const { type, unitConfig } = def as { type?: unknown; unitConfig?: unknown };
54+
if (type !== 'number' || unitConfig === null || typeof unitConfig !== 'object') return undefined;
55+
const { unitMode, unitField } = unitConfig as { unitMode?: unknown; unitField?: unknown };
56+
return unitMode === 'record' && typeof unitField === 'string' && unitField !== '' ? unitField : undefined;
57+
}
58+
59+
/**
60+
* The field naming each record's unit of `def`'s measure — a `record`-mode
61+
* amount's code field, or a `record`-mode quantity's unit field — or
62+
* `undefined` when every row of `def` is in one unit.
63+
*/
64+
export function recordMeasureUnitField(def: MeasureFieldLike): string | undefined {
65+
return recordCurrencyField(def as Parameters<typeof recordCurrencyField>[0]) ?? recordUnitField(def);
66+
}
3167

3268
/**
33-
* The code field a money aggregate over `field` needs to be grouped by, or
34-
* `undefined` when `field` is not a `record`-mode amount (any aggregate over
35-
* it is honest as it stands).
69+
* The field a measure aggregate over `field` needs to be grouped by, or
70+
* `undefined` when `type` reads no measure or `field` is in one unit (any
71+
* aggregate over it is honest as it stands).
3672
*/
37-
export function requiredCurrencyGrouping(
73+
export function requiredAggregateGrouping(
3874
field: string,
3975
type: string,
40-
objectFields: Readonly<Record<string, CurrencyFieldLike>> | undefined,
76+
objectFields: Readonly<Record<string, MeasureFieldLike>> | undefined,
4177
): string | undefined {
42-
if (!isMoneyAggregate(type)) return undefined;
43-
return recordCurrencyField(objectFields?.[field] as Parameters<typeof recordCurrencyField>[0] | undefined);
78+
if (!isMeasureAggregate(type)) return undefined;
79+
return recordMeasureUnitField(objectFields?.[field]);
4480
}
4581

4682
/**
4783
* The group-header aggregations the grid may draw: every configured one,
48-
* minus each money aggregate over a `record`-mode amount whose code field is
49-
* not among the grouping fields. Dropped before the rows are bucketed and
50-
* before the server is asked, so neither path computes a cross-currency sum.
84+
* minus each measure aggregate over a `record`-mode amount or quantity whose
85+
* unit field is not among the grouping fields. Dropped before the rows are
86+
* bucketed and before the server is asked, so neither path adds amounts in
87+
* different currencies or quantities in different units.
5188
*/
5289
export function honestGroupAggregations(
5390
aggregations: GroupAggregationConfig[] | undefined,
54-
objectFields: Readonly<Record<string, CurrencyFieldLike>> | undefined,
91+
objectFields: Readonly<Record<string, MeasureFieldLike>> | undefined,
5592
groupingFields: readonly string[],
5693
): GroupAggregationConfig[] | undefined {
5794
if (!aggregations || aggregations.length === 0) return aggregations;
5895
const kept = aggregations.filter(({ field, type }) => {
59-
const code = requiredCurrencyGrouping(field, type, objectFields);
60-
return code === undefined || groupingFields.includes(code);
96+
const unit = requiredAggregateGrouping(field, type, objectFields);
97+
return unit === undefined || groupingFields.includes(unit);
6198
});
6299
return kept.length === aggregations.length ? aggregations : kept;
63100
}

0 commit comments

Comments
 (0)