diff --git a/.changeset/currency-iso-4217-minor-units-4361.md b/.changeset/currency-iso-4217-minor-units-4361.md new file mode 100644 index 0000000000..75aa188c36 --- /dev/null +++ b/.changeset/currency-iso-4217-minor-units-4361.md @@ -0,0 +1,49 @@ +--- +'@object-ui/fields': patch +--- + +Currency amounts now follow each currency's own ISO 4217 fraction-digit +convention instead of a hardcoded 2 (objectui#4361). + +Both currency formatting paths in `@object-ui/fields` picked a fraction-digit +width and handed it to `Intl.NumberFormat`, which OVERRIDES the digit count +`Intl` already knows for the currency being rendered. `formatCurrency` derived +its width from the VALUE's wholeness alone (`isWhole ? 0 : 2` — a literal 2 for +every currency on earth), and `CurrencyField` defaulted an undeclared +`precision` to the same literal. So a yen amount was printed with cents the +currency does not have and a dinar amount with one digit fewer than it does: + +| | before | after | +| --- | --- | --- | +| JPY `1234.5` | `¥1,234.50` | `¥1,235` | +| KWD `1.5` | `KWD 1.50` | `KWD 1.500` | +| CLP `1234.5` | `CLP 1,234.50` | `CLP 1,235` | +| BHD `2.5` | `BHD 2.50` | `BHD 2.500` | +| USD `1234.5` | `$1,234.50` | `$1,234.50` | +| USD `1234` | `$1,234` | `$1,234` | + +Both call sites now derive the width from the currency itself +(`Intl.NumberFormat(undefined, { style: 'currency', currency }) +.resolvedOptions().maximumFractionDigits`, memoized per code) and switch +wholeness against THAT. + +**The whole-number convention is extended, not retired.** Simply dropping both +bounds and letting `Intl` decide would have fixed the digit count while turning +`$1,234` back into `$1,234.00` — the Salesforce convention `formatCurrency` +documents and objectui#4033 pinned. A whole amount still drops the fraction, now +for every currency: `KWD 1` renders `KWD 1`, not `KWD 1.000`. Two-decimal +currencies are byte-identical to before, which is why the objectui#4033 and +objectui#4332 pins pass unchanged. + +**On `CurrencyField`, an explicitly authored `precision` still wins** — it is +authored metadata and authored metadata keeps priority, so a JPY field declaring +`precision: 2` still renders `¥1,234.50`. Only an ABSENT `precision` derives from +the currency; because that derivation is the widget's one precision, it also +reaches the spinner `step` and the blur rounding, so a JPY field no longer offers +a `0.01` step for a currency with no minor unit. Whether a declared `precision` +that contradicts the currency's ISO 4217 digits should be REJECTED at publish +time is a contract question, filed upstream in `@objectstack/spec` rather than +answered here by overriding the author. + +Reachable wherever the resolved currency is not a 2-decimal one — the field's +`currency`, `currencyConfig.defaultCurrency`, or the tenant default (ADR-0053). diff --git a/packages/fields/src/__tests__/CurrencyField.minorUnits.test.tsx b/packages/fields/src/__tests__/CurrencyField.minorUnits.test.tsx new file mode 100644 index 0000000000..9679189796 --- /dev/null +++ b/packages/fields/src/__tests__/CurrencyField.minorUnits.test.tsx @@ -0,0 +1,191 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectui#4361, second path — `CurrencyField`'s `precision`. + * + * `formatAmount` passes the field's `precision` to BOTH `Intl` bounds, and the + * widget defaulted that precision to a literal `2`. So a JPY field that + * declared no precision rendered `¥1,234.50` for the same reason + * `formatCurrency` did, one layer up. + * + * The PM ruling on this card (issue #4361, claim comment) splits it in two, + * and both halves are pinned here: + * + * 1. **An explicitly authored `precision` WINS.** It is authored metadata and + * this repo's convention is that authored metadata keeps priority. A JPY + * field declaring `precision: 2` still renders `¥1,234.50` — whether that + * combination should be REJECTED at publish time is a spec question filed + * upstream (contract-first), not something the renderer decides by + * overriding the author. + * 2. **An ABSENT `precision` derives from the currency** instead of falling + * back to 2. + * + * MEASURED, per the ruling's stop condition — is "absent" distinguishable from + * "authored 2" by the time the renderer sees it? Yes: + * + * - `CurrencyFieldMetadata.precision` is `precision?: number` in + * `packages/types/src/field-types.ts` — optional, no default; + * - the field-level key is `z.ZodOptional` in + * `@objectstack/spec` (no `.default()`), so a parsed field metadata object + * does NOT carry a materialized 2; + * - the only `.default(2)` in the spec's currency surface is on + * `CurrencyConfigSchema.precision` — a DIFFERENT key on a different object + * (the `currencyConfig` block), which this widget never reads; and + * - the `?? 2` itself lived in the widget, at `CurrencyField.tsx`. + * + * So the renderer holds an `undefined` it can act on, and this half lands. + * + * The derived precision is the widget's ONE precision, so it reaches the edit + * affordances too (`step`, and the blur rounding) — pinned below. Leaving + * those at 2 would have produced a JPY field that displays whole yen but + * offers a 0.01 spinner step and rounds typed input to 1234.56 yen. + */ + +import { describe, it, expect, vi } from 'vitest'; +import React from 'react'; +import { render, screen, fireEvent } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { CurrencyField } from '../widgets/CurrencyField'; + +/** + * ICU separates a currency CODE from the amount with U+00A0 (`KWD` + NBSP + + * `1.500`), while a SYMBOL is flush against it (`¥1,235`). `textContent` is + * raw, so normalizing keeps these pins about the DIGIT COUNT this card is + * about rather than about ICU's spacing. Written as an escape, never a pasted + * byte — a raw NBSP in source is invisible to readers and unfindable by grep. + */ +const normalizeNbsp = (s: string | null) => (s ?? '').replace(/\u00a0/g, ' '); + +const renderField = ( + value: number | null, + field: Record, + opts: { readonly?: boolean; locale?: string; tenantCurrency?: string; onChange?: (v: any) => void } = {}, +) => + render( + + + , + ); + +describe('CurrencyField — an ABSENT precision derives from the currency (objectui#4361)', () => { + it('a JPY field that declares no precision shows no cents', () => { + const { container } = renderField(1234.5, { currency: 'JPY' }, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('¥1,235'); + }); + + it('a KWD field that declares no precision shows all three digits', () => { + const { container } = renderField(1.5, { currency: 'KWD' }, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('KWD 1.500'); + }); + + it('the tenant default currency reaches the derivation too (ADR-0053)', () => { + const { container } = renderField(1234.5, {}, { readonly: true, tenantCurrency: 'JPY' }); + expect(normalizeNbsp(container.textContent)).toBe('¥1,235'); + }); + + it('`currencyConfig.defaultCurrency` reaches it as well', () => { + const { container } = renderField( + 1.5, + { currencyConfig: { defaultCurrency: 'KWD' } }, + { readonly: true }, + ); + expect(normalizeNbsp(container.textContent)).toBe('KWD 1.500'); + }); +}); + +describe('CurrencyField — an AUTHORED precision still wins (authored metadata keeps priority)', () => { + it('a JPY field declaring `precision: 2` keeps its two digits', () => { + // The renderer does not overrule the author. Whether publish-time + // validation should reject this combination is the upstream spec question + // filed alongside this card — deliberately NOT decided here. + const { container } = renderField(1234.5, { currency: 'JPY', precision: 2 }, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('¥1,234.50'); + }); + + it('an authored `precision: 0` on a 2-digit currency still wins', () => { + // The other direction, so the pin cannot be satisfied by "authored wins + // only when it asks for MORE digits". + const { container } = renderField(1234.5, { currency: 'USD', precision: 0 }, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('$1,235'); + }); + + it('an authored `precision: 3` on JPY wins', () => { + const { container } = renderField(1234.5, { currency: 'JPY', precision: 3 }, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('¥1,234.500'); + }); +}); + +describe('CurrencyField — CONTROL: the 2-digit and no-currency cases are unchanged', () => { + it('a USD field with no declared precision renders exactly as before', () => { + // Derivation and the old literal agree at 2, which is the whole point of + // "byte-identical for USD". + const { container } = renderField(1234.5, { currency: 'USD' }, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('$1,234.50'); + }); + + it('a USD field declaring `precision: 2` renders exactly as before', () => { + const { container } = renderField(1234.56, { currency: 'USD', precision: 2 }, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('$1,234.56'); + }); + + it('a field with NO currency keeps the literal 2 — nothing to derive from', () => { + const { container } = renderField(1234.5, {}, { readonly: true }); + expect(normalizeNbsp(container.textContent)).toBe('1,234.50'); + }); + + it('a null value is still the empty marker, not a formatted zero', () => { + const { container } = renderField(null, { currency: 'JPY' }, { readonly: true }); + expect(container.textContent).not.toContain('¥'); + }); +}); + +describe('CurrencyField — the derived precision is the widget\'s ONE precision', () => { + it('a JPY field with no declared precision offers a whole-unit spinner step', () => { + renderField(1234, { currency: 'JPY' }); + expect(screen.getByRole('spinbutton')).toHaveAttribute('step', '1'); + }); + + it('a KWD field with no declared precision offers a three-digit step', () => { + renderField(1, { currency: 'KWD' }); + expect(screen.getByRole('spinbutton')).toHaveAttribute('step', '0.001'); + }); + + it('CONTROL: USD is still 0.01, authored or derived', () => { + const { unmount } = renderField(1, { currency: 'USD' }); + expect(screen.getByRole('spinbutton')).toHaveAttribute('step', '0.01'); + unmount(); + renderField(1, { currency: 'JPY', precision: 2 }); + expect(screen.getByRole('spinbutton')).toHaveAttribute('step', '0.01'); + }); + + it('blur rounds a typed amount to the currency\'s own unit', () => { + const onChange = vi.fn(); + renderField(null, { currency: 'JPY' }, { onChange }); + const input = screen.getByRole('spinbutton'); + fireEvent.change(input, { target: { value: '1234.56' } }); + fireEvent.blur(input, { target: { value: '1234.56' } }); + // Before: 1234.56 yen — a sub-unit amount the currency cannot express. + expect(onChange).toHaveBeenLastCalledWith(1235); + }); + + it('CONTROL: blur on a USD field still rounds to cents', () => { + const onChange = vi.fn(); + renderField(null, { currency: 'USD' }, { onChange }); + const input = screen.getByRole('spinbutton'); + fireEvent.change(input, { target: { value: '1234.567' } }); + fireEvent.blur(input, { target: { value: '1234.567' } }); + expect(onChange).toHaveBeenLastCalledWith(1234.57); + }); +}); diff --git a/packages/fields/src/__tests__/formatCurrency.minorUnits.test.tsx b/packages/fields/src/__tests__/formatCurrency.minorUnits.test.tsx new file mode 100644 index 0000000000..5244a2c251 --- /dev/null +++ b/packages/fields/src/__tests__/formatCurrency.minorUnits.test.tsx @@ -0,0 +1,221 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectui#4361 — currency formatting overrode each currency's own ISO 4217 + * fraction-digit convention. + * + * `formatCurrency` picked its width from the VALUE's wholeness alone + * (`isWhole ? 0 : 2`) and handed that literal `2` to `Intl`, which overrides + * what `Intl` already knows about the currency being rendered. A yen amount + * was printed with cents the currency does not have (`¥1,234.50`) and a dinar + * amount with one digit fewer than it does have (`KWD 1.50`). + * + * The fix derives the currency's own digit count first + * (`Intl.NumberFormat(undefined, { style: 'currency', currency }) + * .resolvedOptions().maximumFractionDigits`) + * and switches wholeness against THAT instead of the literal 2. Two halves, + * both pinned here: + * + * 1. **A fractional amount takes the currency's own width** — the defect. + * JPY -> 0, USD/EUR/CNY -> 2, KWD/BHD -> 3. + * 2. **A whole amount still drops the fraction entirely** — the Salesforce + * convention `formatCurrency`'s doc comment states, that objectui#4033 + * pinned and objectui#4332 / PR #4362 re-pinned. It is not retired here, + * it is EXTENDED consistently: `KWD 1` renders `KWD 1`, not the + * `KWD 1.000` a bare `Intl` default would give. Dropping both bounds and + * letting `Intl` decide would have fixed half 1 by breaking this half, so + * the whole-amount cases below are controls, not decorations. + * + * The USD cases are the acceptance evidence for "byte-identical to today": + * the #4033 and #4332/#4362 pins pass UNCHANGED, and the ones repeated here + * are the same assertions run against the new derivation. + * + * Every expected string below was MEASURED against node 22 with full ICU + * (icu 78.2) rather than reasoned about; where ICU's spacing or symbol choice + * is what varies (and not the digit count this card is about), the assertion + * is a regex on the digits. + */ + +import { describe, it, expect } from 'vitest'; +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { + formatCurrency, + formatCompactCurrency, + CurrencyCellRenderer, +} from '../index'; +import { currencyFractionDigits } from '../currency'; + +/** + * ICU separates a currency CODE from the amount with U+00A0 (`KWD` + NBSP + + * `1.500`), while a currency SYMBOL is written flush against it (`$1,234.50`). + * Normalizing the NBSP keeps these pins about the DIGIT COUNT — which is what + * this card is about — rather than about ICU's spacing choices, the same reason + * objectui#4332's de-DE pin matched its separator loosely. + * + * Written as an escape rather than a pasted byte, per the repo's byte + * discipline: a raw NBSP in source is invisible to every reader and unfindable + * by grep in the spelling you would search for. + */ +const normalizeNbsp = (s: string) => s.replace(/\u00a0/g, ' '); + +describe('the environment this card is measured in', () => { + it('has full ICU — a small-ICU build would make every pin below meaningless', () => { + // Written as an assertion rather than a comment: with a reduced ICU data + // set the currency digit table is not present and JPY/KWD would resolve to + // 2, so the fix would look correct while rendering the same wrong output. + // If this one fails, nothing else in this file is evidence of anything. + expect(currencyFractionDigits('JPY')).toBe(0); + expect(currencyFractionDigits('KWD')).toBe(3); + expect(currencyFractionDigits('USD')).toBe(2); + }); +}); + +describe('formatCurrency — a fractional amount takes the CURRENCY\'s width (objectui#4361)', () => { + it('the card\'s two fixtures render as ISO 4217 says they should', () => { + // Before: `¥1,234.50` — cents on a currency that has none. + expect(formatCurrency(1234.5, 'JPY', 'en-US')).toBe('¥1,235'); + // Before: `KWD 1.50` — one digit short of the three a dinar has. + expect(normalizeNbsp(formatCurrency(1.5, 'KWD', 'en-US'))).toBe('KWD 1.500'); + }); + + it.each([ + // 0-digit currencies: the fraction is rounded away, not truncated. + ['JPY', 1234.5, '¥1,235'], + ['CLP', 1234.5, 'CLP 1,235'], + ['ISK', 99.5, 'ISK 100'], + // 3-digit currencies: the third digit is real and now survives. + ['KWD', 1.5, 'KWD 1.500'], + ['BHD', 2.5, 'BHD 2.500'], + ['KWD', 1234.5678, 'KWD 1,234.568'], + // 2-digit currencies: unchanged, by construction. + ['USD', 1234.5, '$1,234.50'], + ['EUR', 1234.5, '€1,234.50'], + ])('%s %s renders %s', (currency, value, expected) => { + expect(normalizeNbsp(formatCurrency(value as number, currency as string, 'en-US'))).toBe( + expected as string, + ); + }); + + it('a 0-digit currency rounds the amount, it does not drop the digits', () => { + // `1234.5` is not `1234`. Rounding is Intl's, and half-up here: the point + // of the pin is that the value is not silently floored. + expect(formatCurrency(1234.4, 'JPY', 'en-US')).toBe('¥1,234'); + expect(formatCurrency(1234.5, 'JPY', 'en-US')).toBe('¥1,235'); + }); +}); + +describe('formatCurrency — CONTROL: the whole-number convention is extended, not retired', () => { + it.each([ + // Salesforce convention, per currency: a whole amount shows no fraction. + ['USD', 1234, '$1,234'], + ['USD', 0, '$0'], + ['EUR', 5000000, '€5,000,000'], + // 3-digit currency: a bare `Intl` default would print `KWD 1.000` here. + // The convention survives the fix and reaches currencies it never met. + ['KWD', 1, 'KWD 1'], + ['BHD', 250, 'BHD 250'], + // 0-digit currency: both halves of the switch agree at 0, so a whole yen + // amount is the one case that was already right and must stay right. + ['JPY', 1234, '¥1,234'], + ])('a whole %s amount drops the fraction: %s', (currency, value, expected) => { + expect(normalizeNbsp(formatCurrency(value as number, currency as string, 'en-US'))).toBe( + expected as string, + ); + }); + + it('a non-finite amount is not "whole" and still falls through unchanged', () => { + expect(formatCurrency(Number.NaN, 'JPY', 'en-US')).toBe('¥NaN'); + }); +}); + +describe('formatCurrency — CONTROL: the branches with no currency to derive from', () => { + it('the no-currency branch keeps the literal 2 — there is nothing to derive', () => { + // Deliberate: with no ISO code in hand there is no convention to follow, + // so this branch keeps the historical width. Unchanged by this card. + expect(formatCurrency(1234.5, undefined, 'en-US')).toBe('1,234.50'); + expect(formatCurrency(5000000, undefined, 'en-US')).toBe('5,000,000'); + }); + + it('the bad-currency fallback is byte-identical to before the fix', () => { + // The probe throws `RangeError: Invalid currency code` for a non-ISO code + // exactly as `Intl` does, so it must NOT be allowed to escape and change + // this fallback's width. It falls back to 2 and `formatDisplayNumber`'s own + // throw then produces the same string objectui#4332 pinned. + expect(formatCurrency(1234.5, 'NOT_A_CODE', 'en-US')).toBe('NOT_A_CODE 1234.50'); + }); + + it('an unknown but well-formed code resolves to 2 without throwing', () => { + // `ZZZ` is not in the CLDR digit table; ICU answers 2 for anything it does + // not know, which is the right default and needs no special-casing here. + expect(currencyFractionDigits('ZZZ')).toBe(2); + expect(normalizeNbsp(formatCurrency(1.5, 'ZZZ', 'en-US'))).toBe('ZZZ 1.50'); + }); + + it('formatCompactCurrency is a different function and is untouched', () => { + // Compact notation has its own `maximumFractionDigits: 1` policy; this card + // does not reach it. `¥1.2K` for JPY is compact's answer, not ISO 4217's. + expect(formatCompactCurrency(1234.5, 'USD', 'en-US')).toBe('$1.2K'); + expect(formatCompactCurrency(1234.5, 'JPY', 'en-US')).toBe('¥1.2K'); + }); +}); + +describe('formatCurrency — the display-locale path (a 0-digit and a 3-digit currency)', () => { + it('a 0-digit currency in its own locale', () => { + // ja-JP spells the symbol with the FULLWIDTH yen sign, en-US with the + // ordinary one; either is ICU's business. The digit count is this card's. + expect(formatCurrency(1234.5, 'JPY', 'ja-JP')).toMatch(/^[¥¥]1,235$/); + }); + + it('a 3-digit currency in a comma-decimal locale', () => { + // de-DE: dot grouping, comma decimal mark, trailing code. Matched loosely + // on the separator so an ICU spacing change cannot fail the digits. + expect(formatCurrency(1.5, 'KWD', 'de-DE')).toMatch(/^1,500\s*KWD$/); + expect(formatCurrency(1234.5, 'JPY', 'de-DE')).toMatch(/^1\.235\s*¥$/); + }); + + it('CONTROL: a 2-digit currency in the same locales is unchanged (objectui#4033)', () => { + expect(formatCurrency(1234.5, 'EUR', 'de-DE')).toMatch(/^1\.234,50\s*€$/); + expect(formatCurrency(1234.5, 'CNY', 'zh-CN')).toBe('¥1,234.50'); + }); +}); + +describe('CurrencyCellRenderer — the user-visible surface (objectui#4361)', () => { + const renderCurrency = (value: unknown, field: Record, locale?: string, tenantCurrency?: string) => + render( + + + , + ); + + it('a JPY grid cell shows no cents', () => { + renderCurrency(1234.5, { currency: 'JPY' }, 'en-US'); + expect(screen.getByText('¥1,235')).toBeInTheDocument(); + }); + + it('a KWD grid cell shows all three fils digits', () => { + renderCurrency(1.5, { currency: 'KWD' }, 'en-US'); + expect(screen.getByText('KWD 1.500')).toBeInTheDocument(); + }); + + it('the TENANT default currency reaches the same derivation (ADR-0053)', () => { + // `resolveFieldCurrency` falls through field -> currencyConfig -> tenant + // default, and the card's reachability rests on that third step: a JPY + // tenant with a currency field that declares nothing. + renderCurrency(1234.5, {}, 'en-US', 'JPY'); + expect(screen.getByText('¥1,235')).toBeInTheDocument(); + }); + + it('CONTROL: a USD grid cell is byte-identical to objectui#4332', () => { + renderCurrency(1234.5, { currency: 'USD' }, 'en-US'); + expect(screen.getByText('$1,234.50')).toBeInTheDocument(); + }); +}); diff --git a/packages/fields/src/currency.ts b/packages/fields/src/currency.ts index 4991141d27..a1f947ca1f 100644 --- a/packages/fields/src/currency.ts +++ b/packages/fields/src/currency.ts @@ -12,3 +12,63 @@ * every field/cell renderer that already depends on it. */ export { resolveFieldCurrency } from '@object-ui/i18n'; + +/** + * Fallback width for a currency whose digit count cannot be resolved: the + * literal both call sites used unconditionally before objectui#4361. It is + * reached only when there is no ISO code to ask about (an invalid code, or a + * runtime with no currency data at all), never as a policy. + */ +const DEFAULT_FRACTION_DIGITS = 2; + +/** + * ISO 4217 minor-unit width, memoized per currency code. + * + * The probe is deliberately made with NO locale. Measured across + * en-US / de-DE / ja-JP / ar-KW / zh-CN / fr-FR / pl-PL / es-ES and the runtime + * default, every locale answers the same digit count for the same code (USD 2, + * JPY 0, KWD 3, BHD 3, CLP 0, ISK 0) — the count comes from CLDR's + * `currencyData`, which is keyed by the currency, not by who is reading it. + * Dropping the locale from the probe therefore loses nothing and removes a + * failure mode: a malformed locale tag makes `Intl.NumberFormat` throw + * `RangeError: Incorrect locale information provided`, which would turn a bad + * LOCALE into a wrong CURRENCY width. It also makes the code the whole cache + * key. + */ +const fractionDigitsByCurrency = new Map(); + +/** + * The number of fraction digits ISO 4217 gives `currency` — 0 for JPY/KRW/CLP, + * 2 for USD/EUR/CNY, 3 for KWD/BHD/OMR/TND — as ICU reports it. + * + * Returns {@link DEFAULT_FRACTION_DIGITS} when the code is not a currency code + * at all: `Intl` throws `RangeError: Invalid currency code` for those, and the + * throw must not escape, or a bad code would change the width used by the + * callers' own bad-currency fallbacks (objectui#4332 pinned those strings). A + * code that is well-formed but unknown to CLDR (e.g. `ZZZ`) does not throw — + * ICU answers 2 for anything outside its table, which is the same default. + * + * Memoized because the currency cell renderer runs once per grid cell: measured + * at 24.3us per uncached probe against 0.02us cached (200k iterations, node 22), + * so a 500-row grid pays ~12ms per render pass for a value that cannot change. + */ +export function currencyFractionDigits(currency: string): number { + const cached = fractionDigitsByCurrency.get(currency); + if (cached !== undefined) return cached; + let digits = DEFAULT_FRACTION_DIGITS; + try { + // `maximumFractionDigits` is typed `number | undefined` on + // `ResolvedNumberFormatOptions` — it is absent when a format resolves with + // significant-digit rounding instead of fraction-digit rounding, which a + // bare `style: 'currency'` never does. Coalesced rather than asserted so + // the value is a number by construction and not by claim. + digits = + new Intl.NumberFormat(undefined, { style: 'currency', currency }).resolvedOptions() + .maximumFractionDigits ?? DEFAULT_FRACTION_DIGITS; + } catch { + // Not a currency code — keep the historical width and let the caller's own + // formatting attempt surface the bad code. + } + fractionDigitsByCurrency.set(currency, digits); + return digits; +} diff --git a/packages/fields/src/index.tsx b/packages/fields/src/index.tsx index 636b7cb184..47af5796c1 100644 --- a/packages/fields/src/index.tsx +++ b/packages/fields/src/index.tsx @@ -357,13 +357,14 @@ export function coerceToSafeValue(value: unknown): string | number | boolean | n * USD for unconfigured currency fields was the #1 source of "why is my * RMB amount showing as dollars?" bug reports. * - * Trailing `.00` is dropped when the value is a whole number — Salesforce - * convention: `$1,234.50` keeps cents; `$1,234` does not. Wholeness picks ONE - * fraction-digit width, never a range: a whole amount shows 0 digits, and a - * fractional amount shows exactly 2 — so a real cents value of `.50` renders - * `.50`, not `.5`. + * Trailing minor units are dropped when the value is a whole number — + * Salesforce convention: `$1,234.50` keeps cents; `$1,234` does not. Wholeness + * picks ONE fraction-digit width, never a range: a whole amount shows 0 digits, + * and a fractional amount shows the width the CURRENCY has — so a real cents + * value of `.50` renders `.50`, not `.5`, and a yen amount renders `¥1,235` + * rather than cents the yen does not have. */ -import { resolveFieldCurrency } from './currency'; +import { resolveFieldCurrency, currencyFractionDigits } from './currency'; export { resolveFieldCurrency }; export function formatCurrency(value: number, currency?: string, locale?: string): string { @@ -377,7 +378,23 @@ export function formatCurrency(value: number, currency?: string, locale?: string // `formatNumber`, which sets both bounds to the width it is given, and the // bad-currency fallback below has always used `toFixed`. Both already // rendered `1,234.50` for the same amount. - const fracDigits = isWhole ? 0 : 2; + // + // The non-whole width is the CURRENCY's own ISO 4217 minor-unit count, not a + // literal 2 (objectui#4361). Passing 2 for every currency on earth OVERRODE + // what `Intl` already knows: JPY has no minor unit and KWD has three, so a + // yen amount was printed with cents it does not have (`¥1,234.50`) and a + // dinar amount one digit short (`KWD 1.50`). + // + // The wholeness switch itself is NOT retired — dropping both bounds and + // letting `Intl` decide would fix the digit count by turning `$1,234` back + // into `$1,234.00`, which is exactly the convention this function documents + // and objectui#4033 pinned. It is extended instead: whole amounts drop the + // fraction for EVERY currency (`KWD 1`, not `KWD 1.000`), fractional amounts + // take that currency's own count. + // + // With no currency in hand there is nothing to derive from, so that branch + // keeps the historical 2. + const fracDigits = isWhole ? 0 : currency ? currencyFractionDigits(currency) : 2; if (!currency) { return formatNumber(value, fracDigits, locale); } diff --git a/packages/fields/src/widgets/CurrencyField.tsx b/packages/fields/src/widgets/CurrencyField.tsx index 7423b558aa..abe01fb1c2 100644 --- a/packages/fields/src/widgets/CurrencyField.tsx +++ b/packages/fields/src/widgets/CurrencyField.tsx @@ -3,12 +3,16 @@ import { Input, EmptyValue } from '@object-ui/components'; import { FieldWidgetComponentProps } from './types'; import { toDomProps } from './toDomProps'; import { useLocalization, useDisplayLocale, formatDisplayNumber } from '@object-ui/i18n'; -import { resolveFieldCurrency } from '../currency'; +import { resolveFieldCurrency, currencyFractionDigits } from '../currency'; /** * Format currency value for display. When `currency` is undefined the value * is rendered as a plain number with thousands separators (no symbol), * because silently assuming USD is misleading for non-USD businesses. + * + * `precision` is a display width the caller resolved — either the field's + * authored `precision` or, when it declared none, the currency's own ISO 4217 + * minor-unit count (see the derivation at the call site, objectui#4361). */ function formatAmount( value: number, @@ -52,7 +56,28 @@ export function CurrencyField({ value, onChange, field, readonly, error, classNa const { currency: tenantCurrency } = useLocalization(); const locale = useDisplayLocale(); const currency: string | undefined = resolveFieldCurrency(currencyField, tenantCurrency); - const precision = currencyField?.precision ?? 2; + // An AUTHORED `precision` wins: it is authored metadata, and this repo's + // convention is that authored metadata keeps priority. Whether a declared + // `precision` that contradicts the currency's ISO 4217 digits (say + // `precision: 2` on a JPY field) should be REJECTED at publish time is a + // contract question, so it is filed upstream in `@objectstack/spec` rather + // than answered here by overriding the author (objectui#4361). + // + // An ABSENT `precision` derives from the currency instead of defaulting to a + // literal 2, which rendered `¥1,234.50` for a currency with no minor unit. + // "Absent" is genuinely distinguishable from "authored 2" here — MEASURED, + // not assumed: `CurrencyFieldMetadata.precision` is optional in + // `@object-ui/types` and `z.ZodOptional` (no `.default()`) in + // `@objectstack/spec`, so a parsed field carries no materialized 2. The only + // `.default(2)` on the currency surface is `CurrencyConfigSchema.precision`, + // a different key on the `currencyConfig` block that this widget never reads. + // + // This is the widget's ONE precision, so the derivation also reaches the edit + // affordances below. Deliberate: leaving `step`/blur-rounding at 2 would give + // a JPY field that displays whole yen while offering a 0.01 spinner step and + // rounding typed input to 1234.56 yen. + const precision = + currencyField?.precision ?? (currency ? currencyFractionDigits(currency) : 2); if (readonly) { if (value == null) return ;