|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The home-currency lock (ADR-0144 D4, multi-currency M1-3): |
| 5 | + * `localization.currency` saves freely until an exchange rate row or a |
| 6 | + * `homeAmount` declaration uses it, and is refused after either; the refusal |
| 7 | + * and the Localization page name what uses it, in every locale the settings |
| 8 | + * bundle ships. |
| 9 | + */ |
| 10 | + |
| 11 | +import { describe, expect, it, vi } from 'vitest'; |
| 12 | +import type { IHttpServer, IHttpRequest, IHttpResponse, RouteHandler } from '@objectstack/spec/contracts'; |
| 13 | +import { SettingsService } from './settings-service.js'; |
| 14 | +import { registerSettingsRoutes } from './settings-routes.js'; |
| 15 | +import { localizationSettingsManifest } from './manifests/localization.manifest.js'; |
| 16 | +import { mailSettingsManifest } from './manifests/mail.manifest.js'; |
| 17 | +import { settingsBuiltinTranslations } from './translations/index.js'; |
| 18 | +import { SETTINGS_LIVE_STATUS_BANNER_ID, SettingsValidationError } from './settings-service.types.js'; |
| 19 | +import { |
| 20 | + CURRENCY_LOCK_COPY, |
| 21 | + EXCHANGE_RATE_OBJECT, |
| 22 | + readCurrencyUsage, |
| 23 | + registerLocalizationCurrencyLock, |
| 24 | + type CurrencyUsageEngine, |
| 25 | +} from './localization-currency-lock.js'; |
| 26 | + |
| 27 | +const ORG = 'org_alpha'; |
| 28 | +const OTHER_ORG = 'org_beta'; |
| 29 | +const ctx = { tenantId: ORG, userId: 'usr_admin' }; |
| 30 | + |
| 31 | +/** An invoice whose `amount` declares its home-currency projection (#27191's shape). */ |
| 32 | +const INVOICE = { |
| 33 | + name: 'invoice', |
| 34 | + label: 'Invoice', |
| 35 | + fields: { |
| 36 | + amount: { |
| 37 | + type: 'currency', |
| 38 | + currencyConfig: { |
| 39 | + currencyMode: 'record', |
| 40 | + currencyField: 'currency_code', |
| 41 | + homeAmount: { field: 'amount_home', rateDate: 'invoice_date', rateField: 'amount_rate' }, |
| 42 | + }, |
| 43 | + }, |
| 44 | + amount_home: { type: 'currency', readonly: true }, |
| 45 | + }, |
| 46 | +}; |
| 47 | +/** A record-mode amount with no home projection: it does not use the home currency. */ |
| 48 | +const QUOTE = { |
| 49 | + name: 'quote', |
| 50 | + label: 'Quote', |
| 51 | + fields: { total: { type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'code' } } }, |
| 52 | +}; |
| 53 | + |
| 54 | +/** The engine the lock reads: `sys_exchange_rate` rows and the object registry. */ |
| 55 | +function fakeEngine(opts: { rateObjectRegistered?: boolean } = {}) { |
| 56 | + const rates: Array<{ organization_id: string | null; currency: string }> = []; |
| 57 | + const objects: unknown[] = [QUOTE]; |
| 58 | + const count = vi.fn(async (name: string, query?: { where?: Record<string, unknown> }) => { |
| 59 | + if (name !== EXCHANGE_RATE_OBJECT) throw new Error(`unexpected count of ${name}`); |
| 60 | + const org = query?.where?.organization_id; |
| 61 | + return rates.filter((r) => org === undefined || r.organization_id === org).length; |
| 62 | + }); |
| 63 | + const engine: CurrencyUsageEngine = { |
| 64 | + count, |
| 65 | + registry: { |
| 66 | + getAllObjects: () => objects, |
| 67 | + getObject: (name: string) => |
| 68 | + name === EXCHANGE_RATE_OBJECT && opts.rateObjectRegistered !== false ? { name } : undefined, |
| 69 | + }, |
| 70 | + }; |
| 71 | + return { engine, rates, objects, count }; |
| 72 | +} |
| 73 | + |
| 74 | +function rig(opts: { rateObjectRegistered?: boolean } = {}) { |
| 75 | + const svc = new SettingsService({ env: {} }); |
| 76 | + svc.registerManifest(localizationSettingsManifest); |
| 77 | + const fake = fakeEngine(opts); |
| 78 | + expect(registerLocalizationCurrencyLock(svc, fake.engine)).toBe(true); |
| 79 | + return { svc, ...fake }; |
| 80 | +} |
| 81 | + |
| 82 | +async function refusalOf(p: Promise<unknown>): Promise<SettingsValidationError> { |
| 83 | + const err = await p.then(() => undefined, (e: unknown) => e); |
| 84 | + expect(err).toBeInstanceOf(SettingsValidationError); |
| 85 | + return err as SettingsValidationError; |
| 86 | +} |
| 87 | + |
| 88 | +describe('localization.currency — saves freely until used', () => { |
| 89 | + it('saves and changes before the first rate row and before any homeAmount declaration', async () => { |
| 90 | + const { svc } = rig(); |
| 91 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 92 | + await svc.set('localization', 'currency', 'EUR', ctx); |
| 93 | + await svc.set('localization', 'currency', null, ctx); |
| 94 | + await svc.set('localization', 'currency', 'CNY', ctx); |
| 95 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('CNY'); |
| 96 | + }); |
| 97 | + |
| 98 | + it('a record-mode amount without `homeAmount` does not lock it', async () => { |
| 99 | + const { svc } = rig(); |
| 100 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 101 | + await svc.set('localization', 'currency', 'EUR', ctx); |
| 102 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('EUR'); |
| 103 | + }); |
| 104 | + |
| 105 | + it("another organization's rate rows do not lock this one", async () => { |
| 106 | + const { svc, rates } = rig(); |
| 107 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 108 | + rates.push({ organization_id: OTHER_ORG, currency: 'EUR' }); |
| 109 | + await svc.set('localization', 'currency', 'EUR', ctx); |
| 110 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('EUR'); |
| 111 | + }); |
| 112 | +}); |
| 113 | + |
| 114 | +describe('localization.currency — locked once used', () => { |
| 115 | + it('is refused after the first rate row, naming it', async () => { |
| 116 | + const { svc, rates } = rig(); |
| 117 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 118 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 119 | + const err = await refusalOf(svc.set('localization', 'currency', 'EUR', ctx)); |
| 120 | + expect(err.fields).toHaveLength(1); |
| 121 | + expect(err.fields[0]).toMatchObject({ |
| 122 | + field: 'currency', |
| 123 | + code: 'invalid_value', |
| 124 | + label: 'Default currency', |
| 125 | + constraint: { lockedBy: 'in_use', objects: [], exchangeRates: 1 }, |
| 126 | + }); |
| 127 | + expect(err.fields[0].message).toMatch(/^The default currency is locked at USD because it is in use by 1 exchange rate\. /); |
| 128 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('USD'); |
| 129 | + }); |
| 130 | + |
| 131 | + it('is refused after a homeAmount declaration, naming the object', async () => { |
| 132 | + const { svc, objects } = rig(); |
| 133 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 134 | + objects.push(INVOICE); |
| 135 | + const err = await refusalOf(svc.set('localization', 'currency', 'EUR', ctx)); |
| 136 | + expect(err.fields[0].constraint).toEqual({ lockedBy: 'in_use', objects: ['invoice'], exchangeRates: 0 }); |
| 137 | + expect(err.fields[0].message).toContain('in use by 1 object (Invoice).'); |
| 138 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('USD'); |
| 139 | + }); |
| 140 | + |
| 141 | + it('names both users when both exist', async () => { |
| 142 | + const { svc, rates, objects } = rig(); |
| 143 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 144 | + objects.push(INVOICE, { ...INVOICE, name: 'order', label: 'Order' }); |
| 145 | + rates.push({ organization_id: ORG, currency: 'EUR' }, { organization_id: ORG, currency: 'JPY' }); |
| 146 | + const err = await refusalOf(svc.set('localization', 'currency', 'EUR', ctx)); |
| 147 | + expect(err.fields[0].message).toContain('in use by 2 objects (Invoice, Order) and 2 exchange rates.'); |
| 148 | + }); |
| 149 | + |
| 150 | + it('refuses a clear too, and the namespace reset with it', async () => { |
| 151 | + const { svc, rates } = rig(); |
| 152 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 153 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 154 | + await refusalOf(svc.set('localization', 'currency', null, ctx)); |
| 155 | + await refusalOf(svc.setMany('localization', { currency: null, timezone: null }, ctx)); |
| 156 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('USD'); |
| 157 | + }); |
| 158 | + |
| 159 | + it('lets a re-save of the value in force through, and the batch beside it', async () => { |
| 160 | + const { svc, rates } = rig(); |
| 161 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 162 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 163 | + await svc.setMany('localization', { currency: 'USD', timezone: 'Asia/Tokyo' }, ctx); |
| 164 | + expect((await svc.get('localization', 'timezone', ctx)).value).toBe('Asia/Tokyo'); |
| 165 | + }); |
| 166 | + |
| 167 | + it('lets the first value through while the currency is unset (ADR-0144 Open item 4: never blocks choosing one)', async () => { |
| 168 | + const { svc, rates, objects } = rig(); |
| 169 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 170 | + objects.push(INVOICE); |
| 171 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 172 | + await refusalOf(svc.set('localization', 'currency', 'GBP', ctx)); |
| 173 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('USD'); |
| 174 | + }); |
| 175 | + |
| 176 | + it('lifts by itself once the last rate row and the last declaration are gone', async () => { |
| 177 | + const { svc, rates, objects } = rig(); |
| 178 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 179 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 180 | + objects.push(INVOICE); |
| 181 | + await refusalOf(svc.set('localization', 'currency', 'EUR', ctx)); |
| 182 | + rates.length = 0; |
| 183 | + await refusalOf(svc.set('localization', 'currency', 'EUR', ctx)); |
| 184 | + objects.pop(); |
| 185 | + await svc.set('localization', 'currency', 'EUR', ctx); |
| 186 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('EUR'); |
| 187 | + }); |
| 188 | + |
| 189 | + it('counts no rate rows where the composition does not register the rate table', async () => { |
| 190 | + const { svc, count } = rig({ rateObjectRegistered: false }); |
| 191 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 192 | + await svc.set('localization', 'currency', 'EUR', ctx); |
| 193 | + expect(count).not.toHaveBeenCalled(); |
| 194 | + }); |
| 195 | + |
| 196 | + it('fails the write when the rate count fails, rather than guess', async () => { |
| 197 | + const { svc, count } = rig(); |
| 198 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 199 | + count.mockRejectedValueOnce(new Error('driver down')); |
| 200 | + await expect(svc.set('localization', 'currency', 'EUR', ctx)).rejects.toThrow('driver down'); |
| 201 | + expect((await svc.get('localization', 'currency', ctx)).value).toBe('USD'); |
| 202 | + }); |
| 203 | +}); |
| 204 | + |
| 205 | +describe('readCurrencyUsage', () => { |
| 206 | + it("counts the organization's own rows, under a system read", async () => { |
| 207 | + const { engine, rates, count } = fakeEngine(); |
| 208 | + rates.push({ organization_id: ORG, currency: 'EUR' }, { organization_id: OTHER_ORG, currency: 'EUR' }); |
| 209 | + expect((await readCurrencyUsage(engine, ORG)).exchangeRates).toBe(1); |
| 210 | + expect(count).toHaveBeenLastCalledWith(EXCHANGE_RATE_OBJECT, { |
| 211 | + where: { organization_id: ORG }, |
| 212 | + context: { isSystem: true }, |
| 213 | + }); |
| 214 | + }); |
| 215 | + |
| 216 | + it('counts every row in a composition with no organization object', async () => { |
| 217 | + const { engine, rates } = fakeEngine(); |
| 218 | + rates.push({ organization_id: null, currency: 'EUR' }, { organization_id: null, currency: 'JPY' }); |
| 219 | + expect((await readCurrencyUsage(engine, null)).exchangeRates).toBe(2); |
| 220 | + }); |
| 221 | +}); |
| 222 | + |
| 223 | +describe('the copy — every locale the settings bundle ships', () => { |
| 224 | + it('covers exactly the locales of settingsBuiltinTranslations', () => { |
| 225 | + expect(Object.keys(CURRENCY_LOCK_COPY).sort()).toEqual(Object.keys(settingsBuiltinTranslations).sort()); |
| 226 | + }); |
| 227 | + |
| 228 | + it.each([ |
| 229 | + ['zh-CN', '默认币种已锁定为 USD:它已被 1 个对象(Invoice)和 2 条汇率使用。'], |
| 230 | + ['ja', '既定の通貨は USD でロックされています。1 件のオブジェクト(Invoice)と 2 件の為替レートで使用されているためです。'], |
| 231 | + ['es-MX', 'La moneda predeterminada está bloqueada en USD porque está en uso en 1 objeto (Invoice) y 2 tipos de cambio.'], |
| 232 | + ['fr-FR', 'The default currency is locked at USD because it is in use by 1 object (Invoice) and 2 exchange rates.'], |
| 233 | + ])('writes the refusal in %s', async (locale, opening) => { |
| 234 | + const { svc, rates, objects } = rig(); |
| 235 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 236 | + objects.push(INVOICE); |
| 237 | + rates.push({ organization_id: ORG, currency: 'EUR' }, { organization_id: ORG, currency: 'JPY' }); |
| 238 | + const err = await refusalOf(svc.set('localization', 'currency', 'EUR', { ...ctx, locale })); |
| 239 | + expect(err.fields[0].message.startsWith(opening)).toBe(true); |
| 240 | + }); |
| 241 | +}); |
| 242 | + |
| 243 | +// ── The page: GET /api/settings/localization ────────────────────────────── |
| 244 | + |
| 245 | +class MockHttp implements IHttpServer { |
| 246 | + routes = new Map<string, RouteHandler>(); |
| 247 | + private add(method: string, path: string, handler: RouteHandler) { |
| 248 | + this.routes.set(`${method} ${path}`, handler); |
| 249 | + } |
| 250 | + get(path: string, h: RouteHandler) { this.add('GET', path, h); return this as any; } |
| 251 | + post(path: string, h: RouteHandler) { this.add('POST', path, h); return this as any; } |
| 252 | + put(path: string, h: RouteHandler) { this.add('PUT', path, h); return this as any; } |
| 253 | + delete(path: string, h: RouteHandler) { this.add('DELETE', path, h); return this as any; } |
| 254 | + patch(path: string, h: RouteHandler) { this.add('PATCH', path, h); return this as any; } |
| 255 | + use() { return this as any; } |
| 256 | + listen() { return Promise.resolve(); } |
| 257 | + close() { return Promise.resolve(); } |
| 258 | + getInstance() { return null; } |
| 259 | +} |
| 260 | + |
| 261 | +function pageRig() { |
| 262 | + const base = rig(); |
| 263 | + const http = new MockHttp(); |
| 264 | + registerSettingsRoutes(http, base.svc, { |
| 265 | + contextFromRequest: () => ({ ...ctx, enforced: true, permissions: ['setup.access', 'setup.write'] }), |
| 266 | + }); |
| 267 | + const call = async (verb: 'GET' | 'PUT', headers: Record<string, string>, body?: unknown) => { |
| 268 | + const req: IHttpRequest = { |
| 269 | + params: { namespace: 'localization' }, query: {}, body, headers, method: verb, path: '/', |
| 270 | + }; |
| 271 | + const state: { status: number; body?: any } = { status: 200 }; |
| 272 | + const res: IHttpResponse = { |
| 273 | + json: vi.fn((data) => { state.body = data; }) as any, |
| 274 | + send: vi.fn() as any, |
| 275 | + status: vi.fn((code: number) => { state.status = code; return res; }) as any, |
| 276 | + header: vi.fn(() => res) as any, |
| 277 | + }; |
| 278 | + await http.routes.get(`${verb} /api/settings/:namespace`)!(req, res); |
| 279 | + return state; |
| 280 | + }; |
| 281 | + return { ...base, call }; |
| 282 | +} |
| 283 | + |
| 284 | +describe('the Localization page states what uses the currency', () => { |
| 285 | + it('states nothing while nothing uses it', async () => { |
| 286 | + const { svc, call } = pageRig(); |
| 287 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 288 | + const { body } = await call('GET', {}); |
| 289 | + expect(body.data.manifest.specifiers).toEqual(localizationSettingsManifest.specifiers); |
| 290 | + }); |
| 291 | + |
| 292 | + it('heads the page with the lock and its users once used, in the request language', async () => { |
| 293 | + const { svc, rates, objects, call } = pageRig(); |
| 294 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 295 | + objects.push(INVOICE); |
| 296 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 297 | + const en = (await call('GET', {})).body.data.manifest.specifiers[0]; |
| 298 | + expect(en).toMatchObject({ |
| 299 | + type: 'info_banner', |
| 300 | + id: SETTINGS_LIVE_STATUS_BANNER_ID, |
| 301 | + label: 'Default currency locked: USD', |
| 302 | + bannerText: 'In use by 1 object (Invoice) and 1 exchange rate. Converted amounts are stored in this currency, so it can no longer be changed.', |
| 303 | + bannerSeverity: 'info', |
| 304 | + }); |
| 305 | + const zh = (await call('GET', { 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8' })).body.data.manifest.specifiers[0]; |
| 306 | + expect(zh.label).toBe('默认币种已锁定:USD'); |
| 307 | + expect(zh.bannerText).toBe('已被 1 个对象(Invoice)和 1 条汇率使用。换算后的金额都以该币种存储,因此不能再修改。'); |
| 308 | + }); |
| 309 | + |
| 310 | + it('warns while the currency is unset and something already needs it', async () => { |
| 311 | + const { rates, call } = pageRig(); |
| 312 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 313 | + const banner = (await call('GET', { 'accept-language': 'ja-JP' })).body.data.manifest.specifiers[0]; |
| 314 | + expect(banner).toMatchObject({ label: '既定の通貨が設定されていません', bannerSeverity: 'warning' }); |
| 315 | + expect(banner.bannerText).toContain('使用状況: 1 件の為替レート。'); |
| 316 | + }); |
| 317 | + |
| 318 | + it('answers a refused save 400 SETTINGS_VALIDATION, the refusal in the request language', async () => { |
| 319 | + const { svc, rates, call } = pageRig(); |
| 320 | + await svc.set('localization', 'currency', 'USD', ctx); |
| 321 | + rates.push({ organization_id: ORG, currency: 'EUR' }); |
| 322 | + const { status, body } = await call('PUT', { 'accept-language': 'es-ES' }, { currency: 'EUR' }); |
| 323 | + expect(status).toBe(400); |
| 324 | + expect(body.error.code).toBe('SETTINGS_VALIDATION'); |
| 325 | + expect(body.error.details.fields[0]).toMatchObject({ field: 'currency', code: 'invalid_value' }); |
| 326 | + expect(body.error.details.fields[0].message).toMatch(/^La moneda predeterminada está bloqueada en USD porque está en uso en 1 tipo de cambio\./); |
| 327 | + }); |
| 328 | +}); |
| 329 | + |
| 330 | +describe('registerLocalizationCurrencyLock', () => { |
| 331 | + it('registers nothing on a service without the localization namespace', () => { |
| 332 | + const svc = new SettingsService({ env: {} }); |
| 333 | + svc.registerManifest(mailSettingsManifest); |
| 334 | + expect(registerLocalizationCurrencyLock(svc, fakeEngine().engine)).toBe(false); |
| 335 | + }); |
| 336 | +}); |
0 commit comments