diff --git a/.changeset/39069-summary-measure-currency.md b/.changeset/39069-summary-measure-currency.md new file mode 100644 index 00000000000..e6ccbad8db8 --- /dev/null +++ b/.changeset/39069-summary-measure-currency.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-analytics': patch +--- + +fix(service-analytics): a measure over a summary that declares its currency is priced + +Clause-②: yes (widening) +Metadata-protocol: none + +A dataset measure that takes an amount aggregate (`sum`, `avg`, `min`, `max`) over a `summary` field now carries a currency on its result column when the summary declares `currencyConfig`. Before, only a `currency` field counted as money, so such a column came back bare. This affects `POST /analytics/dataset/query` and the dataset draft preview. + +- A summary declaring `currencyMode: 'dynamic'` (or a `currencyConfig` with no mode) rolls up amounts in the home currency, so its column takes the request's tenant currency, as a sum over its child field does. A derived `sum` / `difference` whose operands are all tenant amounts counts such a measure among them, so it is priced too (for example "planned minus actual cost"). +- A summary declaring `currencyMode: 'fixed'` carries its code, as a `fixed` currency field does. +- Unchanged: a summary that declares no `currencyConfig` is still a number, whatever it rolls up, and so is a `count` over it. A `ratio` or `product` stays bare. The compile-time currency guards still judge `currency` fields, and fields of any type through a record-mode `currencyField`, as before; they read no summary's `dynamic` or `fixed` declaration, so every dataset that compiled before still compiles. + +**The widening.** `AnalyticsServiceConfig.sourceFieldMeta` may answer a new optional `currencyMode`, the field's declared `currencyConfig.currencyMode`, given only when a `currencyConfig` is declared. The plugin's own bridge answers it. A host that builds the service by hand and leaves it out keeps today's answer for summaries. `DeclaredCurrency`, the answer type of `DatasetCompileOptions.declaredCurrency` (re-exported from the package entry), gains the same optional `currencyMode?`; it has no effect at compile, because the guards do not read it. diff --git a/packages/services/service-analytics/src/__tests__/summary-measure-currency-39069.test.ts b/packages/services/service-analytics/src/__tests__/summary-measure-currency-39069.test.ts new file mode 100644 index 00000000000..add2d762797 --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/summary-measure-currency-39069.test.ts @@ -0,0 +1,202 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A measure over a `summary` field that declares its currency, through the + * plugin's own composition over a real engine. + * + * A summary declaring `currencyConfig: { currencyMode: 'dynamic' }` rolls up + * amounts in the tenant's currency (`field.zod.ts`, `CurrencyConfigSchema`: + * "A summary that rolls up an amount in the home currency ... declares + * `currencyMode: 'dynamic'` ... and shows in the organization's home + * currency"), so a measure over it is priced like one over its child field. + * A summary declaring nothing has no currency ("Absent: dynamic mode, and no + * currency on a summary"), so it stays a number, whatever it rolls up. A + * summary declaring `fixed` carries its code, as a `fixed` currency field does. + * + * Result column only (ruling record 7361078803): the compile-time guards + * read no summary's `dynamic` or `fixed` declaration, so a derived measure + * over a `fixed` summary and another `fixed` code still compiles. Both strategies, + * since the column is described at the one seam both pass through. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { AnalyticsResult } from '@objectstack/spec/contracts'; +import { DatasetSchema } from '@objectstack/spec/ui'; +import type { AnalyticsService } from '../analytics-service.js'; +import { AnalyticsServicePlugin } from '../plugin.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const PARENT = 'os39069_project'; +const CHILD = 'os39069_expense'; + +const PROJECT = { + name: PARENT, + label: 'Project', + fields: { + name: { name: 'name', type: 'text' as const }, + planned: { name: 'planned', type: 'currency' as const }, + cost_total: { + name: 'cost_total', + type: 'summary' as const, + summaryOperations: { object: CHILD, field: 'cost', function: 'sum' as const }, + currencyConfig: { currencyMode: 'dynamic' as const }, + }, + cost_undeclared: { + name: 'cost_undeclared', + type: 'summary' as const, + summaryOperations: { object: CHILD, field: 'cost', function: 'sum' as const }, + }, + eur_total: { + name: 'eur_total', + type: 'summary' as const, + summaryOperations: { object: CHILD, field: 'cost_eur', function: 'sum' as const }, + currencyConfig: { currencyMode: 'fixed' as const, defaultCurrency: 'EUR' }, + }, + hours_total: { + name: 'hours_total', + type: 'summary' as const, + summaryOperations: { object: CHILD, field: 'hours', function: 'sum' as const }, + }, + budget_usd: { + name: 'budget_usd', + type: 'currency' as const, + currencyConfig: { currencyMode: 'fixed' as const, defaultCurrency: 'USD' }, + }, + }, +}; + +const EXPENSE = { + name: CHILD, + label: 'Expense', + fields: { + project: { name: 'project', type: 'master_detail' as const, reference: PARENT }, + cost: { name: 'cost', type: 'currency' as const }, + cost_eur: { + name: 'cost_eur', + type: 'currency' as const, + currencyConfig: { currencyMode: 'fixed' as const, defaultCurrency: 'EUR' }, + }, + hours: { name: 'hours', type: 'number' as const }, + }, +}; + +const DATASET = DatasetSchema.parse({ + name: 'os39069_project_financials', + label: 'Project financials', + object: PARENT, + dimensions: [{ name: 'name', field: 'name', type: 'string' }], + measures: [ + { name: 'planned_sum', aggregate: 'sum', field: 'planned' }, + { name: 'cost_sum', aggregate: 'sum', field: 'cost_total' }, + { name: 'cost_max', aggregate: 'max', field: 'cost_total' }, + { name: 'undeclared_sum', aggregate: 'sum', field: 'cost_undeclared' }, + { name: 'eur_sum', aggregate: 'sum', field: 'eur_total' }, + { name: 'hours_sum', aggregate: 'sum', field: 'hours_total' }, + { name: 'projects', aggregate: 'count', field: 'cost_total' }, + { name: 'budget_sum', aggregate: 'sum', field: 'budget_usd' }, + { name: 'margin', derived: { op: 'difference', of: ['planned_sum', 'cost_sum'] } }, + { name: 'cost_twice', derived: { op: 'sum', of: ['cost_sum', 'cost_max'] } }, + { name: 'cost_and_hours', derived: { op: 'sum', of: ['cost_sum', 'hours_sum'] } }, + { name: 'cost_and_undeclared', derived: { op: 'sum', of: ['cost_sum', 'undeclared_sum'] } }, + { name: 'cost_per_hour', derived: { op: 'ratio', of: ['cost_sum', 'hours_sum'] } }, + { name: 'eur_and_usd', derived: { op: 'sum', of: ['eur_sum', 'budget_sum'] } }, + ], +}); + +const CTX = { currency: 'CNY' } as ExecutionContext; + +const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } }; + +const column = (result: AnalyticsResult, name: string) => + (result.fields ?? []).find((f) => f.name === name) as { name: string; currency?: string } | undefined; + +type Face = 'native' | 'objectql'; +const FACES: readonly Face[] = ['native', 'objectql']; + +describe('a measure over a summary that declares its currency', () => { + let engine: ObjectQL; + const services: Partial> = {}; + + beforeAll(async () => { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); + engine = new ObjectQL({ logger: quiet } as never); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registry.registerObject(PROJECT as never); + engine.registry.registerObject(EXPENSE as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine as never); + await engine.insert(PARENT, { id: 'p1', name: 'alpha', planned: 100, budget_usd: 10 } as never); + + for (const [face, caps] of [ + ['native', undefined], + ['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })], + ] as const) { + const registered: Record = {}; + const provided: Record = { data: engine }; + await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } as never).init({ + getService: (name: string) => provided[name] ?? registered[name], + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + hook: () => {}, + logger: quiet, + } as never); + services[face] = registered.analytics as AnalyticsService; + } + }); + + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + const ALL = DATASET.measures.map((m) => m.name); + + for (const face of FACES) { + describe(`${face} strategy`, () => { + it('prices an amount aggregate over a dynamic-currency summary in the tenant currency', async () => { + const result = await services[face]!.queryDataset(DATASET, { measures: ALL }, CTX); + expect(column(result, 'cost_sum')?.currency).toBe('CNY'); + expect(column(result, 'cost_max')?.currency).toBe('CNY'); + // Control: the currency-field case is unchanged. + expect(column(result, 'planned_sum')?.currency).toBe('CNY'); + expect(column(result, 'budget_sum')?.currency).toBe('USD'); + }); + + it('prices a derived sum / difference whose operands are all tenant amounts, a summary among them', async () => { + const result = await services[face]!.queryDataset(DATASET, { measures: ALL }, CTX); + expect(column(result, 'margin')?.currency).toBe('CNY'); + expect(column(result, 'cost_twice')?.currency).toBe('CNY'); + // Controls: a plain-number operand, an undeclared summary operand and a ratio stay bare. + expect(column(result, 'cost_and_hours')).toBeDefined(); + expect(column(result, 'cost_and_hours')?.currency).toBeUndefined(); + expect(column(result, 'cost_and_undeclared')).toBeDefined(); + expect(column(result, 'cost_and_undeclared')?.currency).toBeUndefined(); + expect(column(result, 'cost_per_hour')).toBeDefined(); + expect(column(result, 'cost_per_hour')?.currency).toBeUndefined(); + }); + + it('leaves a summary that declares no currency, a number summary and a count unpriced', async () => { + const result = await services[face]!.queryDataset(DATASET, { measures: ALL }, CTX); + expect(column(result, 'undeclared_sum')).toBeDefined(); + expect(column(result, 'undeclared_sum')?.currency).toBeUndefined(); + expect(column(result, 'hours_sum')).toBeDefined(); + expect(column(result, 'hours_sum')?.currency).toBeUndefined(); + expect(column(result, 'projects')).toBeDefined(); + expect(column(result, 'projects')?.currency).toBeUndefined(); + }); + + it('gives a fixed-currency summary its code on the column, and still compiles a derived measure over it and another code', async () => { + const result = await services[face]!.queryDataset(DATASET, { measures: ALL }, CTX); + expect(column(result, 'eur_sum')?.currency).toBe('EUR'); + // Result column only: the guards read no summary's `fixed` code, so this + // EUR + USD sum is served, not refused at compile. Its label is not + // pinned: the resolver ignores the summary operand, as it ignores a + // count, and names the other operand's code. + expect(column(result, 'eur_and_usd')).toBeDefined(); + }); + }); + } +}); diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 0c0d9602e38..0a4213fcfd3 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -112,7 +112,7 @@ import { } from './strategies/filter-normalizer.js'; import { findCrossFieldComparand } from './comparand-shape.js'; import { compileDataset, unbackedRelationshipPath, type CompiledDataset, type RelationshipResolver } from './dataset-compiler.js'; -import { measureCurrencyResolver, type DeclaredCurrency } from './measure-currency-coherence.js'; +import { amountCurrencyOf, measureCurrencyResolver, type DeclaredCurrency } from './measure-currency-coherence.js'; import { bindDatasetFiltersToObjectFields } from './dataset-filter-field-binding.js'; import { drillWindowBounds } from './drill-window.js'; import { @@ -1310,6 +1310,16 @@ export interface AnalyticsServiceConfig { defaultCurrency?: string; currencyField?: string; homeAmountField?: string; + /** + * The field's declared `currencyConfig.currencyMode` (`'dynamic'`, + * `'fixed'` or `'record'`), relayed ONLY when the field declares a + * `currencyConfig`; a declared config with no mode answers `'dynamic'`, + * the schema's default. One reader: a `summary` is money only by that + * declaration (`amountCurrencyOf`, `measure-currency-coherence.ts`), and + * `defaultCurrency` / `currencyField` alone cannot tell a `dynamic` + * summary from one that declares nothing. + */ + currencyMode?: string; /** * [ADR-0158 U7 R1] A `number` field's `unitConfig.unitField`, relayed * ONLY under `unitMode: 'record'`: the unit field the cube door's @@ -2916,7 +2926,12 @@ export class AnalyticsService implements IAnalyticsService { private readonly declaredCurrency = (object: string, field: string): DeclaredCurrency | undefined => { const meta = this.sourceFieldMeta?.(object, field); if (!meta) return undefined; - return { type: meta.type, defaultCurrency: meta.defaultCurrency, currencyField: meta.currencyField }; + return { + type: meta.type, + defaultCurrency: meta.defaultCurrency, + currencyField: meta.currencyField, + currencyMode: meta.currencyMode, + }; }; /** @@ -3898,9 +3913,12 @@ export class AnalyticsService implements IAnalyticsService { // currency (`sourceFieldMeta().defaultCurrency`, relayed only under // `currencyMode: 'fixed'` — #20091) → tenant default (`ctx.currency`). // A measure is monetary if it declares a currency OR takes an amount - // aggregate (`AMOUNT_AGGREGATES`) over a `currency`-type field; - // non-monetary measures (a count, over an amount field too, or an avg - // of a plain number) never receive a currency code. + // aggregate (`AMOUNT_AGGREGATES`) over a field that is money in one + // currency (`amountCurrencyOf`): a `currency` field, or a `summary` + // declaring `currencyMode: 'dynamic'` (the tenant's) or `'fixed'` (its + // code). Non-monetary measures (a count, over an amount field too, an + // avg of a plain number, a summary declaring no currency) never + // receive a currency code. // // [ADR-0144 D2] A `record`-mode amount has one currency per ROW, held // in its code field, so no single code describes the column and no @@ -3937,8 +3955,8 @@ export class AnalyticsService implements IAnalyticsService { : undefined; if (fc.currencyField == null && codeColumn !== undefined) fc.currencyField = codeColumn; } else if (fc.currency == null) { - const amount = meta?.type === 'currency' && AMOUNT_AGGREGATES.has(m.aggregate ?? ''); - const monetary = !!mc.currency || amount || derivedCode !== undefined || derivedTenant; + const fieldAmount = AMOUNT_AGGREGATES.has(m.aggregate ?? '') ? amountCurrencyOf(meta) : undefined; + const monetary = !!mc.currency || fieldAmount !== undefined || derivedCode !== undefined || derivedTenant; if (monetary) { const resolved = mc.currency ?? meta?.defaultCurrency ?? derivedCode ?? context?.currency; if (resolved) fc.currency = resolved; diff --git a/packages/services/service-analytics/src/measure-currency-coherence.ts b/packages/services/service-analytics/src/measure-currency-coherence.ts index 87358ae05a2..5cf7c1bfd79 100644 --- a/packages/services/service-analytics/src/measure-currency-coherence.ts +++ b/packages/services/service-analytics/src/measure-currency-coherence.ts @@ -63,6 +63,14 @@ * operand is a tenant-currency amount aggregate, or such a derived measure in * turn. A `ratio` or `product` of two amounts is no amount, and stays bare. * + * A `summary` that declares its currency is money too ({@link amountCurrencyOf}): + * `dynamic` in the tenant's, `fixed` in its code. Its column is priced, and an + * amount aggregate over a `dynamic` one is a tenant operand for + * `inTenantCurrency`. The resolved reading above, and so both guards, read a + * summary only through a record-mode `currencyField`, as they read any field + * that has one, so a summary's `dynamic` or `fixed` declaration moves no + * accept set (ruling record 7361078803: the result column only). + * * ## Not judged * * - No `declaredCurrency` hook (no data engine), or a field it cannot resolve. @@ -77,12 +85,58 @@ import { datasetInvalidError } from './dataset-refusal.js'; /** * A field's declared currency, as the host's `sourceFieldMeta` relays it: - * `defaultCurrency` only under `fixed`, `currencyField` only under `record`. + * `defaultCurrency` only under `fixed`, `currencyField` only under `record`, + * and `currencyMode` only when the field declares a `currencyConfig` (an + * absent mode on a declared config is `'dynamic'`). */ export interface DeclaredCurrency { readonly type?: string; readonly defaultCurrency?: string; readonly currencyField?: string; + readonly currencyMode?: string; +} + +/** + * The one currency a field's amounts are in, when the field is money in a + * single currency: its `fixed` code, or the tenant's. + */ +export type AmountCurrency = + | { readonly kind: 'fixed'; readonly code: string; readonly summary: boolean } + | { readonly kind: 'tenant'; readonly summary: boolean }; + +/** + * Is this source field money in one currency, and which: the ONE reading of + * "an amount aggregate over this field is priced" that the result column + * (`enrichResultColumns`) and the resolver below both ask. A record-mode + * amount (`currencyField`) is answered by its readers before this, because + * its currency is per row. + * + * - A `currency` field: its `fixed` code, else the tenant's (`dynamic`, the + * mode an absent config reads as). + * - A `summary` declaring a `currencyConfig` (`field.zod.ts`, + * `CurrencyConfigSchema`): `dynamic` rolls up amounts in the home currency + * and shows in it, so it is the tenant's; `fixed` is its code. A summary + * declaring nothing has no currency ("Absent: dynamic mode, and no currency + * on a summary"), so nothing is inferred from what it rolls up. + * + * `summary` says which arm answered: the compile guards read only the + * `currency`-field arm (`resolvedOf`), so a summary prices its column and + * never moves what compiles. + */ +export function amountCurrencyOf(field: DeclaredCurrency | undefined): AmountCurrency | undefined { + if (!field || field.currencyField !== undefined) return undefined; + if (field.type === 'currency') { + return field.defaultCurrency !== undefined + ? { kind: 'fixed', code: field.defaultCurrency, summary: false } + : { kind: 'tenant', summary: false }; + } + if (field.type === 'summary') { + if (field.currencyMode === 'dynamic') return { kind: 'tenant', summary: true }; + if (field.currencyMode === 'fixed' && field.defaultCurrency !== undefined) { + return { kind: 'fixed', code: field.defaultCurrency, summary: true }; + } + } + return undefined; } type Resolved = @@ -147,10 +201,14 @@ export function measureCurrencyResolver(dataset: Dataset, declaredCurrency: Decl const field = fieldOf(m); if (field?.currencyField !== undefined) r = { kind: 'record', codeField: field.currencyField }; else if (m.currency) r = { kind: 'code', code: m.currency, fixed: field?.defaultCurrency === m.currency }; - else if (field?.type === 'currency') { - r = field.defaultCurrency !== undefined - ? { kind: 'code', code: field.defaultCurrency, fixed: true } - : { kind: 'tenant' }; + else { + // The `currency`-field arm only: a summary's declared currency prices + // its column (`readsTenantAmount`, `enrichResultColumns`) and moves no + // accept set here. + const amount = amountCurrencyOf(field); + if (amount && !amount.summary) { + r = amount.kind === 'fixed' ? { kind: 'code', code: amount.code, fixed: true } : { kind: 'tenant' }; + } } } resolving.delete(m.name); @@ -168,13 +226,23 @@ export function measureCurrencyResolver(dataset: Dataset, declaredCurrency: Decl const r = resolvedOf(m); return r?.kind === 'code' && r.fixed ? r.code : undefined; }; + /** + * Whether a plain measure is an amount aggregate in the tenant's currency: + * no `currency` of its own, over a field {@link amountCurrencyOf} reads as + * the tenant's. Over a `currency` field that is exactly `resolvedOf`'s + * `tenant`; over a summary declaring `currencyMode: 'dynamic'` it is the + * column's reading, which `resolvedOf` leaves to the column. + */ + const readsTenantAmount = (m: DatasetMeasure): boolean => + !m.derived && !m.duration && !m.currency && AMOUNT_AGGREGATES.has(m.aggregate ?? '') + && amountCurrencyOf(fieldOf(m))?.kind === 'tenant'; /** * Whether a DERIVED measure is an amount in the tenant's currency (module * header): a `sum` / `difference` whose every operand, monetary or not, is - * an amount aggregate resolving to the tenant's currency or such a derived - * measure in turn. Any other operand (a `fixed` or explicit code, a - * record-mode amount, a `count`, a `ratio`, a missing or cyclic name) makes - * it `false`, so the column keeps today's answer. + * an amount aggregate in the tenant's currency ({@link readsTenantAmount}) + * or such a derived measure in turn. Any other operand (a `fixed` or + * explicit code, a record-mode amount, a `count`, a `ratio`, a missing or + * cyclic name) makes it `false`, so the column keeps today's answer. */ const inTenantCurrency = (m: DatasetMeasure, seen: ReadonlySet = new Set()): boolean => { if (!m.derived || (m.derived.op !== 'sum' && m.derived.op !== 'difference')) return false; @@ -182,7 +250,7 @@ export function measureCurrencyResolver(dataset: Dataset, declaredCurrency: Decl return m.derived.of.length > 0 && m.derived.of.every((name) => { const operand = byName.get(name); if (!operand || path.has(name)) return false; - return operand.derived ? inTenantCurrency(operand, path) : resolvedOf(operand)?.kind === 'tenant'; + return operand.derived ? inTenantCurrency(operand, path) : readsTenantAmount(operand); }); }; return { fieldOf, resolvedOf, monetaryOperands, fixedCodeOf, inTenantCurrency }; diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index fb1912aa6d6..5e2ecf79cfc 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -1700,6 +1700,15 @@ export class AnalyticsServicePlugin implements Plugin { const homeAmountField = recordCurrencyField !== undefined ? f.currencyConfig?.homeAmount?.field : undefined; + // …and the declared mode, ONLY when a `currencyConfig` is declared: a + // `summary` is money only by that declaration (`CurrencyConfigSchema`: + // "Absent: dynamic mode, and no currency on a summary"), and the two + // keys above answer the same for a `dynamic` summary and one that + // declares nothing. A declared config with no mode is `dynamic`, the + // schema's default, compared as the keys above are rather than parsed. + const declaredCurrencyMode = f.currencyConfig != null && typeof f.currencyConfig === 'object' + ? (f.currencyConfig.currencyMode ?? 'dynamic') + : undefined; // [ADR-0158 U7 R1] …and a quantity's `unitField` ONLY under // `unitMode: 'record'` on a `number`, the one shape the spec reads it // under: the cube door's record-unit judgment groups by it. @@ -1714,6 +1723,7 @@ export class AnalyticsServicePlugin implements Plugin { defaultCurrency: fixedCurrency, currencyField: recordCurrencyField, homeAmountField, + currencyMode: declaredCurrencyMode, unitField: recordUnitField, }; },