diff --git a/.changeset/27196-home-amount-preview.md b/.changeset/27196-home-amount-preview.md new file mode 100644 index 00000000000..49a788ebecd --- /dev/null +++ b/.changeset/27196-home-amount-preview.md @@ -0,0 +1,15 @@ +--- +'@object-ui/i18n': patch +'@object-ui/fields': patch +--- + +feat(ui): a record-mode amount previews the home amount the save will store + +Clause-②: yes (widening) +Metadata-protocol: none + +While a `record`-mode amount that declares `currencyConfig.homeAmount` (ADR-0144 D5) is edited, a line under it says what the save will store in the home field: "≈ AMOUNT at RATE on DATE" for a foreign currency, or "≈ AMOUNT (home currency)" when the amount is already in the home currency. The rate is the `sys_exchange_rate` row with the latest effective date on or before the document date, read once per currency and date. The arithmetic is `@objectstack/formula`'s, the same functions the engine stores the home amount with, so the preview matches the saved number digit for digit. + +With no rate in force, the line says the save is refused until one is added. With no document date, it asks for one. A member who may not read exchange rates sees that the amount is converted when they save, never "no rate" and never a guessed amount. + +`@object-ui/i18n` adds five locale keys in every pack: `fields.currencyHome.preview`, `previewSame`, `awaitingRate`, `awaitingDate` and `rateUnreadable`. `@object-ui/fields` now depends on `@objectstack/formula`, which `@object-ui/core` already depends on. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2ae1a87a2f3..683ed4ce701 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4613,6 +4613,9 @@ importers: '@object-ui/types': specifier: workspace:* version: link:../types + '@objectstack/formula': + specifier: workspace:^ + version: link:../../../packages/formula '@objectstack/spec': specifier: workspace:^ version: link:../../../packages/spec diff --git a/ui/packages/fields/package.json b/ui/packages/fields/package.json index 2b094ba6942..1ab99a6e58c 100644 --- a/ui/packages/fields/package.json +++ b/ui/packages/fields/package.json @@ -37,6 +37,7 @@ "@object-ui/permissions": "workspace:*", "@object-ui/react": "workspace:*", "@object-ui/types": "workspace:*", + "@objectstack/formula": "workspace:^", "@objectstack/spec": "workspace:^", "hast-util-to-jsx-runtime": "^2.3.6", "hastscript": "^9.0.1", diff --git a/ui/packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx b/ui/packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx new file mode 100644 index 00000000000..0a3a7d92a4c --- /dev/null +++ b/ui/packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx @@ -0,0 +1,153 @@ +/** + * 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. + */ + +/** + * ADR-0144 D5, the live preview: while a `record`-mode amount declaring + * `homeAmount` is edited, the line under it says what the save will store in + * the home field. The arithmetic is `@objectstack/formula`'s (the engine's own + * copy), so the parity cases below are the engine's test cases + * (`packages/objectql/src/home-amount-projection.test.ts` and + * `engine-home-amount-projection.test.ts`), inputs and stored numbers both. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import React from 'react'; +import { render, renderHook, cleanup, screen, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { CurrencyField } from '../widgets/CurrencyField'; +import { useHomeAmountPreview } from '../widgets/homeAmountPreview'; + +afterEach(cleanup); + +const HOME_AMOUNT = { field: 'amount_home', rateDate: 'invoice_date', rateField: 'amount_rate' }; +const AMOUNT = { name: 'amount', type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code', homeAmount: HOME_AMOUNT } } as any; +const text = (s: string | null | undefined) => (s ?? '').replace(/\u00a0/g, ' '); + +/** A data source answering rate rows like the engine's rate table, counting its reads. */ +function rates(table: Record>, fail?: unknown) { + const calls: Array<{ resource: string; params: any }> = []; + const ds = { + calls, + async find(resource: string, params: any) { + calls.push({ resource, params }); + if (fail) throw fail; + const { currency, effective_date } = params.$filter; + const rows = (table[currency] ?? []) + .filter(([d]) => d <= effective_date.$lte) + .sort(([a], [b]) => (a < b ? 1 : -1)) + .slice(0, 1) + .map(([d, rate]) => ({ effective_date: d, rate })); + return { data: rows }; + }, + }; + return ds; +} + +function preview(record: Record, ds: unknown, home = 'CNY', field = AMOUNT) { + return render( + + {}} field={field} dependentValues={record} dataSource={ds} /> + , + ); +} +const line = () => text(screen.queryByTestId('home-amount-preview')?.textContent); + +describe('the live home-amount preview (ADR-0144 D5)', () => { + it('the engine parity cases: the previewed number is the number the engine stores, digit for digit', async () => { + const EUR = { EUR: [['2026-01-01', 0.0065], ['2026-01-02', 0.1289], ['2026-01-03', 3.0103]] as Array<[string, unknown]> }; + const USD = { USD: [['2026-01-01', 0.1389], ['2026-04-01', 0.15]] as Array<[string, unknown]> }; + const cases: Array<[string, Record>, Record, number]> = [ + ['JPY', EUR, { amount: 100, currency_code: 'EUR', invoice_date: '2026-01-01' }, 15385], // JPY 0 digits + ['CNY', EUR, { amount: 100, currency_code: 'EUR', invoice_date: '2026-01-02' }, 775.8], // 2 digits + ['KWD', EUR, { amount: 100, currency_code: 'EUR', invoice_date: '2026-01-03' }, 33.219], // KWD 3 digits + ['CNY', USD, { amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, 71994.24], // the card's two-minute check + ['CNY', USD, { amount: 150, currency_code: 'USD', invoice_date: '2026-04-02' }, 1000], + ]; + for (const [home, table, record, stored] of cases) { + const ds = rates(table); + const { result } = renderHook(() => useHomeAmountPreview(AMOUNT, record.amount, record, ds), { + wrapper: ({ children }) => {children}, + }); + await waitFor(() => expect(result.current?.kind).toBe('converted')); + const state = result.current as Extract; + expect(Number(state.amount), `${home} ${JSON.stringify(record)}`).toBe(stored); + } + }); + + it('a foreign amount reads the rate in force once per currency and date, with the engine\'s query, and says it', async () => { + const ds = rates({ USD: [['2026-01-01', 0.1389], ['2026-04-01', 0.15]] }); + const record = { amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }; + const first = preview(record, ds); + await waitFor(() => expect(line()).toBe('≈ CN¥71,994.24 at 0.1389 on Mar 15, 2026')); + first.rerender( + + {}} field={AMOUNT} dependentValues={{ ...record, amount: 20000 }} dataSource={ds} /> + , + ); + await waitFor(() => expect(line()).toBe('≈ CN¥143,988.48 at 0.1389 on Mar 15, 2026')); + cleanup(); + preview(record, ds); + await waitFor(() => expect(line()).toContain('CN¥71,994.24')); + expect(ds.calls).toEqual([{ + resource: 'sys_exchange_rate', + params: { $filter: { currency: 'USD', effective_date: { $lte: '2026-03-15' } }, $orderby: [{ field: 'effective_date', order: 'desc' }], $top: 1, $select: ['rate', 'effective_date'] }, + }]); + }); + + it('the home currency converts at 1 with no read, rounded half away from zero to the home digits', async () => { + const ds = rates({}); + preview({ amount: 1.005, currency_code: 'CNY' }, ds); + expect(line()).toBe('≈ CN¥1.01 (home currency)'); + expect(ds.calls).toHaveLength(0); + }); + + it('no rate on or before the document date is the awaiting-rate state, naming the currency and date', async () => { + const ds = rates({ USD: [['2026-01-01', 0.1389]] }); + preview({ amount: 1, currency_code: 'USD', invoice_date: '2025-12-31' }, ds); + await waitFor(() => expect(line()).toBe('No USD rate on or before Dec 31, 2025: saving is refused until one is added')); + }); + + it('a foreign amount with no document date asks for it, and reads nothing', () => { + const ds = rates({ USD: [['2026-01-01', 0.1389]] }); + preview({ amount: 1, currency_code: 'USD', invoice_date: '' }, ds); + expect(line()).toBe('Set the document date to see the home amount'); + expect(ds.calls).toHaveLength(0); + }); + + it('a refused read (403) says it converts on save: never awaiting rate, never an amount', async () => { + const refused = Object.assign(new Error('Permission denied'), { httpStatus: 403, code: 'PERMISSION_DENIED' }); + const ds = rates({}, refused); + preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds); + await waitFor(() => expect(line()).toBe('Converted to the home currency when you save')); + expect(screen.getByTestId('home-amount-preview')).toHaveAttribute('data-state', 'refused'); + }); + + it('a failed read that is not a refusal draws nothing and is asked again next time', async () => { + const ds = rates({}, Object.assign(new Error('offline'), { httpStatus: 503 })); + preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds); + await waitFor(() => expect(ds.calls).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 0)); + expect(screen.queryByTestId('home-amount-preview')).toBeNull(); + cleanup(); + preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds); + await waitFor(() => expect(ds.calls).toHaveLength(2)); + }); + + it('CONTROL: an amount with no homeAmount, a blank amount and a blank code preview nothing and read nothing', async () => { + const ds = rates({ USD: [['2026-01-01', 0.1389]] }); + const plain = { ...AMOUNT, currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } }; + preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds, 'CNY', plain); + preview({ amount: null, currency_code: 'USD', invoice_date: '2026-03-15' }, ds); + preview({ amount: 10000, currency_code: '', invoice_date: '2026-03-15' }, ds); + await new Promise((r) => setTimeout(r, 0)); + expect(screen.queryAllByTestId('home-amount-preview')).toHaveLength(0); + expect(screen.getAllByRole('spinbutton')).toHaveLength(3); + expect(ds.calls).toHaveLength(0); + }); +}); diff --git a/ui/packages/fields/src/widgets/CurrencyField.tsx b/ui/packages/fields/src/widgets/CurrencyField.tsx index d068ea902c9..57fa056ba44 100644 --- a/ui/packages/fields/src/widgets/CurrencyField.tsx +++ b/ui/packages/fields/src/widgets/CurrencyField.tsx @@ -9,8 +9,9 @@ import { resolveFieldCurrency, currencySymbol } from '../currency.js'; import { useFieldTranslation } from './useFieldTranslation.js'; import { useBadInputRefusal, BadInputMessage, BAD_INPUT_BORDER } from './numberBadInput.js'; import { formatCurrency, currencyDisplayWidth } from './number-format.js'; +import { HomeAmountPreview } from './homeAmountPreview.js'; -export function CurrencyField({ value, onChange, field, readonly, error, className, dependentValues, ...props }: FieldWidgetComponentProps) { +export function CurrencyField({ value, onChange, field, readonly, error, className, dependentValues, dataSource, ...props }: FieldWidgetComponentProps) { const currencyField = field as any; // Shared precedence: field currency → currencyConfig → tenant default (ADR-0053). // A `record`-mode amount (ADR-0144 D2) reads the code its record holds — @@ -218,6 +219,8 @@ export function CurrencyField({ value, onChange, field, readonly, error, classNa /> + {/* A record-mode amount declaring `homeAmount` (ADR-0144 D5): what the save will store. */} + ); } diff --git a/ui/packages/fields/src/widgets/homeAmountPreview.tsx b/ui/packages/fields/src/widgets/homeAmountPreview.tsx new file mode 100644 index 00000000000..73d7c603980 --- /dev/null +++ b/ui/packages/fields/src/widgets/homeAmountPreview.tsx @@ -0,0 +1,186 @@ +/** + * 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. + */ + +import React, { useContext, useEffect, useState } from 'react'; +import { SchemaRendererContext, classifyLoadError } from '@object-ui/react'; +import { useLocalization, useDisplayLocale, formatDisplayNumber, type FieldCurrencyConfig } from '@object-ui/i18n'; +import { formatDate } from '@object-ui/core'; +import { toScaledDecimal, divideToPlaces, formatScaledDecimal, documentDateOf } from '@objectstack/formula'; +import { CURRENCY_FRACTION_DIGITS } from '@objectstack/spec/data'; +import { isValueDomainMember } from '@objectstack/spec/shared'; +import { useFieldTranslation } from './useFieldTranslation.js'; +import { formatCurrency } from './number-format.js'; + +/** The object the engine reads rates from (ADR-0144 D3). */ +const EXCHANGE_RATE_OBJECT = 'sys_exchange_rate'; + +/** What one rate read answered: a row, no row in force, or a read the caller may not make. */ +type RateRead = { readonly kind: 'rate'; readonly rate: unknown } | { readonly kind: 'none' } | { readonly kind: 'refused' }; + +interface RateSource { + find(resource: string, params?: Record): Promise; +} + +/** + * One read per adapter, currency and document date, kept for the session: the + * engine's memo key (`memoizeHomeAmountServing`) minus the organization, which + * the adapter's session already fixes. A failed read other than a refusal is + * dropped so the next render asks again. + */ +const RATE_READS = new WeakMap>>(); + +/** + * The `currency` row with the latest `effective_date` on or before `date`: + * the engine's own query (`rateOn` in `@objectstack/objectql`), never "the + * most recent row". A 403 is `refused`, which is not "no rate". + */ +export function readRateOn(source: RateSource, currency: string, date: string): Promise { + let byKey = RATE_READS.get(source); + if (!byKey) { + byKey = new Map(); + RATE_READS.set(source, byKey); + } + const key = `${currency}\u0000${date}`; + const held = byKey.get(key); + if (held) return held; + const reads = byKey; + const read = source + .find(EXCHANGE_RATE_OBJECT, { + $filter: { currency, effective_date: { $lte: date } }, + $orderby: [{ field: 'effective_date', order: 'desc' }], + $top: 1, + $select: ['rate', 'effective_date'], + }) + .then( + (answer): RateRead => { + const rows = Array.isArray(answer) ? answer : (answer as { data?: unknown } | null)?.data; + const row = Array.isArray(rows) ? (rows[0] as { rate?: unknown } | undefined) : undefined; + return row ? { kind: 'rate', rate: row.rate } : { kind: 'none' }; + }, + (err: unknown): RateRead => { + if (classifyLoadError(err) === 'forbidden') return { kind: 'refused' }; + reads.delete(key); + throw err; + }, + ); + byKey.set(key, read); + return read; +} + +/** What the line under a record-mode amount says while it is edited. */ +export type HomeAmountPreviewState = + | { readonly kind: 'same'; readonly amount: string; readonly home: string } + | { readonly kind: 'converted'; readonly amount: string; readonly home: string; readonly rate: unknown; readonly date: string } + | { readonly kind: 'awaitingDate' } + | { readonly kind: 'awaitingRate'; readonly currency: string; readonly date: string } + | { readonly kind: 'refused' }; + +const blank = (v: unknown): boolean => v == null || (typeof v === 'string' && v.trim() === ''); +const isIsoCurrency = (code: string): boolean => isValueDomainMember('iso_4217_currency', code); + +/** + * The engine's projection (`projectHomeAmounts`) over the live form record, + * with the same arithmetic imported from `@objectstack/formula`, so the + * previewed number is the number the save stores. `undefined` means no line: + * no `homeAmount`, a blank or unreadable amount or code, no home currency, no + * adapter, or a read still in flight. + */ +export function useHomeAmountPreview( + field: { currencyConfig?: FieldCurrencyConfig } | null | undefined, + amountValue: unknown, + record: Readonly> | null | undefined, + dataSource: unknown, +): HomeAmountPreviewState | undefined { + const { currency: homeSetting, timezone } = useLocalization(); + const ctx = useContext(SchemaRendererContext); + const source = (dataSource ?? ctx?.dataSource) as RateSource | null | undefined; + const config = field?.currencyConfig; + const home = config?.currencyMode === 'record' ? config.homeAmount : undefined; + + const amount = home && !blank(amountValue) ? toScaledDecimal(amountValue) : undefined; + const codeValue = home && typeof config?.currencyField === 'string' ? record?.[config.currencyField] : undefined; + const code = typeof codeValue === 'string' ? codeValue.trim() : ''; + const homeCode = typeof homeSetting === 'string' ? homeSetting.trim() : ''; + const live = amount !== undefined && isIsoCurrency(code) && isIsoCurrency(homeCode); + const places = live ? CURRENCY_FRACTION_DIGITS[homeCode] : undefined; + const dateValue = live && code !== homeCode && typeof home?.rateDate === 'string' ? record?.[home.rateDate] : undefined; + // A `YYYY-MM-DD` value is its own day whatever zone is passed; an instant + // (a `datetime`) takes the organization's day, as the engine takes it. + const date = blank(dateValue) ? undefined : documentDateOf(dateValue, timezone); + const canRead = live && code !== homeCode && date !== undefined && typeof source?.find === 'function'; + + const [answer, setAnswer] = useState<{ key: string; read: RateRead } | undefined>(undefined); + const key = canRead ? `${code}\u0000${date}` : ''; + useEffect(() => { + if (!canRead || !source) return; + let current = true; + readRateOn(source, code, date!).then( + (read) => { if (current) setAnswer({ key, read }); }, + () => { if (current) setAnswer(undefined); }, + ); + return () => { current = false; }; + }, [canRead, source, code, date, key]); + + if (!live || places === undefined || amount === undefined) return undefined; + if (code === homeCode) { + return { kind: 'same', amount: formatScaledDecimal(divideToPlaces(amount, { digits: 1n, scale: 0 }, places)), home: homeCode }; + } + if (blank(dateValue)) return { kind: 'awaitingDate' }; + if (!canRead || answer?.key !== key) return undefined; + const read = answer.read; + if (read.kind === 'refused') return { kind: 'refused' }; + const rate = read.kind === 'rate' ? toScaledDecimal(read.rate) : undefined; + if (rate === undefined || rate.digits <= 0n) return { kind: 'awaitingRate', currency: code, date: date! }; + return { + kind: 'converted', + amount: formatScaledDecimal(divideToPlaces(amount, rate, places)), + home: homeCode, + rate: read.kind === 'rate' ? read.rate : undefined, + date: date!, + }; +} + +/** The "≈ home amount" line under a `record`-mode amount declaring `homeAmount` (ADR-0144 D5). */ +export function HomeAmountPreview({ + field, + amount, + record, + dataSource, +}: { + field: { currencyConfig?: FieldCurrencyConfig } | null | undefined; + amount: unknown; + record: Readonly> | null | undefined; + dataSource?: unknown; +}): React.ReactElement | null { + const { t } = useFieldTranslation(); + const locale = useDisplayLocale(); + const state = useHomeAmountPreview(field, amount, record, dataSource); + if (!state) return null; + const line = (text: string) => ( +

{text}

+ ); + switch (state.kind) { + case 'same': + return line(t('fields.currencyHome.previewSame', { amount: formatCurrency(Number(state.amount), state.home, locale) })); + case 'converted': + return line(t('fields.currencyHome.preview', { + amount: formatCurrency(Number(state.amount), state.home, locale), + rate: formatDisplayNumber(Number(state.rate), { locale, maximumFractionDigits: 12 }), + date: formatDate(state.date, undefined, { alwaysShowYear: true }), + })); + case 'awaitingDate': + return line(t('fields.currencyHome.awaitingDate')); + case 'awaitingRate': + return line(t('fields.currencyHome.awaitingRate', { + currency: state.currency, + date: formatDate(state.date, undefined, { alwaysShowYear: true }), + })); + case 'refused': + return line(t('fields.currencyHome.rateUnreadable')); + } +} diff --git a/ui/packages/fields/src/widgets/useFieldTranslation.ts b/ui/packages/fields/src/widgets/useFieldTranslation.ts index 0f2d219593c..075077deb36 100644 --- a/ui/packages/fields/src/widgets/useFieldTranslation.ts +++ b/ui/packages/fields/src/widgets/useFieldTranslation.ts @@ -29,6 +29,11 @@ const FIELD_DEFAULTS: Record = { // ADR-0144 D5 — the home field's read-only hint (`HomeAmountHint`). 'fields.currencyHome.convertedAt': 'Converted at {{rate}} on {{date}}', 'fields.currencyHome.homeCurrency': 'In the home currency (rate 1)', + 'fields.currencyHome.preview': '≈ {{amount}} at {{rate}} on {{date}}', + 'fields.currencyHome.previewSame': '≈ {{amount}} (home currency)', + 'fields.currencyHome.awaitingRate': 'No {{currency}} rate on or before {{date}}: saving is refused until one is added', + 'fields.currencyHome.awaitingDate': 'Set the document date to see the home amount', + 'fields.currencyHome.rateUnreadable': 'Converted to the home currency when you save', 'fields.boolean.offBadge': '{{label}} — Off', 'fields.boolean.completed': 'Completed', 'fields.boolean.notCompleted': 'Not completed', diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index f18461264f4..d6a367828e9 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -453,6 +453,11 @@ const ar = { currencyHome: { convertedAt: 'محوّل بسعر {{rate}} بتاريخ {{date}}', homeCurrency: 'بالعملة الأساسية (السعر 1)', + preview: '≈ {{amount}} بسعر {{rate}} في {{date}}', + previewSame: '≈ {{amount}} (العملة الأساسية)', + awaitingRate: 'لا يوجد سعر لـ {{currency}} في {{date}} أو قبله: يُرفض الحفظ حتى تتم إضافة سعر', + awaitingDate: 'أدخل تاريخ المستند لرؤية المبلغ بالعملة الأساسية', + rateUnreadable: 'يُحوَّل إلى العملة الأساسية عند الحفظ', }, boolean: { offBadge: "{{label}} — إيقاف", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index bced653e9e2..28802ca7f2d 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -435,6 +435,11 @@ const de = { currencyHome: { convertedAt: 'Umgerechnet zum Kurs {{rate}} vom {{date}}', homeCurrency: 'In der Hauswährung (Kurs 1)', + preview: '≈ {{amount}} zum Kurs {{rate}} am {{date}}', + previewSame: '≈ {{amount}} (Hauswährung)', + awaitingRate: 'Kein {{currency}}-Kurs am oder vor dem {{date}}: Speichern wird abgelehnt, bis einer hinzugefügt ist', + awaitingDate: 'Belegdatum angeben, um den Betrag in der Hauswährung zu sehen', + rateUnreadable: 'Wird beim Speichern in die Hauswährung umgerechnet', }, boolean: { offBadge: "{{label}} — Aus", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3d59fc42628..9165a75a98d 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -402,10 +402,16 @@ const en = { all: 'All currencies (ISO 4217)', }, // ADR-0144 D5 — the home field's read-only hint: the rate and document date - // the engine converted the record's amount at (`CurrencyField`, the record page). + // the engine converted the record's amount at (`CurrencyField`, the record page); + // and the live preview under the amount while it is edited (`homeAmountPreview.tsx`). currencyHome: { convertedAt: 'Converted at {{rate}} on {{date}}', homeCurrency: 'In the home currency (rate 1)', + preview: '≈ {{amount}} at {{rate}} on {{date}}', + previewSame: '≈ {{amount}} (home currency)', + awaitingRate: 'No {{currency}} rate on or before {{date}}: saving is refused until one is added', + awaitingDate: 'Set the document date to see the home amount', + rateUnreadable: 'Converted to the home currency when you save', }, // objectui#13461 — names for icon-only buttons in the field widgets. masterDetail: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index af4abebd361..54ee26ceaf8 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -443,6 +443,11 @@ const es = { currencyHome: { convertedAt: 'Convertido al tipo {{rate}} del {{date}}', homeCurrency: 'En la moneda base (tipo 1)', + preview: '≈ {{amount}} al tipo {{rate}} el {{date}}', + previewSame: '≈ {{amount}} (moneda principal)', + awaitingRate: 'No hay tipo de {{currency}} en o antes del {{date}}: no se puede guardar hasta que se añada uno', + awaitingDate: 'Indique la fecha del documento para ver el importe en la moneda principal', + rateUnreadable: 'Se convierte a la moneda principal al guardar', }, boolean: { offBadge: "{{label}} — Desactivado", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 2f25df2fe72..cae99499e0f 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -438,6 +438,11 @@ const fr = { currencyHome: { convertedAt: 'Converti au taux de {{rate}} du {{date}}', homeCurrency: 'Dans la devise de référence (taux 1)', + preview: '≈ {{amount}} au taux {{rate}} le {{date}}', + previewSame: '≈ {{amount}} (devise principale)', + awaitingRate: 'Aucun taux {{currency}} au plus tard le {{date}} : l’enregistrement est refusé tant qu’aucun n’est ajouté', + awaitingDate: 'Renseignez la date du document pour voir le montant en devise principale', + rateUnreadable: 'Converti dans la devise principale à l’enregistrement', }, boolean: { offBadge: "{{label}} — Désactivé", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 95891c626a2..b0ead490435 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -435,6 +435,11 @@ const ja = { currencyHome: { convertedAt: '{{date}} のレート {{rate}} で換算', homeCurrency: '基準通貨(レート 1)', + preview: '≈ {{amount}}(レート {{rate}}、{{date}})', + previewSame: '≈ {{amount}}(基軸通貨)', + awaitingRate: '{{date}} 以前の {{currency}} のレートがありません。レートを追加するまで保存できません', + awaitingDate: '伝票日付を入力すると基軸通貨の金額が表示されます', + rateUnreadable: '保存時に基軸通貨へ換算されます', }, boolean: { offBadge: "{{label}} — オフ", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index ba19e9d6cdb..73f36c8ee7e 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -435,6 +435,11 @@ const ko = { currencyHome: { convertedAt: '{{date}} 환율 {{rate}}(으)로 환산', homeCurrency: '기준 통화(환율 1)', + preview: '≈ {{amount}} (환율 {{rate}}, {{date}})', + previewSame: '≈ {{amount}} (기준 통화)', + awaitingRate: '{{date}} 이전의 {{currency}} 환율이 없습니다. 환율을 추가할 때까지 저장할 수 없습니다', + awaitingDate: '전표 날짜를 입력하면 기준 통화 금액이 표시됩니다', + rateUnreadable: '저장할 때 기준 통화로 환산됩니다', }, boolean: { offBadge: "{{label}} — 꺼짐", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0c089267166..62efc914bb3 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -438,6 +438,11 @@ const pt = { currencyHome: { convertedAt: 'Convertido à taxa {{rate}} em {{date}}', homeCurrency: 'Na moeda base (taxa 1)', + preview: '≈ {{amount}} à taxa {{rate}} em {{date}}', + previewSame: '≈ {{amount}} (moeda principal)', + awaitingRate: 'Não há taxa de {{currency}} em ou antes de {{date}}: não é possível salvar até que uma seja adicionada', + awaitingDate: 'Informe a data do documento para ver o valor na moeda principal', + rateUnreadable: 'Convertido para a moeda principal ao salvar', }, boolean: { offBadge: "{{label}} — Desativado", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0ee30639eaf..287af9c63cf 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -444,6 +444,11 @@ const ru = { currencyHome: { convertedAt: 'Пересчитано по курсу {{rate}} на {{date}}', homeCurrency: 'В базовой валюте (курс 1)', + preview: '≈ {{amount}} по курсу {{rate}} на {{date}}', + previewSame: '≈ {{amount}} (основная валюта)', + awaitingRate: 'Нет курса {{currency}} на {{date}} или ранее: сохранение невозможно, пока курс не добавлен', + awaitingDate: 'Укажите дату документа, чтобы увидеть сумму в основной валюте', + rateUnreadable: 'Будет пересчитано в основную валюту при сохранении', }, boolean: { offBadge: "{{label}} — Выкл.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index d065c4c8c7f..c805151f8a5 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -448,6 +448,11 @@ const zh = { currencyHome: { convertedAt: '按汇率 {{rate}}({{date}})折算', homeCurrency: '本位币(汇率 1)', + preview: '≈ {{amount}}(按汇率 {{rate}},{{date}})', + previewSame: '≈ {{amount}}(本位币)', + awaitingRate: '{{date}} 及之前没有 {{currency}} 的汇率:添加汇率之前无法保存', + awaitingDate: '填写单据日期后显示本位币金额', + rateUnreadable: '保存时折算为本位币', }, boolean: { offBadge: '{{label}} — 已关闭', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 4026a86cd4c..3a64f7ad5ef 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -448,6 +448,11 @@ const zhHant = { currencyHome: { convertedAt: '按匯率 {{rate}}({{date}})折算', homeCurrency: '本位幣(匯率 1)', + preview: '≈ {{amount}}(按匯率 {{rate}},{{date}})', + previewSame: '≈ {{amount}}(本位幣)', + awaitingRate: '{{date}} 及之前沒有 {{currency}} 的匯率:新增匯率之前無法儲存', + awaitingDate: '填寫單據日期後顯示本位幣金額', + rateUnreadable: '儲存時折算為本位幣', }, boolean: { offBadge: '{{label}} — 已關閉', diff --git a/ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx b/ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx index 04006bd1012..dfa253b3471 100644 --- a/ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx @@ -20,6 +20,7 @@ import { render, waitFor, cleanup } from '@testing-library/react'; import { afterEach } from 'vitest'; import React from 'react'; import { LocalizationProvider } from '@object-ui/i18n'; +import { SchemaRendererProvider } from '@object-ui/react'; import { registerAllFields } from '@object-ui/fields'; import { ModalForm } from '../ModalForm'; import { DrawerForm } from '../DrawerForm'; @@ -78,3 +79,25 @@ describe('authored sections: the home field (ADR-0144 D5)', () => { expect(other.querySelector('[data-testid="home-amount-hint"]')).toBeNull(); }); }); + +describe('the live preview under the amount, through the form (ADR-0144 D5)', () => { + it('an edited record-mode amount shows what the save stores, read through the host adapter', async () => { + const finds: string[] = []; + const ds = { + getObjectSchema: async () => OBJ, findOne: async () => ROW, create: async () => ROW, update: async () => ROW, + find: async (resource: string) => { finds.push(resource); return { data: [{ rate: 0.1389, effective_date: '2026-10-01' }] }; }, + }; + render( + + + + + , + ); + await waitFor(() => { + const line = document.querySelector('[data-field="amount"] [data-testid="home-amount-preview"]'); + expect(line?.textContent?.replace(/\u00a0/g, ' ')).toBe('≈ CN¥71,994.24 at 0.1389 on Nov 1, 2026'); + }, { timeout: 5000 }); + expect(finds).toEqual(['sys_exchange_rate']); + }); +});