|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#20091] A dataset measure's result-column `currency` honours the source |
| 5 | + * field's `currencyConfig.currencyMode`. |
| 6 | + * |
| 7 | + * ## The contract (spec, not this service) |
| 8 | + * |
| 9 | + * `CurrencyConfigSchema` (`packages/spec/src/data/field.zod.ts`) declares |
| 10 | + * `currencyMode: 'dynamic' | 'fixed'`, defaulting to `'dynamic'`, and |
| 11 | + * `defaultCurrency` defaulting to `'CNY'`. Its own precision refinement reads |
| 12 | + * `defaultCurrency` as the field's one currency ONLY under `'fixed'` — "dynamic |
| 13 | + * mode is out of reach BY DESIGN" — and the `FieldSchema` guidance for the |
| 14 | + * mistaken `currency` key says a fixed currency is declared as |
| 15 | + * `currencyConfig: { currencyMode: 'fixed', defaultCurrency: … }` and "A field |
| 16 | + * without one uses the tenant default at runtime". |
| 17 | + * |
| 18 | + * So a `dynamic` field has no field-level currency. Its `defaultCurrency` is |
| 19 | + * not the column's currency; the tenant default (`ExecutionContext.currency`) |
| 20 | + * is. objectstack-ai/objectui#10461 made the renderer's `resolveFieldCurrency` |
| 21 | + * read `defaultCurrency` only under `'fixed'`; the renderer reads an explicit |
| 22 | + * column `currency` FIRST, so an analytics column that still carried a dynamic |
| 23 | + * field's `defaultCurrency` overrode the renderer's rule on exactly the faces |
| 24 | + * this service feeds. |
| 25 | + * |
| 26 | + * ## Why this suite boots the PLUGIN over a REAL engine |
| 27 | + * |
| 28 | + * The defect lived in the RELAY — `AnalyticsServicePlugin`'s `sourceFieldMeta`, |
| 29 | + * which reads the registered object off the `'data'` engine — not in the |
| 30 | + * service's chain. Every pre-existing currency case in this package stubs |
| 31 | + * `sourceFieldMeta` directly, so none of them could see what the relay does |
| 32 | + * with `currencyMode`. Here the object is registered on a real `ObjectQL` |
| 33 | + * engine over `SqliteWasmDriver`, the plugin reads it the way production does, |
| 34 | + * and the currency is read off the `queryDataset` RESULT. |
| 35 | + * |
| 36 | + * ## Two arrival shapes of "a config naming no mode" |
| 37 | + * |
| 38 | + * The registry does not parse (`SchemaRegistry.registerObject` stores what it |
| 39 | + * is handed), so the relay sees whichever shape the door delivered: |
| 40 | + * |
| 41 | + * - RAW — a programmatic `registerObject`: `{ defaultCurrency: 'EUR' }` has |
| 42 | + * NO `currencyMode` key at all, and `{}` has no `defaultCurrency` either. |
| 43 | + * - PARSED — the declared-stack path (`ObjectSchema.parse`): the schema's |
| 44 | + * defaults are materialised, so no-mode reads `currencyMode: 'dynamic'` and |
| 45 | + * `{}` reads `{ currencyMode: 'dynamic', defaultCurrency: 'CNY' }` — the |
| 46 | + * spec's placeholder `CNY` then leaked onto the column as if authored. |
| 47 | + * |
| 48 | + * Both must answer the same: no mode is `dynamic` by the schema default. |
| 49 | + * |
| 50 | + * ## Both `queryDataset` paths |
| 51 | + * |
| 52 | + * The one reader of the relay's currency is `enrichResultColumns`, which the |
| 53 | + * live path and the ADR-0037 P3 draft-preview path both run. Each case below |
| 54 | + * is asserted on both. `AnalyticsService.query` (the cube face) carries no |
| 55 | + * column `currency` at all — the last block pins that, so "the cube face is |
| 56 | + * unaffected" is a measurement rather than an assumption. |
| 57 | + */ |
| 58 | + |
| 59 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 60 | +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; |
| 61 | +import { ObjectQL } from '@objectstack/objectql'; |
| 62 | +import { ObjectSchema } from '@objectstack/spec/data'; |
| 63 | +import { DatasetSchema } from '@objectstack/spec/ui'; |
| 64 | +import type { ExecutionContext } from '@objectstack/spec/kernel'; |
| 65 | +import type { AnalyticsResult } from '@objectstack/spec/contracts'; |
| 66 | + |
| 67 | +import type { AnalyticsService } from '../analytics-service.js'; |
| 68 | +import { AnalyticsServicePlugin } from '../plugin.js'; |
| 69 | + |
| 70 | +const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } }; |
| 71 | + |
| 72 | +const OBJECT = 'money_deal'; |
| 73 | + |
| 74 | +/** The fields as AUTHORED — one per case, plus a non-monetary control. */ |
| 75 | +const AUTHORED_FIELDS = { |
| 76 | + stage: { type: 'text' }, |
| 77 | + amt_fixed: { type: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } }, |
| 78 | + amt_dynamic: { type: 'currency', currencyConfig: { currencyMode: 'dynamic', defaultCurrency: 'EUR' } }, |
| 79 | + amt_nomode: { type: 'currency', currencyConfig: { defaultCurrency: 'EUR' } }, |
| 80 | + amt_emptycfg: { type: 'currency', currencyConfig: {} }, |
| 81 | + amt_bare: { type: 'currency' }, |
| 82 | + units: { type: 'number' }, |
| 83 | +} as const; |
| 84 | + |
| 85 | +const ROWS = [ |
| 86 | + { id: 'd1', stage: 'won', amt_fixed: 10, amt_dynamic: 10, amt_nomode: 10, amt_emptycfg: 10, amt_bare: 10, units: 1 }, |
| 87 | + { id: 'd2', stage: 'lost', amt_fixed: 5, amt_dynamic: 5, amt_nomode: 5, amt_emptycfg: 5, amt_bare: 5, units: 2 }, |
| 88 | +]; |
| 89 | + |
| 90 | +const DATASET = DatasetSchema.parse({ |
| 91 | + name: 'money_by_stage', |
| 92 | + label: 'Money by Stage', |
| 93 | + object: OBJECT, |
| 94 | + dimensions: [{ name: 'stage', field: 'stage', type: 'string' }], |
| 95 | + measures: [ |
| 96 | + { name: 'm_fixed', aggregate: 'sum', field: 'amt_fixed' }, |
| 97 | + { name: 'm_dynamic', aggregate: 'sum', field: 'amt_dynamic' }, |
| 98 | + { name: 'm_nomode', aggregate: 'sum', field: 'amt_nomode' }, |
| 99 | + { name: 'm_emptycfg', aggregate: 'sum', field: 'amt_emptycfg' }, |
| 100 | + { name: 'm_bare', aggregate: 'sum', field: 'amt_bare' }, |
| 101 | + // An explicit measure `currency` wins over every field-side answer, |
| 102 | + // the field's FIXED currency included. |
| 103 | + { name: 'm_explicit_dynamic', aggregate: 'sum', field: 'amt_dynamic', currency: 'JPY' }, |
| 104 | + { name: 'm_explicit_fixed', aggregate: 'sum', field: 'amt_fixed', currency: 'JPY' }, |
| 105 | + { name: 'm_units', aggregate: 'sum', field: 'units' }, |
| 106 | + ], |
| 107 | +}); |
| 108 | + |
| 109 | +const SELECTION = { |
| 110 | + dimensions: ['stage'], |
| 111 | + measures: DATASET.measures!.map((m) => m.name), |
| 112 | +}; |
| 113 | + |
| 114 | +/** A tenant whose default currency differs from every field's `defaultCurrency`. */ |
| 115 | +const CTX = { currency: 'USD' } as ExecutionContext; |
| 116 | + |
| 117 | +type Shape = 'raw' | 'parsed'; |
| 118 | + |
| 119 | +function fieldsFor(shape: Shape): Record<string, unknown> { |
| 120 | + if (shape === 'raw') return AUTHORED_FIELDS as unknown as Record<string, unknown>; |
| 121 | + // The declared-stack door: the spec's own parse materialises the defaults. |
| 122 | + return ObjectSchema.parse({ name: OBJECT, label: 'Money Deal', fields: AUTHORED_FIELDS }).fields as Record<string, unknown>; |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * A `'protocol'` service answering one PENDING seed draft for {@link OBJECT}, |
| 127 | + * which is what routes `queryDataset({ previewDrafts: true })` onto the |
| 128 | + * draft-preview path through the plugin's own `draftRowsResolver`. |
| 129 | + */ |
| 130 | +const pendingSeedProtocol = { |
| 131 | + getMetaItems: async () => [{ name: 'money_seed', object: OBJECT }], |
| 132 | + getMetaItem: async () => ({ item: { records: ROWS } }), |
| 133 | +}; |
| 134 | + |
| 135 | +async function bootPlugin(engine: ObjectQL): Promise<AnalyticsService> { |
| 136 | + const registered: Record<string, unknown> = {}; |
| 137 | + const services: Record<string, unknown> = { data: engine, protocol: pendingSeedProtocol }; |
| 138 | + const ctx = { |
| 139 | + getService: (name: string) => services[name] ?? registered[name], |
| 140 | + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 141 | + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 142 | + logger: quiet, |
| 143 | + }; |
| 144 | + await new AnalyticsServicePlugin({ |
| 145 | + // The engine path, so the live rows really come from the driver. |
| 146 | + queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }), |
| 147 | + }).init(ctx as never); |
| 148 | + return registered.analytics as AnalyticsService; |
| 149 | +} |
| 150 | + |
| 151 | +const currencyByColumn = (result: AnalyticsResult): Record<string, string | undefined> => |
| 152 | + Object.fromEntries( |
| 153 | + (result.fields ?? []) |
| 154 | + .filter((f) => f.name.startsWith('m_')) |
| 155 | + .map((f) => [f.name, (f as { currency?: string }).currency]), |
| 156 | + ); |
| 157 | + |
| 158 | +describe.each<Shape>(['raw', 'parsed'])('[#20091] result-column currency honours currencyMode — %s registration', (shape) => { |
| 159 | + let driver: SqliteWasmDriver; |
| 160 | + let service: AnalyticsService; |
| 161 | + let live: Record<string, string | undefined>; |
| 162 | + let preview: Record<string, string | undefined>; |
| 163 | + let liveRows: AnalyticsResult['rows']; |
| 164 | + |
| 165 | + beforeAll(async () => { |
| 166 | + const fields = fieldsFor(shape); |
| 167 | + driver = new SqliteWasmDriver({ filename: ':memory:' }); |
| 168 | + (driver as unknown as { logger: unknown }).logger = quiet; |
| 169 | + await driver.initObjects([{ name: OBJECT, fields } as never]); |
| 170 | + for (const row of ROWS) await driver.create(OBJECT, { ...row }); |
| 171 | + const engine = new ObjectQL({ logger: quiet } as never); |
| 172 | + engine.registerDriver(driver as never, true); |
| 173 | + await engine.init(); |
| 174 | + engine.registerObject({ name: OBJECT, label: 'Money Deal', fields } as never); |
| 175 | + service = await bootPlugin(engine); |
| 176 | + |
| 177 | + const liveResult = await service.queryDataset(DATASET, SELECTION, CTX); |
| 178 | + const previewResult = await service.queryDataset(DATASET, SELECTION, CTX, { previewDrafts: true }); |
| 179 | + live = currencyByColumn(liveResult); |
| 180 | + preview = currencyByColumn(previewResult); |
| 181 | + liveRows = liveResult.rows; |
| 182 | + }); |
| 183 | + afterAll(async () => { |
| 184 | + await driver?.disconnect?.(); |
| 185 | + }); |
| 186 | + |
| 187 | + it('CONTROL: the registered object is what this shape says it is', () => { |
| 188 | + // Without this the two describe blocks could be measuring one shape twice. |
| 189 | + const nomode = (fieldsFor(shape).amt_nomode as { currencyConfig?: { currencyMode?: string } }).currencyConfig; |
| 190 | + expect(nomode?.currencyMode).toBe(shape === 'raw' ? undefined : 'dynamic'); |
| 191 | + }); |
| 192 | + |
| 193 | + it('CONTROL: the live path really ran over the driver rows', () => { |
| 194 | + const won = (liveRows as Array<Record<string, unknown>>).find((r) => r.stage === 'won'); |
| 195 | + expect(won?.m_fixed).toBe(10); |
| 196 | + }); |
| 197 | + |
| 198 | + it("currencyMode 'fixed' — the column carries the field's currency", () => { |
| 199 | + expect(live.m_fixed).toBe('EUR'); |
| 200 | + expect(preview.m_fixed).toBe('EUR'); |
| 201 | + }); |
| 202 | + |
| 203 | + it("currencyMode 'dynamic' — the column carries the tenant default, never the field's defaultCurrency", () => { |
| 204 | + expect(live.m_dynamic).toBe('USD'); |
| 205 | + expect(preview.m_dynamic).toBe('USD'); |
| 206 | + }); |
| 207 | + |
| 208 | + it('a currencyConfig naming no mode is dynamic — the tenant default', () => { |
| 209 | + expect(live.m_nomode).toBe('USD'); |
| 210 | + expect(preview.m_nomode).toBe('USD'); |
| 211 | + }); |
| 212 | + |
| 213 | + it("an empty currencyConfig is dynamic — the spec's defaulted CNY never reaches the column", () => { |
| 214 | + expect(live.m_emptycfg).toBe('USD'); |
| 215 | + expect(preview.m_emptycfg).toBe('USD'); |
| 216 | + }); |
| 217 | + |
| 218 | + it('a currency field with no currencyConfig — the tenant default', () => { |
| 219 | + expect(live.m_bare).toBe('USD'); |
| 220 | + expect(preview.m_bare).toBe('USD'); |
| 221 | + }); |
| 222 | + |
| 223 | + it('an explicit measure currency wins, over a dynamic field and over a fixed one', () => { |
| 224 | + expect(live.m_explicit_dynamic).toBe('JPY'); |
| 225 | + expect(preview.m_explicit_dynamic).toBe('JPY'); |
| 226 | + expect(live.m_explicit_fixed).toBe('JPY'); |
| 227 | + expect(preview.m_explicit_fixed).toBe('JPY'); |
| 228 | + }); |
| 229 | + |
| 230 | + it('CONTROL: a non-monetary measure carries no currency', () => { |
| 231 | + expect(live.m_units).toBeUndefined(); |
| 232 | + expect(preview.m_units).toBeUndefined(); |
| 233 | + }); |
| 234 | +}); |
| 235 | + |
| 236 | +describe('[#20091] the cube face carries no column currency to disagree about', () => { |
| 237 | + it('AnalyticsService.query over the same registered object mints no `currency` on any column', async () => { |
| 238 | + const driver = new SqliteWasmDriver({ filename: ':memory:' }); |
| 239 | + (driver as unknown as { logger: unknown }).logger = quiet; |
| 240 | + await driver.initObjects([{ name: OBJECT, fields: AUTHORED_FIELDS } as never]); |
| 241 | + for (const row of ROWS) await driver.create(OBJECT, { ...row }); |
| 242 | + const engine = new ObjectQL({ logger: quiet } as never); |
| 243 | + engine.registerDriver(driver as never, true); |
| 244 | + await engine.init(); |
| 245 | + engine.registerObject({ name: OBJECT, label: 'Money Deal', fields: AUTHORED_FIELDS } as never); |
| 246 | + const service = await bootPlugin(engine); |
| 247 | + // Registering the dataset compiles its cube under the dataset's name. |
| 248 | + service.registerDataset(DATASET); |
| 249 | + try { |
| 250 | + const result = await service.query( |
| 251 | + { cube: DATASET.name, dimensions: ['stage'], measures: ['m_fixed', 'm_dynamic'] } as never, |
| 252 | + CTX, |
| 253 | + ); |
| 254 | + // Positive control: the query answered, so "no currency" is about the |
| 255 | + // columns and not about an empty response. |
| 256 | + expect(result.fields?.map((f) => f.name)).toEqual(expect.arrayContaining(['m_fixed', 'm_dynamic'])); |
| 257 | + for (const f of result.fields ?? []) expect((f as { currency?: string }).currency).toBeUndefined(); |
| 258 | + } finally { |
| 259 | + await driver.disconnect?.(); |
| 260 | + } |
| 261 | + }); |
| 262 | +}); |
0 commit comments