Skip to content

Commit c59ee99

Browse files
feat(objectql,service-analytics): refuse a raw aggregate over a record-mode quantity unless grouped by its unit field (#36060)
repo:objectstack#7 · os-tesla · session_01L9qibvMi1U7R2kBd3JbTPu Fixes #35491 A total over a quantity whose unit is stored per row (`unitConfig: { unitMode: 'record', unitField }`) is now refused unless it groups by that unit field. Before, 10 KGM plus 10 LBR answered 20 in the engine aggregate, a dataset or cube measure, and a `summary` roll-up. This is ADR-0158 U7 R1, built as a one-for-one mirror of the ADR-0144 D6 record-currency doors. Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:按单位逐行记录的数量(如一行 10 千克、一行 10 磅),在报表、数据集和汇总字段里不按单位分组直接求和、求平均、取最大最小时,会得到明确的拒绝提示,而不是一个错误的总数;按单位分组后照常出数。 - 为什么做:属于“计量单位”第一期,直接相加不同单位的数量会得出看似合理却错误的数字,这里与多币种的同类保护保持一致。 - 出错会怎样:目前还没有任何应用或示例使用这种按行记录单位的数量,影响面为零;如有问题,撤回这次合并即可恢复原样。 - 要你做什么:无。 ## What changes - **ObjectQL aggregate door** (`packages/objectql/src/record-unit-aggregate-door.ts`, wired in `ObjectQL.aggregate` right after the record-currency door): `sum` / `avg` / `min` / `max` over a `record`-mode quantity answers `INVALID_FIELD` / 400 before any driver is asked, unless `groupBy` includes the quantity's `unitField`. The message names the quantity, its unit field and the grouping to add; the thrown error carries `field`, `fields`, `object`, `param: 'aggregations'` and `unitField` (in process only: the `/data` REST body keeps `field` and `object` and drops `unitField`, measured below). - **`summary` registration** (`recordUnitSummaryRefusal`, in `SchemaRegistry.registerObject` beside `recordCurrencySummaryRefusal`): a roll-up of `sum` / `avg` / `min` / `max` over such a child quantity answers `INVALID_METADATA` / 422 (`RecordUnitSummaryRefusedError`), judged at whichever registration completes the pair. Per ADR-0158 L3 every such roll-up is refused in R1 (no `master_detail` following), so the roll-up recompute gets no bypass channel: the currency door needs `ROLLUP_AGGREGATE_OPTION` only for its admitted roll-up, and units admit none. - **Analytics cube measure door** (`packages/services/service-analytics/src/cube-record-unit-door.ts`, asked right after the record-currency door at all four places that ask it: the inferred, augmented and declared `ensureCube` paths and the draft-preview branch of `queryDataset`): `INVALID_FIELD` / 400, the thrown error carrying `member`, `param: 'measures'`, `field`, `object` and `unitField` (in process only: the analytics REST body is `code` and `message`), unless a dimension's column is the unit field on the same object. The plugin's `sourceFieldMeta` relays `unitField` only for a `number` under `unitMode: 'record'`. The dimension resolver both doors share moved into one private method (`groupedColumnOf`), with no change to what it answers. - **The widening.** `AnalyticsServiceConfig.sourceFieldMeta` may answer one more optional key, `unitField`: a `number` field's `unitConfig.unitField`, under `unitMode: 'record'` only. `AnalyticsServicePlugin` relays it for a `number` under `unitMode: 'record'` and for nothing else. A host that does not answer it gets no record-unit judgment from the cube door. The precedent is a35fc66, `homeAmountField` on the same answer. The errors' `unitField` member is not part of the widening: no REST envelope carries it. - Two ADR anchors (new files only) and a patch changeset for `@objectstack/objectql` and `@objectstack/service-analytics`. **The raw-aggregate set, as built** (ADR-0158 Open item 12, the aggregate half; carried to the ADR text by the weekly ADR revisions card #36086, whose row lands after this PR merges): `sum`, `avg`, `min` and `max` are raw. `count` reads no quantity and `count_distinct` adds nothing, so neither is judged. Grouping by the quantity's own `unitField` admits the aggregate. A `fixed`-mode quantity and a `number` field with no `unitConfig` pass unchanged. No new error code: `INVALID_FIELD` and `INVALID_METADATA`, as ADR-0144 assigned for currency. ## Why ADR-0158 U7 R1: "a build-time refusal of a raw aggregate over a `record`-mode quantity unless it groups by that quantity's unit field (mirrors ADR-0144 D6)". L3: "In R1, a `summary` over `record`-mode child quantities is therefore always refused, as every such currency roll-up was before ADR-0144's D6 amendment". ## Tests Read first (by risk): 1. `packages/objectql/src/engine-delete-and-aggregate.ts`: the one new call, after the record-currency door. 2. `packages/objectql/src/registry-object-registration.ts`: the summary refusal beside the currency one. 3. `packages/services/service-analytics/src/analytics-service.ts`: the four call sites and the extracted `groupedColumnOf`. Two-minute check: `pnpm --filter @objectstack/objectql exec vitest run src/record-unit-aggregate-door.test.ts` shows 8 passed; `pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/record-unit-analytics.test.ts` shows 23 passed. - `packages/objectql/src/record-unit-aggregate-door.test.ts` (8): ungrouped `sum`/`avg`/`min`/`max` refused with code, status, field, unit field and the remedy inside the first 500 characters; grouped by another field refused; grouped by the unit field answers `KGM [15, 7.5, 5, 10]`, `LBR [10, 10, 10, 10]`; `count` 3, `count_distinct` 2, fixed-unit `sum` 11 and `max` 6, plain `sum` 6 and `avg` 2; the summary refused at both registration orders and over itself, naming roll-up, quantity and unit field; `count` over the quantity, `sum` over the fixed quantity and the plain number register in both orders and roll up 2, 9 and 5. - `packages/services/service-analytics/src/__tests__/record-unit-analytics.test.ts` (23, SqlDriver over better-sqlite3, both strategies): grouped values per unit; a totals grouping keeping the unit; refusals (another dimension only, each raw aggregate ungrouped, a grand total) with no read of the object; `count`, `count_distinct`, fixed-unit and plain measures served ungrouped with values; the cube face; the inferred cube refused and then served grouped; the draft preview refused and served grouped. <details><summary>Before and after, measured on a real engine (ObjectQL over SqlDriver / better-sqlite3)</summary> The four wiring files restored to `origin/main` for the before run; the probe is a throwaway file, not committed. | Probe | Before | After | |---|---|---| | `aggregate sum(qty)`, rows 10 KGM and 10 LBR | `20` | `INVALID_FIELD` / 400 | | `avg` / `min` / `max` | `10` / `10` / `10` | `INVALID_FIELD` / 400 each | | `count(qty)` | `2` | `2` | | `sum(qty)` grouped by `unit_code` | KGM 10, LBR 10 | KGM 10, LBR 10 | | `summary` sum over child rows 10 KGM, 10 LBR | registered, stored `20` | `INVALID_METADATA` / 422 at registration | | dataset `total` ungrouped | `20` | `INVALID_FIELD` / 400 | | dataset `total` by unit | KGM 10, LBR 10 | KGM 10, LBR 10 | | inferred cube `qty_sum` | `20` | `INVALID_FIELD` / 400 | </details> <details><summary>Ablation, one per door (committed first; scripts/ablation-replace.mjs; restore proven by blob equality)</summary> The suites resolve `@objectstack/objectql` and the service to `src` (the service-analytics vitest alias), so no `dist` rebuild sits between mutation and run. - Aggregate door: delete the `assertRecordUnitAggregatesGrouped(...)` call in `engine-delete-and-aggregate.ts`: 2 failed / 6 passed (the two refusal pins); restored, blob `691b2595e09a` == HEAD. - Summary door: delete `if (recordUnitSummary) return { refusal: recordUnitSummary };`: 3 failed / 5 passed (both orders and the self roll-up); restored, blob `fa4c14cb923c` == HEAD. - Cube door: make the unit arm skip every measure (`if (unitField === undefined || unitField !== undefined) continue;`): 17 failed / 6 passed (every refusal pin on both strategies, the cube face, the inferred cube and the draft preview); restored, blob `dad0d024e94b` == HEAD. </details> ## Acceptance notes - **Dataset compile, mirrored as currency does it.** Currency's `DATASET_INVALID` compile guards (`measure-currency-coherence.ts`) judge a measure's `currency` key and derived measures across currencies; a dataset that declares an ungrouped `sum` over a record-mode amount compiles, and the refusal rides each query selection through the cube door. Units mirror that: a dataset measure over a record-mode quantity compiles, and every selection that does not group by the unit field is refused `INVALID_FIELD`. A dataset measure has no `unit` key, so guard 1 has no unit twin. A derived measure combining a record-mode quantity with another quantity is not a raw aggregate and is not judged here (no ruling covers it). - **Two-segment `unitField`.** The object door refuses a dotted `unitField`, so no quantity follows a parent's unit and this door has no path arm (the currency door's `MASTER_DETAIL.CODE` arm has no twin). - **Repo-wide sweep.** No pin asserted a raw total over a `record`-mode quantity (grep of `unitMode: 'record'` repo-wide: no aggregate, `summary` or dataset measure over one outside this PR's own tests). No `examples/**`, `packages/**/fixtures` or `packages/**/__fixtures__` file declares `unitConfig`, so no example build is broken by the refusal. - **Declaration basis.** `unitConfig` is not in any released CHANGELOG (`packages/spec/CHANGELOG.md` and `packages/objectql/CHANGELOG.md` at 18.6.0 carry no `unitConfig`; its changeset `35489-unit-config.md` is pending), so the refusal narrows nothing published: `Metadata-protocol: none`. The one published-surface change is the optional `sourceFieldMeta` key above, so `Clause-②: yes (widening)`. - **`unitField` on the wire, measured.** A throwaway probe in `packages/rest` (not committed) threw each door's real error into the real REST writers. `/data` (`mapDataError`): 400, body keys `error`, `code`, `field`, `object`; the INVALID_FIELD arm copies `field` and `object` only (`packages/types/src/data-error-classification.ts` lines 1308 and 1309). `POST /analytics/dataset/query`: 400, body keys `code`, `message`; the declared-4xx arm writes `code`, `message` and an optional `userMessage` only (`packages/rest/src/analytics-routes.ts` line 926). The same holds for the currency twin's `member`, `field` and `object` on the analytics door. - UI whole-set summary over a record-mode quantity: #36082 - Dataset compile guard (both families) and derived-measure twin: #36083 - ADR-0158 amendment with the raw-aggregate set (the card's last Done-when clause): row on #36086, prerequisite this PR merged. ## Verification Suites, typecheck and gate readings at head `f01bd3db4e`, on `origin/main` `8145424b53`. Head `948f998319` adds a changeset-only commit (the widening declaration), re-checked below. Changed lines: 1043 (+1032 / -11, 11 files), measured by `dispatch-gates`. <details><summary>Suites and typecheck</summary> - `pnpm --filter @objectstack/objectql test`: Test Files 625 passed (625), Tests 14223 passed (14223); exit 0. - `pnpm --filter @objectstack/service-analytics test`: Test Files 222 passed (222), Tests 5674 passed, 345 skipped (6019); exit 0. - `pnpm --filter @objectstack/objectql run typecheck` (tsc plus `check:test-typecheck`, OK, debt unchanged) and `pnpm --filter @objectstack/service-analytics run typecheck`: lock VERDICT command-exit 0. Both new test files are in the compiled program (`--listFiles`). - eslint over the eight changed source and test files: exit 0 (the repo-wide `pnpm lint` is CI's). </details> <details><summary>Derived gate families</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 84 families, each run with its exit captured before any pipe. 83 exit 0 on the first pass; `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, no workspace dist). After `turbo run build --filter='./packages/**'` (81/81 tasks), its re-run exits 0: 124 entry points across 72 packages load. - `--ran` reconciliation over the re-run record: "84 derived, 84 run, 0 NOT-MEASURED, 0 UNRUN". - At `948f998319`: `node scripts/check-changeset-no-major.mjs --base origin/main --event` (this body as the payload): exit 0, "clause-② `yes (widening)` and metadata-protocol `none` … a non-protocol change at `patch`"; `check-empty-changeset` and `check-adr-0087-registration` exit 0. - `pnpm check:adr-anchors`: exit 0 with the two new anchors. </details> CI carries the full farm, `test:repo` (`Test Core`) and the dogfood battery (no `!` in the title and no `(narrowing)` arm, so no local full dogfood run is owed). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (CI). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibvMi1U7R2kBd3JbTPu --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 886ba45 commit c59ee99

11 files changed

Lines changed: 1033 additions & 11 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/service-analytics': patch
4+
---
5+
6+
feat(units): a raw total over a `record`-mode quantity is refused unless it groups by the quantity's unit field
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
ADR-0158 U7 R1, mirroring ADR-0144 D6 and its record-currency doors. A `number` field declaring `unitConfig: { unitMode: 'record', unitField }` holds a bare quantity whose unit is each row's code in `unitField`. Before this change, `sum` over a row of 10 KGM and a row of 10 LBR answered `20`, and a `summary` roll-up over such child rows stored `20`.
12+
13+
- **The engine aggregate** (`@objectstack/objectql`, `ObjectQL.aggregate`): `sum`, `avg`, `min` or `max` over such a quantity is refused `INVALID_FIELD` / 400 before any driver is asked, unless the query's `groupBy` includes the quantity's `unitField`. The message names the quantity, its unit field and the grouping to add.
14+
- **A `summary` roll-up** (`@objectstack/objectql`, object registration): a `summary` that rolls up `sum`, `avg`, `min` or `max` of such a child quantity is refused `INVALID_METADATA` / 422, whichever object registers second. In R1 every such roll-up is refused: a child quantity cannot follow its parent's unit yet. Roll up with `function: 'count'`, or total the quantity with an aggregate grouped by its unit field.
15+
- **Analytics** (`@objectstack/service-analytics`): a dataset or cube measure of type `sum`, `avg`, `min` or `max` over such a quantity is refused `INVALID_FIELD` / 400 unless the query has a dimension over the unit field, on every cube path (declared, inferred, augmented), every `totals` grouping and the draft preview.
16+
- **The widening.** `AnalyticsServiceConfig.sourceFieldMeta` may answer one more optional key, `unitField`: a `number` field's `unitConfig.unitField`, under `unitMode: 'record'` only. `AnalyticsServicePlugin` relays it for a `number` under `unitMode: 'record'` and for nothing else. A host that does not answer it gets no record-unit judgment from the cube door; the engine aggregate door still refuses the same query on the ObjectQL strategy.
17+
18+
Not judged: `count` and `count_distinct`, a `fixed`-mode quantity, and a `number` field with no `unitConfig`. No new error code.

‎packages/objectql/src/engine-delete-and-aggregate.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ import { assertNoInternalFieldEvaluated, rejectInternalFieldEvaluation } from '.
6464
import { assertGroupByNamesNoJsonStoredField } from './group-by-structured-json-door.js';
6565
import { assertAggregationFieldTypesAccepted } from './aggregate-field-type-door.js';
6666
import { ROLLUP_AGGREGATE_OPTION, assertRecordCurrencyAggregatesGrouped } from './record-currency-aggregate-door.js';
67+
import { assertRecordUnitAggregatesGrouped } from './record-unit-aggregate-door.js';
6768
import {
6869
assertAggregatedColumnsAreDistinct,
6970
assertDateBucketTargetsAreTemporal,
@@ -1096,6 +1097,10 @@ export class DeleteAndAggregateFacet {
10961097
object, this._registry.getObject(object), query.groupBy, query.aggregations,
10971098
(options as Record<symbol, unknown> | undefined)?.[ROLLUP_AGGREGATE_OPTION],
10981099
);
1100+
// [ADR-0158 U7 R1] …and the same over a `record`-mode quantity that
1101+
// does not group by its unit field: 10 KGM and 10 LBR summed to 20. No
1102+
// roll-up channel: R1 admits no roll-up over such a quantity (L3).
1103+
assertRecordUnitAggregatesGrouped(object, this._registry.getObject(object), query.groupBy, query.aggregations);
10991104
// [#25818] …and the two shapes that answered a plausible wrong table: a
11001105
// `dateGranularity` over a field declared neither a date nor a datetime
11011106
// (every row in one null bucket), and two columns of the aggregated row
Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// [ADR-0158 U7 R1, mirroring ADR-0144 D6] The two record-unit doors, through
4+
// the engine and the registry, beside their currency twins
5+
// (`record-currency-guards.test.ts`):
6+
//
7+
// - `sum` / `avg` / `min` / `max` over a `record`-mode quantity is refused
8+
// `INVALID_FIELD` / 400 unless the query groups by its unit field;
9+
// - a `summary` roll-up reading one is refused `INVALID_METADATA` / 422 at
10+
// registration, whichever end registers second (L3: always refused in R1).
11+
//
12+
// Each admitted shape asserts its value: grouped by the unit field, a `fixed`
13+
// quantity, a plain number, `count` and `count_distinct`. Every refusal here
14+
// precedes the driver, so the driver is a rows-shaped double whose `find` is
15+
// the engine's own in-memory reading of a driver query; the analytics faces
16+
// over SqlDriver are service-analytics' `record-unit-analytics.test.ts`.
17+
18+
import { describe, it, expect, beforeEach } from 'vitest';
19+
import type { EngineAggregateOptions } from '@objectstack/spec/data';
20+
import { ObjectQL } from './engine.js';
21+
import { applyDriverQueryInMemory } from './driver-query-in-memory.js';
22+
23+
function makeDriver() {
24+
const stores = new Map<string, Map<string, Record<string, unknown>>>();
25+
const storeFor = (o: string) => {
26+
let s = stores.get(o);
27+
if (!s) { s = new Map(); stores.set(o, s); }
28+
return s;
29+
};
30+
let n = 0;
31+
const select = (object: string, ast: any) =>
32+
applyDriverQueryInMemory(Array.from(storeFor(object).values()), {
33+
where: ast?.where, orderBy: ast?.orderBy, limit: ast?.limit, offset: ast?.offset,
34+
});
35+
const driver: any = {
36+
name: 'memory', version: '0.0.0', supports: {},
37+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
38+
async find(object: string, ast: any) { return select(object, ast).map((r) => ({ ...r })); },
39+
async findOne(object: string, ast: any) {
40+
const [hit] = select(object, { ...ast, limit: 1 });
41+
return hit ? { ...hit } : null;
42+
},
43+
async create(object: string, data: Record<string, unknown>) {
44+
n += 1;
45+
const id = (data.id as string) ?? `r_${n}`;
46+
const row = { ...data, id };
47+
storeFor(object).set(id, row);
48+
return { ...row };
49+
},
50+
async update(object: string, id: string, data: Record<string, unknown>) {
51+
const s = storeFor(object);
52+
const row = { ...s.get(id), ...data, id };
53+
s.set(id, row);
54+
return { ...row };
55+
},
56+
async updateMany() { return 0; },
57+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
58+
async deleteMany() { return 0; },
59+
async count(object: string, ast: any) { return select(object, ast).length; },
60+
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
61+
return Promise.all(rows.map((r) => this.create(object, r)));
62+
},
63+
async bulkUpdate() { return []; }, async bulkDelete() {},
64+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
65+
async commit() {}, async rollback() {},
66+
};
67+
return { driver, storeFor };
68+
}
69+
70+
type Thrown = (Error & {
71+
code?: string; status?: number; httpStatus?: number; field?: string; fields?: string[]; unitField?: string;
72+
object?: string; param?: string; objectName?: string; fieldName?: string; childObject?: string; childField?: string;
73+
}) | null;
74+
75+
const refusalOf = async (p: Promise<unknown> | (() => unknown)): Promise<Thrown> => {
76+
try {
77+
await (typeof p === 'function' ? p() : p);
78+
return null;
79+
} catch (e) {
80+
return e as Thrown;
81+
}
82+
};
83+
const envelopeOf = (err: Thrown) => ({ code: err?.code, status: err?.status, httpStatus: err?.httpStatus });
84+
85+
const INVALID_FIELD = { code: 'INVALID_FIELD', status: 400, httpStatus: 400 };
86+
const INVALID_METADATA = { code: 'INVALID_METADATA', status: 422, httpStatus: 422 };
87+
const RAW = ['sum', 'avg', 'min', 'max'] as const;
88+
89+
/** Typed at the call, never asserted (`check:query-options-erasure`). */
90+
const aggregateQuery = (query: EngineAggregateOptions): EngineAggregateOptions => query;
91+
const CTX = { context: { isSystem: true, tenantId: 'org_a' } } as const;
92+
93+
const RECORD = { unitMode: 'record', unitField: 'unit_code' } as const;
94+
95+
const UOM_STOCK = {
96+
name: 'uom_stock',
97+
fields: {
98+
title: { type: 'text' },
99+
unit_code: { type: 'text' },
100+
qty: { type: 'number', unitConfig: RECORD },
101+
net_kg: { type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } },
102+
plain: { type: 'number' },
103+
},
104+
};
105+
106+
async function bootEngine() {
107+
const engine = new ObjectQL();
108+
const d = makeDriver();
109+
engine.registerDriver(d.driver, true);
110+
await engine.init();
111+
return { engine, storeFor: d.storeFor };
112+
}
113+
114+
describe('a raw aggregate over a record-mode quantity groups by its unit field (ADR-0158 U7 R1)', () => {
115+
let engine: ObjectQL;
116+
117+
beforeEach(async () => {
118+
({ engine } = await bootEngine());
119+
engine.registry.registerObject(UOM_STOCK as any);
120+
await engine.insert('uom_stock', { title: 's1', unit_code: 'KGM', qty: 10, net_kg: 4, plain: 1 }, CTX as never);
121+
await engine.insert('uom_stock', { title: 's2', unit_code: 'LBR', qty: 10, net_kg: 6, plain: 2 }, CTX as never);
122+
await engine.insert('uom_stock', { title: 's3', unit_code: 'KGM', qty: 5, net_kg: 1, plain: 3 }, CTX as never);
123+
});
124+
125+
it('sum / avg / min / max ungrouped is refused INVALID_FIELD / 400, naming the quantity, its unit field and the grouping', async () => {
126+
for (const fn of RAW) {
127+
const err = await refusalOf(engine.aggregate('uom_stock', aggregateQuery({
128+
aggregations: [{ function: fn, field: 'qty', alias: 'v' }],
129+
})));
130+
expect(envelopeOf(err), fn).toEqual(INVALID_FIELD);
131+
expect(err?.field).toBe('qty');
132+
expect(err?.unitField).toBe('unit_code');
133+
expect(err?.object).toBe('uom_stock');
134+
expect(err?.param).toBe('aggregations');
135+
expect(err?.message).toContain("'qty', a quantity in each record's own unit");
136+
expect(err?.message).toContain("does not group by 'unit_code'");
137+
expect(err?.message.indexOf("Add 'unit_code' to groupBy")).toBeGreaterThan(-1);
138+
expect(err?.message.indexOf("Add 'unit_code' to groupBy")).toBeLessThan(500);
139+
}
140+
});
141+
142+
it('grouped by a field other than the unit field is still refused, every ungrouped quantity named', async () => {
143+
const err = await refusalOf(engine.aggregate('uom_stock', aggregateQuery({
144+
groupBy: ['title'],
145+
aggregations: [
146+
{ function: 'sum', field: 'qty', alias: 'a' },
147+
{ function: 'max', field: 'qty', alias: 'b' },
148+
],
149+
})));
150+
expect(envelopeOf(err)).toEqual(INVALID_FIELD);
151+
expect(err?.fields).toEqual(['qty', 'qty']);
152+
});
153+
154+
it('grouped by the unit field answers one correct value per unit, for each raw aggregate', async () => {
155+
const groupings: Array<EngineAggregateOptions['groupBy']> = [['unit_code'], [{ field: 'unit_code' }]];
156+
for (const groupBy of groupings) {
157+
const rows = await engine.aggregate('uom_stock', aggregateQuery({
158+
groupBy,
159+
aggregations: [
160+
{ function: 'sum', field: 'qty', alias: 'total' },
161+
{ function: 'avg', field: 'qty', alias: 'mean' },
162+
{ function: 'min', field: 'qty', alias: 'least' },
163+
{ function: 'max', field: 'qty', alias: 'most' },
164+
],
165+
}));
166+
const byUnit = Object.fromEntries(rows.map((r: any) => [r.unit_code, [r.total, r.mean, r.least, r.most]]));
167+
expect(byUnit).toEqual({ KGM: [15, 7.5, 5, 10], LBR: [10, 10, 10, 10] });
168+
}
169+
});
170+
171+
it('count and count_distinct over the quantity, a fixed-unit quantity and a plain number are not judged, and answer their values', async () => {
172+
const rows = await engine.aggregate('uom_stock', aggregateQuery({
173+
aggregations: [
174+
{ function: 'count', field: 'qty', alias: 'n' },
175+
{ function: 'count_distinct', field: 'qty', alias: 'distinct' },
176+
{ function: 'sum', field: 'net_kg', alias: 'kg' },
177+
{ function: 'max', field: 'net_kg', alias: 'kg_max' },
178+
{ function: 'sum', field: 'plain', alias: 'p' },
179+
{ function: 'avg', field: 'plain', alias: 'p_avg' },
180+
],
181+
}));
182+
expect(rows).toHaveLength(1);
183+
expect(rows[0]).toMatchObject({ n: 3, distinct: 2, kg: 11, kg_max: 6, p: 6, p_avg: 2 });
184+
});
185+
});
186+
187+
describe('a summary roll-up over a record-mode quantity is refused at registration (ADR-0158 U7 R1, L3)', () => {
188+
const LINE = {
189+
name: 'uom_line',
190+
fields: {
191+
unit_code: { type: 'text' },
192+
qty: { type: 'number', unitConfig: RECORD },
193+
net_kg: { type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } },
194+
plain: { type: 'number' },
195+
shipment: { type: 'master_detail', reference: 'uom_shipment' },
196+
},
197+
};
198+
const parentWith = (fn: string, field = 'qty') => ({
199+
name: 'uom_shipment',
200+
fields: {
201+
title: { type: 'text' },
202+
rolled: { type: 'summary', summaryOperations: { object: 'uom_line', field, function: fn } },
203+
},
204+
});
205+
206+
it('the parent registering after the child is refused, naming the roll-up, the quantity and its unit field', async () => {
207+
for (const fn of RAW) {
208+
const { engine } = await bootEngine();
209+
engine.registry.registerObject(LINE as any);
210+
const err = await refusalOf(() => engine.registry.registerObject(parentWith(fn) as any));
211+
expect(envelopeOf(err), fn).toEqual(INVALID_METADATA);
212+
expect(err?.name).toBe('RecordUnitSummaryRefusedError');
213+
expect(err?.objectName).toBe('uom_shipment');
214+
expect(err?.fieldName).toBe('rolled');
215+
expect(err?.childObject).toBe('uom_line');
216+
expect(err?.childField).toBe('qty');
217+
expect(err?.unitField).toBe('unit_code');
218+
expect(err?.message).toContain(`rolls up ${fn}(uom_line.qty)`);
219+
expect(err?.message).toContain("the unit code in 'unit_code'");
220+
expect(err?.message).toContain("groups by 'unit_code'");
221+
expect(engine.registry.getObject('uom_shipment')).toBeUndefined();
222+
}
223+
});
224+
225+
it('the child registering after the parent is refused, naming the same roll-up', async () => {
226+
const { engine } = await bootEngine();
227+
engine.registry.registerObject(parentWith('sum') as any);
228+
const err = await refusalOf(() => engine.registry.registerObject(LINE as any));
229+
expect(envelopeOf(err)).toEqual(INVALID_METADATA);
230+
expect(err?.name).toBe('RecordUnitSummaryRefusedError');
231+
expect(err?.objectName).toBe('uom_shipment');
232+
expect(err?.message).toContain('rolls up sum(uom_line.qty)');
233+
expect(engine.registry.getObject('uom_line')).toBeUndefined();
234+
});
235+
236+
it('a roll-up over the object itself is refused', async () => {
237+
const { engine } = await bootEngine();
238+
const SELF = {
239+
name: 'uom_self',
240+
fields: {
241+
unit_code: { type: 'text' },
242+
qty: { type: 'number', unitConfig: RECORD },
243+
parent: { type: 'lookup', reference: 'uom_self' },
244+
rolled: { type: 'summary', summaryOperations: { object: 'uom_self', field: 'qty', function: 'sum' } },
245+
},
246+
};
247+
const err = await refusalOf(() => engine.registry.registerObject(SELF as any));
248+
expect(envelopeOf(err)).toEqual(INVALID_METADATA);
249+
expect(err?.name).toBe('RecordUnitSummaryRefusedError');
250+
expect(engine.registry.getObject('uom_self')).toBeUndefined();
251+
});
252+
253+
it('a count roll-up over the quantity, and sums over a fixed-unit quantity and a plain number, register and total their rows', async () => {
254+
for (const [fn, field, expected] of [['count', 'qty', 2], ['sum', 'net_kg', 9], ['sum', 'plain', 5]] as const) {
255+
for (const parentFirst of [true, false]) {
256+
const { engine, storeFor } = await bootEngine();
257+
const order = parentFirst ? [parentWith(fn, field), LINE] : [LINE, parentWith(fn, field)];
258+
for (const o of order) engine.registry.registerObject(o as any);
259+
expect(engine.registry.getObject('uom_shipment'), `${fn}(${field})`).toBeDefined();
260+
await engine.insert('uom_shipment', { id: 'sh1', title: 'one' }, CTX as never);
261+
await engine.insert('uom_line', { shipment: 'sh1', unit_code: 'KGM', qty: 10, net_kg: 4, plain: 2 }, CTX as never);
262+
await engine.insert('uom_line', { shipment: 'sh1', unit_code: 'LBR', qty: 10, net_kg: 5, plain: 3 }, CTX as never);
263+
expect(storeFor('uom_shipment').get('sh1')?.rolled, `${fn}(${field}) parentFirst=${parentFirst}`).toBe(expected);
264+
}
265+
}
266+
});
267+
});

0 commit comments

Comments
 (0)