diff --git a/.changeset/31609-home-amount-arithmetic-formula.md b/.changeset/31609-home-amount-arithmetic-formula.md new file mode 100644 index 00000000000..c740df21551 --- /dev/null +++ b/.changeset/31609-home-amount-arithmetic-formula.md @@ -0,0 +1,11 @@ +--- +'@objectstack/formula': patch +'@objectstack/objectql': patch +--- + +feat(formula): `@objectstack/formula` publishes the home-amount conversion arithmetic, `toScaledDecimal`, `divideToPlaces`, `formatScaledDecimal`, `documentDateOf` and the `ScaledDecimal` type + +Clause-②: yes (widening) +Metadata-protocol: none + +The four functions the write-time home projection (ADR-0144 D5) converts a record amount with: exact decimal reading, the one division by the rate rounded half away from zero to the decimals you pass (the home currency's `CURRENCY_FRACTION_DIGITS`, still in `@objectstack/spec`), the canonical decimal spelling, and the calendar day a document date names in the organization's timezone (UTC when unset). They move unchanged out of `@objectstack/objectql`, which now imports them back and still re-exports them from its projection module, so a form can preview "≈ home amount" with the engine's own arithmetic instead of a second copy. Stored home amounts, rates and refusals do not change. diff --git a/docs/adr/0144-multi-currency-record-currency-dated-rates-write-time-home-projection.md b/docs/adr/0144-multi-currency-record-currency-dated-rates-write-time-home-projection.md index bc4572f505d..29a69acc7f2 100644 --- a/docs/adr/0144-multi-currency-record-currency-dated-rates-write-time-home-projection.md +++ b/docs/adr/0144-multi-currency-record-currency-dated-rates-write-time-home-projection.md @@ -384,7 +384,7 @@ Where a source leans one way, the lean is quoted here, not adopted. This record calendar day in the organization's `localization.timezone`, UTC when the setting is unset or unknown to the host, never the writer's request zone, so a REST write, an import and a flow pick the same rate for the same stored instant — ruling [`6539345871`](https://github.com/objectstack-ai/objectstack/issues/8345#issuecomment-6539345871) on #8345, letter B - (`packages/objectql/src/home-amount-projection.ts#documentDateOf`; the zone rides the same settings bridge as the + (`packages/formula/src/home-amount-arithmetic.ts#documentDateOf`; the zone rides the same settings bridge as the home currency, item 4). Not chosen: A, the UTC day now and the organization's zone as a later card, a semantic change over stored rows once released. A foreign-currency amount with a blank document date is refused `VALIDATION_FAILED` with `required` on the date field (item 9). Review: contract review @@ -399,7 +399,9 @@ Where a source leans one way, the lean is quoted here, not adopted. This record exact scaled-decimal arithmetic over `BigInt` with no float step, rounded **once, half away from zero** (accounting `HALF_UP`; `1.005` stores `1.01`, `-0.125` stores `-0.13`) to the home currency's fraction digits, and stored as the rounded decimal's own spelling, the bare number ADR-0104 D1 requires - (`packages/objectql/src/home-amount-projection.ts#divideToPlaces`, `#divideRoundHalfAwayFromZero`, `#toScaledDecimal`). + (`packages/formula/src/home-amount-arithmetic.ts#divideToPlaces`, `#divideRoundHalfAwayFromZero`, `#toScaledDecimal`; + moved there unchanged from `packages/objectql/src/home-amount-projection.ts`, which imports them back, on 2026-11-08 + in #31609, so the form's live home-amount preview reads the engine's one copy). The rate is stored in `homeAmount.rateField` **unrounded**, as the rate row holds it, so the stored home amount reproduces from the stored amount and rate (`packages/objectql/src/home-amount-projection.ts#projectHomeAmounts`); a `scale` declared on that field reaches diff --git a/packages/formula/src/home-amount-arithmetic.test.ts b/packages/formula/src/home-amount-arithmetic.test.ts new file mode 100644 index 00000000000..d2bc0e6228a --- /dev/null +++ b/packages/formula/src/home-amount-arithmetic.test.ts @@ -0,0 +1,64 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0144 D5, D7 parameter 3, Open items 2 and 3] The home-amount +// conversion arithmetic, pinned at its published home on the engine's own +// samples. The write-time projection (`@objectstack/objectql`) and the form's +// live "≈ home amount" preview both read these four exports, so the number a +// form shows before save is the number the engine stores. The projection's +// verdicts over a served rate stay pinned in objectql's +// `home-amount-projection.test.ts`. + +import { describe, it, expect } from 'vitest'; +import { CURRENCY_FRACTION_DIGITS } from '@objectstack/spec/data'; +import { documentDateOf, divideToPlaces, formatScaledDecimal, toScaledDecimal } from './index'; + +/** `amount ÷ rate` to the home currency's CLDR fraction digits, as the projection spells it. */ +const homeAmount = (amount: number | string, rate: number | string, home: string): string => + formatScaledDecimal(divideToPlaces(toScaledDecimal(amount)!, toScaledDecimal(rate)!, CURRENCY_FRACTION_DIGITS[home]!)); + +describe('the home-amount arithmetic exported from @objectstack/formula', () => { + it('reads an exact decimal from a number, a string and a bigint; spells none for a non-number', () => { + expect(toScaledDecimal(0.1389)).toEqual({ digits: 1389n, scale: 4 }); + expect(toScaledDecimal('7.123456789012')).toEqual({ digits: 7123456789012n, scale: 12 }); + expect(toScaledDecimal(12n)).toEqual({ digits: 12n, scale: 0 }); + expect(toScaledDecimal(1e21)).toEqual({ digits: 10n ** 21n, scale: 0 }); + for (const bad of ['', 'abc', '1,000', NaN, Infinity, null, undefined, {}]) { + expect(toScaledDecimal(bad), String(bad)).toBeUndefined(); + } + }); + + it('rounds to each home currency\'s CLDR digits: JPY 0, USD 2, KWD 3', () => { + expect(homeAmount(100, 0.0065, 'JPY')).toBe('15385'); // 15384.615… + expect(homeAmount(100, 1.0857, 'USD')).toBe('92.11'); // 92.106… + expect(homeAmount(100, 3.2468, 'KWD')).toBe('30.800'); // 30.79955… + // The #27196 preview sample: USD 10,000 at 0.1389 is ¥71,994.24 in a CNY home. + expect(homeAmount(10000, 0.1389, 'CNY')).toBe('71994.24'); + }); + + it('rounds a tie half away from zero, on both signs, with no float in the way', () => { + expect(homeAmount('0.125', 1, 'USD')).toBe('0.13'); + expect(homeAmount('-0.125', 1, 'USD')).toBe('-0.13'); + expect(homeAmount('0.5', 1, 'JPY')).toBe('1'); + expect(homeAmount('-0.0005', 1, 'KWD')).toBe('-0.001'); + // 1.005 has no exact binary double, so a float `toFixed(2)` answers 1.00; the decimal is 1.01. + expect(homeAmount(1.005, 1, 'USD')).toBe('1.01'); + }); + + it('takes a datetime as its calendar day in a non-UTC timezone', () => { + // 2026-03-15T17:00Z is 01:00 on the 16th in Shanghai and 13:00 on the 15th in New York. + expect(documentDateOf('2026-03-15T17:00:00Z', 'Asia/Shanghai')).toBe('2026-03-16'); + expect(documentDateOf(new Date('2026-03-15T17:00:00Z'), 'Asia/Shanghai')).toBe('2026-03-16'); + expect(documentDateOf('2026-03-16T02:00:00Z', 'America/New_York')).toBe('2026-03-15'); + // A calendar date is its own day whatever the zone. + expect(documentDateOf('2026-03-15', 'Asia/Shanghai')).toBe('2026-03-15'); + }); + + it('takes the UTC day when the timezone is unset, UTC or unknown', () => { + expect(documentDateOf('2026-03-15T17:00:00Z')).toBe('2026-03-15'); + expect(documentDateOf('2026-03-31T23:30:00-05:00')).toBe('2026-04-01'); + expect(documentDateOf('2026-03-15T17:00:00Z', 'UTC')).toBe('2026-03-15'); + expect(documentDateOf('2026-03-15T17:00:00Z', 'Mars/Olympus')).toBe('2026-03-15'); + expect(documentDateOf('not a date')).toBeUndefined(); + expect(documentDateOf(20260315)).toBeUndefined(); + }); +}); diff --git a/packages/formula/src/home-amount-arithmetic.ts b/packages/formula/src/home-amount-arithmetic.ts new file mode 100644 index 00000000000..2784460738b --- /dev/null +++ b/packages/formula/src/home-amount-arithmetic.ts @@ -0,0 +1,139 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0144 D5, D7 parameter 3, Open items 2 and 3] The home-amount + * conversion arithmetic: exact decimal reading, the one division by the rate + * rounded half away from zero, the canonical spelling, and the document date + * a rate is picked for. + * + * Published here, not kept inside `@objectstack/objectql`, because two readers + * must give the same answer: the engine's write-time home projection + * (`@objectstack/objectql`'s `home-amount-projection.ts`, which imports these + * back) and the form's live "≈ home amount" preview under `ui/`. A second + * copy in the browser is exactly the drift a JPY (0 digits) or KWD (3 digits) + * amount would hide. The fraction digits themselves stay in + * `@objectstack/spec` (`CURRENCY_FRACTION_DIGITS`); this module is the + * arithmetic only, and has no dependency of its own. + */ + +// ── Exact decimal arithmetic ────────────────────────────────────────────── + +/** A decimal as a scaled integer: the value is `digits / 10^scale`. */ +export interface ScaledDecimal { + readonly digits: bigint; + readonly scale: number; +} + +const DECIMAL_SPELLING = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/; + +/** + * The exact decimal a stored or written number spells, or `undefined` when it + * spells none. A JavaScript number is read through its shortest round-trip + * spelling (`String(0.1389)` is `'0.1389'`), which is the decimal the writer + * wrote; a string (a driver answering an exact-decimal column as text) is read + * as written. Exponent spellings are accepted. + */ +export function toScaledDecimal(value: unknown): ScaledDecimal | undefined { + let text: string; + if (typeof value === 'number') { + if (!Number.isFinite(value)) return undefined; + text = String(value); + } else if (typeof value === 'bigint') { + text = value.toString(); + } else if (typeof value === 'string') { + text = value.trim(); + } else { + return undefined; + } + const m = DECIMAL_SPELLING.exec(text); + if (!m) return undefined; + const [, sign, int = '', frac = '', exp] = m; + if (int === '' && frac === '') return undefined; + let digits = BigInt(`${int}${frac}` || '0'); + let scale = frac.length - (exp === undefined ? 0 : Number(exp)); + if (scale < 0) { + digits *= 10n ** BigInt(-scale); + scale = 0; + } + return { digits: sign === '-' ? -digits : digits, scale }; +} + +const abs = (n: bigint): bigint => (n < 0n ? -n : n); + +/** + * `numerator / denominator`, rounded to an integer half away from zero — + * the one rounding step of the projection. + */ +function divideRoundHalfAwayFromZero(numerator: bigint, denominator: bigint): bigint { + const negative = (numerator < 0n) !== (denominator < 0n); + const n = abs(numerator); + const d = abs(denominator); + let q = n / d; + if ((n % d) * 2n >= d) q += 1n; + return negative ? -q : q; +} + +/** + * `amount ÷ rate`, rounded once, half away from zero, to `places` decimals — + * parameter 3 as arithmetic. Both operands are exact; so is every + * intermediate. + */ +export function divideToPlaces(amount: ScaledDecimal, rate: ScaledDecimal, places: number): ScaledDecimal { + // (a / 10^as) / (r / 10^rs) × 10^places = a × 10^(rs + places) / (r × 10^as) + const numerator = amount.digits * 10n ** BigInt(rate.scale + places); + const denominator = rate.digits * 10n ** BigInt(amount.scale); + return { digits: divideRoundHalfAwayFromZero(numerator, denominator), scale: places }; +} + +/** The canonical decimal spelling of a scaled decimal (`-1234.50` for `{ -123450n, 2 }`). */ +export function formatScaledDecimal(value: ScaledDecimal): string { + const text = abs(value.digits).toString().padStart(value.scale + 1, '0'); + const body = value.scale === 0 ? text : `${text.slice(0, -value.scale)}.${text.slice(-value.scale)}`; + return value.digits < 0n ? `-${body}` : body; +} + +// ── The document date ───────────────────────────────────────────────────── + +const CALENDAR_DATE = /^\d{4}-\d{2}-\d{2}$/; + +/** + * The calendar date a document-date value names, as `YYYY-MM-DD`, or + * `undefined` when it names none. A `date` value is its own calendar date, and + * so is a bare `YYYY-MM-DD` spelling of any value. An instant (a `datetime` + * value) is given `timezone`, the organization's `localization.timezone` + * (IANA), and its calendar date is taken there (ruling 6539345871, letter B): + * an invoice written at 01:00 in Shanghai is dated that Shanghai day. It is + * the organization's setting and never the writer's request zone, so every + * write path (a REST write, an import, a flow) picks the same rate for the + * same stored instant. No timezone, or one `Intl` does not know, reads UTC, + * the `localization.timezone` default — the `autonumber-format` reading. + */ +export function documentDateOf(value: unknown, timezone?: string): string | undefined { + if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : calendarDayIn(value, timezone); + if (typeof value !== 'string') return undefined; + const text = value.trim(); + if (CALENDAR_DATE.test(text)) return text; + const ms = Date.parse(text); + return Number.isNaN(ms) ? undefined : calendarDayIn(new Date(ms), timezone); +} + +/** The `YYYY-MM-DD` calendar day of `instant` in `timezone` (IANA), UTC when absent or unknown. */ +function calendarDayIn(instant: Date, timezone: string | undefined): string { + if (timezone && timezone !== 'UTC') { + try { + const parts = new Intl.DateTimeFormat('en-CA', { + timeZone: timezone, + year: 'numeric', + month: '2-digit', + day: '2-digit', + }).formatToParts(instant); + const y = parts.find((p) => p.type === 'year')?.value; + const m = parts.find((p) => p.type === 'month')?.value; + const d = parts.find((p) => p.type === 'day')?.value; + if (y && m && d) return `${y}-${m}-${d}`; + } catch { + // An unknown zone reads UTC, below. + } + } + return instant.toISOString().slice(0, 10); +} diff --git a/packages/formula/src/index.ts b/packages/formula/src/index.ts index a3d4fb78da4..21b3ce1ad9e 100644 --- a/packages/formula/src/index.ts +++ b/packages/formula/src/index.ts @@ -185,6 +185,12 @@ export type { FieldRole, ExprInput, ExprSchemaHint, ExprFaultOutcome, ExprValida // source field's own `currencyConfig`. The producer behind `returnType: 'currency'`. export { inferFormulaReturn } from './formula-return'; export type { FormulaReturnDeclaration, FormulaSourceField } from './formula-return'; +// ADR-0144 D5 — the home-amount conversion arithmetic: the engine's write-time +// home projection (`@objectstack/objectql`) and the form's live "≈ home amount" +// preview read this one copy, so the number a form shows before save is the +// number the engine stores. +export { toScaledDecimal, divideToPlaces, formatScaledDecimal, documentDateOf } from './home-amount-arithmetic'; +export type { ScaledDecimal } from './home-amount-arithmetic'; // The closed set of refusal codes `validateExpression` and // `collectCelRootIdentifiers` carry beside their English message, with the // typed params each message interpolates — so a localized author surface keys diff --git a/packages/objectql/src/home-amount-projection.ts b/packages/objectql/src/home-amount-projection.ts index 8eb82c5ee2d..44760169f12 100644 --- a/packages/objectql/src/home-amount-projection.ts +++ b/packages/objectql/src/home-amount-projection.ts @@ -64,6 +64,14 @@ import { CURRENCY_FRACTION_DIGITS } from '@objectstack/spec/data'; import { isRecordCurrencyBlank, recordCurrencyFieldOf } from './validation/record-currency-code.js'; import { ValidationError } from './validation/record-validator.js'; +// The conversion arithmetic and the document date live in `@objectstack/formula` +// (`home-amount-arithmetic.ts`), the one copy this projection and the form's +// live home-amount preview both read. Re-exported so this module's callers +// keep their import site. +import { documentDateOf, divideToPlaces, formatScaledDecimal, toScaledDecimal, type ScaledDecimal } from '@objectstack/formula'; +export { documentDateOf, divideToPlaces, formatScaledDecimal, toScaledDecimal }; +export type { ScaledDecimal }; + /** The object the rates are read from (ADR-0144 D3). */ export const EXCHANGE_RATE_OBJECT = 'sys_exchange_rate'; @@ -138,80 +146,6 @@ export function homeAmountsTouched( // ── Exact decimal arithmetic ────────────────────────────────────────────── -/** A decimal as a scaled integer: the value is `digits / 10^scale`. */ -export interface ScaledDecimal { - readonly digits: bigint; - readonly scale: number; -} - -const DECIMAL_SPELLING = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/; - -/** - * The exact decimal a stored or written number spells, or `undefined` when it - * spells none. A JavaScript number is read through its shortest round-trip - * spelling (`String(0.1389)` is `'0.1389'`), which is the decimal the writer - * wrote; a string (a driver answering an exact-decimal column as text) is read - * as written. Exponent spellings are accepted. - */ -export function toScaledDecimal(value: unknown): ScaledDecimal | undefined { - let text: string; - if (typeof value === 'number') { - if (!Number.isFinite(value)) return undefined; - text = String(value); - } else if (typeof value === 'bigint') { - text = value.toString(); - } else if (typeof value === 'string') { - text = value.trim(); - } else { - return undefined; - } - const m = DECIMAL_SPELLING.exec(text); - if (!m) return undefined; - const [, sign, int = '', frac = '', exp] = m; - if (int === '' && frac === '') return undefined; - let digits = BigInt(`${int}${frac}` || '0'); - let scale = frac.length - (exp === undefined ? 0 : Number(exp)); - if (scale < 0) { - digits *= 10n ** BigInt(-scale); - scale = 0; - } - return { digits: sign === '-' ? -digits : digits, scale }; -} - -const abs = (n: bigint): bigint => (n < 0n ? -n : n); - -/** - * `numerator / denominator`, rounded to an integer half away from zero — - * the one rounding step of the projection. - */ -function divideRoundHalfAwayFromZero(numerator: bigint, denominator: bigint): bigint { - const negative = (numerator < 0n) !== (denominator < 0n); - const n = abs(numerator); - const d = abs(denominator); - let q = n / d; - if ((n % d) * 2n >= d) q += 1n; - return negative ? -q : q; -} - -/** - * `amount ÷ rate`, rounded once, half away from zero, to `places` decimals — - * parameter 3 as arithmetic. Both operands are exact; so is every - * intermediate. - */ -export function divideToPlaces(amount: ScaledDecimal, rate: ScaledDecimal, places: number): ScaledDecimal { - // (a / 10^as) / (r / 10^rs) × 10^places = a × 10^(rs + places) / (r × 10^as) - const numerator = amount.digits * 10n ** BigInt(rate.scale + places); - const denominator = rate.digits * 10n ** BigInt(amount.scale); - return { digits: divideRoundHalfAwayFromZero(numerator, denominator), scale: places }; -} - -/** The canonical decimal spelling of a scaled decimal (`-1234.50` for `{ -123450n, 2 }`). */ -export function formatScaledDecimal(value: ScaledDecimal): string { - const text = abs(value.digits).toString().padStart(value.scale + 1, '0'); - const body = value.scale === 0 ? text : `${text.slice(0, -value.scale)}.${text.slice(-value.scale)}`; - return value.digits < 0n ? `-${body}` : body; -} - /** * The number the home field stores: the rounded decimal's own spelling read * back as a number. A currency value is a bare number (ADR-0104 D1); the @@ -222,52 +156,6 @@ function toStoredNumber(value: ScaledDecimal): number { return Object.is(n, -0) ? 0 : n; } -// ── The document date ───────────────────────────────────────────────────── - -const CALENDAR_DATE = /^\d{4}-\d{2}-\d{2}$/; - -/** - * The calendar date a document-date value names, as `YYYY-MM-DD`, or - * `undefined` when it names none. A `date` value is its own calendar date, and - * so is a bare `YYYY-MM-DD` spelling of any value. An instant (a `datetime` - * value) is given `timezone`, the organization's `localization.timezone` - * (IANA), and its calendar date is taken there (ruling 6539345871, letter B): - * an invoice written at 01:00 in Shanghai is dated that Shanghai day. It is - * the organization's setting and never the writer's request zone, so every - * write path (a REST write, an import, a flow) picks the same rate for the - * same stored instant. No timezone, or one `Intl` does not know, reads UTC, - * the `localization.timezone` default — the `autonumber-format` reading. - */ -export function documentDateOf(value: unknown, timezone?: string): string | undefined { - if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : calendarDayIn(value, timezone); - if (typeof value !== 'string') return undefined; - const text = value.trim(); - if (CALENDAR_DATE.test(text)) return text; - const ms = Date.parse(text); - return Number.isNaN(ms) ? undefined : calendarDayIn(new Date(ms), timezone); -} - -/** The `YYYY-MM-DD` calendar day of `instant` in `timezone` (IANA), UTC when absent or unknown. */ -function calendarDayIn(instant: Date, timezone: string | undefined): string { - if (timezone && timezone !== 'UTC') { - try { - const parts = new Intl.DateTimeFormat('en-CA', { - timeZone: timezone, - year: 'numeric', - month: '2-digit', - day: '2-digit', - }).formatToParts(instant); - const y = parts.find((p) => p.type === 'year')?.value; - const m = parts.find((p) => p.type === 'month')?.value; - const d = parts.find((p) => p.type === 'day')?.value; - if (y && m && d) return `${y}-${m}-${d}`; - } catch { - // An unknown zone reads UTC, below. - } - } - return instant.toISOString().slice(0, 10); -} - // ── What the projection reads ───────────────────────────────────────────── /** The rate row the projection picked. */