Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/39069-summary-measure-currency.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<Record<Face, AnalyticsService>> = {};

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<string, unknown> = {};
const provided: Record<string, unknown> = { 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();
});
});
}
});
32 changes: 25 additions & 7 deletions packages/services/service-analytics/src/analytics-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
};
};

/**
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading