Skip to content

Commit 321991c

Browse files
committed
feat(objectql): a datetime document date is dated in the organization's localization.timezone; the R2 core ships with R1 (#27192)
Claude-Session: https://claude.ai/code/session_01Utp6CYjLJ7sxfUehRrLbT3 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2fe4a2c commit 321991c

10 files changed

Lines changed: 300 additions & 58 deletions

‎.changeset/27192-home-amount-error-codes.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ feat(spec): the error-code ledger registers `ERR_EXCHANGE_RATE_MISSING` and `ERR
77
Clause-②: yes (widening: two new error codes under `@objectstack/objectql` in `ERROR_CODE_LEDGER`; the `CURRENCY_FRACTION_DIGITS` table, already in the package, is now exported from `@objectstack/spec/data`. No Zod schema shape and no table value changes)
88
Metadata-protocol: none
99

10-
⛔ Not released alone: these ship in release R2 with the write-time home-currency projection that answers them (ADR-0144 D9).
10+
⛔ Not released alone: these are part of the R2 core (ADR-0144 D9) and ship with R1 in 18.3.0, together with the write-time home-currency projection that answers them, the `sys_exchange_rate` table (#27185) and the `localization.currency` lock (#27198).
1111

1212
- `ERR_EXCHANGE_RATE_MISSING` (400): a write that must convert an amount into the home currency found no exchange rate in force on the record's document date.
1313
- `ERR_HOME_CURRENCY_UNSET` (400): the same write found no home currency, because the organization's `localization.currency` setting is not set.

‎.changeset/27192-home-amount-projection.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,17 @@
44

55
feat(objectql): a record-mode amount that declares `currencyConfig.homeAmount` stores its value converted into the home currency, with the rate used, on every write (ADR-0144 D5)
66

7-
Clause-②: yes (widening: `ObjectQL.setHomeCurrencyResolver(resolver)` is new public engine surface; the write refusals below reach only an object that declares `currencyConfig.homeAmount`, a key that ships in this same release, so no released accept set narrows)
7+
Clause-②: yes (widening: `ObjectQL.setHomeLocalizationResolver(resolver)` is new public engine surface; the write refusals below reach only an object that declares `currencyConfig.homeAmount`, a key that ships in this same release, so no released accept set narrows)
88
Metadata-protocol: none
99

10-
⛔ Not released alone: this is the engine half of release R2 (ADR-0144 D9). It ships in the same release as the `currencyConfig.homeAmount` key (`@objectstack/spec`), never ahead of it and never without it.
10+
⛔ Not released alone: this is the engine half of the R2 core (ADR-0144 D9). It ships with R1 in 18.3.0, together with the `currencyConfig.homeAmount` key (#27191), the `sys_exchange_rate` table (#27185) and the `localization.currency` lock (#27198).
1111

1212
When a record is inserted, and when an update changes its amount, its currency code or its document date, the engine writes the two fields `homeAmount` names:
1313

14-
- **The rate** is the organization's `sys_exchange_rate` row for the record's currency with the latest `effective_date` on or before the document date (`homeAmount.rateDate`). A `datetime` document date is read as its UTC calendar day. The row's rate is stored in `homeAmount.rateField` as it is, unrounded.
14+
- **The rate** is the organization's `sys_exchange_rate` row for the record's currency with the latest `effective_date` on or before the document date (`homeAmount.rateDate`). A `datetime` document date is dated in the organization's `localization.timezone` (UTC when unset): an invoice written at 01:00 in Shanghai takes that Shanghai day's rate. A `date` is its own day. The row's rate is stored in `homeAmount.rateField` as it is, unrounded.
1515
- **The home amount** is the amount divided by the rate (a rate states how many units of the foreign currency one unit of the home currency buys), computed in exact decimal arithmetic and rounded once, half away from zero, to the home currency's CLDR fraction digits (0 for JPY, 2 for USD and CNY, 3 for KWD; for a few codes, such as IQD, HUF, COP, IDR and PKR, CLDR's count differs from ISO 4217's minor units, and CLDR's applies). USD 10,000 at 0.1389 into CNY stores 71994.24.
1616
- **Same currency as home:** rate `1`, no rate read. **Blank amount:** blank home amount and rate.
17-
- **The home currency** is the `localization.currency` setting, read for the row's organization through the `settings` service. `ObjectQLPlugin` wires it; an engine booted without the plugin answers it through `setHomeCurrencyResolver`.
17+
- **The home currency** is the `localization.currency` setting, read for the row's organization through the `settings` service, in one grouped read with `localization.timezone`. `ObjectQLPlugin` wires it; an engine booted without the plugin answers both through `setHomeLocalizationResolver`.
1818
- **The engine's alone.** A value a caller sends for either field is dropped (or refused under `strictReadonlyWrites`) as before; a `defaultValue`, a system write or a historical (`preserveAudit`) import of either field is computed over.
1919
- **Refusals, before anything is written:** `ERR_EXCHANGE_RATE_MISSING` / 400 when no rate row is in force on the document date (the message names the currency and the date; never a rate of 1, a later rate or an empty home amount); `ERR_HOME_CURRENCY_UNSET` / 400 when the organization has no `localization.currency` (never an assumed home currency); `VALIDATION_FAILED` `required` on the date field when a foreign-currency amount has no document date. A multi-row insert (`insertMany`, the import) refuses only the offending row; an update by filter is refused when its one patch would convert the matched rows to different home amounts.
2020
- **Every door, one path.** REST create and update, the import (batched and per row, dry run included) and `validate()` reach the same insert and update seam, so they convert and refuse alike.

‎content/docs/data-modeling/currency.mdx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,9 @@ document date, the engine computes the home amount:
261261
- **The rate** is the row for the record's currency with the latest effective date **on
262262
or before** the document date. A row dated after the document never applies, and
263263
neither does "the most recent rate" when it is dated later. A `datetime` document date
264-
is read as its calendar day in UTC.
264+
is dated in the organization's timezone (the `localization.timezone` setting, UTC when
265+
unset): an invoice written at 01:00 on April 1 in Shanghai takes the April 1 rate. A
266+
`date` document date is its own day.
265267
- **The home amount** is the amount **divided by** the rate, computed in exact decimal
266268
arithmetic and rounded once, half away from zero, to the home currency's decimal
267269
places as CLDR gives them (its fraction digits): 0 for JPY, 2 for USD and CNY, 3 for

‎packages/objectql/src/engine-home-amount-projection.test.ts‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
// below the rate's decimals stores the full rate, never rounded and never
2626
// refused (a `readonly` value is checked for shape only, so the declared
2727
// scale reaches display only);
28+
// - a `datetime` document date is dated in the organization's
29+
// `localization.timezone` (UTC when unset); a `date` is its own day;
2830
// - an update projects when it moves the amount, its code or its document
2931
// date, and never otherwise (a corrected rate reaches stored rows only
3032
// through a recompute).
@@ -101,12 +103,12 @@ const RATE_OBJECT = {
101103
};
102104

103105
const HOME_AMOUNT = { field: 'amount_home', rateDate: 'invoice_date', rateField: 'amount_rate' };
104-
const invoice = (over: { home?: Record<string, unknown>; rate?: Record<string, unknown> } = {}) => ({
106+
const invoice = (over: { home?: Record<string, unknown>; rate?: Record<string, unknown>; dateType?: 'date' | 'datetime' } = {}) => ({
105107
name: 'fx_invoice',
106108
fields: {
107109
title: { type: 'text' },
108110
currency_code: { type: 'text', valueDomain: 'iso_4217_currency' },
109-
invoice_date: { type: 'date' },
111+
invoice_date: { type: over.dateType ?? 'date' },
110112
amount: { type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code', homeAmount: HOME_AMOUNT } },
111113
amount_home: { type: 'currency', readonly: true, ...over.home },
112114
amount_rate: { type: 'number', readonly: true, ...over.rate },
@@ -127,7 +129,7 @@ async function boot(object = invoice(), home: string | null = 'CNY') {
127129
await engine.init();
128130
engine.registry.registerObject(RATE_OBJECT as any);
129131
engine.registry.registerObject(object as any);
130-
if (home !== null) engine.setHomeCurrencyResolver(async () => home);
132+
if (home !== null) engine.setHomeLocalizationResolver(async () => ({ currency: home }));
131133
const rate = (currency: string, effective_date: string, value: number) =>
132134
d.storeFor('sys_exchange_rate').set(`${currency}_${effective_date}`, { id: `${currency}_${effective_date}`, currency, effective_date, rate: value });
133135
return { engine, ...d, rate };
@@ -219,12 +221,59 @@ describe('the home currency is the organization\'s setting, never a default', ()
219221
it('the resolver is asked for the row\'s organization', async () => {
220222
const t = await boot(invoice(), null);
221223
const asked: Array<string | undefined> = [];
222-
t.engine.setHomeCurrencyResolver(async (org) => { asked.push(org); return 'CNY'; });
224+
t.engine.setHomeLocalizationResolver(async (org) => { asked.push(org); return { currency: 'CNY' }; });
223225
await t.engine.insert('fx_invoice', { title: 'i1', currency_code: 'CNY', amount: 1 }, { context: { isSystem: true, tenantId: 'org_a' } } as any);
224226
expect(asked).toEqual(['org_a']);
225227
});
226228
});
227229

230+
describe('a datetime document date is dated in the organization\'s localization.timezone', () => {
231+
// 2026-03-15T17:00Z is 01:00 on 2026-03-16 in Shanghai, and still the 15th in UTC.
232+
const AT_0100_SHANGHAI = '2026-03-15T17:00:00Z';
233+
async function bootZoned(zones: Record<string, string | undefined>) {
234+
const t = await boot(invoice({ dateType: 'datetime' }), null);
235+
const asked: Array<string | undefined> = [];
236+
t.engine.setHomeLocalizationResolver(async (org) => { asked.push(org); return { currency: 'CNY', timezone: zones[org ?? ''] }; });
237+
t.rate('USD', '2026-03-15', 0.1389);
238+
t.rate('USD', '2026-03-16', 0.15);
239+
return { ...t, asked };
240+
}
241+
const as = (org: string) => ({ context: { isSystem: true, tenantId: org } }) as any;
242+
243+
it('an Asia/Shanghai organization writing at 01:00 local time gets the rate of that local day', async () => {
244+
const t = await bootZoned({ org_sh: 'Asia/Shanghai' });
245+
const row = await t.engine.insert('fx_invoice', { title: 'sh', currency_code: 'USD', invoice_date: AT_0100_SHANGHAI, amount: 1500 }, as('org_sh'));
246+
expect(t.storeFor('fx_invoice').get(row.id)).toMatchObject({ amount_home: 10000, amount_rate: 0.15 });
247+
// One localization read per organization per write answers the currency and the timezone.
248+
expect(t.asked).toEqual(['org_sh']);
249+
});
250+
251+
it('a UTC organization, or one with no timezone set, keeps the UTC day', async () => {
252+
const t = await bootZoned({ org_utc: 'UTC', org_unset: undefined });
253+
for (const org of ['org_utc', 'org_unset']) {
254+
const row = await t.engine.insert('fx_invoice', { title: org, currency_code: 'USD', invoice_date: AT_0100_SHANGHAI, amount: 1389 }, as(org));
255+
expect(t.storeFor('fx_invoice').get(row.id)).toMatchObject({ amount_home: 10000, amount_rate: 0.1389 });
256+
}
257+
});
258+
259+
it('an update of the datetime re-dates it in the same timezone', async () => {
260+
const t = await bootZoned({ org_sh: 'Asia/Shanghai' });
261+
const row = await t.engine.insert('fx_invoice', { title: 'sh', currency_code: 'USD', invoice_date: '2026-03-15T03:00:00Z', amount: 1389 }, as('org_sh'));
262+
expect(t.storeFor('fx_invoice').get(row.id)).toMatchObject({ amount_home: 10000, amount_rate: 0.1389 });
263+
await t.engine.update('fx_invoice', { id: row.id, invoice_date: AT_0100_SHANGHAI }, as('org_sh'));
264+
expect(t.storeFor('fx_invoice').get(row.id)).toMatchObject({ amount_home: 9260, amount_rate: 0.15 });
265+
});
266+
267+
it('a date document date is never moved by the timezone', async () => {
268+
const t = await boot(invoice(), null);
269+
t.engine.setHomeLocalizationResolver(async () => ({ currency: 'CNY', timezone: 'Asia/Shanghai' }));
270+
t.rate('USD', '2026-03-15', 0.1389);
271+
t.rate('USD', '2026-03-16', 0.15);
272+
const row = await t.engine.insert('fx_invoice', { title: 'd', currency_code: 'USD', invoice_date: '2026-03-15', amount: 1389 }, as('org_sh'));
273+
expect(t.storeFor('fx_invoice').get(row.id)).toMatchObject({ amount_home: 10000, amount_rate: 0.1389 });
274+
});
275+
});
276+
228277
describe('only the engine writes the home and rate fields', () => {
229278
it('a caller\'s value is stripped as readonly and the projection is stored', async () => {
230279
const t = await boot();

‎packages/objectql/src/engine.ts‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,8 @@ import {
324324
settleBulkHomeAmounts,
325325
type HomeAmountPlanEntry,
326326
type HomeAmountServing,
327+
type HomeLocalization,
328+
type HomeLocalizationResolver,
327329
} from './home-amount-projection.js';
328330
import { assertAggregatedColumnsAreDistinct, assertDateBucketTargetsAreTemporal } from './aggregate-query-shape-door.js';
329331
import { applyProtection, pluralToSingular, ExternalWriteForbiddenError } from '@objectstack/spec/shared';
@@ -9666,18 +9668,20 @@ export class ObjectQL implements IObjectQLEngine {
96669668

96679669
/**
96689670
* [ADR-0144 D4, Open item 4] Where the write-time home projection reads an
9669-
* organization's home currency: its `localization.currency` setting, or
9671+
* organization's localization: its `localization.currency` setting (the
9672+
* home currency) and its `localization.timezone` setting (the zone a
9673+
* `datetime` document date is dated in; ruling 6539345871, letter B), each
96709674
* `undefined` when unset. Bridged by `ObjectQLPlugin`, which resolves the
96719675
* settings service when a write asks, not when it starts. With no resolver
96729676
* every organization's home currency is unset, so a write of an amount
96739677
* declaring `homeAmount` is refused `ERR_HOME_CURRENCY_UNSET` — the engine
9674-
* never assumes one.
9678+
* never assumes one — and an unset timezone reads UTC.
96759679
*/
9676-
setHomeCurrencyResolver(resolver: ((organizationId: string | undefined) => Promise<string | undefined>) | undefined): void {
9677-
this.homeCurrencyResolver = resolver;
9680+
setHomeLocalizationResolver(resolver: HomeLocalizationResolver | undefined): void {
9681+
this.homeLocalizationResolver = resolver;
96789682
}
96799683

9680-
private homeCurrencyResolver?: (organizationId: string | undefined) => Promise<string | undefined>;
9684+
private homeLocalizationResolver?: HomeLocalizationResolver;
96819685

96829686
/**
96839687
* [ADR-0144 D5, Open item 2] What one write's home projection reads, memoized
@@ -9695,8 +9699,21 @@ export class ObjectQL implements IObjectQLEngine {
96959699
* currency.
96969700
*/
96979701
private homeAmountServing(context: ExecutionContext | undefined): HomeAmountServing {
9702+
// One settings read per organization per write answers both the home
9703+
// currency and the timezone.
9704+
const localizations = new Map<string, Promise<HomeLocalization | undefined>>();
9705+
const localizationOf = (organizationId: string | undefined) => {
9706+
const key = organizationId ?? '';
9707+
let hit = localizations.get(key);
9708+
if (!hit) {
9709+
hit = Promise.resolve(this.homeLocalizationResolver?.(organizationId));
9710+
localizations.set(key, hit);
9711+
}
9712+
return hit;
9713+
};
96989714
return memoizeHomeAmountServing({
9699-
homeCurrency: async (organizationId) => this.homeCurrencyResolver?.(organizationId),
9715+
homeCurrency: async (organizationId) => (await localizationOf(organizationId))?.currency,
9716+
timezone: async (organizationId) => (await localizationOf(organizationId))?.timezone,
97009717
rateOn: async (organizationId, currency, onOrBefore) => {
97019718
if (!this._registry.getObject(EXCHANGE_RATE_OBJECT)) return undefined;
97029719
const rows = await this.find(EXCHANGE_RATE_OBJECT, {

0 commit comments

Comments
 (0)