|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [ADR-0144, multi-currency M0-3] Analytics over a `currencyMode: 'record'` |
| 5 | + * amount, through the plugin's own composition over a real engine. |
| 6 | + * |
| 7 | + * ## What these pins hold |
| 8 | + * |
| 9 | + * - A grouped answer carries the PER-ROW currency: the measure column names, |
| 10 | + * by `currencyField`, the dimension column that groups by the amount's code |
| 11 | + * field, and carries no `currency` (`AnalyticsResult.fields`, |
| 12 | + * `@objectstack/spec/contracts`). Before, probe C of the #8345 measurement |
| 13 | + * round saw every group of a correct breakdown labelled with ONE currency. |
| 14 | + * - The cube door refuses a `sum` / `avg` / `min` / `max` over the amount that |
| 15 | + * does not group by the code field — `INVALID_FIELD` / 400 with the member, |
| 16 | + * the column and its object — before anything is read. A `totals` grand |
| 17 | + * total is such an aggregate too. `count` reads no amount and is served. |
| 18 | + * - Both of the above on both strategies (`NativeSQLStrategy`, the plugin's |
| 19 | + * own capabilities; `ObjectQLStrategy`, narrowed to the engine aggregate), |
| 20 | + * and the column on the draft-preview path, which shares the one |
| 21 | + * column-description seam. |
| 22 | + * - The two compile-time guards (`measure-currency-coherence.ts`): |
| 23 | + * `DATASET_INVALID` / 400 for a measure `currency` that contradicts its |
| 24 | + * field, and for a derived measure across currencies that provably differ. |
| 25 | + * |
| 26 | + * The SQLite cell runs everywhere; the strategies are the axis here, not the |
| 27 | + * dialect (the door stands ahead of both and reads nothing). |
| 28 | + */ |
| 29 | + |
| 30 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 31 | +import { ObjectQL } from '@objectstack/objectql'; |
| 32 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 33 | +import type { ExecutionContext } from '@objectstack/spec/kernel'; |
| 34 | +import type { AnalyticsResult } from '@objectstack/spec/contracts'; |
| 35 | +import { DatasetSchema } from '@objectstack/spec/ui'; |
| 36 | +import type { AnalyticsService } from '../analytics-service.js'; |
| 37 | +import { AnalyticsServicePlugin } from '../plugin.js'; |
| 38 | +import { installDefaultOrganization } from './default-organization.testkit.js'; |
| 39 | + |
| 40 | +const OBJECT = 'os27187_fx_invoice'; |
| 41 | + |
| 42 | +const INVOICE = { |
| 43 | + name: OBJECT, |
| 44 | + label: 'FX invoice', |
| 45 | + fields: { |
| 46 | + currency_code: { name: 'currency_code', type: 'text' as const, valueDomain: 'iso_4217_currency' }, |
| 47 | + region: { name: 'region', type: 'text' as const }, |
| 48 | + amount: { |
| 49 | + name: 'amount', |
| 50 | + type: 'currency' as const, |
| 51 | + currencyConfig: { currencyMode: 'record' as const, currencyField: 'currency_code' }, |
| 52 | + }, |
| 53 | + amt_usd: { name: 'amt_usd', type: 'currency' as const, currencyConfig: { currencyMode: 'fixed' as const, defaultCurrency: 'USD' } }, |
| 54 | + amt_eur: { name: 'amt_eur', type: 'currency' as const, currencyConfig: { currencyMode: 'fixed' as const, defaultCurrency: 'EUR' } }, |
| 55 | + amt_tenant: { name: 'amt_tenant', type: 'currency' as const }, |
| 56 | + }, |
| 57 | +}; |
| 58 | + |
| 59 | +const ROWS = [ |
| 60 | + { id: 'i1', currency_code: 'USD', region: 'amer', amount: 100, amt_usd: 100, amt_eur: 10, amt_tenant: 1 }, |
| 61 | + { id: 'i2', currency_code: 'EUR', region: 'amer', amount: 100, amt_usd: 0, amt_eur: 90, amt_tenant: 1 }, |
| 62 | + { id: 'i3', currency_code: 'USD', region: 'emea', amount: 50, amt_usd: 50, amt_eur: 0, amt_tenant: 1 }, |
| 63 | +] as const; |
| 64 | + |
| 65 | +const DATASET = DatasetSchema.parse({ |
| 66 | + name: 'os27187_fx_by_currency', |
| 67 | + label: 'Invoices by currency', |
| 68 | + object: OBJECT, |
| 69 | + dimensions: [ |
| 70 | + { name: 'currency', field: 'currency_code', type: 'string' }, |
| 71 | + { name: 'region', field: 'region', type: 'string' }, |
| 72 | + ], |
| 73 | + measures: [ |
| 74 | + { name: 'total', aggregate: 'sum', field: 'amount' }, |
| 75 | + { name: 'largest', aggregate: 'max', field: 'amount' }, |
| 76 | + { name: 'invoices', aggregate: 'count' }, |
| 77 | + { name: 'usd_total', aggregate: 'sum', field: 'amt_usd' }, |
| 78 | + ], |
| 79 | +}); |
| 80 | + |
| 81 | +const CTX = { currency: 'CNY' } as ExecutionContext; |
| 82 | + |
| 83 | +type Face = 'native' | 'objectql'; |
| 84 | +const FACES: readonly Face[] = ['native', 'objectql']; |
| 85 | + |
| 86 | +const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } }; |
| 87 | + |
| 88 | +type Refusal = Error & { code?: string; status?: number; member?: string; param?: string; field?: string; object?: string }; |
| 89 | + |
| 90 | +const refusalOf = (p: Promise<unknown>): Promise<Refusal> => |
| 91 | + p.then<never, Refusal>( |
| 92 | + () => { |
| 93 | + throw new Error('expected a refusal, but the query resolved'); |
| 94 | + }, |
| 95 | + (e) => e as Refusal, |
| 96 | + ); |
| 97 | + |
| 98 | +const column = (result: AnalyticsResult, name: string) => |
| 99 | + (result.fields ?? []).find((f) => f.name === name) as |
| 100 | + | { name: string; currency?: string; currencyField?: string } |
| 101 | + | undefined; |
| 102 | + |
| 103 | +/** A `'protocol'` service answering one pending seed draft, which routes `previewDrafts` onto the preview path. */ |
| 104 | +const pendingSeedProtocol = { |
| 105 | + getMetaItems: async () => [{ name: 'os27187_seed', object: OBJECT }], |
| 106 | + getMetaItem: async () => ({ item: { records: ROWS } }), |
| 107 | +}; |
| 108 | + |
| 109 | +describe('[ADR-0144 M0-3] analytics over a record-currency amount', () => { |
| 110 | + let engine: ObjectQL; |
| 111 | + /** Raw-SQL statements and engine aggregates that read THIS object. */ |
| 112 | + const reads = { rawSql: 0, aggregate: 0 }; |
| 113 | + const services: Partial<Record<Face, AnalyticsService>> = {}; |
| 114 | + |
| 115 | + beforeAll(async () => { |
| 116 | + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); |
| 117 | + engine = new ObjectQL({ logger: quiet } as never); |
| 118 | + engine.registerDriver(driver as never, true); |
| 119 | + await engine.init(); |
| 120 | + engine.registry.registerObject(INVOICE as never); |
| 121 | + await engine.syncSchemas(); |
| 122 | + await installDefaultOrganization(engine as never); |
| 123 | + for (const row of ROWS) await engine.insert(OBJECT, { ...row } as never); |
| 124 | + |
| 125 | + const realExecute = (engine as any).execute.bind(engine); |
| 126 | + (engine as any).execute = (sql: unknown, opts?: { object?: string }) => { |
| 127 | + if (opts?.object === OBJECT) reads.rawSql += 1; |
| 128 | + return realExecute(sql, opts); |
| 129 | + }; |
| 130 | + const realAggregate = engine.aggregate.bind(engine); |
| 131 | + (engine as any).aggregate = (object: string, ...rest: unknown[]) => { |
| 132 | + if (object === OBJECT) reads.aggregate += 1; |
| 133 | + return (realAggregate as any)(object, ...rest); |
| 134 | + }; |
| 135 | + |
| 136 | + for (const [face, caps] of [ |
| 137 | + ['native', undefined], |
| 138 | + ['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })], |
| 139 | + ] as const) { |
| 140 | + const registered: Record<string, unknown> = {}; |
| 141 | + const provided: Record<string, unknown> = { data: engine, protocol: pendingSeedProtocol }; |
| 142 | + await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } as never).init({ |
| 143 | + getService: (name: string) => provided[name] ?? registered[name], |
| 144 | + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 145 | + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 146 | + hook: () => {}, |
| 147 | + logger: quiet, |
| 148 | + } as never); |
| 149 | + services[face] = registered.analytics as AnalyticsService; |
| 150 | + } |
| 151 | + }); |
| 152 | + |
| 153 | + afterAll(async () => { |
| 154 | + try { await engine?.destroy(); } catch { /* noop */ } |
| 155 | + }); |
| 156 | + |
| 157 | + for (const face of FACES) { |
| 158 | + describe(`${face} strategy`, () => { |
| 159 | + it('grouped by the code field: per-group totals are right, and the column names the per-row currency', async () => { |
| 160 | + const result = await services[face]!.queryDataset( |
| 161 | + DATASET, |
| 162 | + { dimensions: ['currency'], measures: ['total', 'largest', 'invoices', 'usd_total'] }, |
| 163 | + CTX, |
| 164 | + ); |
| 165 | + const byCode = Object.fromEntries( |
| 166 | + (result.rows as Array<Record<string, unknown>>).map((r) => [r.currency, Number(r.total)]), |
| 167 | + ); |
| 168 | + expect(byCode).toEqual({ USD: 150, EUR: 100 }); |
| 169 | + expect(column(result, 'total')).toMatchObject({ currencyField: 'currency' }); |
| 170 | + expect(column(result, 'total')?.currency).toBeUndefined(); |
| 171 | + expect(column(result, 'largest')).toMatchObject({ currencyField: 'currency' }); |
| 172 | + expect(column(result, 'largest')?.currency).toBeUndefined(); |
| 173 | + // Controls: a fixed field keeps its one code, and a count is no amount. |
| 174 | + expect(column(result, 'usd_total')?.currency).toBe('USD'); |
| 175 | + expect(column(result, 'usd_total')?.currencyField).toBeUndefined(); |
| 176 | + expect(column(result, 'invoices')?.currency).toBeUndefined(); |
| 177 | + expect(column(result, 'invoices')?.currencyField).toBeUndefined(); |
| 178 | + }); |
| 179 | + |
| 180 | + it('grouped by the code field and another dimension, with a totals grouping that keeps the code: served', async () => { |
| 181 | + const result = await services[face]!.queryDataset( |
| 182 | + DATASET, |
| 183 | + { dimensions: ['currency', 'region'], measures: ['total'], totals: { groupings: [['currency']] } }, |
| 184 | + CTX, |
| 185 | + ); |
| 186 | + expect(column(result, 'total')?.currencyField).toBe('currency'); |
| 187 | + const totals = Object.fromEntries( |
| 188 | + (result.totals?.[0]?.rows as Array<Record<string, unknown>>).map((r) => [r.currency, Number(r.total)]), |
| 189 | + ); |
| 190 | + expect(totals).toEqual({ USD: 150, EUR: 100 }); |
| 191 | + }); |
| 192 | + |
| 193 | + for (const [label, selection] of [ |
| 194 | + ['grouped by another dimension only', { dimensions: ['region'], measures: ['total'] }], |
| 195 | + ['not grouped at all (a KPI)', { measures: ['largest'] }], |
| 196 | + ['a totals grand total over the amount', { dimensions: ['currency'], measures: ['total'], totals: { groupings: [[]] } }], |
| 197 | + ] as const) { |
| 198 | + it(`${label}: refused INVALID_FIELD / 400 before anything is read`, async () => { |
| 199 | + const before = { ...reads }; |
| 200 | + const err = await refusalOf(services[face]!.queryDataset(DATASET, selection as never, CTX)); |
| 201 | + expect(err.code, err.message).toBe('INVALID_FIELD'); |
| 202 | + expect(err.status).toBe(400); |
| 203 | + expect(['total', 'largest']).toContain(err.member); |
| 204 | + expect(err.param).toBe('measures'); |
| 205 | + expect(err.field).toBe('amount'); |
| 206 | + expect(err.object).toBe(OBJECT); |
| 207 | + if (label !== 'a totals grand total over the amount') { |
| 208 | + expect(reads.rawSql - before.rawSql).toBe(0); |
| 209 | + expect(reads.aggregate - before.aggregate).toBe(0); |
| 210 | + } |
| 211 | + }); |
| 212 | + } |
| 213 | + |
| 214 | + it('a count over the record-currency object is served ungrouped, with neither currency key', async () => { |
| 215 | + const result = await services[face]!.queryDataset(DATASET, { measures: ['invoices'] }, CTX); |
| 216 | + expect(Number((result.rows[0] as Record<string, unknown>).invoices)).toBe(3); |
| 217 | + expect(column(result, 'invoices')?.currency).toBeUndefined(); |
| 218 | + expect(column(result, 'invoices')?.currencyField).toBeUndefined(); |
| 219 | + }); |
| 220 | + |
| 221 | + it('the cube face refuses the same ungrouped aggregate', async () => { |
| 222 | + services[face]!.registerDataset(DATASET); |
| 223 | + const err = await refusalOf(services[face]!.query({ cube: DATASET.name, measures: ['total'] } as never, CTX)); |
| 224 | + expect(err.code).toBe('INVALID_FIELD'); |
| 225 | + expect(err.status).toBe(400); |
| 226 | + expect(err.member).toBe('total'); |
| 227 | + }); |
| 228 | + }); |
| 229 | + } |
| 230 | + |
| 231 | + it('the draft-preview path carries the same per-row currency column', async () => { |
| 232 | + const result = await services.objectql!.queryDataset( |
| 233 | + DATASET, |
| 234 | + { dimensions: ['currency'], measures: ['total'] }, |
| 235 | + CTX, |
| 236 | + { previewDrafts: true }, |
| 237 | + ); |
| 238 | + expect(column(result, 'total')?.currencyField).toBe('currency'); |
| 239 | + expect(column(result, 'total')?.currency).toBeUndefined(); |
| 240 | + }); |
| 241 | + |
| 242 | + describe('compile-time guards on measure currencies', () => { |
| 243 | + const datasetWith = (measures: unknown[]) => |
| 244 | + DatasetSchema.parse({ |
| 245 | + name: 'os27187_guard', |
| 246 | + label: 'Guard', |
| 247 | + object: OBJECT, |
| 248 | + dimensions: [{ name: 'currency', field: 'currency_code', type: 'string' }], |
| 249 | + measures, |
| 250 | + }); |
| 251 | + const compileRefusal = (measures: unknown[]): Refusal | undefined => { |
| 252 | + try { |
| 253 | + services.objectql!.registerDataset(datasetWith(measures)); |
| 254 | + return undefined; |
| 255 | + } catch (e) { |
| 256 | + return e as Refusal; |
| 257 | + } |
| 258 | + }; |
| 259 | + const expectRefused = (measures: unknown[], named: string) => { |
| 260 | + const err = compileRefusal(measures); |
| 261 | + expect(err?.code, err?.message).toBe('DATASET_INVALID'); |
| 262 | + expect(err?.status).toBe(400); |
| 263 | + expect(err?.message).toContain(`"${named}"`); |
| 264 | + }; |
| 265 | + |
| 266 | + it('a measure currency contradicting a fixed field is refused', () => { |
| 267 | + expectRefused([{ name: 'eur_as_jpy', aggregate: 'sum', field: 'amt_eur', currency: 'JPY' }], 'eur_as_jpy'); |
| 268 | + }); |
| 269 | + |
| 270 | + it("a measure currency restating a fixed field's code is accepted", () => { |
| 271 | + expect(compileRefusal([{ name: 'eur', aggregate: 'sum', field: 'amt_eur', currency: 'EUR' }])).toBeUndefined(); |
| 272 | + }); |
| 273 | + |
| 274 | + it('a measure currency over a record-currency amount is refused', () => { |
| 275 | + expectRefused([{ name: 'total_usd', aggregate: 'sum', field: 'amount', currency: 'USD' }], 'total_usd'); |
| 276 | + }); |
| 277 | + |
| 278 | + it('a measure currency over a dynamic field is not judged (the tenant currency is unknown at compile)', () => { |
| 279 | + expect(compileRefusal([{ name: 'tenant_as_usd', aggregate: 'sum', field: 'amt_tenant', currency: 'USD' }])).toBeUndefined(); |
| 280 | + }); |
| 281 | + |
| 282 | + const base = [ |
| 283 | + { name: 'usd', aggregate: 'sum', field: 'amt_usd' }, |
| 284 | + { name: 'eur', aggregate: 'sum', field: 'amt_eur' }, |
| 285 | + { name: 'tenant', aggregate: 'sum', field: 'amt_tenant' }, |
| 286 | + { name: 'total', aggregate: 'sum', field: 'amount' }, |
| 287 | + { name: 'invoices', aggregate: 'count' }, |
| 288 | + ]; |
| 289 | + |
| 290 | + for (const op of ['sum', 'difference', 'ratio', 'product'] as const) { |
| 291 | + it(`a derived ${op} across two fixed currencies is refused`, () => { |
| 292 | + expectRefused([...base, { name: 'mixed', derived: { op, of: ['usd', 'eur'] } }], 'mixed'); |
| 293 | + }); |
| 294 | + } |
| 295 | + |
| 296 | + it('a derived measure across a record-currency amount and a fixed one is refused', () => { |
| 297 | + expectRefused([...base, { name: 'mixed', derived: { op: 'difference', of: ['total', 'usd'] } }], 'mixed'); |
| 298 | + }); |
| 299 | + |
| 300 | + it('a derived measure built on a mixed-currency derived sum is refused at the first mixed one', () => { |
| 301 | + expectRefused( |
| 302 | + [...base, { name: 'usd_twice', derived: { op: 'sum', of: ['usd', 'usd'] } }, { name: 'mixed', derived: { op: 'sum', of: ['usd_twice', 'eur'] } }], |
| 303 | + 'mixed', |
| 304 | + ); |
| 305 | + }); |
| 306 | + |
| 307 | + it('accepted: one currency with a count (revenue per invoice), one fixed with the tenant (not provably different)', () => { |
| 308 | + expect( |
| 309 | + compileRefusal([ |
| 310 | + ...base, |
| 311 | + { name: 'per_invoice', derived: { op: 'ratio', of: ['usd', 'invoices'] } }, |
| 312 | + { name: 'usd_and_tenant', derived: { op: 'sum', of: ['usd', 'tenant'] } }, |
| 313 | + { name: 'total_share', derived: { op: 'ratio', of: ['total', 'total'] } }, |
| 314 | + ]), |
| 315 | + ).toBeUndefined(); |
| 316 | + }); |
| 317 | + }); |
| 318 | +}); |
0 commit comments