Skip to content

Commit 6748f74

Browse files
committed
test(service-analytics): a consolidated measure over the stored home field, on the preview, SQLite and Postgres
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CbmDUh2Sx7fvaGgu7r
1 parent d53098d commit 6748f74

1 file changed

Lines changed: 369 additions & 0 deletions

File tree

Lines changed: 369 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,369 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0144 D6, multi-currency M3-1] A consolidated total over a record-mode
5+
* amount is a plain `sum` over its stored home field, through the dataset
6+
* compile + query path, with no code of its own.
7+
*
8+
* ## What these pins hold
9+
*
10+
* - **The proof.** Rows in three record currencies (USD, EUR and the home
11+
* CNY) are written through the engine, whose write-time projection (D5,
12+
* `home-amount-projection.ts` in `@objectstack/objectql`) stores each
13+
* amount converted into the home currency in the declared home field. A
14+
* dataset measure `sum` over that field answers the home-currency total,
15+
* ungrouped (a KPI), grouped by the code field, and as a `totals` grand
16+
* total; the column carries the home currency (the tenant's, because the
17+
* home field is `dynamic`) and no per-row `currencyField`. The raw `sum`
18+
* over the record amount of the same rows is a different number (it adds
19+
* dollars to euros), which the controls show.
20+
* - **The door's words.** The ungrouped `sum` over the record amount is
21+
* still refused `INVALID_FIELD` / 400 before anything is read, and its
22+
* message now names both remedies: the declared home field by name, or the
23+
* grouping over the code field. An amount that declares no `homeAmount`
24+
* reads the declaration to add instead.
25+
*
26+
* ## The axes
27+
*
28+
* Three stores: the draft-preview evaluator (in memory, over the very rows
29+
* the projection wrote, read back from the store), SQLite, and PostgreSQL.
30+
* The SQLite cell always runs. The PostgreSQL cell runs where
31+
* `OS_TEST_POSTGRES_URL` is set and is a named skip otherwise; CI provisions
32+
* that variable for this package in the Temporal Conformance job
33+
* (`.github/workflows/ci.yml`). The live cell owns a schema of its own,
34+
* dropped before and after. Both SQL cells run both strategies
35+
* (`NativeSQLStrategy`, the plugin's own capabilities; `ObjectQLStrategy`,
36+
* narrowed to the engine aggregate).
37+
*/
38+
39+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
40+
import { ObjectQL } from '@objectstack/objectql';
41+
import { SqlDriver } from '@objectstack/driver-sql';
42+
import type { ExecutionContext } from '@objectstack/spec/kernel';
43+
import type { AnalyticsResult } from '@objectstack/spec/contracts';
44+
import { DatasetSchema } from '@objectstack/spec/ui';
45+
import type { AnalyticsService } from '../analytics-service.js';
46+
import { AnalyticsServicePlugin } from '../plugin.js';
47+
import { installDefaultOrganization } from './default-organization.testkit.js';
48+
49+
const OBJECT = 'os27195_fx_invoice';
50+
const BARE = 'os27195_fx_bare';
51+
const PG_SCHEMA = 'os27195_home_measure';
52+
53+
/** The rate table's shape (`sys_exchange_rate`, owned by platform-objects; a stand-in here, as in objectql's own pins). */
54+
const RATE_OBJECT = {
55+
name: 'sys_exchange_rate',
56+
label: 'Exchange rate',
57+
fields: {
58+
currency: { name: 'currency', type: 'text' as const, valueDomain: 'iso_4217_currency' },
59+
rate: { name: 'rate', type: 'number' as const, scale: 12, precision: 24 },
60+
effective_date: { name: 'effective_date', type: 'date' as const },
61+
},
62+
};
63+
64+
const INVOICE = {
65+
name: OBJECT,
66+
label: 'FX invoice',
67+
fields: {
68+
currency_code: { name: 'currency_code', type: 'text' as const, valueDomain: 'iso_4217_currency' },
69+
invoice_date: { name: 'invoice_date', type: 'date' as const },
70+
amount: {
71+
name: 'amount',
72+
type: 'currency' as const,
73+
currencyConfig: {
74+
currencyMode: 'record' as const,
75+
currencyField: 'currency_code',
76+
homeAmount: { field: 'amount_home', rateDate: 'invoice_date', rateField: 'amount_rate' },
77+
},
78+
},
79+
amount_home: { name: 'amount_home', type: 'currency' as const, readonly: true },
80+
amount_rate: { name: 'amount_rate', type: 'number' as const, readonly: true },
81+
},
82+
};
83+
84+
/** The same record amount with no `homeAmount`: the refusal has no home field to name. */
85+
const BARE_INVOICE = {
86+
name: BARE,
87+
label: 'FX invoice without a home field',
88+
fields: {
89+
currency_code: { name: 'currency_code', type: 'text' as const, valueDomain: 'iso_4217_currency' },
90+
amount: {
91+
name: 'amount',
92+
type: 'currency' as const,
93+
currencyConfig: { currencyMode: 'record' as const, currencyField: 'currency_code' },
94+
},
95+
},
96+
};
97+
98+
const HOME = 'CNY';
99+
100+
/** "1 home unit = rate units of the foreign currency" (ADR-0144 D7 parameter 3), so home = amount ÷ rate. */
101+
const RATES: ReadonlyArray<[currency: string, effective_date: string, rate: number]> = [
102+
['USD', '2026-01-01', 0.125],
103+
['EUR', '2026-01-01', 0.1],
104+
];
105+
106+
/** Three record currencies; the home amount each row's projection stores is in the comment. */
107+
const ROWS = [
108+
{ id: 'h1', currency_code: 'USD', invoice_date: '2026-03-01', amount: 100 }, // 800
109+
{ id: 'h2', currency_code: 'USD', invoice_date: '2026-03-02', amount: 20 }, // 160
110+
{ id: 'h3', currency_code: 'EUR', invoice_date: '2026-03-03', amount: 100 }, // 1000
111+
{ id: 'h4', currency_code: 'CNY', invoice_date: '2026-03-04', amount: 50 }, // 50 (rate 1)
112+
] as const;
113+
114+
const HOME_TOTAL = 2010;
115+
const HOME_BY_CODE = { USD: 960, EUR: 1000, CNY: 50 };
116+
/** What the raw amounts add to: dollars, euros and yuan as one number — the shape the door refuses. */
117+
const RAW_SUM = 270;
118+
119+
const DATASET = DatasetSchema.parse({
120+
name: 'os27195_consolidated',
121+
label: 'Invoices, consolidated',
122+
object: OBJECT,
123+
dimensions: [{ name: 'currency', field: 'currency_code', type: 'string' }],
124+
measures: [
125+
{ name: 'home_total', aggregate: 'sum', field: 'amount_home' },
126+
{ name: 'raw_total', aggregate: 'sum', field: 'amount' },
127+
{ name: 'invoices', aggregate: 'count' },
128+
],
129+
});
130+
131+
const BARE_DATASET = DatasetSchema.parse({
132+
name: 'os27195_bare',
133+
label: 'Invoices without a home field',
134+
object: BARE,
135+
dimensions: [{ name: 'currency', field: 'currency_code', type: 'string' }],
136+
measures: [{ name: 'raw_total', aggregate: 'sum', field: 'amount' }],
137+
});
138+
139+
const CTX = { currency: HOME } as ExecutionContext;
140+
const SYS = { context: { isSystem: true } } as const;
141+
142+
type Face = 'native' | 'objectql';
143+
const FACES: readonly Face[] = ['native', 'objectql'];
144+
145+
interface Cell {
146+
id: 'sqlite' | 'pg';
147+
label: string;
148+
env: string | null;
149+
config: () => Record<string, unknown> | null;
150+
}
151+
152+
const CELLS: readonly Cell[] = [
153+
{ id: 'sqlite', label: 'sqlite', env: null, config: () => ({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) },
154+
{
155+
id: 'pg',
156+
label: 'live postgres',
157+
env: 'OS_TEST_POSTGRES_URL',
158+
config: () => (process.env.OS_TEST_POSTGRES_URL
159+
? { client: 'pg', connection: process.env.OS_TEST_POSTGRES_URL, searchPath: [PG_SCHEMA] }
160+
: null),
161+
},
162+
];
163+
164+
const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } };
165+
166+
type Refusal = Error & { code?: string; status?: number; member?: string; param?: string; field?: string; object?: string };
167+
168+
const refusalOf = (p: Promise<unknown>): Promise<Refusal> =>
169+
p.then<never, Refusal>(
170+
() => {
171+
throw new Error('expected a refusal, but the query resolved');
172+
},
173+
(e) => e as Refusal,
174+
);
175+
176+
const column = (result: AnalyticsResult, name: string) =>
177+
(result.fields ?? []).find((f) => f.name === name) as
178+
| { name: string; currency?: string; currencyField?: string }
179+
| undefined;
180+
181+
const byCode = (rows: unknown[], measure: string) =>
182+
Object.fromEntries((rows as Array<Record<string, unknown>>).map((r) => [r.currency, Number(r[measure])]));
183+
184+
/** The live cell's own schema, created or dropped on a connection outside it. */
185+
async function pgSchema(statement: 'create' | 'drop'): Promise<void> {
186+
const admin = new SqlDriver({ client: 'pg', connection: process.env.OS_TEST_POSTGRES_URL } as never);
187+
try {
188+
await admin.execute(`drop schema if exists ${PG_SCHEMA} cascade`);
189+
if (statement === 'create') await admin.execute(`create schema ${PG_SCHEMA}`);
190+
} finally {
191+
await admin.disconnect().catch(() => {});
192+
}
193+
}
194+
195+
for (const cell of CELLS) {
196+
const config = cell.config();
197+
describe.skipIf(!config)(
198+
`[ADR-0144 D6 · M3-1] a consolidated measure over the stored home field (${cell.label})${config ? '' : ` (skipped: set ${cell.env} to run this cell)`}`,
199+
() => {
200+
let engine: ObjectQL;
201+
/** Raw-SQL statements and engine aggregates that read the invoice objects. */
202+
const reads = { rawSql: 0, aggregate: 0 };
203+
const services: Partial<Record<Face, AnalyticsService>> = {};
204+
/** The rows as the projection stored them, read back — the draft preview's seed. */
205+
let stored: Array<Record<string, unknown>> = [];
206+
207+
beforeAll(async () => {
208+
if (cell.id === 'pg') await pgSchema('create');
209+
const driver = new SqlDriver(config as never);
210+
engine = new ObjectQL({ logger: quiet } as never);
211+
engine.registerDriver(driver as never, true);
212+
await engine.init();
213+
for (const object of [RATE_OBJECT, INVOICE, BARE_INVOICE]) engine.registry.registerObject(object as never);
214+
await engine.syncSchemas();
215+
await installDefaultOrganization(engine as never);
216+
engine.setHomeLocalizationResolver(async () => ({ currency: HOME }));
217+
for (const [currency, effective_date, rate] of RATES) {
218+
await engine.insert('sys_exchange_rate', { currency, effective_date, rate }, SYS as never);
219+
}
220+
for (const row of ROWS) await engine.insert(OBJECT, { ...row } as never, SYS as never);
221+
for (const row of ROWS) {
222+
await engine.insert(BARE, { id: row.id, currency_code: row.currency_code, amount: row.amount } as never, SYS as never);
223+
}
224+
stored = (await engine.find(OBJECT, { context: SYS.context } as never)) as Array<Record<string, unknown>>;
225+
226+
const realExecute = (engine as any).execute.bind(engine);
227+
(engine as any).execute = (sql: unknown, opts?: { object?: string }) => {
228+
if (opts?.object === OBJECT || opts?.object === BARE) reads.rawSql += 1;
229+
return realExecute(sql, opts);
230+
};
231+
const realAggregate = engine.aggregate.bind(engine);
232+
(engine as any).aggregate = (object: string, ...rest: unknown[]) => {
233+
if (object === OBJECT || object === BARE) reads.aggregate += 1;
234+
return (realAggregate as any)(object, ...rest);
235+
};
236+
237+
// A `'protocol'` service answering one pending seed draft of the STORED
238+
// rows, which routes `previewDrafts` onto the in-memory evaluator.
239+
const pendingSeedProtocol = {
240+
getMetaItems: async () => [{ name: 'os27195_seed', object: OBJECT }],
241+
getMetaItem: async () => ({ item: { records: stored } }),
242+
};
243+
for (const [face, caps] of [
244+
['native', undefined],
245+
['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })],
246+
] as const) {
247+
const registered: Record<string, unknown> = {};
248+
const provided: Record<string, unknown> = { data: engine, protocol: pendingSeedProtocol };
249+
await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } as never).init({
250+
getService: (name: string) => provided[name] ?? registered[name],
251+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
252+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
253+
hook: () => {},
254+
logger: quiet,
255+
} as never);
256+
services[face] = registered.analytics as AnalyticsService;
257+
}
258+
});
259+
260+
afterAll(async () => {
261+
try { await engine?.destroy(); } catch { /* noop */ }
262+
if (cell.id === 'pg') await pgSchema('drop');
263+
});
264+
265+
it('the projection stored each row in the home currency (the fixture the proof reads)', () => {
266+
const home = Object.fromEntries(stored.map((r) => [r.id, [Number(r.amount_home), Number(r.amount_rate)]]));
267+
expect(home).toEqual({ h1: [800, 0.125], h2: [160, 0.125], h3: [1000, 0.1], h4: [50, 1] });
268+
});
269+
270+
for (const face of FACES) {
271+
describe(`${face} strategy`, () => {
272+
it('a sum over the home field, ungrouped, answers the home-currency total, labelled with the home currency', async () => {
273+
const result = await services[face]!.queryDataset(DATASET, { measures: ['home_total', 'invoices'] }, CTX);
274+
const [row] = result.rows as Array<Record<string, unknown>>;
275+
expect(Number(row!.home_total)).toBe(HOME_TOTAL);
276+
expect(Number(row!.invoices)).toBe(ROWS.length);
277+
expect(column(result, 'home_total')?.currency).toBe(HOME);
278+
expect(column(result, 'home_total')?.currencyField).toBeUndefined();
279+
});
280+
281+
it('grouped by the code field: each currency\'s home subtotal, and a grand total equal to the KPI', async () => {
282+
const result = await services[face]!.queryDataset(
283+
DATASET,
284+
{ dimensions: ['currency'], measures: ['home_total', 'raw_total'], totals: { groupings: [[]] } },
285+
CTX,
286+
).catch((e: Refusal) => e);
287+
// The grand total over `raw_total` drops the code, so the door refuses
288+
// it; the home field alone is served under the same grand total.
289+
expect((result as Refusal).code).toBe('INVALID_FIELD');
290+
expect((result as Refusal).member).toBe('raw_total');
291+
292+
const served = await services[face]!.queryDataset(
293+
DATASET,
294+
{ dimensions: ['currency'], measures: ['home_total'], totals: { groupings: [[]] } },
295+
CTX,
296+
);
297+
expect(byCode(served.rows, 'home_total')).toEqual(HOME_BY_CODE);
298+
expect(Number((served.totals?.[0]?.rows[0] as Record<string, unknown>).home_total)).toBe(HOME_TOTAL);
299+
expect(column(served, 'home_total')?.currency).toBe(HOME);
300+
expect(column(served, 'home_total')?.currencyField).toBeUndefined();
301+
});
302+
303+
it('the control: grouped by the code, the raw amount is served per currency and does not add to the home total', async () => {
304+
const result = await services[face]!.queryDataset(DATASET, { dimensions: ['currency'], measures: ['raw_total'] }, CTX);
305+
expect(byCode(result.rows, 'raw_total')).toEqual({ USD: 120, EUR: 100, CNY: 50 });
306+
expect(Object.values(byCode(result.rows, 'raw_total')).reduce((a, b) => a + b, 0)).toBe(RAW_SUM);
307+
expect(column(result, 'raw_total')?.currencyField).toBe('currency');
308+
});
309+
310+
it('the ungrouped sum over the record amount is refused before anything is read, and the words name the home field and the grouping', async () => {
311+
const before = { ...reads };
312+
const err = await refusalOf(services[face]!.queryDataset(DATASET, { measures: ['raw_total'] }, CTX));
313+
expect(err.code, err.message).toBe('INVALID_FIELD');
314+
expect(err.status).toBe(400);
315+
expect(err.member).toBe('raw_total');
316+
expect(err.field).toBe('amount');
317+
expect(err.object).toBe(OBJECT);
318+
expect(err.message).toContain(`point the measure at 'amount_home', the home-currency amount object '${OBJECT}' declares for 'amount'`);
319+
expect(err.message).toContain("add the dimension over 'currency_code' to the query");
320+
expect(reads.rawSql - before.rawSql).toBe(0);
321+
expect(reads.aggregate - before.aggregate).toBe(0);
322+
});
323+
324+
it('an amount declaring no homeAmount reads the declaration to add, and the grouping', async () => {
325+
const err = await refusalOf(services[face]!.queryDataset(BARE_DATASET, { measures: ['raw_total'] }, CTX));
326+
expect(err.code, err.message).toBe('INVALID_FIELD');
327+
expect(err.object).toBe(BARE);
328+
expect(err.message).toContain(
329+
`declare \`currencyConfig.homeAmount\` on 'amount' of object '${BARE}' and point the measure at its home field`,
330+
);
331+
expect(err.message).toContain("add the dimension over 'currency_code' to the query");
332+
});
333+
334+
it('the inferred cube (no registered dataset): `amount_home_sum` is served, `amount_sum` is refused naming amount_home', async () => {
335+
const served = await services[face]!.query({ cube: OBJECT, measures: ['amount_home_sum'] } as never, CTX);
336+
expect(Number((served.rows[0] as Record<string, unknown>).amount_home_sum)).toBe(HOME_TOTAL);
337+
const err = await refusalOf(services[face]!.query({ cube: OBJECT, measures: ['amount_sum'] } as never, CTX));
338+
expect(err.code, err.message).toBe('INVALID_FIELD');
339+
expect(err.message).toContain("point the measure at 'amount_home'");
340+
});
341+
});
342+
}
343+
344+
describe('the draft preview (the in-memory evaluator, over the stored rows)', () => {
345+
it('a sum over the home field answers the home-currency total, ungrouped and grouped by the code', async () => {
346+
const kpi = await services.native!.queryDataset(DATASET, { measures: ['home_total'] }, CTX, { previewDrafts: true });
347+
expect(Number((kpi.rows[0] as Record<string, unknown>).home_total)).toBe(HOME_TOTAL);
348+
expect(column(kpi, 'home_total')?.currency).toBe(HOME);
349+
const grouped = await services.native!.queryDataset(
350+
DATASET,
351+
{ dimensions: ['currency'], measures: ['home_total'] },
352+
CTX,
353+
{ previewDrafts: true },
354+
);
355+
expect(byCode(grouped.rows, 'home_total')).toEqual(HOME_BY_CODE);
356+
});
357+
358+
it('the ungrouped raw amount is refused with the same words', async () => {
359+
const err = await refusalOf(
360+
services.native!.queryDataset(DATASET, { measures: ['raw_total'] }, CTX, { previewDrafts: true }),
361+
);
362+
expect(err.code, err.message).toBe('INVALID_FIELD');
363+
expect(err.member).toBe('raw_total');
364+
expect(err.message).toContain("point the measure at 'amount_home'");
365+
});
366+
});
367+
},
368+
);
369+
}

0 commit comments

Comments
 (0)