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
16 changes: 16 additions & 0 deletions .changeset/36082-record-unit-summary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@object-ui/plugin-grid': patch
---

fix(plugin-grid): leave a raw aggregate over a record-mode quantity out of the whole-set footer and the group headers

Clause-②: no
Metadata-protocol: none

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:

- 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.
- The footer draws no `sum` / `avg` / `min` / `max` for that column, and its menu offers the count family only; the counts stand.
- A group-header aggregate over it stands only when the grid is grouped by its `unitField`.

A `fixed`-mode quantity and a `number` with no `unitConfig` total as before.
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
* - ADR-0144 D6: a money aggregate over a `record`-mode amount is left out
* of the whole-set query (the double refuses it as the engine does), so
* the other columns keep their whole-set figures.
* - ADR-0158 U7 R1: the same for a `record`-mode quantity.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react';
Expand Down Expand Up @@ -74,12 +75,13 @@ afterEach(() => {
const OBJECT = 'plan_line';
const PAGE = 25;

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>;
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>;
/**
* 300 rows; every fifth `note` is empty, every third row is `won`, and
* `closed_at` is one day later per row, so the last row is the latest.
* `currency_code` alternates USD / EUR, for the `record`-mode amount cases
* (ADR-0144 D6); `qty` is a plain number beside it.
* (ADR-0144 D6); `qty` is a plain number beside it. `unit_code` alternates
* KGM / LBR, for the `record`-mode quantity cases (ADR-0158 U7 R1).
*/
const ROWS: Row[] = Array.from({ length: 300 }, (_, i) => ({
id: `r${i}`,
Expand All @@ -90,6 +92,7 @@ const ROWS: Row[] = Array.from({ length: 300 }, (_, i) => ({
closed_at: new Date(Date.UTC(2025, 0, 1, 9, 30) + i * 86_400_000).toISOString(),
qty: (i % 7) + 1,
currency_code: i % 2 === 0 ? 'USD' : 'EUR',
unit_code: i % 2 === 0 ? 'KGM' : 'LBR',
// objectstack#35702 — a boolean: every fourth unset, then true / false alternating (75 / 75 / 150).
approved: i % 4 === 0 ? null : i % 2 === 0,
}));
Expand Down Expand Up @@ -162,6 +165,14 @@ const recordPointerOf = (def: unknown): string | undefined => {
return config?.currencyMode === 'record' && typeof config.currencyField === 'string' ? config.currencyField : undefined;
};

/** A field def's `record`-mode unit pointer, as the engine's ADR-0158 U7 R1 door reads it. */
const recordUnitOf = (def: unknown): string | undefined => {
const { type, unitConfig } = (def ?? {}) as { type?: unknown; unitConfig?: { unitMode?: unknown; unitField?: unknown } };
return type === 'number' && unitConfig?.unitMode === 'record' && typeof unitConfig.unitField === 'string' && unitConfig.unitField !== ''
? unitConfig.unitField
: undefined;
};

function makeDataSource(opts: {
door?: 'answers' | 'absent' | 'refuses' | 'no-row' | 'strings';
/** The object definition's fields `getObjectSchema` answers (default `OBJECT_FIELDS`). */
Expand Down Expand Up @@ -195,10 +206,12 @@ function makeDataSource(opts: {
if (door === 'refuses') throw Object.assign(new Error('refused'), { code: 'UNSUPPORTED_QUERY_PARAM' });
const groupBy = query.groupBy ?? [];
if (groupBy.length > 0) throw new Error('double: this suite asks no grouped query');
// [ADR-0144 D6] The engine refuses a raw sum / avg / min / max over a
// `record`-mode amount in an ungrouped query, and runs none of it.
// [ADR-0144 D6, ADR-0158 U7 R1] The engine refuses a raw sum / avg /
// min / max over a `record`-mode amount or quantity in an ungrouped
// query, and runs none of it.
const raw = (query.aggregations ?? []).filter((node) => ['sum', 'avg', 'min', 'max'].includes(node.function)
&& node.field !== undefined && recordPointerOf(fields[node.field]) !== undefined);
&& node.field !== undefined
&& (recordPointerOf(fields[node.field]) ?? recordUnitOf(fields[node.field])) !== undefined);
if (raw.length > 0) {
refusals.push(...raw.map((node) => `${node.function}(${node.field})`));
throw Object.assign(new Error('refused: a raw aggregate across currencies'), { code: 'INVALID_FIELD', status: 400 });
Expand Down Expand Up @@ -751,3 +764,48 @@ describe('a money aggregate over a `record`-mode amount is left out of the whole
]);
});
});

describe('a raw aggregate over a `record`-mode quantity is left out of the whole-set query (ADR-0158 U7 R1)', () => {
/** `qty` in each row's own unit, the code in the sibling `unit_code`; `amount` a plain number beside it. */
const recordQty = (unitConfig: Record<string, unknown>) => ({
...OBJECT_FIELDS,
qty: { type: 'number', label: 'Qty', unitConfig },
unit_code: { type: 'text', label: 'Unit' },
});
const RECORD_QTY = recordQty({ unitMode: 'record', unitField: 'unit_code' });
const COLUMNS = [
{ field: 'name', label: 'Name' },
{ field: 'qty', label: 'Qty', type: 'number', summary: 'sum' },
{ field: 'amount', label: 'Amount', type: 'number', summary: 'sum' },
];
const amountWhole = `Amount: Sum: ${fmt(sumOf(ROWS))}`;
const qtyNodes = (ds: TestDataSource) => ds.queryGroupHeaders.mock.calls
.flatMap(([, query]) => (query as AggregateQuery).aggregations ?? [])
.filter((node) => node.field === 'qty');

it('the plain-number sum keeps its whole-set figure, and no refused request is sent', async () => {
const ds = makeDataSource({ fields: RECORD_QTY });
render(hostGrid(ds, { rows: ROWS, columns: COLUMNS }));

await waitFor(() => expect(footerText('amount')).toBe(amountWhole));
// The record-mode quantity draws nothing: no whole-set figure, and no page sum over KGM and LBR.
expect(footerText('qty')).toBeNull();
expect(ds.refusals).toEqual([]);
expect(qtyNodes(ds)).toEqual([]);
expect(ds.queryGroupHeaders).toHaveBeenCalledTimes(1);
expect((ds.queryGroupHeaders.mock.calls[0][1] as AggregateQuery).aggregations).toEqual([
{ function: 'count', alias: 'count' },
{ function: 'sum', field: 'amount', alias: 'sum_amount' },
]);
});

it('CONTROL: a fixed-mode quantity is asked and totals over the whole set', async () => {
const ds = makeDataSource({ fields: recordQty({ unitMode: 'fixed', unit: 'KGM' }) });
render(hostGrid(ds, { rows: ROWS, columns: COLUMNS }));

await waitFor(() => expect(footerText('qty')).toBe(`Qty: Sum: ${fmt(ROWS.reduce((a, r) => a + r.qty, 0))}`));
expect(footerText('amount')).toBe(amountWhole);
expect(ds.refusals).toEqual([]);
expect(qtyNodes(ds)).toEqual([{ function: 'sum', field: 'qty', alias: 'sum_qty' }]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import { describe, it, expect, afterEach } from 'vitest';
import * as React from 'react';
import { renderHook, cleanup } from '@testing-library/react';
import { I18nProvider, LocalizationProvider } from '@object-ui/i18n';
import { useColumnSummary } from '../useColumnSummary';
import { honestGroupAggregations, requiredCurrencyGrouping } from '../recordCurrencyAggregates';
import { useColumnSummary, offeredColumnSummaries } from '../useColumnSummary';
import { honestGroupAggregations, requiredAggregateGrouping } from '../recordCurrencyAggregates';

afterEach(cleanup);

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

it('only a money aggregate over a record-mode amount needs the code grouping', () => {
expect(requiredCurrencyGrouping('amount', 'sum', META)).toBe('currency_code');
expect(requiredCurrencyGrouping('amount', 'count_distinct', META)).toBeUndefined();
expect(requiredCurrencyGrouping('amount_home', 'sum', META)).toBeUndefined();
expect(requiredAggregateGrouping('amount', 'sum', META)).toBe('currency_code');
expect(requiredAggregateGrouping('amount', 'count_distinct', META)).toBeUndefined();
expect(requiredAggregateGrouping('amount_home', 'sum', META)).toBeUndefined();
});
});

/**
* ADR-0158 U7 R1, the same rule over a quantity: a `number` declaring
* `unitConfig: { unitMode: 'record', unitField }` holds a quantity in each
* row's own unit, so a sum / avg / min / max over it stands only inside one
* unit. The engine refuses one unless grouped by `unitField`; a `fixed`-mode
* quantity and a number with no `unitConfig` total as before.
*/
describe('a record-mode quantity: footer and group headers (ADR-0158 U7 R1)', () => {
const UNIT_META: NonNullable<Parameters<typeof useColumnSummary>[2]> = {
qty: { type: 'number', unitConfig: { unitMode: 'record', unitField: 'unit_code' } },
qty_kg: { type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } },
weight: { type: 'number' },
unit_code: { type: 'text' },
};
const UNIT_ROWS = [
{ qty: 10, qty_kg: 10, weight: 3, unit_code: 'KGM' },
{ qty: 10, qty_kg: 5, weight: 4, unit_code: 'LBR' },
];
const unitFooter = (field: string, summary: string): string | undefined => {
const columns: any[] = [{ field, summary }];
const { result } = renderHook(() => useColumnSummary(columns, UNIT_ROWS, UNIT_META), { wrapper: Providers });
return result.current.summaries.get(field)?.label;
};

it('the footer draws no sum / avg / min / max — 10 KGM and 10 LBR are not 20; a count stands', () => {
for (const s of ['sum', 'avg', 'min', 'max']) expect(unitFooter('qty', s)).toBeUndefined();
expect(unitFooter('qty', 'count')).toBe('Count: 2');
});

it('CONTROL: a fixed-mode quantity and a plain number sum as before', () => {
expect(unitFooter('qty_kg', 'sum')).toBe('Sum: 15');
expect(unitFooter('weight', 'sum')).toBe('Sum: 7');
});

it('the footer menu offers the count family only, as for a record-mode amount', () => {
const offered = offeredColumnSummaries(UNIT_META.qty);
for (const s of ['sum', 'avg', 'min', 'max'] as const) expect(offered).not.toContain(s);
expect(offered).toContain('count_filled');
expect(offeredColumnSummaries(UNIT_META.qty_kg)).toContain('sum');
});

const UNIT_AGGS = [
{ field: 'qty', type: 'sum' as const },
{ field: 'qty', type: 'count' as const },
{ field: 'weight', type: 'sum' as const },
{ field: 'qty_kg', type: 'max' as const },
];

it('a group-header aggregate over it stands when the grid is grouped by its unit field', () => {
expect(honestGroupAggregations(UNIT_AGGS, UNIT_META, ['unit_code'])).toBe(UNIT_AGGS);
});

it('it is dropped when grouped by anything else; the counts, the fixed-mode and the plain aggregates stand', () => {
expect(honestGroupAggregations(UNIT_AGGS, UNIT_META, ['region'])).toEqual([UNIT_AGGS[1], UNIT_AGGS[2], UNIT_AGGS[3]]);
});

it('the unit field is read as the engine reads it: a `number` in record mode with a non-empty unitField', () => {
expect(requiredAggregateGrouping('qty', 'avg', UNIT_META)).toBe('unit_code');
expect(requiredAggregateGrouping('qty', 'count_distinct', UNIT_META)).toBeUndefined();
expect(requiredAggregateGrouping('qty_kg', 'sum', UNIT_META)).toBeUndefined();
expect(requiredAggregateGrouping('weight', 'sum', UNIT_META)).toBeUndefined();
expect(requiredAggregateGrouping('q', 'sum', { q: { type: 'number', unitConfig: { unitMode: 'record', unitField: '' } } })).toBeUndefined();
expect(requiredAggregateGrouping('q', 'sum', { q: { type: 'text', unitConfig: { unitMode: 'record', unitField: 'unit_code' } } })).toBeUndefined();
});
});
11 changes: 6 additions & 5 deletions ui/packages/plugin-grid/src/objectGridGrouping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,15 +291,16 @@ export function useObjectGridGrouping({
}
}, [groupRowQueryKey]);
const groupReloadKey = `${refreshKey}:${invalidationNonce}`;
// [ADR-0144 D6] A money aggregate over a `record`-mode amount stands only in
// groups bucketed by that amount's code field; elsewhere it would add
// amounts in different currencies, so it is dropped before either the
// server or the client bucketing computes it. Keyed on what it reads, so a
// [ADR-0144 D6, ADR-0158 U7 R1] A measure aggregate over a `record`-mode
// amount or quantity stands only in groups bucketed by its code or unit
// field; elsewhere it would add amounts in different currencies or
// quantities in different units, so it is dropped before either the server
// or the client bucketing computes it. Keyed on what it reads, so a
// host that rebuilds `schema` every render does not re-key the header query.
// [objectstack#32119] Per aggregated field whose cell paints a date-family
// face, that face, resolved as the group headings' faces are: a `min` /
// `max` over it is a time, drawn as the cell draws it, and a `sum` / `avg`
// over it is no figure at all, so it is dropped here with the money
// over it is no figure at all, so it is dropped here with the measure
// aggregates, before either path computes it or the server is asked.
const groupAggregationKey = JSON.stringify({
aggregations: schema.aggregations ?? null,
Expand Down
89 changes: 63 additions & 26 deletions ui/packages/plugin-grid/src/recordCurrencyAggregates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,94 @@
*/

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

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

/** Whether `type` aggregates the amounts themselves (not a count of rows). */
export function isMoneyAggregate(type: string): boolean {
return MONEY_AGGREGATES.has(type);
/** Whether `type` aggregates the measure itself (not a count of rows). */
export function isMeasureAggregate(type: string): boolean {
return MEASURE_AGGREGATES.has(type);
}

/** Any object field def; only its `currencyConfig` is read. */
type CurrencyFieldLike = object | null | undefined;
/** Any object field def; only its `type`, `currencyConfig` and `unitConfig` are read. */
type MeasureFieldLike = object | null | undefined;

/**
* [ADR-0158 U7 R1] The unit field of a `record`-mode quantity, or
* `undefined`: a `number` field declaring `unitConfig: { unitMode: 'record',
* unitField }` with a non-empty `unitField`, the reading the engine's
* aggregate door makes. A `fixed`-mode quantity has one unit for every row,
* and a number with no `unitConfig` has none to mix.
*/
export function recordUnitField(def: unknown): string | undefined {
if (def === null || typeof def !== 'object') return undefined;
const { type, unitConfig } = def as { type?: unknown; unitConfig?: unknown };
if (type !== 'number' || unitConfig === null || typeof unitConfig !== 'object') return undefined;
const { unitMode, unitField } = unitConfig as { unitMode?: unknown; unitField?: unknown };
return unitMode === 'record' && typeof unitField === 'string' && unitField !== '' ? unitField : undefined;
}

/**
* The field naming each record's unit of `def`'s measure — a `record`-mode
* amount's code field, or a `record`-mode quantity's unit field — or
* `undefined` when every row of `def` is in one unit.
*/
export function recordMeasureUnitField(def: MeasureFieldLike): string | undefined {
return recordCurrencyField(def as Parameters<typeof recordCurrencyField>[0]) ?? recordUnitField(def);
}

/**
* The code field a money aggregate over `field` needs to be grouped by, or
* `undefined` when `field` is not a `record`-mode amount (any aggregate over
* it is honest as it stands).
* The field a measure aggregate over `field` needs to be grouped by, or
* `undefined` when `type` reads no measure or `field` is in one unit (any
* aggregate over it is honest as it stands).
*/
export function requiredCurrencyGrouping(
export function requiredAggregateGrouping(
field: string,
type: string,
objectFields: Readonly<Record<string, CurrencyFieldLike>> | undefined,
objectFields: Readonly<Record<string, MeasureFieldLike>> | undefined,
): string | undefined {
if (!isMoneyAggregate(type)) return undefined;
return recordCurrencyField(objectFields?.[field] as Parameters<typeof recordCurrencyField>[0] | undefined);
if (!isMeasureAggregate(type)) return undefined;
return recordMeasureUnitField(objectFields?.[field]);
}

/**
* The group-header aggregations the grid may draw: every configured one,
* minus each money aggregate over a `record`-mode amount whose code field is
* not among the grouping fields. Dropped before the rows are bucketed and
* before the server is asked, so neither path computes a cross-currency sum.
* minus each measure aggregate over a `record`-mode amount or quantity whose
* unit field is not among the grouping fields. Dropped before the rows are
* bucketed and before the server is asked, so neither path adds amounts in
* different currencies or quantities in different units.
*/
export function honestGroupAggregations(
aggregations: GroupAggregationConfig[] | undefined,
objectFields: Readonly<Record<string, CurrencyFieldLike>> | undefined,
objectFields: Readonly<Record<string, MeasureFieldLike>> | undefined,
groupingFields: readonly string[],
): GroupAggregationConfig[] | undefined {
if (!aggregations || aggregations.length === 0) return aggregations;
const kept = aggregations.filter(({ field, type }) => {
const code = requiredCurrencyGrouping(field, type, objectFields);
return code === undefined || groupingFields.includes(code);
const unit = requiredAggregateGrouping(field, type, objectFields);
return unit === undefined || groupingFields.includes(unit);
});
return kept.length === aggregations.length ? aggregations : kept;
}
Loading
Loading