Skip to content

Commit 2e33533

Browse files
feat(ui): show the rate and date a home amount was converted at, and a Studio homeAmount editor (#31638)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbKY5oMZsVopxN5eVhk1kG6N)_ Part-of #27196 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - **改了什么:** 多币种「本位币金额」字段(`currencyConfig.homeAmount.field`)在记录页和表单分区里改为只读金额,下面一行写明「按汇率 0.1389(2026-11-01)折算」,数据取自记录自己的汇率字段和单据日期字段;同币种记录显示「本位币(汇率 1)」。Studio 字段编辑器在 record 模式下新增三个下拉:本位币金额字段、单据日期、汇率字段,只列规范接受的字段;顺手修了一个缺陷:改选币种代码字段时会把已写的 `homeAmount` 静默删掉。 - **为什么改:** 财务对账要看到折算用的是哪条汇率、哪一天;作者在 Studio 里也要能声明这三个指针。 - **风险与回滚:** 只影响声明了 `homeAmount` 的对象:其余币种字段的渲染逐字不变(有对照测试)。新增两个翻译键,属于 widening。回滚即 revert 本 PR。自动布局表单仍然不显示只读字段(含本位币字段),未改。 - **先看:** `ui/packages/i18n/src/currency.ts`(`homeAmountSourceOf`)、`ui/packages/fields/src/widgets/CurrencyField.tsx`(`HomeAmountHint`)、`ui/packages/app-shell/src/views/metadata-admin/inspectors/CurrencyConfigField.tsx`(`homeAmountCandidates` 与改选币种字段时保留 `homeAmount`)。 - **两分钟验证:** `cd ui && pnpm exec vitest run packages/plugin-detail/src/__tests__/DetailSection.homeAmount-27196.test.tsx packages/app-shell/src/views/metadata-admin/inspectors/CurrencyConfigField.recordMode-27188.test.tsx`,预期全绿,其中记录页一例断言提示为 "Converted at 0.1389 on Nov 1, 2026"。 - **需要你做的:** 无,席位落地(落地前席位欠一次 Clause-② 声明复审)。 ## What changes The ui half of multi-currency M3-2, slice 1 of 2 (Tasks 1 and 3 of the card). The preview (Task 2) is slice 2, waiting on #31609, which moves the engine's conversion functions into a package the ui can import. **Task 1: the home field reads as what it is.** A `record`-mode amount's `homeAmount.field` is written by the engine alone, and until now nothing in the ui knew a field was one: the declaration sits on the AMOUNT. - `@object-ui/i18n` gains one reader, `homeAmountSourceOf(fields, name)`: the amount, code field, document date and rate field that name `name` as home. Producers stamp it on the field metadata they hand a currency renderer (`withHomeAmountSource`, read back with `readHomeAmountSource`), the way the form stamps a code field's `usedCurrencyCodes`. - Producers: the record page (`DetailSection`), the section builder the record dialog and drawer share (`sectionFields.ts`), and an inline `ObjectForm`'s own field build (`ObjectForm.tsx`, added to the claim by amendment 6724257070). - Consumers: `CurrencyField` draws a stamped field's read face even when the form hands it `disabled` (it was a disabled number box with no symbol), and `CurrencyCellRenderer` adds the same line on the record page. The line is `HomeAmountHint`: "Converted at RATE on DATE" from the record's own `rateField` / `rateDate` values (the rate unrounded, the date with its year), or "In the home currency (rate 1)" when the amount's code is the home currency. Nothing is drawn while the record holds no rate. Nothing is recomputed in the ui. - Two new locale keys in all eleven packs (`fields.currencyHome.convertedAt`, `fields.currencyHome.homeCurrency`; zh-Hant generated with `gen:zh-hant`) and in `FIELD_DEFAULTS`. **Task 3: the Studio `homeAmount` editor.** Under `record` mode, `CurrencyConfigField` shows three pickers: home amount field, document date, rate field. `homeAmountCandidates` lists what the spec's object judge (`refuseDishonestHomeAmount`) accepts for each: a stored `dynamic` `currency` field that is `readonly`, has no `expression` and is no other amount's home field; a `date` / `datetime`; a `readonly` `number` with no `expression`, `scale` 12 or none, shared only with an amount on the same code field and document date. The judge exports no predicate, so per the amendment the spec is the test oracle (below), and no refusal text is copied. Unpicking a pointer deletes it, and `homeAmount` goes once none is left. No editor on a `formula` amount, which the spec refuses `homeAmount` on. **Defect fixed in Task 3.** Re-picking an amount's currency code field committed `{ currencyMode: 'record', currencyField }` and silently deleted an authored `homeAmount`. It is now kept; leaving `record` mode still drops it, as the spec requires. ## Tests - `ui/packages/fields/src/__tests__/recordCurrency.faces-27188.test.tsx`, new top-level `describe('home field faces (ADR-0144 D5)')`: the reader and the no-stamp identity; the form widget draws no input and the line "Converted at 0.1389 on Nov 1, 2026"; the cell says the same, and "In the home currency (rate 1)" for a same-currency row; no rate ⇒ no line. CONTROL: an unstamped readonly amount stays an input in the form and a bare cell. - `ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx`: the record dialog (edit and view), the drawer and an inline `ObjectForm`, each with authored sections, draw the home field with its line and no input. CONTROL: a readonly currency field no amount names stays the disabled box. - `ui/packages/plugin-detail/src/__tests__/DetailSection.homeAmount-27196.test.tsx`: the record page's home row carries the line, and only that row; rate 1 case. - `ui/packages/app-shell/src/views/metadata-admin/inspectors/CurrencyConfigField.recordMode-27188.test.tsx`, new top-level `describe('Studio homeAmount editor (ADR-0144 D5)')`: - candidate lists, the rate field judged against the picked document date and code field; - **ORACLE, offered ⇒ parses:** every field × document date × rate field the editor offers on the fixture object parses through `ObjectSchema` (10 combinations); - **ORACLE, left out ⇒ refused:** a writable, an `expression`, a `fixed`-mode and an already-claimed home field, a `scale: 2` and a writable rate field, a rate field shared across document dates, a text document date and a `formula` amount are each refused at a `homeAmount` path (no message asserted); - picking the three pointers writes `homeAmount` and the object parses; re-picking the code field keeps `homeAmount`; switching to `dynamic` drops it; no editor under `dynamic` or on a `formula` amount. CONTROL: the five existing cases in the file stay green. - The file now loads `@objectstack/formula` and `@objectstack/lint` at module top: editing it put it under `check:test-source-alias`'s source-reach half, which found both reached through the inspector's CEL authoring. ## Acceptance notes - **Out of scope, kept as today (amendment 6724151062):** an auto-layout `ObjectForm` keeps dropping every `readonly` field (`plugin-form/src/autoLayout.ts`, `filterSystemFields`), the home field included. Changing that would move every readonly field on every auto form. The home field shows on the record page and on authored sections. - The display trusts the stored rate and date; it never recomputes. The live preview before save is slice 2 (`Blocked-by: #31609`); its refused-read (403) state is still NOT MEASURED live and is owed there. - The hint's date is the document-date field's own value, formatted as a date. For a `datetime` document date the engine takes the calendar day in `localization.timezone`; the display formats the instant in the display time zone, which the Console sets from the same setting. ## Verification Head `68f353bae4e9ac4082d9aa91ac0bdf156bab698c` (origin/main `69244406` merged in; no file on this PR changed on main in between). 28 files, +700 / −11. - **Gates:** `node scripts/pm/dispatch-gates.mjs --ran` reports 39 derived, 39 run, 0 NOT-MEASURED, 0 UNRUN; every recorded exit code is 0. - **Package suites** (all exit 0, under the verify lock): - `@object-ui/i18n`: 99 files passed; 1804 tests passed, 13 skipped. - `@object-ui/fields`: 300 files passed, 1 skipped; 4548 tests passed, 7 skipped. - `@object-ui/plugin-form`: 226 files passed; 2465 tests passed, 1 skipped. - `@object-ui/plugin-detail`: 374 files passed, 1 skipped; 3355 tests passed, 18 skipped. - app-shell, narrowed to the 54 files naming `CurrencyConfigField` or `ObjectFieldInspector`: 54 files and 578 tests passed. The rest of app-shell was not run locally. - `pnpm --dir ui exec vitest run scripts/`: 170 files passed, 2 skipped; 5002 tests passed, 2 skipped. - **Ablations** (`ablation-replace.mjs`; each one restored to a blob equal to HEAD with an empty `git diff HEAD`): 1. `readHomeAmountSource` returns `undefined`: 9 of 22 display pins red, across the fields, plugin-form and plugin-detail files. 2. The rate-field filter keeps only the `number` type test (no readonly, expression or sharing check): 2 of 13 Studio pins red. 3. Re-picking the code field drops `homeAmount` again: 1 of 13 Studio pins red. <details><summary>Gate list (39, 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-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.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/snapshot-next.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:error-code-provenance :: 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:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:merge-driver :: exit 0 pnpm check:nul-bytes :: 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:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: 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 ce965cf commit 2e33533

29 files changed

Lines changed: 705 additions & 11 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@object-ui/i18n': patch
3+
'@object-ui/fields': patch
4+
'@object-ui/plugin-form': patch
5+
'@object-ui/plugin-detail': patch
6+
---
7+
8+
feat(ui): a home-currency amount shows the rate and document date it was converted at
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: none
12+
13+
A `record`-mode amount that declares `currencyConfig.homeAmount` (ADR-0144 D5) has its home field filled by the server when the record is saved. That home field now draws as a read-only amount in the organization's home currency, with the line "Converted at RATE on DATE" taken from the record's own rate and document-date fields, or "In the home currency (rate 1)" when the amount was already in the home currency. This holds on the record page and on authored form sections (the record dialog, the drawer and an inline `ObjectForm`), where it used to be a disabled number box with no currency symbol. A form laid out automatically still leaves readonly fields out, the home field included.
14+
15+
`@object-ui/i18n` adds `homeAmountSourceOf`, `withHomeAmountSource`, `readHomeAmountSource`, `HOME_AMOUNT_SOURCE_KEY` and the `HomeAmountSource` type, plus two locale keys in every pack: `fields.currencyHome.convertedAt` and `fields.currencyHome.homeCurrency`. `@object-ui/fields` exports `HomeAmountHint`.
16+
17+
The Studio field editor gains the three `homeAmount` pickers under `record` mode (home amount field, document date, rate field), listing only the fields the spec accepts for each. Re-picking an amount's currency code field no longer deletes its `homeAmount`.

‎ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,11 @@ const LEDGER: Readonly<Record<string, LedgerRow>> = {
331331
why: 'RUNTIME-ONLY (objectstack#28245) — object-field metadata (the spec\'s `FieldSchema.lookupAutofill`) read off the '
332332
+ 'resolved `field` stash: which fields a pick fills is a fact about the object, not about one form.',
333333
},
334+
homeAmountSource: {
335+
readers: [CURRENCY],
336+
why: 'RUNTIME-ONLY (objectstack#27196) — the producers stamp the home-amount source onto the resolved field '
337+
+ '(ADR-0144 D5): it is read off the object\'s field map, never authored on a form.',
338+
},
334339
currency: {
335340
readers: [CURRENCY],
336341
why: 'RUNTIME-ONLY (objectui#11070 round 13) — the spec\'s `FieldSchema` refuses it; `currencyConfig` is the declared spelling.',

‎ui/packages/app-shell/src/views/metadata-admin/inspectors/CurrencyConfigField.recordMode-27188.test.tsx‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,16 @@ import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest';
1111
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
1212
import userEvent from '@testing-library/user-event';
1313
import { ObjectSchema } from '@objectstack/spec/data';
14+
// Paid during collection, not inside a case: the inspector reaches both
15+
// through dynamic imports (CEL authoring), and a clocked window measures
16+
// behaviour, never loading (check:test-source-alias).
17+
import '@objectstack/formula';
18+
import '@objectstack/lint';
1419
import {
1520
currencyCodeFieldCandidates,
21+
homeAmountCandidates,
1622
nextCurrencyCodeFieldName,
23+
setHomeAmountPointer,
1724
switchCurrencyMode,
1825
} from './CurrencyConfigField';
1926

@@ -143,3 +150,127 @@ describe('Studio currency section (ADR-0144 D2)', () => {
143150
expect(ObjectSchema.safeParse({ name: 'invoice', label: 'Invoice', fields }).success).toBe(true);
144151
});
145152
});
153+
154+
// ADR-0144 D5: the `homeAmount` pickers. The spec's object judge
155+
// (`refuseDishonestHomeAmount`) exports no predicate, so the spec itself is the
156+
// oracle: every pick the editor offers must parse, and every shape it leaves
157+
// out must be refused, at `homeAmount`. No refusal text is asserted.
158+
describe('Studio homeAmount editor (ADR-0144 D5)', () => {
159+
const RO_CURRENCY = (label: string) => ({ type: 'currency', label, readonly: true });
160+
const RO_NUMBER = (label: string, extra: Record<string, unknown> = {}) => ({ type: 'number', label, readonly: true, ...extra });
161+
const RECORD = { currencyMode: 'record', currencyField: 'currency_code' } as const;
162+
const OBJECT: Record<string, Record<string, unknown>> = {
163+
currency_code: CODE,
164+
other_code: { ...CODE, label: 'Other currency' },
165+
invoice_date: { type: 'date', label: 'Invoice date' },
166+
posted_at: { type: 'datetime', label: 'Posted at' },
167+
note: { type: 'text', label: 'Note' },
168+
amount: { type: 'currency', label: 'Amount', currencyConfig: RECORD },
169+
amount_home: RO_CURRENCY('Home'),
170+
home_2: RO_CURRENCY('Home 2'),
171+
home_writable: { type: 'currency', label: 'Writable' },
172+
home_expr: { ...RO_CURRENCY('Computed'), expression: 'record.amount' },
173+
home_fixed: { ...RO_CURRENCY('Fixed'), currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } },
174+
amount_rate: RO_NUMBER('Rate'),
175+
rate_12: RO_NUMBER('Rate 12', { scale: 12 }),
176+
rate_low: RO_NUMBER('Rate 2', { scale: 2 }),
177+
rate_writable: { type: 'number', label: 'Writable rate' },
178+
other_amount: { type: 'currency', label: 'Other', currencyConfig: { ...RECORD, homeAmount: { field: 'claimed_home', rateDate: 'invoice_date', rateField: 'shared_rate' } } },
179+
claimed_home: RO_CURRENCY('Claimed'),
180+
shared_rate: RO_NUMBER('Shared rate'),
181+
};
182+
const withHome = (homeAmount: Record<string, string>, amount: Record<string, unknown> = {}) => ({
183+
...OBJECT,
184+
amount: { ...OBJECT.amount, ...amount, currencyConfig: { ...RECORD, ...(amount.currencyConfig as object), homeAmount } },
185+
});
186+
const entriesOf = (fields: Record<string, Record<string, unknown>>) => Object.entries(fields).map(([name, def]) => ({ name, def }));
187+
const parse = (fields: Record<string, unknown>) => ObjectSchema.safeParse({ name: 'invoice', label: 'Invoice', fields });
188+
const refusedAtHomeAmount = (fields: Record<string, unknown>) => {
189+
const r = parse(fields);
190+
// At either claimant's `homeAmount`: the judge gives a shared home field to
191+
// the first amount declared and refuses the other one.
192+
return !r.success && r.error.issues.some((i) => /^fields\.[a-z_]+\.currencyConfig\.homeAmount/.test(i.path.join('.')));
193+
};
194+
195+
it('the fixture object parses as it stands', () => {
196+
expect(parse(OBJECT).success).toBe(true);
197+
});
198+
199+
it('lists each pointer\'s candidates, the rate field judged against the picked document date and code field', () => {
200+
expect(homeAmountCandidates(entriesOf(OBJECT), 'amount')).toEqual({
201+
field: ['amount_home', 'home_2'],
202+
rateDate: ['invoice_date', 'posted_at'],
203+
rateField: ['amount_rate', 'rate_12'],
204+
});
205+
// Same code field and document date as `other_amount`: its rate field may be shared.
206+
expect(homeAmountCandidates(entriesOf(withHome({ rateDate: 'invoice_date' })), 'amount').rateField).toEqual(['amount_rate', 'rate_12', 'shared_rate']);
207+
expect(homeAmountCandidates(entriesOf(withHome({ rateDate: 'invoice_date' }, { currencyConfig: { currencyField: 'other_code' } })), 'amount').rateField).toEqual(['amount_rate', 'rate_12']);
208+
});
209+
210+
it('ORACLE: every combination the editor offers parses', () => {
211+
const offered = homeAmountCandidates(entriesOf(OBJECT), 'amount');
212+
let combos = 0;
213+
for (const rateDate of offered.rateDate) {
214+
const now = homeAmountCandidates(entriesOf(withHome({ rateDate })), 'amount');
215+
for (const field of now.field) {
216+
for (const rateField of now.rateField) {
217+
const fields = withHome({ field, rateDate, rateField });
218+
expect(parse(fields).success, `${field} / ${rateDate} / ${rateField}`).toBe(true);
219+
combos += 1;
220+
}
221+
}
222+
}
223+
expect(combos).toBe(2 * 3 + 2 * 2);
224+
});
225+
226+
it('ORACLE: every shape the editor leaves out is refused at homeAmount', () => {
227+
const ok = { field: 'amount_home', rateDate: 'invoice_date', rateField: 'amount_rate' };
228+
expect(parse(withHome(ok)).success).toBe(true);
229+
for (const field of ['home_writable', 'home_expr', 'home_fixed', 'claimed_home']) {
230+
expect(refusedAtHomeAmount(withHome({ ...ok, field })), field).toBe(true);
231+
}
232+
for (const rateField of ['rate_low', 'rate_writable']) {
233+
expect(refusedAtHomeAmount(withHome({ ...ok, rateField })), rateField).toBe(true);
234+
}
235+
expect(refusedAtHomeAmount(withHome({ ...ok, rateDate: 'posted_at', rateField: 'shared_rate' })), 'shared rate, other date').toBe(true);
236+
expect(refusedAtHomeAmount(withHome({ ...ok, rateDate: 'note' })), 'text date').toBe(true);
237+
const formula = { type: 'formula', label: 'Net', expression: 'record.gross * 0.9', returnType: 'currency' };
238+
expect(refusedAtHomeAmount({ ...withHome(ok, formula), gross: { type: 'currency', label: 'Gross' } }), 'formula amount').toBe(true);
239+
});
240+
241+
it('a pointer unpicked is deleted, and homeAmount with it once none is left', () => {
242+
const one = setHomeAmountPointer({ currencyMode: 'record', currencyField: 'currency_code' }, 'field', 'amount_home');
243+
expect(one).toEqual({ currencyMode: 'record', currencyField: 'currency_code', homeAmount: { field: 'amount_home' } });
244+
expect(setHomeAmountPointer(one, 'field', '')).toEqual({ currencyMode: 'record', currencyField: 'currency_code' });
245+
});
246+
247+
it('picking the three pointers writes homeAmount, and the object parses', async () => {
248+
const { saved } = renderAmountLive(OBJECT);
249+
expect(screen.getByTestId('currency-config-home-amount')).toBeInTheDocument();
250+
await pick('Home amount field', 'amount_home');
251+
await pick('Document date', 'invoice_date');
252+
await pick('Rate field', 'shared_rate');
253+
const fields = saved();
254+
expect((fields.amount.currencyConfig as any).homeAmount).toEqual({ field: 'amount_home', rateDate: 'invoice_date', rateField: 'shared_rate' });
255+
expect(parse(fields).success).toBe(true);
256+
});
257+
258+
it('re-picking the currency field keeps homeAmount; leaving record mode drops it', async () => {
259+
const home = { field: 'amount_home', rateDate: 'invoice_date', rateField: 'amount_rate' };
260+
const { saved } = renderAmountLive(withHome(home));
261+
await pick(/Currency field/, 'other_code');
262+
expect(saved().amount.currencyConfig).toEqual({ currencyMode: 'record', currencyField: 'other_code', homeAmount: home });
263+
await pick('Currency mode', 'Dynamic — the organization currency');
264+
expect(saved().amount.currencyConfig).toEqual({ currencyMode: 'dynamic' });
265+
expect(switchCurrencyMode({ currencyMode: 'record', currencyField: 'currency_code', homeAmount: home }, 'record')).toEqual({ currencyMode: 'record', currencyField: 'currency_code', homeAmount: home });
266+
});
267+
268+
it('shows the editor only under record mode, and never on a formula amount', () => {
269+
renderAmount({ ...OBJECT, amount: { type: 'currency', label: 'Amount' } });
270+
expect(screen.queryByTestId('currency-config-home-amount')).toBeNull();
271+
cleanup();
272+
renderAmount({ ...OBJECT, amount: { type: 'formula', label: 'Net', expression: 'record.gross', returnType: 'currency', currencyConfig: RECORD } });
273+
expect(screen.getByRole('combobox', { name: /Currency field/ })).toBeInTheDocument();
274+
expect(screen.queryByTestId('currency-config-home-amount')).toBeNull();
275+
});
276+
});

‎ui/packages/app-shell/src/views/metadata-admin/inspectors/CurrencyConfigField.tsx‎

Lines changed: 132 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@
2323
* convention to get a valid declaration. Nothing here guesses a code or a
2424
* pointer: an unpicked pointer stays absent and the spec's own refusal says so
2525
* on save.
26+
*
27+
* A stored `record`-mode amount may also declare `homeAmount` (ADR-0144 D5):
28+
* the home field, document date and rate field the engine writes the amount's
29+
* home-currency conversion into. The three pickers list what the spec's object
30+
* judge accepts; the judge stays the authority, and the tests hold every
31+
* offered pick to it by parsing the object.
2632
*/
2733

2834
import * as React from 'react';
@@ -39,10 +45,90 @@ export const CURRENCY_CODE_FIELD_NAME = 'currency_code';
3945

4046
export type CurrencyMode = 'dynamic' | 'fixed' | 'record';
4147

48+
/** `homeAmount` as authored: each pointer absent until picked (the spec refuses a partial one on save). */
49+
export interface HomeAmountDraft {
50+
field?: string;
51+
rateDate?: string;
52+
rateField?: string;
53+
}
54+
4255
export interface CurrencyConfigDraft {
4356
currencyMode?: CurrencyMode;
4457
defaultCurrency?: string;
4558
currencyField?: string;
59+
homeAmount?: HomeAmountDraft;
60+
}
61+
62+
/** The fields each `homeAmount` pointer may name, from {@link homeAmountCandidates}. */
63+
export interface HomeAmountCandidates {
64+
field: string[];
65+
rateDate: string[];
66+
rateField: string[];
67+
}
68+
69+
/** The scale an exchange rate carries; a rate field declaring less would show it rounded. */
70+
const RATE_SCALE = 12;
71+
72+
/** Written by the engine alone: `readonly: true` and no `expression` (ADR-0144 D5). */
73+
const isEngineWritten = (def: Record<string, unknown> | undefined): boolean =>
74+
def?.readonly === true && def.expression === undefined;
75+
76+
const homeAmountOf = (def: Record<string, unknown> | undefined): HomeAmountDraft | undefined => {
77+
const config = def?.currencyConfig as CurrencyConfigDraft | undefined;
78+
return config?.currencyMode === 'record' && config.homeAmount && typeof config.homeAmount === 'object'
79+
? config.homeAmount
80+
: undefined;
81+
};
82+
83+
/**
84+
* The fields of `entries` each `homeAmount` pointer of the amount `self` may
85+
* name: a stored `dynamic` `currency` field no other amount stores its home
86+
* amount in; a `date` / `datetime` document date; a `number` rate field with
87+
* scale 12 or none, not shared with an amount in another code field or on
88+
* another document date. The home and rate fields are engine-written.
89+
*/
90+
export function homeAmountCandidates(entries: readonly FieldEntry[], self: string): HomeAmountCandidates {
91+
const own = entries.find((e) => e.name === self)?.def;
92+
const ownConfig = own?.currencyConfig as CurrencyConfigDraft | undefined;
93+
const others = entries.filter((e) => e.name !== self && homeAmountOf(e.def));
94+
const homeTaken = new Set(others.map((e) => homeAmountOf(e.def)!.field));
95+
const rateDate = ownConfig?.homeAmount?.rateDate;
96+
const rateTaken = new Set(
97+
others
98+
.filter((e) => {
99+
const config = e.def.currencyConfig as CurrencyConfigDraft;
100+
return config.currencyField !== ownConfig?.currencyField || config.homeAmount!.rateDate !== rateDate;
101+
})
102+
.map((e) => homeAmountOf(e.def)!.rateField),
103+
);
104+
const rest = entries.filter((e) => e.name !== self);
105+
return {
106+
field: rest
107+
.filter((e) => e.def.type === 'currency' && isEngineWritten(e.def) && !homeTaken.has(e.name))
108+
.filter((e) => ((e.def.currencyConfig as CurrencyConfigDraft | undefined)?.currencyMode ?? 'dynamic') === 'dynamic')
109+
.map((e) => e.name),
110+
rateDate: rest.filter((e) => e.def.type === 'date' || e.def.type === 'datetime').map((e) => e.name),
111+
rateField: rest
112+
.filter((e) => e.def.type === 'number' && isEngineWritten(e.def) && !rateTaken.has(e.name))
113+
.filter((e) => typeof e.def.scale !== 'number' || e.def.scale >= RATE_SCALE)
114+
.map((e) => e.name),
115+
};
116+
}
117+
118+
/**
119+
* `config` with one `homeAmount` pointer set, or deleted when `value` is
120+
* empty; `homeAmount` itself is deleted once no pointer is left.
121+
*/
122+
export function setHomeAmountPointer(
123+
config: CurrencyConfigDraft,
124+
key: keyof HomeAmountDraft,
125+
value: string,
126+
): CurrencyConfigDraft {
127+
const { homeAmount, ...rest } = config;
128+
const next: HomeAmountDraft = { ...homeAmount };
129+
if (value) next[key] = value;
130+
else delete next[key];
131+
return Object.keys(next).length > 0 ? { ...rest, homeAmount: next } : rest;
46132
}
47133

48134
/** Whether a field def is a record-currency code field: `text` + the ISO 4217 domain. */
@@ -75,7 +161,12 @@ export function switchCurrencyMode(prev: CurrencyConfigDraft | undefined, mode:
75161
return { currencyMode: 'fixed', ...(prev?.defaultCurrency ? { defaultCurrency: prev.defaultCurrency } : {}) };
76162
}
77163
if (mode === 'record') {
78-
return { currencyMode: 'record', ...(prev?.currencyField ? { currencyField: prev.currencyField } : {}) };
164+
return {
165+
currencyMode: 'record',
166+
...(prev?.currencyField ? { currencyField: prev.currencyField } : {}),
167+
// `homeAmount` is read only under `record`, so only a record config carries one over.
168+
...(prev?.currencyMode === 'record' && prev.homeAmount ? { homeAmount: prev.homeAmount } : {}),
169+
};
79170
}
80171
return { currencyMode: 'dynamic' };
81172
}
@@ -92,6 +183,7 @@ export function newCurrencyCodeFieldDef(label: string): Record<string, unknown>
92183
export function CurrencyConfigField({
93184
config,
94185
candidates,
186+
homeCandidates,
95187
onCommit,
96188
onCreateCodeField,
97189
disabled,
@@ -100,6 +192,11 @@ export function CurrencyConfigField({
100192
config: CurrencyConfigDraft | undefined;
101193
/** {@link currencyCodeFieldCandidates} of the object this field belongs to. */
102194
candidates: readonly string[];
195+
/**
196+
* {@link homeAmountCandidates} of the object; absent where `homeAmount` is
197+
* refused (a `formula` amount, never written, is never converted at write).
198+
*/
199+
homeCandidates?: HomeAmountCandidates;
103200
/** Write the whole config. */
104201
onCommit: (next: CurrencyConfigDraft) => void;
105202
/** Append a record-currency code field and point this amount at it, in one write. */
@@ -147,7 +244,15 @@ export function CurrencyConfigField({
147244
// Unpicking DELETES the pointer: the spec refuses a `record` config
148245
// without one on save, which is the honest answer, rather than a
149246
// pointer at a field the author never chose.
150-
onCommit={(v) => onCommit(v ? { currencyMode: 'record', currencyField: v } : { currencyMode: 'record' })}
247+
// Re-picking the code field keeps an authored `homeAmount`: it
248+
// names other fields, which the new pointer does not move.
249+
onCommit={(v) =>
250+
onCommit({
251+
currencyMode: 'record',
252+
...(v ? { currencyField: v } : {}),
253+
...(config?.homeAmount ? { homeAmount: config.homeAmount } : {}),
254+
})
255+
}
151256
required
152257
disabled={disabled}
153258
/>
@@ -163,6 +268,31 @@ export function CurrencyConfigField({
163268
{tr('designer.field.currency.createCodeField')}
164269
</Button>
165270
<p className="text-xs text-muted-foreground">{tr('designer.field.currency.recordHint')}</p>
271+
{homeCandidates && (
272+
<div className="space-y-2 pt-2" data-testid="currency-config-home-amount">
273+
<p className="text-xs font-medium">{tr('designer.field.currency.homeAmount')}</p>
274+
{(
275+
[
276+
['field', 'homeField', 'homeFieldNone'],
277+
['rateDate', 'rateDate', 'rateDateNone'],
278+
['rateField', 'rateField', 'rateFieldNone'],
279+
] as const
280+
).map(([key, label, none]) => (
281+
<InspectorSelectField
282+
key={key}
283+
label={tr(`designer.field.currency.${label}`)}
284+
value={config?.homeAmount?.[key] ?? ''}
285+
options={[
286+
{ value: '', label: tr(`designer.field.currency.${none}`) },
287+
...homeCandidates[key].map((name) => ({ value: name, label: name })),
288+
]}
289+
onCommit={(v) => onCommit(setHomeAmountPointer(config ?? { currencyMode: 'record' }, key, v))}
290+
disabled={disabled}
291+
/>
292+
))}
293+
<p className="text-xs text-muted-foreground">{tr('designer.field.currency.homeAmountHint')}</p>
294+
</div>
295+
)}
166296
</>
167297
)}
168298
</div>

‎ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ import { FieldTypePicker } from './FieldTypePicker.js';
121121
import {
122122
CurrencyConfigField,
123123
currencyCodeFieldCandidates,
124+
homeAmountCandidates,
124125
nextCurrencyCodeFieldName,
125126
newCurrencyCodeFieldDef,
126127
type CurrencyConfigDraft,
@@ -1713,6 +1714,7 @@ export function ObjectFieldInspector({
17131714
<CurrencyConfigField
17141715
config={def.currencyConfig as CurrencyConfigDraft | undefined}
17151716
candidates={currencyCodeFieldCandidates(view.entries, name)}
1717+
homeCandidates={type === 'currency' ? homeAmountCandidates(view.entries, name) : undefined}
17161718
onCommit={(next) => patchDef({ currencyConfig: next })}
17171719
onCreateCodeField={createCurrencyCodeField}
17181720
disabled={locked}

0 commit comments

Comments
 (0)