Skip to content

Commit 2a32bd4

Browse files
feat(ui): preview the home amount a record-mode amount will store, and say so when the rate cannot be read (#31724)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbKY5oMZsVopxN5eVhk1kG6N)_ Fixes #27196 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - **改了什么:** 编辑多币种金额(`record` 模式且声明了 `homeAmount`)时,输入框下方实时显示保存后会写入的本位币金额,例如「≈ CN¥71,994.24 at 0.1389 on Mar 15, 2026」。汇率取自 `sys_exchange_rate` 中单据日期当天或之前最近的一条,同一币种和日期只读一次。换算函数直接引用 `@objectstack/formula`(#31631 从引擎提出来的同一份),所以预览数字与保存后的数字逐位一致。同币种显示「≈ 金额 (home currency)」,没有汇率时提示保存会被拒绝,没有单据日期时提示先填日期。无权读取汇率的成员(403)看到「保存时折算为本位币」,不会看到「没有汇率」,也不会看到估算金额。 - **为什么改:** 卡片 Task 2:录入外币单据时,用户应在保存前看到折算结果,而不是保存后才发现汇率缺失被拒。 - **风险与回滚:** 只影响声明了 `homeAmount` 的金额字段的编辑态:其他币种字段不读取任何数据、不渲染新行(有对照测试)。新增五个翻译键(widening)。`@object-ui/fields` 新增依赖 `@objectstack/formula`(`@object-ui/core` 早已依赖,依赖图不变);fields 包体积 +3.6 KB(gzip +1.0 KB)。回滚即 revert 本 PR。 - **先看:** `ui/packages/fields/src/widgets/homeAmountPreview.tsx`(`readRateOn` 与 `useHomeAmountPreview`),以及 `CurrencyField.tsx` 中挂载它的一行。 - **两分钟验证:** `cd ui && pnpm exec vitest run packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx`,预期 8 例全绿。其中一致性一例逐个比对引擎测试里的 JPY / CNY / KWD 和 71994.24 用例。 - **需要你做的:** 无,席位落地(落地前席位欠一次 Clause-② 声明复审)。 ## What changes The ui half of multi-currency M3-2, slice 2 of 2 (Task 2 of the card). Slice 1 was #31638. The arithmetic moved into `@objectstack/formula` in #31631, which this PR imports. Nothing is copied. - **`ui/packages/fields/src/widgets/homeAmountPreview.tsx` (new, internal to the package, not exported).** - `readRateOn(source, currency, date)` issues the engine's own `rateOn` query: `find('sys_exchange_rate', { $filter: { currency, effective_date: { $lte: date } }, $orderby: [{ field: 'effective_date', order: 'desc' }], $top: 1, $select: ['rate', 'effective_date'] })`. Results are cached per adapter (a `WeakMap`), then by currency and date. A 403 (`classifyLoadError(...) === 'forbidden'`) is cached as `refused`. Any other failure is dropped from the cache so the next render asks again. - `useHomeAmountPreview` replays `projectHomeAmounts` over the live form record: a blank amount or code gives no line; a code or home currency outside ISO 4217 gives no line. The same currency as home converts at 1 with no read, through `divideToPlaces`. A foreign currency with a blank date asks for the date. `documentDateOf(value, localization.timezone)` gives the day, and a `YYYY-MM-DD` value is its own day. No row, or a rate that is not positive, is awaiting-rate. Otherwise the line shows `divideToPlaces(amount, rate, CURRENCY_FRACTION_DIGITS[home])`. - The adapter is the widget's `dataSource` prop when a host passes one, else the `SchemaRendererContext` adapter, the `LookupField` order. The form renderer's strip is unchanged: `form.tsx` hands registered widgets the context adapter anyway, so forwarding it again would add a line no test could tell apart. This differs from step-1 item 2, which listed the strip as surface. - **`CurrencyField`:** mounts `HomeAmountPreview` under the edit box. The read face, and therefore the record page, is unchanged. - **Five locale keys** in all eleven packs (zh-Hant generated with `gen:zh-hant`) and in `FIELD_DEFAULTS`: `fields.currencyHome.preview`, `previewSame`, `awaitingRate`, `awaitingDate` and `rateUnreadable`. `awaitingDate` reads "Set the document date to see the home amount" instead of the step-1 "Pick FIELD …", because the amount widget does not hold its sibling field's label (step-0 6727854849). - **`ui/packages/fields/package.json`** gains `"@objectstack/formula": "workspace:^"`, approved in the claim amendment. `pnpm-lock.yaml` moves by one importer entry. ## Tests - `ui/packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx` (new, 8 cases): - **Parity with the engine.** The engine's own cases go through the ui hook and must equal the number it stores. From `home-amount-projection.test.ts`: EUR 100 into JPY 15385, CNY 775.8, KWD 33.219. From `engine-home-amount-projection.test.ts`: USD 10,000 at 0.1389 into CNY 71994.24, and USD 150 on 2026-04-02 into 1000. - A foreign amount reads once per currency and date across a re-render and a remount, with exactly the engine's query, and the line follows a typed amount. - The same currency converts at 1 with zero reads: 1.005 gives 1.01, as the engine's decimal rounding does. - No rate in force shows awaiting-rate, naming the currency and date. A blank date asks for one and reads nothing. - A 403 shows "Converted to the home currency when you save" (`data-state="refused"`). - A non-refusal failure draws nothing and is asked again. - CONTROL: no `homeAmount`, a blank amount or a blank code previews nothing and reads nothing, and the input stays. - `ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx`, new `describe`: an `ObjectForm` in edit mode under a `SchemaRendererProvider` shows the line under the amount. This proves the adapter reaches the widget through the form. - `form-field-channel-census-12130` passes unchanged. The census records no new key on the channel, so the approved reader extension was not needed. ## Acceptance notes - **Measured live** on `pnpm dev:crm` with the built Console at `/_console`. The fixture is a scratch package with a record-mode amount declaring `homeAmount`, home currency CNY, and USD rates 0.1389 (2026-01-01) and 0.15 (2026-04-01). The engine stored the invoice (USD 10,000, 2026-03-15) as `amount_home` 71994.24 and `amount_rate` 0.1389. - **Admin:** the edit form's line reads "≈ CN¥71,994.24 at 0.1389 on Mar 15, 2026", the stored number. One `sys_exchange_rate` read answered 200 and picked the 2026-01-01 row, not the later one. Typing 20000 moved the line to "≈ CN¥143,988.48 …" with no second read. - **Member** (a permission set grants the invoice object only): the same read answered **403 `PERMISSION_DENIED`**. The adapter threw `httpStatus: 403`, `code: 'PERMISSION_DENIED'`, which `classifyLoadError` classes as `forbidden`. The line reads "Converted to the home currency when you save". Typing did not read again. - Scripts, readings and screenshots: `/mnt/project-files/issue-27196/live-pr2/` (`setup.mjs`, `measure.mjs`, `shot.cjs`, `live-report.json`, `shots/`). - **Bundle delta:** `@object-ui/fields` `dist/index.js` grows 349,245 → 352,872 bytes (+3,627), gzip 90,342 → 91,356 (+1,014). This was measured by building with and without the mount. `@objectstack/formula` is external to the fields build and already in the Console's graph through `@object-ui/core`. - **Display width:** the previewed NUMBER is rounded with the spec's `CURRENCY_FRACTION_DIGITS`, the engine's table. It is drawn with `formatCurrency`, the same call that draws the stored home field, so the preview and the saved field read the same. - **Document date:** the engine passes the timezone only for a `datetime` document date. The preview passes `localization.timezone` always. A `date` value in the form is `YYYY-MM-DD`, which `documentDateOf` returns as-is whatever zone it is given, so both agree for both types. ## Verification Head `57993ba65a6d74dadc132374899bf4d3356da389`. It merges `origin/main` (10 commits); none of them touches a file on this PR. The suites and gates below ran on `78863476`, the pre-merge head with the same PR files. 19 files, +447 / −2. - **Gates:** `node scripts/pm/dispatch-gates.mjs --ran` reports 59 derived, 59 run, 0 NOT-MEASURED, 0 UNRUN, and every exit code is 0. - `check:query-options-erasure` timed out at 300 s in the loop. It was re-run alone: exit 0 in 5m22s. - `check:dual-build-cjs-loads` answered exit 3 (unbuilt) until the platform packages were built. It was re-run: exit 0. - **Also run:** `turbo run type-check` for fields, i18n and plugin-form, 55 tasks, green. eslint on the touched files: 0 errors. `check-i18n-en-drift` (from `ui/`): 0. The form-field census: 34/34. - **Package suites** (all exit 0, under the verify lock): - `@object-ui/i18n` + `ui/examples/schema-catalog`: 144 files, 4241 passed, 13 skipped. - `@object-ui/fields`: 301 files passed, 1 skipped; 4556 tests passed, 7 skipped. - `@object-ui/plugin-form`: 226 files; 2466 passed, 1 skipped. - `pnpm --dir ui exec vitest run scripts/`: 170 files passed, 2 skipped; 5027 tests passed, 2 skipped. - **Examples census grep** (`git grep -l PATH -- 'ui/examples/**/test/**' 'ui/e2e/**'` for every touched path): only `catalog-gallery-render.test.tsx` names `useFieldTranslation.ts`. It is inside the schema-catalog run above, green. - **Ablations** (`ablation-replace.mjs`; each restored to a blob equal to HEAD with an empty `git diff HEAD`): 1. The rate cache removed (`if (held) return held;`): 1 of 8 red, the once-per-currency-and-date pin. 2. The 403 branch removed: 1 of 8 red, the refused pin. 3. The home digits taken as 2 instead of `CURRENCY_FRACTION_DIGITS[home]`: 1 of 8 red, the engine parity pin (JPY and KWD). 4. The `HomeAmountPreview` mount removed from `CurrencyField`: 7 of 14 red across the two files, the form pin included. The 7 that stay green are PR 1's five home-field pins, the parity case (it calls the hook directly) and the CONTROL. <details><summary>Gate list (59, exit codes as recorded)</summary> ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-console-intercept-disarm.mjs :: exit 0 node scripts/check-console-intercept-disarm.mjs --self-test :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-osv-exemptions.mjs :: exit 0 node scripts/check-osv-exemptions.mjs --self-test :: exit 0 node scripts/check-sdui-manifest.mjs :: exit 0 node scripts/check-sdui-manifest.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/osv-base-relative.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:llms-txt :: exit 0 pnpm check:changeset-fixed :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:manifest-repository-directory :: exit 0 pnpm check:merge-driver :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:override-consistency :: exit 0 pnpm check:pnpm-flag-spellings :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:role-word :: exit 0 pnpm check:skill-identifier-liveness :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:turbo-task-graph :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vendor-export-contract-resolve :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 pnpm check:workspace-manifest-cycles :: exit 0 pnpm --dir ui exec vitest run scripts/ :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 ``` </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jQyTLkpKcX2UF8X3Ss --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8aaa69f commit 2a32bd4

19 files changed

Lines changed: 447 additions & 2 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/i18n': patch
3+
'@object-ui/fields': patch
4+
---
5+
6+
feat(ui): a record-mode amount previews the home amount the save will store
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
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.
12+
13+
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.
14+
15+
`@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.

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎ui/packages/fields/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
"@object-ui/permissions": "workspace:*",
3838
"@object-ui/react": "workspace:*",
3939
"@object-ui/types": "workspace:*",
40+
"@objectstack/formula": "workspace:^",
4041
"@objectstack/spec": "workspace:^",
4142
"hast-util-to-jsx-runtime": "^2.3.6",
4243
"hastscript": "^9.0.1",
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* ADR-0144 D5, the live preview: while a `record`-mode amount declaring
11+
* `homeAmount` is edited, the line under it says what the save will store in
12+
* the home field. The arithmetic is `@objectstack/formula`'s (the engine's own
13+
* copy), so the parity cases below are the engine's test cases
14+
* (`packages/objectql/src/home-amount-projection.test.ts` and
15+
* `engine-home-amount-projection.test.ts`), inputs and stored numbers both.
16+
*/
17+
18+
import { describe, it, expect, afterEach } from 'vitest';
19+
import React from 'react';
20+
import { render, renderHook, cleanup, screen, waitFor } from '@testing-library/react';
21+
import '@testing-library/jest-dom';
22+
import { LocalizationProvider } from '@object-ui/i18n';
23+
import { CurrencyField } from '../widgets/CurrencyField';
24+
import { useHomeAmountPreview } from '../widgets/homeAmountPreview';
25+
26+
afterEach(cleanup);
27+
28+
const HOME_AMOUNT = { field: 'amount_home', rateDate: 'invoice_date', rateField: 'amount_rate' };
29+
const AMOUNT = { name: 'amount', type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code', homeAmount: HOME_AMOUNT } } as any;
30+
const text = (s: string | null | undefined) => (s ?? '').replace(/\u00a0/g, ' ');
31+
32+
/** A data source answering rate rows like the engine's rate table, counting its reads. */
33+
function rates(table: Record<string, Array<[string, unknown]>>, fail?: unknown) {
34+
const calls: Array<{ resource: string; params: any }> = [];
35+
const ds = {
36+
calls,
37+
async find(resource: string, params: any) {
38+
calls.push({ resource, params });
39+
if (fail) throw fail;
40+
const { currency, effective_date } = params.$filter;
41+
const rows = (table[currency] ?? [])
42+
.filter(([d]) => d <= effective_date.$lte)
43+
.sort(([a], [b]) => (a < b ? 1 : -1))
44+
.slice(0, 1)
45+
.map(([d, rate]) => ({ effective_date: d, rate }));
46+
return { data: rows };
47+
},
48+
};
49+
return ds;
50+
}
51+
52+
function preview(record: Record<string, unknown>, ds: unknown, home = 'CNY', field = AMOUNT) {
53+
return render(
54+
<LocalizationProvider value={{ locale: 'en-US', currency: home }}>
55+
<CurrencyField value={record.amount as number} onChange={() => {}} field={field} dependentValues={record} dataSource={ds} />
56+
</LocalizationProvider>,
57+
);
58+
}
59+
const line = () => text(screen.queryByTestId('home-amount-preview')?.textContent);
60+
61+
describe('the live home-amount preview (ADR-0144 D5)', () => {
62+
it('the engine parity cases: the previewed number is the number the engine stores, digit for digit', async () => {
63+
const EUR = { EUR: [['2026-01-01', 0.0065], ['2026-01-02', 0.1289], ['2026-01-03', 3.0103]] as Array<[string, unknown]> };
64+
const USD = { USD: [['2026-01-01', 0.1389], ['2026-04-01', 0.15]] as Array<[string, unknown]> };
65+
const cases: Array<[string, Record<string, Array<[string, unknown]>>, Record<string, unknown>, number]> = [
66+
['JPY', EUR, { amount: 100, currency_code: 'EUR', invoice_date: '2026-01-01' }, 15385], // JPY 0 digits
67+
['CNY', EUR, { amount: 100, currency_code: 'EUR', invoice_date: '2026-01-02' }, 775.8], // 2 digits
68+
['KWD', EUR, { amount: 100, currency_code: 'EUR', invoice_date: '2026-01-03' }, 33.219], // KWD 3 digits
69+
['CNY', USD, { amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, 71994.24], // the card's two-minute check
70+
['CNY', USD, { amount: 150, currency_code: 'USD', invoice_date: '2026-04-02' }, 1000],
71+
];
72+
for (const [home, table, record, stored] of cases) {
73+
const ds = rates(table);
74+
const { result } = renderHook(() => useHomeAmountPreview(AMOUNT, record.amount, record, ds), {
75+
wrapper: ({ children }) => <LocalizationProvider value={{ locale: 'en-US', currency: home }}>{children}</LocalizationProvider>,
76+
});
77+
await waitFor(() => expect(result.current?.kind).toBe('converted'));
78+
const state = result.current as Extract<typeof result.current, { kind: 'converted' }>;
79+
expect(Number(state.amount), `${home} ${JSON.stringify(record)}`).toBe(stored);
80+
}
81+
});
82+
83+
it('a foreign amount reads the rate in force once per currency and date, with the engine\'s query, and says it', async () => {
84+
const ds = rates({ USD: [['2026-01-01', 0.1389], ['2026-04-01', 0.15]] });
85+
const record = { amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' };
86+
const first = preview(record, ds);
87+
await waitFor(() => expect(line()).toBe('≈ CN¥71,994.24 at 0.1389 on Mar 15, 2026'));
88+
first.rerender(
89+
<LocalizationProvider value={{ locale: 'en-US', currency: 'CNY' }}>
90+
<CurrencyField value={20000} onChange={() => {}} field={AMOUNT} dependentValues={{ ...record, amount: 20000 }} dataSource={ds} />
91+
</LocalizationProvider>,
92+
);
93+
await waitFor(() => expect(line()).toBe('≈ CN¥143,988.48 at 0.1389 on Mar 15, 2026'));
94+
cleanup();
95+
preview(record, ds);
96+
await waitFor(() => expect(line()).toContain('CN¥71,994.24'));
97+
expect(ds.calls).toEqual([{
98+
resource: 'sys_exchange_rate',
99+
params: { $filter: { currency: 'USD', effective_date: { $lte: '2026-03-15' } }, $orderby: [{ field: 'effective_date', order: 'desc' }], $top: 1, $select: ['rate', 'effective_date'] },
100+
}]);
101+
});
102+
103+
it('the home currency converts at 1 with no read, rounded half away from zero to the home digits', async () => {
104+
const ds = rates({});
105+
preview({ amount: 1.005, currency_code: 'CNY' }, ds);
106+
expect(line()).toBe('≈ CN¥1.01 (home currency)');
107+
expect(ds.calls).toHaveLength(0);
108+
});
109+
110+
it('no rate on or before the document date is the awaiting-rate state, naming the currency and date', async () => {
111+
const ds = rates({ USD: [['2026-01-01', 0.1389]] });
112+
preview({ amount: 1, currency_code: 'USD', invoice_date: '2025-12-31' }, ds);
113+
await waitFor(() => expect(line()).toBe('No USD rate on or before Dec 31, 2025: saving is refused until one is added'));
114+
});
115+
116+
it('a foreign amount with no document date asks for it, and reads nothing', () => {
117+
const ds = rates({ USD: [['2026-01-01', 0.1389]] });
118+
preview({ amount: 1, currency_code: 'USD', invoice_date: '' }, ds);
119+
expect(line()).toBe('Set the document date to see the home amount');
120+
expect(ds.calls).toHaveLength(0);
121+
});
122+
123+
it('a refused read (403) says it converts on save: never awaiting rate, never an amount', async () => {
124+
const refused = Object.assign(new Error('Permission denied'), { httpStatus: 403, code: 'PERMISSION_DENIED' });
125+
const ds = rates({}, refused);
126+
preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds);
127+
await waitFor(() => expect(line()).toBe('Converted to the home currency when you save'));
128+
expect(screen.getByTestId('home-amount-preview')).toHaveAttribute('data-state', 'refused');
129+
});
130+
131+
it('a failed read that is not a refusal draws nothing and is asked again next time', async () => {
132+
const ds = rates({}, Object.assign(new Error('offline'), { httpStatus: 503 }));
133+
preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds);
134+
await waitFor(() => expect(ds.calls).toHaveLength(1));
135+
await new Promise((r) => setTimeout(r, 0));
136+
expect(screen.queryByTestId('home-amount-preview')).toBeNull();
137+
cleanup();
138+
preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds);
139+
await waitFor(() => expect(ds.calls).toHaveLength(2));
140+
});
141+
142+
it('CONTROL: an amount with no homeAmount, a blank amount and a blank code preview nothing and read nothing', async () => {
143+
const ds = rates({ USD: [['2026-01-01', 0.1389]] });
144+
const plain = { ...AMOUNT, currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } };
145+
preview({ amount: 10000, currency_code: 'USD', invoice_date: '2026-03-15' }, ds, 'CNY', plain);
146+
preview({ amount: null, currency_code: 'USD', invoice_date: '2026-03-15' }, ds);
147+
preview({ amount: 10000, currency_code: '', invoice_date: '2026-03-15' }, ds);
148+
await new Promise((r) => setTimeout(r, 0));
149+
expect(screen.queryAllByTestId('home-amount-preview')).toHaveLength(0);
150+
expect(screen.getAllByRole('spinbutton')).toHaveLength(3);
151+
expect(ds.calls).toHaveLength(0);
152+
});
153+
});

‎ui/packages/fields/src/widgets/CurrencyField.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ import { resolveFieldCurrency, currencySymbol } from '../currency.js';
99
import { useFieldTranslation } from './useFieldTranslation.js';
1010
import { useBadInputRefusal, BadInputMessage, BAD_INPUT_BORDER } from './numberBadInput.js';
1111
import { formatCurrency, currencyDisplayWidth } from './number-format.js';
12+
import { HomeAmountPreview } from './homeAmountPreview.js';
1213

13-
export function CurrencyField({ value, onChange, field, readonly, error, className, dependentValues, ...props }: FieldWidgetComponentProps<number>) {
14+
export function CurrencyField({ value, onChange, field, readonly, error, className, dependentValues, dataSource, ...props }: FieldWidgetComponentProps<number>) {
1415
const currencyField = field as any;
1516
// Shared precedence: field currency → currencyConfig → tenant default (ADR-0053).
1617
// 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
218219
/>
219220
</div>
220221
<BadInputMessage refusal={refusal} />
222+
{/* A record-mode amount declaring `homeAmount` (ADR-0144 D5): what the save will store. */}
223+
<HomeAmountPreview field={currencyField} amount={value} record={dependentValues} dataSource={dataSource} />
221224
</div>
222225
);
223226
}

0 commit comments

Comments
 (0)