();
+ for (const item of reportMeasureNames(report)) {
+ const listed = childOfType(from, TYPE_MEASURE, item.slice(item.lastIndexOf(CHILD_REF_SEPARATOR) + 1));
+ if (!(listed instanceof MetaMeasure)) continue;
+ for (const m of aggregatesRead(listed, from)) {
+ if (!(m instanceof MetaMeasure) || m.subType !== MEASURE_SUBTYPE_AGGREGATE || checked.has(m)) continue;
+ checked.add(m);
+ const agg = m.agg();
+ if (agg !== AGG_SUM && agg !== AGG_AVG && agg !== AGG_MIN && agg !== AGG_MAX) continue;
+ const of = m.ofColumns()[0] ?? "";
+ const parts = splitDotted(of);
+ if (parts?.path.length !== 2) continue;
+ const [fieldName, memberName] = parts.path as [string, string];
+ const field = fieldOf(from, fieldName);
+ const valueObject = field !== undefined && isFlattenedField(field) ? refTargetOf(field) : undefined;
+ const member = valueObject === undefined ? undefined : fieldOf(valueObject, memberName);
+ if (valueObject === undefined || member === undefined || !NUMERIC_FIELD_SUBTYPES.includes(member.subType)) continue;
+ // ADR-0039: resolving — a unit member the value object inherits qualifies its amounts too.
+ for (const unit of valueObject.children().filter((c) => c.type === TYPE_FIELD)) {
+ if (NUMERIC_FIELD_SUBTYPES.includes(unit.subType) || grouped.has(`${fieldName}.${unit.name}`)) continue;
+ err(
+ `: measure '${m.name}' takes @agg '${agg}' of '${of}', a member of value object ` +
+ `'${valueObject.resolutionKey()}', but the report does not group by its member '${unit.name}', so ` +
+ `amounts with different '${unit.name}' values would be combined. List an attribute dimension of ` +
+ `@from whose @of is '${parts.owner}.${fieldName}.${unit.name}'.`,
+ );
+ }
+ }
+ }
+}
+
+/**
+ * The measures `listed` aggregates through: itself for a measure.aggregate, its two operands for a
+ * ratio, and for a measure.derived each measure its @expr names (a ratio there read through its
+ * operands). Unresolved names are left out; the member rules report them.
+ */
+function aggregatesRead(listed: MetaMeasure, from: MetaData): MetaData[] {
+ const measure = (n: string | undefined): MetaData | undefined =>
+ n === undefined ? undefined : childOfType(from, TYPE_MEASURE, n);
+ const operandsOf = (m: MetaData | undefined): (MetaData | undefined)[] =>
+ m instanceof MetaMeasure && m.isRatio() ? [measure(m.numerator()), measure(m.denominator())] : [m];
+ if (listed.isDerived()) {
+ const expr = listed.expr();
+ return (expr === undefined ? [] : derivedExprFields(expr))
+ .flatMap((n) => operandsOf(measure(n)))
+ .filter((m): m is MetaData => m !== undefined);
+ }
+ return operandsOf(listed).filter((m): m is MetaData => m !== undefined);
+}
+
+/**
+ * R13 — a measure.derived that reads an attribute dimension reads that dimension's value for each
+ * group, so the report must list the dimension in @dimensions. A name that is also a measure is
+ * M11's to report.
+ */
+function checkDerivedDimensions(report: MetaData, from: MetaData, err: (message: string) => void): void {
+ const listedDims = new Set(reportDimensionItems(report).map((i) => i.name));
+ for (const item of reportMeasureNames(report)) {
+ const m = childOfType(from, TYPE_MEASURE, item.slice(item.lastIndexOf(CHILD_REF_SEPARATOR) + 1));
+ const expr = m instanceof MetaMeasure && m.isDerived() ? m.expr() : undefined;
+ if (expr === undefined) continue;
+ for (const name of derivedExprFields(expr)) {
+ if (listedDims.has(name) || childOfType(from, TYPE_MEASURE, name) !== undefined) continue;
+ if (childOfType(from, TYPE_DIMENSION, name) === undefined) continue;
+ err(
+ `: measure '${m!.name}' reads dimension '${name}', which @dimensions does not list. A derived measure ` +
+ `reads a dimension's value for each group, so the report must group by it.`,
+ );
+ }
+ }
+}
+
/**
* R3 for one `@measures` item (bare `name` or dotted `Entity.name`). Returns
* the measure's name when it is a measure of @from (for R6), else reports
diff --git a/server/typescript/packages/metadata/test/report-describe.test.ts b/server/typescript/packages/metadata/test/report-describe.test.ts
index 6244e59a2..e259e2c2d 100644
--- a/server/typescript/packages/metadata/test/report-describe.test.ts
+++ b/server/typescript/packages/metadata/test/report-describe.test.ts
@@ -248,3 +248,28 @@ describe("the attrs a describer reads", () => {
}
});
});
+
+describe("describing a measure.derived (FR-044 R13)", () => {
+ test("the arithmetic in words, parenthesised below the top, and null on a zero divisor", async () => {
+ const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({
+ "metadata.root": { package: "acme::time", children: [
+ { "object.entity": { name: "Entry", children: [
+ { "source.rdb": { "@table": "entries" } },
+ { "field.long": { name: "id" } },
+ { "field.decimal": { name: "hours" } },
+ { "identity.primary": { name: "id", "@fields": ["id"] } },
+ { "measure.aggregate": { name: "total", "@agg": "sum", "@of": "Entry.hours" } },
+ { "measure.aggregate": { name: "entries", "@agg": "count", "@of": "Entry.id" } },
+ { "measure.derived": { name: "perEntry", "@expr": { fn: "divide", args: [{ field: "total" }, { fn: "add", args: [{ field: "entries" }, { value: 1 }] }] } } },
+ { "measure.derived": { name: "doubled", "@expr": { fn: "multiply", args: [{ field: "total" }, { value: 2 }] } } },
+ ] } },
+ ] },
+ }))]);
+ expect(errors).toEqual([]);
+ const entity = root.objects().find((o) => o.name === "Entry")!;
+ const m = (name: string) => entity.children().find((c) => c.type === "measure" && c.name === name)!;
+ expect(describeMeasure(m("perEntry"))).toBe("`total` ÷ (`entries` + `1`), null when a divisor is 0");
+ expect(describeMeasure(m("doubled"))).toBe("`total` × `2`");
+ expect(reportingDescribedAttrs(m("doubled"))).toEqual(["expr"]);
+ });
+});
diff --git a/server/typescript/packages/metadata/test/report-shape.test.ts b/server/typescript/packages/metadata/test/report-shape.test.ts
index c46c2e772..52ac3b5d3 100644
--- a/server/typescript/packages/metadata/test/report-shape.test.ts
+++ b/server/typescript/packages/metadata/test/report-shape.test.ts
@@ -719,3 +719,25 @@ describe("reportShape: @agg any / all without @of (R6)", () => {
]);
});
});
+
+describe("reportShape: measure.derived (FR-044 R13)", () => {
+ test("a derived measure is a nullable decimal with no type source, whatever its operands", async () => {
+ const fixture = join(REPO_ROOT, "fixtures", "conformance", "reporting-derived-measures", "input", "meta.studio.json");
+ const result = await loadUris([pathToFileURL(fixture).href]);
+ expect(result.errors).toEqual([]);
+ const rows = (name: string) =>
+ reportShape(report(result.root, name), result.root).fields.map(
+ (f) => `${f.name} ${f.subType} ${f.required} ${f.typeSource ? `${f.typeSource.parent!.name}.${f.typeSource.name}` : "-"}`,
+ );
+ expect(rows("MemberUtilization")).toEqual([
+ "memberId long false Member.id", "memberName string true Member.firstName",
+ "weeklyCapacityHours decimal true Member.weeklyCapacityHours", "workedOnMonth date true -",
+ "totalHours decimal true -", "billableHours decimal true -", "capacityHours decimal false -",
+ "utilization decimal false -", "nonBillableHours decimal false -", "billableSharePct decimal false -",
+ ]);
+ expect(rows("ProjectBurn")).toEqual([
+ "projectId long false Project.id", "projectBudget decimal false Project.budget", "cost decimal false -",
+ "budgetBurn decimal false -",
+ ]);
+ });
+});
diff --git a/server/typescript/packages/metadata/test/reporting-registry.test.ts b/server/typescript/packages/metadata/test/reporting-registry.test.ts
index 5deaeca98..b4d666775 100644
--- a/server/typescript/packages/metadata/test/reporting-registry.test.ts
+++ b/server/typescript/packages/metadata/test/reporting-registry.test.ts
@@ -3,7 +3,8 @@ import { composeRegistry, coreProviders } from "../src/index.js";
import {
TYPE_DIMENSION, TYPE_MEASURE, TYPE_SEGMENT,
DIMENSION_SUBTYPE_ATTRIBUTE, DIMENSION_SUBTYPE_TIME,
- MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO, SEGMENT_SUBTYPE_FILTER,
+ MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO, MEASURE_SUBTYPE_DERIVED, SEGMENT_SUBTYPE_FILTER,
+ REPORTING_ATTR_EXPR,
TIME_GRAINS, MEASURE_AGGS,
} from "../src/core/reporting/reporting-constants.js";
import { TYPE_OBJECT } from "../src/shared/base-types.js";
@@ -22,8 +23,13 @@ describe("FR-044 reporting vocabulary registration", () => {
}
});
- test("does not register measure.derived (waits for FR-037 R5)", () => {
- expect(registry.find(TYPE_MEASURE, "derived")).toBeUndefined();
+ test("registers measure.derived with a required expression @expr and no @default (R13)", () => {
+ const derived = registry.find(TYPE_MEASURE, MEASURE_SUBTYPE_DERIVED)!;
+ expect(derived).toBeDefined();
+ const expr = derived.attributes.find((a) => a.name === REPORTING_ATTR_EXPR);
+ expect(expr?.valueType).toBe("expression");
+ expect(expr?.required).toBe(true);
+ expect(derived.attributes.find((a) => a.name === "default")).toBeUndefined();
});
test("object.report registers an optional string @spine (R8)", () => {
diff --git a/site-reference/index.html b/site-reference/index.html
index 9ef6fbf71..79a602afa 100644
--- a/site-reference/index.html
+++ b/site-reference/index.html
@@ -256,6 +256,11 @@
| types/measure.md#measureaggregate |
+measure.derived |
+A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension. |
+types/measure.md#measurederived |
+
+
measure.ratio |
A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null. |
types/measure.md#measureratio |
diff --git a/site-reference/types/dimension.html b/site-reference/types/dimension.html
index 3bb94fc6f..e033e0e11 100644
--- a/site-reference/types/dimension.html
+++ b/site-reference/types/dimension.html
@@ -73,7 +73,7 @@ dimension.attribute
|
|
— |
-Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). |
+Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own. |
@via |
@@ -119,7 +119,7 @@ dimension.time
|
|
— |
-Dotted Entity.field reference naming the date or timestamp column. |
+Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object. |
@via |
diff --git a/site-reference/types/measure.html b/site-reference/types/measure.html
index 70e4064c4..08479ad7a 100644
--- a/site-reference/types/measure.html
+++ b/site-reference/types/measure.html
@@ -109,7 +109,7 @@ measure.aggregate
|
|
— |
-Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. |
+Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. |
@segment |
@@ -123,6 +123,34 @@ measure.aggregate
Allowed children
No structural children.
+measure.derived
+A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.
+When to use: A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).
+Attributes
+
+
+
+| Attribute |
+Type |
+Required |
+Default |
+Allowed values |
+Provider |
+Description |
+
+
+
+@expr |
+expression |
+yes |
+ |
+ |
+— |
+The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands. |
+
+
+Allowed children
+No structural children.
measure.ratio
A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null.
When to use: Averages per unit that are not a plain avg: average days engaged per starter.
diff --git a/spec/metamodel/reporting.json b/spec/metamodel/reporting.json
index 98c0bd24f..adbe87f9e 100644
--- a/spec/metamodel/reporting.json
+++ b/spec/metamodel/reporting.json
@@ -5,14 +5,14 @@
"description": "A named group-by attribute of the entity that declares it (FR-044). Groups report rows by a column value as-is. @of names Entity.field: the owning entity, or the @via terminal. @via may follow only to-one hops, so grouping by a related row's column can never multiply the measured rows.",
"whenToUse": "A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via)." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference." }
] },
{ "type": "dimension", "subType": "time",
"description": "A named time dimension (FR-044): groups report rows by a date or timestamp column truncated to a grain. @of names a field.date or field.timestamp. Weeks start on Monday (ISO-8601) in every lowering. A report names it as 'dimension:grain' and the derived report field is (e.g. purchasedAtDay).",
"whenToUse": "Per-day, per-week or per-month series on a dashboard.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path, as on dimension.attribute." },
{ "type": "attr", "subType": "string", "name": "grains", "isArray": true, "min": 1, "max": 1, "allowedValues": ["hour", "day", "week", "month", "quarter", "year"], "description": "The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date." }
] },
@@ -21,7 +21,7 @@
"whenToUse": "A number a dashboard shows: revenue, purchases, distinct buyers, last activity.",
"children": [
{ "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all"], "description": "The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment." },
- { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
+ { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
{ "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Count distinct values. Legal only with @agg: count." },
{ "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: \"-P7D\" }). Combines with @segment by AND." },
{ "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment declared on the same entity. Combines with @filter by AND." },
@@ -35,6 +35,12 @@
{ "type": "attr", "subType": "string", "name": "denominator", "min": 1, "max": 1, "description": "Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field." },
{ "type": "attr", "subType": "int", "name": "default", "min": 0, "max": 1, "description": "Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio." }
] },
+ { "type": "measure", "subType": "derived",
+ "description": "A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.",
+ "whenToUse": "A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).",
+ "children": [
+ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands." }
+ ] },
{ "type": "segment", "subType": "filter",
"description": "A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment.",
"whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.",