diff --git a/.changeset/36082-record-unit-summary.md b/.changeset/36082-record-unit-summary.md new file mode 100644 index 00000000000..49627d10361 --- /dev/null +++ b/.changeset/36082-record-unit-summary.md @@ -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. diff --git a/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx index 230038c8eb5..12eeca66034 100644 --- a/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx @@ -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'; @@ -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; +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; /** * 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}`, @@ -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, })); @@ -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`). */ @@ -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 }); @@ -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) => ({ + ...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' }]); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/recordCurrencyAggregates-27188.test.tsx b/ui/packages/plugin-grid/src/__tests__/recordCurrencyAggregates-27188.test.tsx index 12087680490..cebeb9a1b61 100644 --- a/ui/packages/plugin-grid/src/__tests__/recordCurrencyAggregates-27188.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/recordCurrencyAggregates-27188.test.tsx @@ -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); @@ -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[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(); }); }); diff --git a/ui/packages/plugin-grid/src/objectGridGrouping.ts b/ui/packages/plugin-grid/src/objectGridGrouping.ts index caefb01b9e6..96e1a18b237 100644 --- a/ui/packages/plugin-grid/src/objectGridGrouping.ts +++ b/ui/packages/plugin-grid/src/objectGridGrouping.ts @@ -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, diff --git a/ui/packages/plugin-grid/src/recordCurrencyAggregates.ts b/ui/packages/plugin-grid/src/recordCurrencyAggregates.ts index eaeb7d7ab27..b3d9693ecd6 100644 --- a/ui/packages/plugin-grid/src/recordCurrencyAggregates.ts +++ b/ui/packages/plugin-grid/src/recordCurrencyAggregates.ts @@ -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[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> | undefined, + objectFields: Readonly> | undefined, ): string | undefined { - if (!isMoneyAggregate(type)) return undefined; - return recordCurrencyField(objectFields?.[field] as Parameters[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> | undefined, + objectFields: Readonly> | 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; } diff --git a/ui/packages/plugin-grid/src/useColumnSummary.ts b/ui/packages/plugin-grid/src/useColumnSummary.ts index 73dc6034b9f..fdcca52c31a 100644 --- a/ui/packages/plugin-grid/src/useColumnSummary.ts +++ b/ui/packages/plugin-grid/src/useColumnSummary.ts @@ -10,11 +10,12 @@ import { useMemo } from 'react'; import type { ListColumn } from '@object-ui/types'; import type { ColumnSummary, ListViewGroupHeaderRow } from '@objectstack/spec/ui'; import { deriveColumnSummary, isColumnSummaryCompatibleWithFieldType } from '@objectstack/spec/ui'; -import type { CurrencyConfig } from '@objectstack/spec/data'; +import type { CurrencyConfig, UnitConfig } from '@objectstack/spec/data'; import { resolveFieldScale, isAggregateCompatibleWithFieldType } from '@objectstack/spec/data'; import { useLocalization, useDisplayLocale, resolveFieldCurrency, recordCurrencyField, createSafeTranslation } from '@object-ui/i18n'; import { formatCurrency, formatPercent, percentCellScale, summaryDeclaresCurrency } from '@object-ui/fields'; import { temporalCellFaceOf, temporalCellText, temporalExtreme, temporalInstant } from './temporalCellFace'; +import { recordMeasureUnitField } from './recordCurrencyAggregates'; /** * Aggregation functions for the column footer — the spec's `ColumnSummary` @@ -168,7 +169,8 @@ export const useSummaryTranslation = createSafeTranslation( * any. ⛔ No `count`: the row's first cell already carries the record count. * Booleans get their yes / no counts first, then the count family — never * the arithmetic, which reads a boolean as 0 / 1 — and a record-currency - * amount (whose sum the footer withholds) gets the count family only. The + * amount or a record-unit quantity (whose sum the footer withholds) gets the + * count family only. The * yes / no counts are offered exactly where the spec's member table allows * them (`isColumnSummaryCompatibleWithFieldType`). */ @@ -180,10 +182,10 @@ const MENU_COUNTS: ReadonlyArray = [ ]; const MENU_BOOLEAN_COUNTS: ReadonlyArray = ['count_true', 'count_false']; export function offeredColumnSummaries( - field: ({ type?: string } & NonNullable[0]>) | undefined, + field: ({ type?: string; unitConfig?: UnitConfig } & NonNullable[0]>) | undefined, ): ColumnSummaryType[] { const type = field?.type; - const numeric = !!type && !BOOLEAN_FIELD_TYPES.has(type) && !recordCurrencyField(field); + const numeric = !!type && !BOOLEAN_FIELD_TYPES.has(type) && recordMeasureUnitField(field) === undefined; return [ ...(type ? MENU_BOOLEAN_COUNTS.filter((m) => isColumnSummaryCompatibleWithFieldType(m, type)) : []), ...(numeric ? MENU_AGGREGATES.filter((m) => isAggregateCompatibleWithFieldType(m, type!)) : []), @@ -652,7 +654,7 @@ function formatSummaryLabel( } /** The `objectSchema.fields` slice the footer formats with. */ -type SummaryFieldMetadata = Record; +type SummaryFieldMetadata = Record; /** * Which rows the footer's figures describe (objectui#12081 item 3). @@ -766,12 +768,13 @@ export function useScopedColumnSummary( const targetField = config.field || col.field; - // [ADR-0144 D6] The footer spans every row, so it is never inside one - // currency: a sum / avg / min / max over a `record`-mode amount would add - // amounts in different currencies. It draws nothing for that column (the - // counts stand); the consolidated figure is the home field's, and a - // per-currency figure is the header of a group bucketed by the code. - if (!NON_NUMERIC_TYPES.has(config.type) && recordCurrencyField(fieldMetadata?.[targetField])) continue; + // [ADR-0144 D6, ADR-0158 U7 R1] The footer spans every row, so it is + // never inside one unit: a sum / avg / min / max over a `record`-mode + // amount would add amounts in different currencies, and one over a + // `record`-mode quantity quantities in different units. It draws nothing + // for that column (the counts stand); a per-unit figure is the header of + // a group bucketed by the unit field. + if (!NON_NUMERIC_TYPES.has(config.type) && recordMeasureUnitField(fieldMetadata?.[targetField]) !== undefined) continue; // objectstack#32119 — a column whose cell paints a date-family face // holds times, not numbers: its `min` / `max` is the extreme time, drawn diff --git a/ui/packages/plugin-grid/src/useWholeSetSummary.ts b/ui/packages/plugin-grid/src/useWholeSetSummary.ts index d7f83349e83..0b55f9a8dac 100644 --- a/ui/packages/plugin-grid/src/useWholeSetSummary.ts +++ b/ui/packages/plugin-grid/src/useWholeSetSummary.ts @@ -53,24 +53,26 @@ * estimate, not a count — the two describe different numbers of rows, * and the footer stays on the page, labelled as the page's. * - * ## ⛔ Never a raw money aggregate over a `record`-mode amount + * ## ⛔ Never a raw aggregate over a `record`-mode amount or quantity * - * [ADR-0144 D6] The whole set is never inside one currency, so a `sum` / - * `avg` / `min` / `max` over a `record`-mode amount (its `currencyField` a - * sibling code field or a parent path) would add amounts in different - * currencies, and the engine refuses such an aggregate with the query NOT - * run. The footer draws no figure for that column (`useScopedColumnSummary` - * skips it), so the question leaves it out: `wholeSetSummaryNodes` drops the - * node by the same predicate the group headers use - * (`requiredCurrencyGrouping`). Asked anyway, the refusal would cost every - * other column in the query its whole-set figure. A per-currency total is a - * query grouped by the code, which this read does not ask. + * [ADR-0144 D6, ADR-0158 U7 R1] The whole set is never inside one unit, so a + * `sum` / `avg` / `min` / `max` over a `record`-mode amount (its + * `currencyField` a sibling code field or a parent path) would add amounts in + * different currencies, and one over a `record`-mode quantity (its + * `unitConfig.unitField`) quantities in different units; the engine refuses + * either aggregate with the query NOT run. The footer draws no figure for + * that column (`useScopedColumnSummary` skips it), so the question leaves it + * out: `wholeSetSummaryNodes` drops the node by the same predicate the group + * headers use (`requiredAggregateGrouping`). Asked anyway, the refusal would + * cost every other column in the query its whole-set figure. A per-currency + * or per-unit total is a query grouped by the unit field, which this read + * does not ask. * * The leave-out needs the object's field catalogue. While the grid still * awaits it (`objectFieldsPending`), a column summary that aggregates the - * amounts themselves is not asked: its currency mode is unknown, and a guess - * that it is not `record` is the refused request. The answer comes once the - * catalogue lands. + * measure itself is not asked: its mode is unknown, and a guess that it is + * not `record` is the refused request. The answer comes once the catalogue + * lands. * * ## Asked only for a footer, once per question * @@ -100,10 +102,10 @@ import { type ListViewGroupHeaderRow, } from '@objectstack/spec/ui'; import { useDataInvalidation } from '@object-ui/react'; -import { isMoneyAggregate, requiredCurrencyGrouping } from './recordCurrencyAggregates'; +import { isMeasureAggregate, requiredAggregateGrouping } from './recordCurrencyAggregates'; -/** The object's field catalogue; only a field's `currencyConfig` is read here. */ -export type WholeSetSummaryFields = Parameters[2]; +/** The object's field catalogue; only a field's `type`, `currencyConfig` and `unitConfig` are read here. */ +export type WholeSetSummaryFields = Parameters[2]; /** Find-param keys that shape the WINDOW or the row's SHAPE — never which rows match. */ const WINDOW_KEYS: ReadonlySet = new Set(['$top', '$skip', '$orderby', '$select', '$expand', '$count']); @@ -118,9 +120,10 @@ const WINDOW_KEYS: ReadonlySet = new Set(['$top', '$skip', '$orderby', ' * (objectui#12081 item 3, rework round 1): the `count` node alone is not a * question anybody asked. * - * [ADR-0144 D6] A money aggregate over a `record`-mode amount in - * `objectFields` is no node either (see the module note): the footer draws - * nothing for it, and the engine refuses the query that carries it. + * [ADR-0144 D6, ADR-0158 U7 R1] A measure aggregate over a `record`-mode + * amount or quantity in `objectFields` is no node either (see the module + * note): the footer draws nothing for it, and the engine refuses the query + * that carries it. */ export function wholeSetSummaryNodes( columns: readonly ListColumn[] | undefined, @@ -145,7 +148,7 @@ export function wholeSetSummaryNodes( // `count_false` asks `SUM(field)` and `COUNT(field)`), off the spec's own // reading of the row, so this question and the group header's agree. const fns = columnSummaryNodeFunctions(mapping); - if (fns.some((fn) => requiredCurrencyGrouping(field, fn, objectFields) !== undefined)) continue; + if (fns.some((fn) => requiredAggregateGrouping(field, fn, objectFields) !== undefined)) continue; declared = true; const aggregated = mapping.fieldless ? undefined : field; for (const fn of fns) { @@ -218,13 +221,14 @@ export interface WholeSetSummaryInput { columns: ListColumn[] | undefined; /** * The object's field catalogue, read for each summarised field's currency - * mode: a money aggregate over a `record`-mode amount is left out of the - * question (ADR-0144 D6, see the module note). + * or unit mode: a measure aggregate over a `record`-mode amount or quantity + * is left out of the question (ADR-0144 D6, ADR-0158 U7 R1, see the module + * note). */ objectFields: WholeSetSummaryFields; /** - * The grid still awaits `objectFields` (`objectTypesPending`): a money - * aggregate is not asked until the catalogue says its currency mode. + * The grid still awaits `objectFields` (`objectTypesPending`): a measure + * aggregate is not asked until the catalogue says its currency or unit mode. */ objectFieldsPending: boolean; /** @@ -243,7 +247,7 @@ export interface WholeSetSummaryInput { * - `off` — not asked: the rows are the whole set, or no column declares a * summary that maps to an aggregate. * - `pending` — asked, no answer to THIS question in hand yet; or not yet - * askable, a money aggregate awaiting the field catalogue. + * askable, a measure aggregate awaiting the field catalogue. * - `answered` — the whole set's header row, its `count` agreeing with the grid's. * - `unavailable` — no door, a refusal, an unaskable query, or an answer whose * count is not the grid's. @@ -273,10 +277,11 @@ export function useWholeSetSummary(input: WholeSetSummaryInput): WholeSetSummary // nothing — the read is `off`, exactly as for rows that are the whole set. const nodes = enabled ? wholeSetSummaryNodes(columns, objectFields) : null; const active = nodes !== null; - // [ADR-0144 D6] A money aggregate waits for the catalogue that says whether - // its amount is `record`-mode; it is never asked on a guess. A read that - // never lands keeps it unasked, and the footer on the page. - const awaitingFields = active && objectFieldsPending && nodes.some((node) => isMoneyAggregate(node.function)); + // [ADR-0144 D6, ADR-0158 U7 R1] A measure aggregate waits for the catalogue + // that says whether its amount or quantity is `record`-mode; it is never + // asked on a guess. A read that never lands keeps it unasked, and the + // footer on the page. + const awaitingFields = active && objectFieldsPending && nodes.some((node) => isMeasureAggregate(node.function)); const query = active && !awaitingFields && findParams ? compileWholeSetSummaryQuery(columns, findParams, objectFields) : null; const canAsk = active && !!objectName