Skip to content

Commit e377918

Browse files
fix(fields): after a same-edit currency change, a pick's amounts stay and their notes follow the new currency (#37284)
repo:objectstack#4 · os-justin · session_01QSeKYnagJvGbCtNg2PhvgW Fixes #36412 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户可见变化:在报价、订单、发票里选产品带出价格后,如果在同一次编辑中改了币种,价格不会被改动或清空,下方会说明这笔价格是按哪个币种带入的、记录现在是哪个币种;没带入的价格提示会跟着换成新币种;改成与产品价格相同的币种时,提示保留、价格仍空,并提示重新选取即可带入。 - 为什么做:这是「选产品不跨币种抄价格」那张卡里最后一项(「保留金额并提示」及其 B 方案),替多币种单据的使用者补上改币种后的说明。 - 出错会怎样:只影响价格下方的提示文字,不写入、不清除任何金额;手动输入的金额不显示提示;可以直接撤回这一个合并。 - 要你做什么:无。 ## What changes The ruling item on this card (comment 7118795825, 「保留金额并提示」) and its branch B (comment 7158109013), on both hosts: the line-item grid (`GridFieldWidget`) and the record form (`LookupField` with the declared pairs). Scope is bounded by ADR-0144 D2: new records, records with no saved lines, lines staged in the same edit, and declared pairs on the record's own amounts. Items 1–4 landed in #36918. With this PR the card's last open item is done. - **Point 1: a currency change in the same edit never changes or clears a filled amount.** Measured first. This already holds on `main` (`057cedfa9b6`): nothing writes an amount when the code changes. The new pins were run against main's source files, and every amount assertion passed there; the only failures were the note lines that come after them (see Tests). Pinned either way, on both hosts. This PR adds no write. - **Point 2: an amount a pick copied gets a note once the currencies differ.** `judgePickWrites` now records each amount it copies as `CopiedAutofill` (`target`, `source`, `value`, `under`: the code the target was in at the write). The plan gains the optional `copied`, absent when there is none. Each host keeps these beside the withheld values of the same pick. When drawing, it shows "Unit Price was copied as $100.00, but the record is now in EUR. Enter Unit Price in EUR if it should change." only when all of these hold (`copiedAutofillNow`): the field still holds that pick, the target still holds the copied value, and the code the target is in now is known and differs from `under`. A currency change back ends the note. - **Point 3: a withheld note already shown refreshes to the record's new currency.** `withheldAutofillNow` judges each shown withheld item again with `crossCurrencyRefusal`, using the picked amount's own currency (its `from`) against the target's currency as it is now. The note follows the new code, and its reason too: a code cleared reads "no currency is chosen". - **Point 4: a hand-typed amount gets no note.** Only a pick records a copied amount, and the note needs the target to still hold the copied value. So an amount typed by hand, or typed over a copied one, says nothing. - **Branch B.** When the record's currency turns to the picked amount's own, the re-judgement copies nothing. The item takes the new reason `nowSameCurrency`, the note stays and the cell stays empty: "Unit Price was not filled when it was picked. The record is now in USD: pick again to fill $100.00." A pick again fills it (pinned as the control on the record form). When the target still holds an earlier value (`held`), the sentence says to clear the field, then pick again (`lookup.autofillNowSameCurrencyHeld`, round 3). - "Now" on each host is the same context the pick used, with no picked row. On the grid that is `gridAutofillCurrency` on the current line, with `columnCurrencies` (a header-following line) or `columnFields` (the line's own code). On the record form it is `currencyFor` on the live record, followed parent included. So a code written later in the edit is read exactly as a pick would read it. - i18n: three sentences, `lookup.autofillNowSameCurrency`, `lookup.autofillNowSameCurrencyHeld` and `lookup.autofillCopiedUnder`, in all 11 packs (zh-Hant generated by `gen:zh-hant`) and in `FIELD_DEFAULTS`. - One changeset, `.changeset/36412-currency-change-notes.md`: `@object-ui/fields` and `@object-ui/i18n`, both `patch`. The #36918 changeset is left untouched. `@object-ui/plugin-form` changes in its test file only, which is not published. ## Clause-② rework: route (a), `copied` optional At the seat's rework the first declaration, `Clause-②: no`, did not hold. Route (a) is taken; no route (b), nothing here needs `copied` to be required. `LookupAutofillPlan.copied` is now optional (`copied?: CopiedAutofill[]`). `judgePickWrites` leaves it out when the pick copied no amount under a judged currency, and every in-package reader treats absent as none (`LookupField`'s two `noteWithheld` calls, `GridFieldWidget`'s pick, `planLookupAutofill`'s pass-through). A plan built without `copied` is still a plan, so nothing is narrowed. The published `@object-ui/fields` surface widens: - new exports `withheldAutofillNow`, `copiedAutofillNow`, `copiedAutofillMessage` and the type `CopiedAutofill`; - the optional member `LookupAutofillPlan.copied`; - the `WithheldAutofill.reason` union gains `nowSameCurrency`, so code that switches over every reason gains one case. The same declaration is in the changeset. `Metadata-protocol: none` stands: no spec key, value or metadata type changes. A pin asserts that a plan which copied no amount carries no `copied`. ## Tests Round 3 (the seat's S1, N1, N2 and N4), all under `os-verify-lock`: - Both pin files at `dd0ebf7f96`: Tests 71 passed (71). Two new pins hold the held branch B case on each host (grid: header USD over a line holding 80, then EUR; form: an `overwrite: true` pair over a typed 80 on a EUR quote, then USD). Each asserts the exact clear-then-pick-again sentence and that the earlier value stays. The grid branch B pin now ends with the N4 control: a pick again fills 100 and no note remains. - Ablation: the held arm in `withheldAutofillMessage` is deleted (`ablation-replace --delete`, restored to the HEAD blob `848e5fd1844c`). Tests 2 failed, 9 passed: exactly the two held pins fail. The non-held branch B pins on both hosts stay green, so their wording is unchanged. - The three-package run at `dd0ebf7f96` failed one test, `all-locales-key-parity` "placeholders match en in every pack": the first zh-Hans text of the new key named `{{field}}` three times against en's two, and zh-Hant was generated from it. Fixed in `315c0d8fef`. At that head, `packages/i18n/` gives Test Files 111 passed, Tests 2028 passed, 13 skipped. Only locale strings changed between the two heads; fields and plugin-form were green at `dd0ebf7f96` (685 of 687 files passed, 1 skipped, and the one failure was that i18n test). `type-check` of the three packages exits 0 at `315c0d8fef`. Round 2 (the Clause-② rework), head `a602513471`, all under `os-verify-lock`: the same three-package run gives Test Files 686 passed, 1 skipped (687), and Tests 9840 passed, 21 skipped (9861), `VERDICT command-exit 0`. `type-check` of the three packages exits 0. Ablations of the reworked lines, each restored to the HEAD blob `e96dadd3fbba`: - `copied` always present (`return copiedAmounts.length > 0 ? { ...plan, copied: copiedAmounts } : plan;` becomes `return { ...plan, copied: copiedAmounts };`): Tests 1 failed, 8 passed. The absent-means-none pin fails. - No copied note, re-run on the new head: Tests 3 failed, 6 passed. The copied note fails on both hosts, plus the pure pin. Round 1 readings follow. Tests on head `482148532`, all under `os-verify-lock`: `pnpm --dir ui exec vitest run --maxWorkers=2 packages/fields/ packages/plugin-form/ packages/i18n/` gives Test Files 686 passed, 1 skipped (687), and Tests 9840 passed, 21 skipped (9861), `VERDICT command-exit 0`. `type-check` of `@object-ui/fields`, `@object-ui/plugin-form` and `@object-ui/i18n` exits 0, after the closure build. Both pin files are in the `tsconfig.test.json` program (`--listFiles`: 1 hit each). <details><summary>New pins, the point 1 measurement, and ablations</summary> - `ObjectForm.lookupAutofill-28245.test.tsx`, new describe "a same-edit currency change keeps amounts and says so", 4 tests through `ObjectForm`. (1) A USD quote picks a $100 product. Changed to EUR, it keeps 100 and shows the copied note with its exact text. Control: before the change there is no note, and changing back to USD ends it. (2) A JPY quote's withheld note names GBP and no longer JPY after the code becomes GBP, and the price stays empty. (3) Branch B: a EUR quote's withheld note reads exactly "Unit Price was not filled when it was picked. The record is now in USD: pick again to fill $100.00." once the code becomes USD, and the price stays empty. Control: the pick again fills 100 and no note remains. (4) A typed 55 gets no note through a currency change, and neither does 55 typed over a copied 100. - `GridField.lookupAutofill-28245.test.tsx`, new describe of the same name, 5 tests. The same four cases through `GridField`, with the header currency handed in as `columnCurrencies` and changed by a rerender, for a product priced in EUR. One more is pure: `withheldAutofillNow` follows the currency now, `nowSameCurrency` applies when it matches, and with no currency known the item is returned unchanged; `copiedAutofillNow` names a differing code only while the target holds the copied value. The #36412 declared-pairs pin now also asserts `copied` (the price is recorded under the code the same pick wrote). - **Point 1 measured on main's code.** The five source files were restored to `057cedfa9b6` in the tree only, the `-t ruling` pins were run, and the files were restored with `git checkout HEAD` (`git diff HEAD` empty afterwards). Result: 7 failed, 2 passed. The two hand-typed pins passed. Both copied-amount pins failed on the note line after their amount assertion (ObjectForm line 745, GridField line 641): the amount kept its value through the currency change on main. The refresh and branch B pins failed on their note text, and the pure pin failed on the missing export. Point 1 has no implementing line to ablate: nothing writes an amount on a currency change, before or after this PR. - Ablations on the committed tree with `scripts/ablation-replace.mjs` (`lookupAutofill.ts`; vitest aliases `@object-ui/*` to `src`, so no `dist` sits between mutation and run), `-t ruling`, each restored to the HEAD blob `18535d11faef`: - ` if (!now) return item;` becomes ` return item;` (no refresh): Tests 5 failed, 4 passed. Refresh and branch B on both hosts, plus the pure pin. - ` return to && to !== item.under ? to : undefined;` becomes ` return undefined;` (no copied note): Tests 3 failed, 6 passed. Copied note on both hosts, plus the pure pin. - ` if (!sameValue(current, item.value) || !now) return undefined;` becomes ` if (!now) return undefined;` (a typed-over amount keeps the note): Tests 3 failed, 6 passed. Hand-typed on both hosts, plus the pure pin. </details> ## Acceptance notes - Clause-②: `yes (widening)` (see the rework section above). The diff touches no `packages/spec/**` and no metadata. `git grep` finds `LookupAutofillPlan` only inside `ui/packages/fields`. - Branch B over a filled target (round 3, the seat's S1): a withheld value that carries `held` (a pick over a target that still holds an earlier value) now gets its own branch B sentence, `lookup.autofillNowSameCurrencyHeld`: "Unit Price was not filled when it was picked and still holds its earlier value. The record is now in USD: clear Unit Price, then pick again to fill $100.00." For a declared pair without `overwrite`, picking the same record again does not replace a value that record did not fill (the spec's overwrite rule), so the sentence says to clear the field first. Re-pick behaviour is unchanged. - A copied amount whose record's currency becomes unset or unreadable gets no note (no current code to name). Only a known, different code is named, as the ruling's example reads. - N9 (record-page editor re-renders): not measured. The new work per render is one re-judgement per shown note, and nothing runs when no pick left a note. ## Verification <details><summary>Gates</summary> - Round 3: `dispatch-gates --commands` derived the same 41 at `315c0d8fef`. All 41 ran with exit 0, including the ui `scripts/` family (172 files passed, 2 skipped; 5130 tests passed). `--ran`: 41 derived, 41 run, 0 NOT-MEASURED, 0 UNRUN. ui `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys` and `check:new-line-citations` exit 0 (run at `dd0ebf7f96`; the later commit changes two locale strings, and key parity is pinned by the i18n suite above). Size: 19 files, +582/-38 (620 changed lines); with #36918's 714 the card totals 1,334, under 3,000. - Round 2: `dispatch-gates --commands` derived the same 41 at `a602513471`. All 41 ran with exit 0, including the ui `scripts/` family (172 files passed, 2 skipped; 5130 tests passed). `--ran`: 41 derived, 41 run, 0 NOT-MEASURED, 0 UNRUN. - Round 1: `dispatch-gates --commands` (no paths, change set from the merge base) derived 41 commands at `482148532`. All 41 ran with exit 0. `pnpm --dir ui exec vitest run scripts/` ran under the lock with `--maxWorkers=2`: Test Files 172 passed, 2 skipped, and Tests 5130 passed, 2 skipped. `dispatch-gates --ran` with exit codes recorded: 41 derived, 41 run, 0 NOT-MEASURED, 0 UNRUN, exit 0. - ui `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys` and `check:new-line-citations`: exit 0, with 0 new citations. - `overlap-check` before each push: VERDICT clean, exit 0. Re-read after `git fetch` against `origin/main` `622f3985fe` and 5 PR heads that share files (#37282, #37249, #37226, #37210, #37166): clean. `--pr=37264` named explicitly: merges cleanly. </details> Read first, by risk: (1) `judgeCopy`, `withheldAutofillNow` and `copiedAutofillNow` in `lookupAutofill.ts`; (2) the note block at the end of `LookupField.tsx` (`pickStands`, `currencyNow`); (3) the per-row note block in `GridFieldWidget.tsx` (`lineCurrencyNow`). Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx -t ruling` passes 4 tests. In them, a USD quote picks a $100 product, changes its currency to EUR, keeps 100, and shows "Unit Price was copied as $100.00, but the record is now in EUR." https://claude.ai/code/session_01QSeKYnagJvGbCtNg2PhvgW 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYnagJvGbCtNg2PhvgW)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 6361b99 commit e377918

19 files changed

Lines changed: 582 additions & 38 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@object-ui/fields': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
fix(fields): after a currency change in the same edit, a lookup pick's amounts stay as they are and the notes beside them follow the new currency
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
Follows the cross-currency pick rule (a pick copies an amount only into a field in the same currency). Changing the record's currency in the same edit (a new record, one with no saved lines, lines staged in this edit) still changes and clears no amount. Now the notes say what that means, in the line-item grid and in the record form. Nothing is converted, and no metadata changes.
12+
13+
- **An amount a pick copied gets a note once the currency changes.** If a pick copied a price while the record was in one currency and the record is now in another, a note under the field says so: "Unit Price was copied as $100.00, but the record is now in EUR. Enter Unit Price in EUR if it should change." The note goes away when the currency changes back or someone edits the amount. An amount typed by hand gets no note.
14+
- **A note about a price that was not copied follows the new currency.** The "was not filled" note is judged again against the record's currency as it is now, so it names the new currency, not the one at the pick.
15+
- **When the record changes to the picked price's own currency, the note stays and the field stays empty.** It now says "Unit Price was not filled when it was picked. The record is now in USD: pick again to fill $100.00." A currency change never fills a field by itself. If the field still holds an earlier value (a pick over a filled field), the note says to clear it first, because picking the same record again does not replace a value that record did not fill: "Unit Price was not filled when it was picked and still holds its earlier value. The record is now in USD: clear Unit Price, then pick again to fill $100.00."
16+
17+
Also in `@object-ui/fields`, a widening of its published surface, with nothing removed or made required: new exports `withheldAutofillNow`, `copiedAutofillNow`, `copiedAutofillMessage` and the type `CopiedAutofill`. `LookupAutofillPlan` gains the optional `copied`, the amounts a pick wrote and the currency each was written in; it is absent when there are none, so a plan built without it is still a valid plan. The `WithheldAutofill.reason` union widens with `nowSameCurrency`: code that switches over every reason gains one case to say. In `@object-ui/i18n`: three new `lookup.*` sentences, `autofillNowSameCurrency`, `autofillNowSameCurrencyHeld` and `autofillCopiedUnder`, in every locale pack.

‎ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ import {
3535
lookupAutofillByField,
3636
pickedAmountCurrencyOf,
3737
planDeclaredLookupAutofill,
38+
copiedAutofillNow,
39+
withheldAutofillNow,
3840
} from './lookupAutofill';
3941

4042
afterEach(cleanup);
@@ -456,6 +458,8 @@ describe('cross-currency pick follow-ups: a re-pick over a filled cell, and a co
456458
expect(planDeclaredLookupAutofill(both, product, {}, null, context({}))).toEqual({
457459
patch: { currency_code: 'EUR', unit_price: 100 },
458460
withheld: [],
461+
// objectstack#36412: the price is recorded as copied under the code the same pick wrote.
462+
copied: [{ target: 'unit_price', source: 'unit_price', value: 100, under: 'EUR' }],
459463
});
460464
// Control: a code the record already holds is kept (no `overwrite`), and
461465
// the price is judged in it.
@@ -572,3 +576,149 @@ describe('cross-currency pick follow-ups: a re-pick over a filled cell, and a co
572576
});
573577
});
574578
});
579+
580+
describe('a same-edit currency change keeps a line’s amounts and says so (objectstack#36412, ruling 「保留金额并提示」)', () => {
581+
// A product priced in its own code (EUR); a line whose price follows its
582+
// header's currency, which the host hands over per column.
583+
const recordPrice = { type: 'currency', currencyConfig: { currencyMode: 'record' as const, currencyField: 'currency_code' } };
584+
const ROWS = [{ id: 'p1', name: 'Euro widget', description: 'Euro widget', currency_code: 'EUR', unit_price: 100 }];
585+
const ds = {
586+
getObjectSchema: vi.fn(async () => ({
587+
name: 'product',
588+
fields: { name: { type: 'text' }, description: { type: 'text' }, currency_code: { type: 'text' }, unit_price: { ...recordPrice, label: 'Unit Price' } },
589+
})),
590+
find: vi.fn(async () => ({ data: ROWS.map((r) => ({ ...r })), total: ROWS.length })),
591+
findOne: vi.fn(async (_o: string, id: string) => {
592+
const row = ROWS.find((r) => r.id === id);
593+
return row ? { ...row } : null;
594+
}),
595+
};
596+
const drawn = [
597+
{ name: 'product', type: 'lookup' as const, reference: 'product' },
598+
{ name: 'description', type: 'text' as const },
599+
{ name: 'unit_price', type: 'currency' as const, label: 'Unit Price' },
600+
];
601+
function Line({ header, line }: { header: string; line?: Record<string, unknown> }) {
602+
const [rows, setRows] = React.useState<Record<string, unknown>[]>([{ product: null, description: null, unit_price: null, ...line }]);
603+
return (
604+
<LocalizationProvider value={{ currency: 'USD' }}>
605+
<SchemaRendererContext.Provider value={{ dataSource: ds } as never}>
606+
<GridField value={rows} onChange={(next: Record<string, unknown>[]) => setRows(next)} field={{ columns: drawn } as never} columnCurrencies={{ unit_price: header }} />
607+
<output data-testid="rows">{JSON.stringify(rows)}</output>
608+
</SchemaRendererContext.Provider>
609+
</LocalizationProvider>
610+
);
611+
}
612+
const rowsNow = () => JSON.parse(screen.getByTestId('rows').textContent || '[]');
613+
async function pickProduct(): Promise<void> {
614+
await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled());
615+
await act(async () => { await new Promise((r) => setTimeout(r, 0)); });
616+
await act(async () => {
617+
fireEvent.click(screen.getAllByTestId('lookup-trigger')[0]);
618+
});
619+
const option = await waitFor(() => {
620+
const el = screen.getAllByRole('option').find((o) => (o.getAttribute('title') ?? o.textContent ?? '').includes('Euro widget'));
621+
if (!el) throw new Error('Euro widget not offered');
622+
return el;
623+
}, { timeout: 3000 });
624+
await act(async () => {
625+
fireEvent.click(option);
626+
});
627+
await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Euro widget' }));
628+
}
629+
const copiedNote = () => screen.queryByTestId('line-items-autofill-copied-0');
630+
const withheldNote = () => screen.queryByTestId('line-items-autofill-withheld-0');
631+
632+
it('a copied amount stays through a header currency change, and a note names the code it was copied under', async () => {
633+
const view = render(<Line header="EUR" />);
634+
await pickProduct();
635+
expect(rowsNow()[0].unit_price).toBe(100);
636+
// Control: copied in the line's own currency, nothing to say.
637+
expect(copiedNote()).toBeNull();
638+
639+
view.rerender(<Line header="USD" />);
640+
expect(rowsNow()[0].unit_price).toBe(100);
641+
expect(copiedNote()?.textContent).toBe('Unit Price was copied as €100.00, but the record is now in USD. Enter Unit Price in USD if it should change.');
642+
643+
// Control: back in the currency it was copied under, the note ends.
644+
view.rerender(<Line header="EUR" />);
645+
expect(copiedNote()).toBeNull();
646+
expect(rowsNow()[0].unit_price).toBe(100);
647+
});
648+
649+
it('a withheld note refreshes to the header’s new currency, and the cell stays empty', async () => {
650+
const view = render(<Line header="JPY" />);
651+
await pickProduct();
652+
expect(withheldNote()?.textContent).toContain('here is in JPY');
653+
654+
view.rerender(<Line header="GBP" />);
655+
expect(withheldNote()?.textContent).toContain('here is in GBP');
656+
expect(withheldNote()?.textContent).not.toContain('JPY');
657+
expect(rowsNow()[0].unit_price).toBeNull();
658+
});
659+
660+
it('branch B: the header turns to the picked amount’s own currency, the note stays and says so, and the cell stays empty', async () => {
661+
const view = render(<Line header="USD" />);
662+
await pickProduct();
663+
expect(withheldNote()?.textContent).toContain('here is in USD');
664+
665+
view.rerender(<Line header="EUR" />);
666+
expect(withheldNote()?.textContent).toBe('Unit Price was not filled when it was picked. The record is now in EUR: pick again to fill €100.00.');
667+
expect(rowsNow()[0].unit_price).toBeNull();
668+
expect(copiedNote()).toBeNull();
669+
670+
// Control: the pick again the note offers fills it, and nothing is left to say.
671+
await pickProduct();
672+
await waitFor(() => expect(rowsNow()[0].unit_price).toBe(100));
673+
expect(withheldNote()).toBeNull();
674+
expect(copiedNote()).toBeNull();
675+
});
676+
677+
it('branch B over a cell that still holds an earlier value: the note says to clear it, then pick again', async () => {
678+
const view = render(<Line header="USD" line={{ unit_price: 80 }} />);
679+
await pickProduct();
680+
expect(withheldNote()?.textContent).toContain('Unit Price still holds its earlier value.');
681+
682+
view.rerender(<Line header="EUR" />);
683+
expect(withheldNote()?.textContent).toBe(
684+
'Unit Price was not filled when it was picked and still holds its earlier value. The record is now in EUR: clear Unit Price, then pick again to fill €100.00.',
685+
);
686+
expect(rowsNow()[0].unit_price).toBe(80);
687+
});
688+
689+
it('a hand-typed amount gets no note through a currency change, nor one typed over a copied amount', async () => {
690+
const view = render(<Line header="EUR" />);
691+
fireEvent.change(screen.getAllByLabelText('Unit Price')[0], { target: { value: '70' } });
692+
await waitFor(() => expect(rowsNow()[0].unit_price).toBe(70));
693+
view.rerender(<Line header="USD" />);
694+
expect(rowsNow()[0].unit_price).toBe(70);
695+
expect(copiedNote()).toBeNull();
696+
expect(withheldNote()).toBeNull();
697+
698+
cleanup();
699+
700+
const over = render(<Line header="EUR" />);
701+
await pickProduct();
702+
expect(rowsNow()[0].unit_price).toBe(100);
703+
fireEvent.change(screen.getAllByLabelText('Unit Price')[0], { target: { value: '9000' } });
704+
await waitFor(() => expect(rowsNow()[0].unit_price).toBe(9000));
705+
over.rerender(<Line header="USD" />);
706+
expect(rowsNow()[0].unit_price).toBe(9000);
707+
expect(copiedNote()).toBeNull();
708+
});
709+
710+
it('the pure judgement: a withheld item follows the currency now, and a copied one is named only while its target holds it', () => {
711+
const item = { target: 'unit_price', source: 'unit_price', amount: 100, reason: 'differs' as const, from: 'EUR', to: 'JPY' };
712+
expect(withheldAutofillNow(item, { kind: 'code', code: 'GBP' }, 'USD')).toEqual({ ...item, to: 'GBP' });
713+
expect(withheldAutofillNow(item, { kind: 'code', code: 'EUR' }, 'USD')).toEqual({ ...item, reason: 'nowSameCurrency', to: 'EUR' });
714+
// Control: a currency not known now leaves the note as it was judged.
715+
expect(withheldAutofillNow(item, undefined, 'USD')).toBe(item);
716+
const copied = { target: 'unit_price', source: 'unit_price', value: 100, under: 'EUR' };
717+
expect(copiedAutofillNow(copied, 100, { kind: 'home' }, 'USD')).toBe('USD');
718+
expect(copiedAutofillNow(copied, 100, { kind: 'code', code: 'EUR' }, 'USD')).toBeUndefined();
719+
expect(copiedAutofillNow(copied, 90, { kind: 'home' }, 'USD')).toBeUndefined();
720+
// A plan that wrote no amount under a judged currency carries no `copied`: absent means none.
721+
expect(planDeclaredLookupAutofill(pairs, widget, {}, null)).not.toHaveProperty('copied');
722+
expect(planLookupAutofill(cols, cols[0], widget, { pairs, row: {} })).not.toHaveProperty('copied');
723+
});
724+
});

‎ui/packages/fields/src/widgets/GridField.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ export function planLookupAutofill(
243243
}
244244
writes.push(...declaredPickWrites(declared?.pairs, record, declared?.row, declared?.previous));
245245
const plan = judgePickWrites(writes, currency);
246-
return { patch: { [col.name]: record?.value ?? record?.id ?? record?._id, ...plan.patch }, withheld: plan.withheld };
246+
return { patch: { [col.name]: record?.value ?? record?.id ?? record?._id, ...plan.patch }, withheld: plan.withheld, ...(plan.copied ? { copied: plan.copied } : {}) };
247247
}
248248

249249
/** {@link planLookupAutofill}'s writes alone. */

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

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,12 @@ import {
4343
planDeclaredLookupAutofill,
4444
readLookupAutofillTargets,
4545
withheldAutofillMessage,
46+
withheldAutofillNow,
4647
withheldStillStands,
48+
copiedAutofillMessage,
49+
copiedAutofillNow,
4750
type AutofillCurrencyContext,
51+
type CopiedAutofill,
4852
type LookupAutofillPair,
4953
type WithheldAutofill,
5054
} from './lookupAutofill.js';
@@ -1310,10 +1314,18 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
13101314
},
13111315
[currencyTargets, refObjectSchema, homeCurrency, editedRecordForCurrency, followedParentUnread],
13121316
);
1313-
/** What the last fill left empty, for the record it picked; said under the field. */
1314-
const [withheldFill, setWithheldFill] = useState<{ picked: string; items: readonly WithheldAutofill[] } | null>(null);
1315-
const noteWithheld = useCallback((picked: unknown, items: readonly WithheldAutofill[]) => {
1316-
setWithheldFill(items.length > 0 && picked != null ? { picked: String(picked), items } : null);
1317+
/**
1318+
* What the last fill left unwritten and the amounts it copied (with the
1319+
* code each was copied under), for the record it picked; said under the
1320+
* field, judged against the record's currency as it is now.
1321+
*/
1322+
const [withheldFill, setWithheldFill] = useState<{
1323+
picked: string;
1324+
items: readonly WithheldAutofill[];
1325+
copied: readonly CopiedAutofill[];
1326+
} | null>(null);
1327+
const noteWithheld = useCallback((picked: unknown, items: readonly WithheldAutofill[], copied: readonly CopiedAutofill[]) => {
1328+
setWithheldFill(items.length + copied.length > 0 && picked != null ? { picked: String(picked), items, copied } : null);
13171329
}, []);
13181330

13191331
/**
@@ -1332,8 +1344,8 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
13321344
heldId == null || heldId === ''
13331345
? null
13341346
: pickedRecords.find((r) => String(recordValue(r, idField)) === String(heldId)) ?? null;
1335-
const { patch, withheld } = planDeclaredLookupAutofill(autofillPairs, row, resolvedDependentValues, previous, currencyFor(row));
1336-
noteWithheld(recordValue(row, idField), withheld);
1347+
const { patch, withheld, copied } = planDeclaredLookupAutofill(autofillPairs, row, resolvedDependentValues, previous, currencyFor(row));
1348+
noteWithheld(recordValue(row, idField), withheld, copied ?? []);
13371349
if (Object.keys(patch).length > 0) onAutofill(patch);
13381350
},
13391351
[autofillPairs, onAutofill, normalizeId, value, pickedRecords, idField, resolvedDependentValues, currencyFor, noteWithheld],
@@ -1378,14 +1390,14 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
13781390
if (autofillCurrency && (!refSchemaSettled || followedParentPending)) return;
13791391
openingFilledRef.current = key;
13801392
setPickedRecords((prev) => mergeRowsByValue(prev, [row], idField));
1381-
const { patch, withheld } = planDeclaredLookupAutofill(
1393+
const { patch, withheld, copied } = planDeclaredLookupAutofill(
13821394
autofillPairs.map(({ target, source }) => ({ target, source })),
13831395
row,
13841396
resolvedDependentValues,
13851397
null,
13861398
currencyFor(row),
13871399
);
1388-
noteWithheld(key, withheld);
1400+
noteWithheld(key, withheld, copied ?? []);
13891401
if (Object.keys(patch).length > 0) onAutofill(patch, { opening: true });
13901402
}, [autofillPairs, onAutofill, openingValue, value, normalizeId, hydratedRecords, idField, resolvedDependentValues, autofillCurrency, refSchemaSettled, followedParentPending, currencyFor, noteWithheld]);
13911403

@@ -2457,12 +2469,25 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
24572469
// objectstack#36249 — what the last fill did not copy because the picked
24582470
// amount is in another currency, while the field still holds that pick and
24592471
// the target still holds what it held at the pick (empty, or the earlier
2460-
// value a re-pick left in place).
2472+
// value a re-pick left in place). objectstack#36412 (ruling 「保留金额并提示」)
2473+
// — each note is judged against the record's currency now, so a currency
2474+
// change in the same edit refreshes it; an amount the pick copied, still
2475+
// held, is named with the code it was copied under once the record's
2476+
// differs. A currency change writes no amount.
24612477
const heldNow = normalizeId(value);
2462-
const withheldShown =
2463-
withheldFill && heldNow != null && String(heldNow) === withheldFill.picked
2464-
? withheldFill.items.filter((w) => withheldStillStands(w, resolvedDependentValues?.[w.target]))
2465-
: [];
2478+
const pickStands = !!withheldFill && heldNow != null && String(heldNow) === withheldFill.picked;
2479+
const currencyNow = currencyFor({});
2480+
const withheldShown = pickStands
2481+
? withheldFill.items
2482+
.filter((w) => withheldStillStands(w, resolvedDependentValues?.[w.target]))
2483+
.map((w) => withheldAutofillNow(w, currencyNow?.targetCurrency(w.target), homeCurrency))
2484+
: [];
2485+
const copiedShown = pickStands
2486+
? withheldFill.copied.flatMap((c) => {
2487+
const now = copiedAutofillNow(c, resolvedDependentValues?.[c.target], currencyNow?.targetCurrency(c.target), homeCurrency);
2488+
return now ? [{ item: c, now }] : [];
2489+
})
2490+
: [];
24662491
const withheldLabel = (target: string): string => {
24672492
const label = (autofillTargets?.[target] as { label?: unknown } | undefined)?.label;
24682493
return typeof label === 'string' && label !== '' ? label : target;
@@ -2665,6 +2690,15 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
26652690
))}
26662691
</div>
26672692
)}
2693+
{copiedShown.length > 0 && (
2694+
<div className="text-xs text-muted-foreground" role="status" data-testid="lookup-autofill-copied">
2695+
{copiedShown.map(({ item, now }) => (
2696+
<p key={item.target} data-copied-target={item.target}>
2697+
{copiedAutofillMessage(item, now, withheldLabel(item.target), t, displayLocale)}
2698+
</p>
2699+
))}
2700+
</div>
2701+
)}
26682702

26692703
{recordPickerDialog}
26702704
</div>

0 commit comments

Comments
 (0)