diff --git a/.changeset/36412-currency-change-notes.md b/.changeset/36412-currency-change-notes.md new file mode 100644 index 00000000000..b6823aa8658 --- /dev/null +++ b/.changeset/36412-currency-change-notes.md @@ -0,0 +1,17 @@ +--- +'@object-ui/fields': patch +'@object-ui/i18n': patch +--- + +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 + +Clause-②: yes (widening) +Metadata-protocol: none + +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. + +- **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. +- **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. +- **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." + +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. diff --git a/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx b/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx index 3afe0e93d1b..71233701ac5 100644 --- a/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx @@ -35,6 +35,8 @@ import { lookupAutofillByField, pickedAmountCurrencyOf, planDeclaredLookupAutofill, + copiedAutofillNow, + withheldAutofillNow, } from './lookupAutofill'; afterEach(cleanup); @@ -456,6 +458,8 @@ describe('cross-currency pick follow-ups: a re-pick over a filled cell, and a co expect(planDeclaredLookupAutofill(both, product, {}, null, context({}))).toEqual({ patch: { currency_code: 'EUR', unit_price: 100 }, withheld: [], + // objectstack#36412: the price is recorded as copied under the code the same pick wrote. + copied: [{ target: 'unit_price', source: 'unit_price', value: 100, under: 'EUR' }], }); // Control: a code the record already holds is kept (no `overwrite`), and // 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 }); }); }); + +describe('a same-edit currency change keeps a line’s amounts and says so (objectstack#36412, ruling 「保留金额并提示」)', () => { + // A product priced in its own code (EUR); a line whose price follows its + // header's currency, which the host hands over per column. + const recordPrice = { type: 'currency', currencyConfig: { currencyMode: 'record' as const, currencyField: 'currency_code' } }; + const ROWS = [{ id: 'p1', name: 'Euro widget', description: 'Euro widget', currency_code: 'EUR', unit_price: 100 }]; + const ds = { + getObjectSchema: vi.fn(async () => ({ + name: 'product', + fields: { name: { type: 'text' }, description: { type: 'text' }, currency_code: { type: 'text' }, unit_price: { ...recordPrice, label: 'Unit Price' } }, + })), + find: vi.fn(async () => ({ data: ROWS.map((r) => ({ ...r })), total: ROWS.length })), + findOne: vi.fn(async (_o: string, id: string) => { + const row = ROWS.find((r) => r.id === id); + return row ? { ...row } : null; + }), + }; + const drawn = [ + { name: 'product', type: 'lookup' as const, reference: 'product' }, + { name: 'description', type: 'text' as const }, + { name: 'unit_price', type: 'currency' as const, label: 'Unit Price' }, + ]; + function Line({ header, line }: { header: string; line?: Record }) { + const [rows, setRows] = React.useState[]>([{ product: null, description: null, unit_price: null, ...line }]); + return ( + + + []) => setRows(next)} field={{ columns: drawn } as never} columnCurrencies={{ unit_price: header }} /> + {JSON.stringify(rows)} + + + ); + } + const rowsNow = () => JSON.parse(screen.getByTestId('rows').textContent || '[]'); + async function pickProduct(): Promise { + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalled()); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + await act(async () => { + fireEvent.click(screen.getAllByTestId('lookup-trigger')[0]); + }); + const option = await waitFor(() => { + const el = screen.getAllByRole('option').find((o) => (o.getAttribute('title') ?? o.textContent ?? '').includes('Euro widget')); + if (!el) throw new Error('Euro widget not offered'); + return el; + }, { timeout: 3000 }); + await act(async () => { + fireEvent.click(option); + }); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Euro widget' })); + } + const copiedNote = () => screen.queryByTestId('line-items-autofill-copied-0'); + const withheldNote = () => screen.queryByTestId('line-items-autofill-withheld-0'); + + it('a copied amount stays through a header currency change, and a note names the code it was copied under', async () => { + const view = render(); + await pickProduct(); + expect(rowsNow()[0].unit_price).toBe(100); + // Control: copied in the line's own currency, nothing to say. + expect(copiedNote()).toBeNull(); + + view.rerender(); + expect(rowsNow()[0].unit_price).toBe(100); + 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.'); + + // Control: back in the currency it was copied under, the note ends. + view.rerender(); + expect(copiedNote()).toBeNull(); + expect(rowsNow()[0].unit_price).toBe(100); + }); + + it('a withheld note refreshes to the header’s new currency, and the cell stays empty', async () => { + const view = render(); + await pickProduct(); + expect(withheldNote()?.textContent).toContain('here is in JPY'); + + view.rerender(); + expect(withheldNote()?.textContent).toContain('here is in GBP'); + expect(withheldNote()?.textContent).not.toContain('JPY'); + expect(rowsNow()[0].unit_price).toBeNull(); + }); + + 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 () => { + const view = render(); + await pickProduct(); + expect(withheldNote()?.textContent).toContain('here is in USD'); + + view.rerender(); + 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.'); + expect(rowsNow()[0].unit_price).toBeNull(); + expect(copiedNote()).toBeNull(); + + // Control: the pick again the note offers fills it, and nothing is left to say. + await pickProduct(); + await waitFor(() => expect(rowsNow()[0].unit_price).toBe(100)); + expect(withheldNote()).toBeNull(); + expect(copiedNote()).toBeNull(); + }); + + it('branch B over a cell that still holds an earlier value: the note says to clear it, then pick again', async () => { + const view = render(); + await pickProduct(); + expect(withheldNote()?.textContent).toContain('Unit Price still holds its earlier value.'); + + view.rerender(); + expect(withheldNote()?.textContent).toBe( + '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.', + ); + expect(rowsNow()[0].unit_price).toBe(80); + }); + + it('a hand-typed amount gets no note through a currency change, nor one typed over a copied amount', async () => { + const view = render(); + fireEvent.change(screen.getAllByLabelText('Unit Price')[0], { target: { value: '70' } }); + await waitFor(() => expect(rowsNow()[0].unit_price).toBe(70)); + view.rerender(); + expect(rowsNow()[0].unit_price).toBe(70); + expect(copiedNote()).toBeNull(); + expect(withheldNote()).toBeNull(); + + cleanup(); + + const over = render(); + await pickProduct(); + expect(rowsNow()[0].unit_price).toBe(100); + fireEvent.change(screen.getAllByLabelText('Unit Price')[0], { target: { value: '9000' } }); + await waitFor(() => expect(rowsNow()[0].unit_price).toBe(9000)); + over.rerender(); + expect(rowsNow()[0].unit_price).toBe(9000); + expect(copiedNote()).toBeNull(); + }); + + it('the pure judgement: a withheld item follows the currency now, and a copied one is named only while its target holds it', () => { + const item = { target: 'unit_price', source: 'unit_price', amount: 100, reason: 'differs' as const, from: 'EUR', to: 'JPY' }; + expect(withheldAutofillNow(item, { kind: 'code', code: 'GBP' }, 'USD')).toEqual({ ...item, to: 'GBP' }); + expect(withheldAutofillNow(item, { kind: 'code', code: 'EUR' }, 'USD')).toEqual({ ...item, reason: 'nowSameCurrency', to: 'EUR' }); + // Control: a currency not known now leaves the note as it was judged. + expect(withheldAutofillNow(item, undefined, 'USD')).toBe(item); + const copied = { target: 'unit_price', source: 'unit_price', value: 100, under: 'EUR' }; + expect(copiedAutofillNow(copied, 100, { kind: 'home' }, 'USD')).toBe('USD'); + expect(copiedAutofillNow(copied, 100, { kind: 'code', code: 'EUR' }, 'USD')).toBeUndefined(); + expect(copiedAutofillNow(copied, 90, { kind: 'home' }, 'USD')).toBeUndefined(); + // A plan that wrote no amount under a judged currency carries no `copied`: absent means none. + expect(planDeclaredLookupAutofill(pairs, widget, {}, null)).not.toHaveProperty('copied'); + expect(planLookupAutofill(cols, cols[0], widget, { pairs, row: {} })).not.toHaveProperty('copied'); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.ts b/ui/packages/fields/src/widgets/GridField.ts index 0f66848d5bd..d35f143a0ab 100644 --- a/ui/packages/fields/src/widgets/GridField.ts +++ b/ui/packages/fields/src/widgets/GridField.ts @@ -243,7 +243,7 @@ export function planLookupAutofill( } writes.push(...declaredPickWrites(declared?.pairs, record, declared?.row, declared?.previous)); const plan = judgePickWrites(writes, currency); - return { patch: { [col.name]: record?.value ?? record?.id ?? record?._id, ...plan.patch }, withheld: plan.withheld }; + return { patch: { [col.name]: record?.value ?? record?.id ?? record?._id, ...plan.patch }, withheld: plan.withheld, ...(plan.copied ? { copied: plan.copied } : {}) }; } /** {@link planLookupAutofill}'s writes alone. */ diff --git a/ui/packages/fields/src/widgets/LookupField.tsx b/ui/packages/fields/src/widgets/LookupField.tsx index 01485cad8d7..ea4796a3554 100644 --- a/ui/packages/fields/src/widgets/LookupField.tsx +++ b/ui/packages/fields/src/widgets/LookupField.tsx @@ -43,8 +43,12 @@ import { planDeclaredLookupAutofill, readLookupAutofillTargets, withheldAutofillMessage, + withheldAutofillNow, withheldStillStands, + copiedAutofillMessage, + copiedAutofillNow, type AutofillCurrencyContext, + type CopiedAutofill, type LookupAutofillPair, type WithheldAutofill, } from './lookupAutofill.js'; @@ -1310,10 +1314,18 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro }, [currencyTargets, refObjectSchema, homeCurrency, editedRecordForCurrency, followedParentUnread], ); - /** What the last fill left empty, for the record it picked; said under the field. */ - const [withheldFill, setWithheldFill] = useState<{ picked: string; items: readonly WithheldAutofill[] } | null>(null); - const noteWithheld = useCallback((picked: unknown, items: readonly WithheldAutofill[]) => { - setWithheldFill(items.length > 0 && picked != null ? { picked: String(picked), items } : null); + /** + * What the last fill left unwritten and the amounts it copied (with the + * code each was copied under), for the record it picked; said under the + * field, judged against the record's currency as it is now. + */ + const [withheldFill, setWithheldFill] = useState<{ + picked: string; + items: readonly WithheldAutofill[]; + copied: readonly CopiedAutofill[]; + } | null>(null); + const noteWithheld = useCallback((picked: unknown, items: readonly WithheldAutofill[], copied: readonly CopiedAutofill[]) => { + setWithheldFill(items.length + copied.length > 0 && picked != null ? { picked: String(picked), items, copied } : null); }, []); /** @@ -1332,8 +1344,8 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro heldId == null || heldId === '' ? null : pickedRecords.find((r) => String(recordValue(r, idField)) === String(heldId)) ?? null; - const { patch, withheld } = planDeclaredLookupAutofill(autofillPairs, row, resolvedDependentValues, previous, currencyFor(row)); - noteWithheld(recordValue(row, idField), withheld); + const { patch, withheld, copied } = planDeclaredLookupAutofill(autofillPairs, row, resolvedDependentValues, previous, currencyFor(row)); + noteWithheld(recordValue(row, idField), withheld, copied ?? []); if (Object.keys(patch).length > 0) onAutofill(patch); }, [autofillPairs, onAutofill, normalizeId, value, pickedRecords, idField, resolvedDependentValues, currencyFor, noteWithheld], @@ -1378,14 +1390,14 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro if (autofillCurrency && (!refSchemaSettled || followedParentPending)) return; openingFilledRef.current = key; setPickedRecords((prev) => mergeRowsByValue(prev, [row], idField)); - const { patch, withheld } = planDeclaredLookupAutofill( + const { patch, withheld, copied } = planDeclaredLookupAutofill( autofillPairs.map(({ target, source }) => ({ target, source })), row, resolvedDependentValues, null, currencyFor(row), ); - noteWithheld(key, withheld); + noteWithheld(key, withheld, copied ?? []); if (Object.keys(patch).length > 0) onAutofill(patch, { opening: true }); }, [autofillPairs, onAutofill, openingValue, value, normalizeId, hydratedRecords, idField, resolvedDependentValues, autofillCurrency, refSchemaSettled, followedParentPending, currencyFor, noteWithheld]); @@ -2457,12 +2469,25 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro // objectstack#36249 — what the last fill did not copy because the picked // amount is in another currency, while the field still holds that pick and // the target still holds what it held at the pick (empty, or the earlier - // value a re-pick left in place). + // value a re-pick left in place). objectstack#36412 (ruling 「保留金额并提示」) + // — each note is judged against the record's currency now, so a currency + // change in the same edit refreshes it; an amount the pick copied, still + // held, is named with the code it was copied under once the record's + // differs. A currency change writes no amount. const heldNow = normalizeId(value); - const withheldShown = - withheldFill && heldNow != null && String(heldNow) === withheldFill.picked - ? withheldFill.items.filter((w) => withheldStillStands(w, resolvedDependentValues?.[w.target])) - : []; + const pickStands = !!withheldFill && heldNow != null && String(heldNow) === withheldFill.picked; + const currencyNow = currencyFor({}); + const withheldShown = pickStands + ? withheldFill.items + .filter((w) => withheldStillStands(w, resolvedDependentValues?.[w.target])) + .map((w) => withheldAutofillNow(w, currencyNow?.targetCurrency(w.target), homeCurrency)) + : []; + const copiedShown = pickStands + ? withheldFill.copied.flatMap((c) => { + const now = copiedAutofillNow(c, resolvedDependentValues?.[c.target], currencyNow?.targetCurrency(c.target), homeCurrency); + return now ? [{ item: c, now }] : []; + }) + : []; const withheldLabel = (target: string): string => { const label = (autofillTargets?.[target] as { label?: unknown } | undefined)?.label; return typeof label === 'string' && label !== '' ? label : target; @@ -2665,6 +2690,15 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro ))} )} + {copiedShown.length > 0 && ( +
+ {copiedShown.map(({ item, now }) => ( +

+ {copiedAutofillMessage(item, now, withheldLabel(item.target), t, displayLocale)} +

+ ))} +
+ )} {recordPickerDialog} diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index 424153bd951..7f8aa2b031d 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -24,9 +24,13 @@ import { pickedAmountCurrencyOf, type AmountCurrency, type AutofillCurrencyContext, + type CopiedAutofill, type LookupAutofillByField, type WithheldAutofill, + copiedAutofillMessage, + copiedAutofillNow, withheldAutofillMessage, + withheldAutofillNow, withheldStillStands, } from '../lookupAutofill.js'; import { FileCell } from '../FileField.js'; @@ -518,12 +522,15 @@ function gridAutofillCurrency( * column picked, the value it committed, and each withheld value. The note * stands while the line still holds that pick and the withheld cell still * holds what it held at the pick (`withheldStillStands`): empty, or the - * earlier value a re-pick left in place. + * earlier value a re-pick left in place. `copied` is each amount the pick + * wrote, with the code it was written under (objectstack#36412): both are + * judged against the line's currency as it is when drawn. */ interface WithheldPick { lookup: string; picked: unknown; items: readonly WithheldAutofill[]; + copied: readonly CopiedAutofill[]; } export type GridFieldWidgetProps = FieldWidgetComponentProps & { @@ -974,15 +981,16 @@ function GridFieldBody({ const heldId = row[col.name]; const previous = heldId == null || heldId === '' ? null : pickedLookupRecords.current.get(pickKey(heldId)) ?? null; const currency = gridAutofillCurrency(columns, picked?.sourceFields, record, columnCurrencies, tenantCurrency, columnFields, row); - const { patch, withheld } = planLookupAutofill(columns, col, record, { pairs: lookupAutofill?.[col.name], row, previous }, currency); + const { patch, withheld, copied = [] } = planLookupAutofill(columns, col, record, { pairs: lookupAutofill?.[col.name], row, previous }, currency); if (record && typeof record === 'object' && patch[col.name] != null) { pickedLookupRecords.current.set(pickKey(patch[col.name]), record); } setWithheldFills((prev) => { - if (withheld.length === 0 && !prev.has(rowIdx)) return prev; + const said = withheld.length + copied.length > 0; + if (!said && !prev.has(rowIdx)) return prev; const next = new Map(prev); - if (withheld.length === 0) next.delete(rowIdx); - else next.set(rowIdx, { lookup: col.name, picked: patch[col.name], items: withheld }); + if (!said) next.delete(rowIdx); + else next.set(rowIdx, { lookup: col.name, picked: patch[col.name], items: withheld, copied }); return next; }); applyPatch(rowIdx, patch); @@ -1732,11 +1740,27 @@ function GridFieldBody({ const reorderable = allowReorder && !isGhost && !isList; // objectstack#36249 — the values this line's pick did not copy, // while the pick stands and the cell still holds what it held. + // objectstack#36412 (ruling 「保留金额并提示」) — each judged + // against the line's currency now, and each amount the pick + // copied, still held, named with the code it was copied under + // once the line's differs. A currency change writes no amount. const withheldPick = withheldFills.get(rowIdx); - const withheldShown = - withheldPick && !isList && String(row[withheldPick.lookup] ?? '') === String(withheldPick.picked ?? '') - ? withheldPick.items.filter((w) => withheldStillStands(w, row[w.target])) - : []; + const pickStands = + !!withheldPick && !isList && String(row[withheldPick.lookup] ?? '') === String(withheldPick.picked ?? ''); + const lineCurrencyNow = pickStands + ? gridAutofillCurrency(columns, undefined, undefined, columnCurrencies, tenantCurrency, columnFields, row) + : undefined; + const withheldShown = pickStands + ? withheldPick.items + .filter((w) => withheldStillStands(w, row[w.target])) + .map((w) => withheldAutofillNow(w, lineCurrencyNow?.targetCurrency(w.target), tenantCurrency)) + : []; + const copiedShown = pickStands + ? withheldPick.copied.flatMap((c) => { + const now = copiedAutofillNow(c, row[c.target], lineCurrencyNow?.targetCurrency(c.target), tenantCurrency); + return now ? [{ item: c, now }] : []; + }) + : []; return ( )} + {copiedShown.length > 0 && ( + + + + {copiedShown.map(({ item, now }) => ( +

+ {copiedAutofillMessage(item, now, columns.find((x) => x.name === item.target)?.label || item.target, t, displayLocale)} +

+ ))} + + + )}
); }) diff --git a/ui/packages/fields/src/widgets/lookupAutofill.ts b/ui/packages/fields/src/widgets/lookupAutofill.ts index 83b9b5ba924..848e5fd1844 100644 --- a/ui/packages/fields/src/widgets/lookupAutofill.ts +++ b/ui/packages/fields/src/widgets/lookupAutofill.ts @@ -108,14 +108,16 @@ export function judgePickWrites( currency: AutofillCurrencyContext | undefined, ): LookupAutofillPlan { const plan: LookupAutofillPlan = { patch: {}, withheld: [] }; + const copiedAmounts: CopiedAutofill[] = []; const writes: Values = {}; for (const c of candidates) writes[c.target] = c.value; for (const c of candidates) { - const refused = judgeCopy(currency, c, writes); - if (refused) plan.withheld.push(refused); + const { withheld, copied } = judgeCopy(currency, c, writes); + if (withheld) plan.withheld.push(withheld); else plan.patch[c.target] = c.value; + if (copied) copiedAmounts.push(copied); } - return plan; + return copiedAmounts.length > 0 ? { ...plan, copied: copiedAmounts } : plan; } /** {@link planDeclaredLookupAutofill}'s writes alone. */ @@ -258,6 +260,11 @@ function codeOf(c: AmountCurrency, home: string | undefined): string | undefined * - `targetCurrencyUnread`: the amount being filled follows a parent whose * code could not be read. * + * - `nowSameCurrency`: the record's currency has since changed, in the same + * edit, to the picked amount's own (`to`). The value stays unwritten (a + * currency change fills nothing), and a pick again fills it (the + * maintainer's ruling on objectstack-ai/objectstack#36412, branch B). + * * `held` is the value the target held at the pick when it held one (a re-pick * over a filled target): the target keeps it, and the note says so. */ @@ -265,7 +272,7 @@ export interface WithheldAutofill { readonly target: string; readonly source: string; readonly amount: number; - readonly reason: 'differs' | 'noTargetCurrency' | 'noSourceCurrency' | 'targetCurrencyUnread'; + readonly reason: 'differs' | 'noTargetCurrency' | 'noSourceCurrency' | 'targetCurrencyUnread' | 'nowSameCurrency'; readonly from?: string; readonly to?: string; readonly held?: unknown; @@ -314,23 +321,90 @@ export interface AutofillCurrencyContext { home: string | undefined; } -/** The writes and the withheld values of one pick. */ +/** + * An amount one pick copied into `target`: the `value` written and `under`, + * the code the target was in when it was written. A currency change in the + * same edit leaves the amount as it is (the maintainer's ruling on + * objectstack-ai/objectstack#36412, 「保留金额并提示」), and the host says + * under which currency it was copied while the target still holds it + * ({@link copiedAutofillNow}). + */ +export interface CopiedAutofill { + readonly target: string; + readonly source: string; + readonly value: unknown; + readonly under: string; +} + +/** + * The writes and the withheld values of one pick, and `copied`, the amounts + * it wrote with the code each was written under. `copied` is absent when the + * pick wrote no amount a currency judged (absent means none), so a plan built + * without it stays a plan. + */ export interface LookupAutofillPlan { patch: Values; withheld: WithheldAutofill[]; + copied?: CopiedAutofill[]; } -/** `write` judged against the record with this pick's `writes` applied, or the reason it is not copied. */ +/** `write` judged against the record with this pick's `writes` applied: withheld with the reason, or copied (an amount under its target's code). */ function judgeCopy( ctx: AutofillCurrencyContext | undefined, { target, source, value, held }: PickWrite, writes: Readonly, -): WithheldAutofill | undefined { - if (!ctx) return undefined; - const refusal = crossCurrencyRefusal(ctx.sourceCurrency(source, value), ctx.targetCurrency(target, writes), ctx.home); - if (!refusal) return undefined; +): { withheld?: WithheldAutofill; copied?: CopiedAutofill } { + if (!ctx) return {}; + const to = ctx.targetCurrency(target, writes); + const refusal = crossCurrencyRefusal(ctx.sourceCurrency(source, value), to, ctx.home); + if (!refusal) { + const under = to ? codeOf(to, ctx.home) : undefined; + return under ? { copied: { target, source, value, under } } : {}; + } const amount = typeof value === 'number' ? value : Number(value); - return { target, source, amount, ...refusal, ...(isEmptyValue(held) ? {} : { held }) }; + return { withheld: { target, source, amount, ...refusal, ...(isEmptyValue(held) ? {} : { held }) } }; +} + +/** + * `item` judged again against `now`, the currency its target is in now: a + * currency change in the same edit refreshes a withheld note to the new + * currency (the maintainer's ruling on objectstack-ai/objectstack#36412, + * item 3). Once the target is in the picked amount's own currency, the + * value stays unwritten and the note says a pick again fills it + * (`nowSameCurrency`, branch B). `item` itself when `now` is not known, or + * when it names no code to say. + */ +export function withheldAutofillNow( + item: WithheldAutofill, + now: AmountCurrency | undefined, + home: string | undefined, +): WithheldAutofill { + if (!now) return item; + const source: AmountCurrency = item.from ? { kind: 'code', code: item.from } : UNKNOWN; + const { target, amount, held } = item; + const base = { target, source: item.source, amount, ...(held === undefined ? {} : { held }) }; + const refusal = crossCurrencyRefusal(source, now, home); + if (refusal) return { ...base, ...refusal }; + const to = codeOf(now, home); + return to ? { ...base, reason: 'nowSameCurrency', ...(item.from ? { from: item.from } : {}), to } : item; +} + +/** + * The code to name beside an amount a pick copied (`item`) while its target + * still holds it (`current`): the code the target is in `now`, when that is + * known and differs from the one it was copied under. `undefined` says + * nothing is to be said: the target was written since (a typed amount gets + * no note), or the currency is unchanged or cannot be named. + */ +export function copiedAutofillNow( + item: CopiedAutofill, + current: unknown, + now: AmountCurrency | undefined, + home: string | undefined, +): string | undefined { + if (!sameValue(current, item.value) || !now) return undefined; + const to = codeOf(now, home); + return to && to !== item.under ? to : undefined; } /** @@ -350,7 +424,8 @@ type Translate = (key: string, options?: Record) => string; * The sentence that says why a pick left `item.target` empty, naming both * currencies and the picked amount in its own currency, so a person can * price it by hand. `label` is the target's label. A target that kept the - * value it held at the pick (`held`) is said to keep it. + * value it held at the pick (`held`) is said to keep it; under + * `nowSameCurrency` it is told to clear the field before a pick again. */ export function withheldAutofillMessage( item: WithheldAutofill, @@ -366,8 +441,33 @@ export function withheldAutofillMessage( ? t('lookup.autofillSourceNoCurrency', { field: label, amount, to: item.to }) : item.reason === 'targetCurrencyUnread' ? t('lookup.autofillCurrencyUnread', { field: label, amount }) - : t('lookup.autofillNoCurrency', { field: label, amount }); - return item.held === undefined ? why : `${why} ${t('lookup.autofillKept', { field: label })}`; + : item.reason === 'nowSameCurrency' + ? t('lookup.autofillNowSameCurrency', { field: label, amount, to: item.to }) + : t('lookup.autofillNoCurrency', { field: label, amount }); + if (item.held === undefined) return why; + // A target that still holds an earlier value: a pick again of the same + // record does not replace it (a declared pair without `overwrite` keeps a + // value this record did not fill), so the sentence says to clear it first. + if (item.reason === 'nowSameCurrency') return t('lookup.autofillNowSameCurrencyHeld', { field: label, amount, to: item.to }); + return `${why} ${t('lookup.autofillKept', { field: label })}`; +} + +/** + * The sentence beside an amount a pick copied, once the record's currency + * changed in the same edit: the amount as it was copied, in the code it was + * copied under, and the code the record is in `now` + * ({@link copiedAutofillNow}). + */ +export function copiedAutofillMessage( + item: CopiedAutofill, + now: string, + label: string, + t: Translate, + locale: string | undefined, +): string { + const n = typeof item.value === 'number' ? item.value : Number(item.value); + const amount = Number.isFinite(n) ? formatCurrency(n, item.under, locale) : String(item.value); + return t('lookup.autofillCopiedUnder', { field: label, amount, to: now }); } /** diff --git a/ui/packages/fields/src/widgets/useFieldTranslation.ts b/ui/packages/fields/src/widgets/useFieldTranslation.ts index 460ff4aebd1..80d86cbe511 100644 --- a/ui/packages/fields/src/widgets/useFieldTranslation.ts +++ b/ui/packages/fields/src/widgets/useFieldTranslation.ts @@ -65,6 +65,9 @@ const FIELD_DEFAULTS: Record = { 'lookup.autofillNoCurrency': '{{field}} was not filled: the picked amount is {{amount}}, but no currency is chosen here yet. Choose the currency, then enter {{field}}.', 'lookup.autofillCurrencyUnread': '{{field}} was not filled: the picked amount is {{amount}}, but the currency here could not be read. Check the currency, then enter {{field}}.', 'lookup.autofillKept': '{{field}} still holds its earlier value.', + 'lookup.autofillNowSameCurrency': '{{field}} was not filled when it was picked. The record is now in {{to}}: pick again to fill {{amount}}.', + 'lookup.autofillNowSameCurrencyHeld': '{{field}} was not filled when it was picked and still holds its earlier value. The record is now in {{to}}: clear {{field}}, then pick again to fill {{amount}}.', + 'lookup.autofillCopiedUnder': '{{field}} was copied as {{amount}}, but the record is now in {{to}}. Enter {{field}} in {{to}} if it should change.', 'lookup.pageOf': 'Page {{current}} of {{total}}', 'lookup.filters': 'Filters', 'lookup.clear': 'Clear', diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 9c39b5bca8b..276ae4ec179 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -76,6 +76,9 @@ const ar = { autofillNoCurrency: 'لم يُملأ {{field}}: المبلغ المختار هو {{amount}}، لكن لم تُختر عملة هنا بعد. اختر العملة، ثم أدخل {{field}}.', autofillCurrencyUnread: 'لم يُملأ {{field}}: المبلغ المختار هو {{amount}}، لكن تعذّرت قراءة العملة هنا. تحقّق من العملة، ثم أدخل {{field}}.', autofillKept: 'يحتفظ {{field}} بقيمته السابقة.', + autofillNowSameCurrency: 'لم يُملأ {{field}} عند الاختيار. السجل الآن بعملة {{to}}: اختر مرة أخرى لملء {{amount}}.', + autofillNowSameCurrencyHeld: 'لم يُملأ {{field}} عند الاختيار ويحتفظ بقيمته السابقة. السجل الآن بعملة {{to}}: امسح {{field}} ثم اختر مرة أخرى لملء {{amount}}.', + autofillCopiedUnder: 'نُسخ {{field}} بقيمة {{amount}}، لكن السجل الآن بعملة {{to}}. أدخل {{field}} بعملة {{to}} إذا لزم التغيير.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index b2d796da744..1e23646764c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -69,6 +69,9 @@ const de = { autofillNoCurrency: '{{field}} wurde nicht ausgefüllt: Der gewählte Betrag ist {{amount}}, hier ist aber noch keine Währung gewählt. Wählen Sie die Währung und geben Sie dann {{field}} ein.', autofillCurrencyUnread: '{{field}} wurde nicht ausgefüllt: Der gewählte Betrag ist {{amount}}, die Währung hier konnte aber nicht gelesen werden. Prüfen Sie die Währung und geben Sie dann {{field}} ein.', autofillKept: '{{field}} behält seinen bisherigen Wert.', + autofillNowSameCurrency: '{{field}} wurde bei der Auswahl nicht ausgefüllt. Der Datensatz ist jetzt in {{to}}: Wählen Sie erneut, um {{amount}} einzutragen.', + autofillNowSameCurrencyHeld: '{{field}} wurde bei der Auswahl nicht ausgefüllt und behält seinen bisherigen Wert. Der Datensatz ist jetzt in {{to}}: Leeren Sie {{field}} und wählen Sie erneut, um {{amount}} einzutragen.', + autofillCopiedUnder: '{{field}} wurde als {{amount}} übernommen, der Datensatz ist jetzt aber in {{to}}. Geben Sie {{field}} bei Bedarf in {{to}} ein.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index e9501132287..a5beefed4b0 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -78,6 +78,9 @@ const en = { autofillNoCurrency: '{{field}} was not filled: the picked amount is {{amount}}, but no currency is chosen here yet. Choose the currency, then enter {{field}}.', autofillCurrencyUnread: '{{field}} was not filled: the picked amount is {{amount}}, but the currency here could not be read. Check the currency, then enter {{field}}.', autofillKept: '{{field}} still holds its earlier value.', + autofillNowSameCurrency: '{{field}} was not filled when it was picked. The record is now in {{to}}: pick again to fill {{amount}}.', + autofillNowSameCurrencyHeld: '{{field}} was not filled when it was picked and still holds its earlier value. The record is now in {{to}}: clear {{field}}, then pick again to fill {{amount}}.', + autofillCopiedUnder: '{{field}} was copied as {{amount}}, but the record is now in {{to}}. Enter {{field}} in {{to}} if it should change.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 5084d8ecadd..7d70b212e81 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -70,6 +70,9 @@ const es = { autofillNoCurrency: 'No se rellenó {{field}}: el importe elegido es {{amount}}, pero aquí aún no se ha elegido moneda. Elija la moneda y luego introduzca {{field}}.', autofillCurrencyUnread: 'No se rellenó {{field}}: el importe elegido es {{amount}}, pero no se pudo leer la moneda de aquí. Compruebe la moneda y luego introduzca {{field}}.', autofillKept: '{{field}} conserva su valor anterior.', + autofillNowSameCurrency: 'No se rellenó {{field}} al elegirlo. El registro ahora está en {{to}}: vuelva a elegirlo para rellenar {{amount}}.', + autofillNowSameCurrencyHeld: 'No se rellenó {{field}} al elegirlo y conserva su valor anterior. El registro ahora está en {{to}}: vacíe {{field}} y vuelva a elegirlo para rellenar {{amount}}.', + autofillCopiedUnder: '{{field}} se copió como {{amount}}, pero el registro ahora está en {{to}}. Introduzca {{field}} en {{to}} si debe cambiar.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 44923d0442b..c40f9f3be2f 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -70,6 +70,9 @@ const fr = { autofillNoCurrency: '{{field}} n’a pas été rempli : le montant choisi est de {{amount}}, mais aucune devise n’est encore choisie ici. Choisissez la devise, puis saisissez {{field}}.', autofillCurrencyUnread: '{{field}} n’a pas été rempli : le montant choisi est de {{amount}}, mais la devise ici n’a pas pu être lue. Vérifiez la devise, puis saisissez {{field}}.', autofillKept: '{{field}} garde sa valeur précédente.', + autofillNowSameCurrency: '{{field}} n’a pas été rempli lors du choix. L’enregistrement est maintenant en {{to}} : choisissez à nouveau pour remplir {{amount}}.', + autofillNowSameCurrencyHeld: '{{field}} n’a pas été rempli lors du choix et garde sa valeur précédente. L’enregistrement est maintenant en {{to}} : videz {{field}}, puis choisissez à nouveau pour remplir {{amount}}.', + autofillCopiedUnder: '{{field}} a été copié comme {{amount}}, mais l’enregistrement est maintenant en {{to}}. Saisissez {{field}} en {{to}} s’il doit changer.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index b3574a00762..862442145c4 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -69,6 +69,9 @@ const ja = { autofillNoCurrency: '{{field}}は入力されませんでした。選択した金額は {{amount}} ですが、ここではまだ通貨が選択されていません。通貨を選択してから{{field}}を入力してください。', autofillCurrencyUnread: '{{field}}は入力されませんでした。選択した金額は {{amount}} ですが、ここでの通貨を読み取れませんでした。通貨を確認してから{{field}}を入力してください。', autofillKept: '{{field}}は以前の値のままです。', + autofillNowSameCurrency: '選択時に{{field}}は入力されませんでした。レコードは現在 {{to}} です。もう一度選択すると {{amount}} が入力されます。', + autofillNowSameCurrencyHeld: '選択時に{{field}}は入力されず、以前の値のままです。レコードは現在 {{to}} です。{{field}}を空にしてからもう一度選択すると {{amount}} が入力されます。', + autofillCopiedUnder: '{{field}}は {{amount}} として入力されましたが、レコードは現在 {{to}} です。必要に応じて {{to}} で{{field}}を入力してください。', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index c0f879bdc4c..a0a5117773b 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -69,6 +69,9 @@ const ko = { autofillNoCurrency: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액은 {{amount}}이지만 여기에는 아직 통화가 선택되지 않았습니다. 통화를 선택한 후 {{field}}을(를) 입력하세요.', autofillCurrencyUnread: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액은 {{amount}}이지만 여기의 통화를 읽을 수 없습니다. 통화를 확인한 후 {{field}}을(를) 입력하세요.', autofillKept: '{{field}}은(는) 이전 값을 유지합니다.', + autofillNowSameCurrency: '선택 시 {{field}}이(가) 입력되지 않았습니다. 레코드는 이제 {{to}} 기준입니다. 다시 선택하면 {{amount}}이(가) 입력됩니다.', + autofillNowSameCurrencyHeld: '선택 시 {{field}}이(가) 입력되지 않았고 이전 값을 유지합니다. 레코드는 이제 {{to}} 기준입니다. {{field}}을(를) 비운 뒤 다시 선택하면 {{amount}}이(가) 입력됩니다.', + autofillCopiedUnder: '{{field}}은(는) {{amount}}(으)로 입력되었지만 레코드는 이제 {{to}} 기준입니다. 필요하면 {{to}}(으)로 {{field}}을(를) 입력하세요.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index b13fd967c30..5a61681ef3d 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -70,6 +70,9 @@ const pt = { autofillNoCurrency: '{{field}} não foi preenchido: o valor escolhido é {{amount}}, mas ainda não há moeda escolhida aqui. Escolha a moeda e depois informe {{field}}.', autofillCurrencyUnread: '{{field}} não foi preenchido: o valor escolhido é {{amount}}, mas não foi possível ler a moeda aqui. Verifique a moeda e depois informe {{field}}.', autofillKept: '{{field}} mantém o valor anterior.', + autofillNowSameCurrency: '{{field}} não foi preenchido na escolha. O registro agora está em {{to}}: escolha novamente para preencher {{amount}}.', + autofillNowSameCurrencyHeld: '{{field}} não foi preenchido na escolha e mantém o valor anterior. O registro agora está em {{to}}: limpe {{field}} e escolha novamente para preencher {{amount}}.', + autofillCopiedUnder: '{{field}} foi copiado como {{amount}}, mas o registro agora está em {{to}}. Informe {{field}} em {{to}} se precisar mudar.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 98537eef25a..3c4d3a31532 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -71,6 +71,9 @@ const ru = { autofillNoCurrency: 'Поле «{{field}}» не заполнено: выбранная сумма — {{amount}}, но валюта здесь ещё не выбрана. Выберите валюту, затем введите «{{field}}».', autofillCurrencyUnread: 'Поле «{{field}}» не заполнено: выбранная сумма — {{amount}}, но валюту здесь не удалось прочитать. Проверьте валюту, затем введите «{{field}}».', autofillKept: 'В поле «{{field}}» осталось прежнее значение.', + autofillNowSameCurrency: 'Поле «{{field}}» не заполнено при выборе. Теперь запись в {{to}}: выберите снова, чтобы заполнить {{amount}}.', + autofillNowSameCurrencyHeld: 'Поле «{{field}}» не заполнено при выборе и сохраняет прежнее значение. Теперь запись в {{to}}: очистите «{{field}}» и выберите снова, чтобы заполнить {{amount}}.', + autofillCopiedUnder: 'Поле «{{field}}» скопировано как {{amount}}, но теперь запись в {{to}}. При необходимости введите «{{field}}» в {{to}}.', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index ca2e1d18873..ea0db48ec87 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -78,6 +78,9 @@ const zh = { autofillNoCurrency: '未填入{{field}}:所选金额为 {{amount}},但此处尚未选择币种。请先选择币种,再填写{{field}}。', autofillCurrencyUnread: '未填入{{field}}:所选金额为 {{amount}},但无法读取此处的币种。请先确认币种,再填写{{field}}。', autofillKept: '{{field}}仍保留原来的值。', + autofillNowSameCurrency: '选取时未填入{{field}}。记录现已改为 {{to}}:重新选取即可填入 {{amount}}。', + autofillNowSameCurrencyHeld: '选取时未填入{{field}},且仍保留原来的值。记录现已改为 {{to}}:请先清空{{field}},再重新选取即可填入 {{amount}}。', + autofillCopiedUnder: '{{field}}按 {{amount}} 带入,但记录现已改为 {{to}}。如需调整,请按 {{to}} 填写{{field}}。', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 3559d6dc0c5..5d001f86f58 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -78,6 +78,9 @@ const zhHant = { autofillNoCurrency: '未填入{{field}}:所選金額為 {{amount}},但此處尚未選擇幣種。請先選擇幣種,再填寫{{field}}。', autofillCurrencyUnread: '未填入{{field}}:所選金額為 {{amount}},但無法讀取此處的幣種。請先確認幣種,再填寫{{field}}。', autofillKept: '{{field}}仍保留原來的值。', + autofillNowSameCurrency: '選取時未填入{{field}}。記錄現已改為 {{to}}:重新選取即可填入 {{amount}}。', + autofillNowSameCurrencyHeld: '選取時未填入{{field}},且仍保留原來的值。記錄現已改為 {{to}}:請先清空{{field}},再重新選取即可填入 {{amount}}。', + autofillCopiedUnder: '{{field}}按 {{amount}} 帶入,但記錄現已改為 {{to}}。如需調整,請按 {{to}} 填寫{{field}}。', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx b/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx index 4c9648761bf..ba20895903c 100644 --- a/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx @@ -18,7 +18,7 @@ * lookup without the key fills nothing, not even a same-named field. */ import { describe, it, expect, vi } from 'vitest'; -import { render, waitFor, fireEvent, screen, act } from '@testing-library/react'; +import { render, waitFor, fireEvent, screen, act, cleanup } from '@testing-library/react'; import React from 'react'; import { ObjectForm } from './ObjectForm'; @@ -671,3 +671,170 @@ describe('ObjectForm — cross-currency pick follow-ups (objectstack#36412)', () expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); }); }); + +describe('ObjectForm — a same-edit currency change keeps amounts and says so (objectstack#36412, ruling 「保留金额并提示」)', () => { + // A quote whose price follows its own code, and a catalog priced in the + // home currency (USD here). + const SCHEMAS_RULING: Record = { + cn_quote: { + name: 'cn_quote', + fields: { + currency_code: { type: 'text', label: 'Currency' }, + product: { + type: 'lookup', + label: 'Product', + reference: 'cn_product', + lookupAutofill: [ + { target: 'unit_price', source: 'list_price' }, + { target: 'description', source: 'summary' }, + ], + }, + unit_price: { type: 'currency', label: 'Unit Price', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } }, + description: { type: 'text', label: 'Description' }, + }, + }, + // The same quote whose pick replaces a price somebody wrote. + cn_ow_quote: { + name: 'cn_ow_quote', + fields: { + currency_code: { type: 'text', label: 'Currency' }, + product: { + type: 'lookup', + label: 'Product', + reference: 'cn_product', + lookupAutofill: [ + { target: 'unit_price', source: 'list_price', overwrite: true }, + { target: 'description', source: 'summary' }, + ], + }, + unit_price: { type: 'currency', label: 'Unit Price', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } }, + description: { type: 'text', label: 'Description' }, + }, + }, + cn_product: { + name: 'cn_product', + fields: { + name: { type: 'text', label: 'Name' }, + list_price: { type: 'currency', label: 'List Price' }, + summary: { type: 'text', label: 'Summary' }, + }, + }, + }; + const PRODUCTS = [{ id: 'p1', name: 'Widget', list_price: 100, summary: 'A widget' }]; + function renderQuote(currency_code: string, objectName = 'cn_quote', extra: Record = {}) { + const ds = { + getObjectSchema: vi.fn(async (name: string) => SCHEMAS_RULING[name]), + find: vi.fn(async (name: string) => { + const rows = name === 'cn_product' ? PRODUCTS : []; + return { data: rows.map((r) => ({ ...r })), total: rows.length }; + }), + findOne: vi.fn(async (name: string, id: string) => (name === 'cn_product' ? { ...PRODUCTS.find((r) => r.id === id) } : null)), + create: vi.fn(async (_o: string, d: Record) => ({ id: 'q1', ...d })), + update: vi.fn(), + }; + const view = render( + + + + + , + ); + return view.container; + } + const valueOf = (c: HTMLElement, name: string) => (c.querySelector(`input[name="${name}"]`) as HTMLInputElement | null)?.value ?? ''; + async function type(c: HTMLElement, name: string, value: string): Promise { + const el = await input(c, name); + await act(async () => { + fireEvent.change(el, { target: { value } }); + }); + await waitFor(() => expect(valueOf(c, name)).toContain(value)); + } + + it('a copied amount stays through a currency change, and a note names the code it was copied under', async () => { + const c = renderQuote('USD'); + await input(c, 'description'); + await pick('product', 'Widget'); + await waitFor(() => expect(valueOf(c, 'unit_price')).toContain('100')); + // Control: copied in the record's own currency, nothing to say. + expect(screen.queryByTestId('lookup-autofill-copied')).toBeNull(); + + await type(c, 'currency_code', 'EUR'); + expect(valueOf(c, 'unit_price')).toContain('100'); + const note = await screen.findByTestId('lookup-autofill-copied'); + expect(note.querySelector('[data-copied-target="unit_price"]')?.textContent).toBe( + 'Unit Price was copied as $100.00, but the record is now in EUR. Enter Unit Price in EUR if it should change.', + ); + + // Control: back in the currency it was copied under, the note ends. + await type(c, 'currency_code', 'USD'); + await waitFor(() => expect(screen.queryByTestId('lookup-autofill-copied')).toBeNull()); + expect(valueOf(c, 'unit_price')).toContain('100'); + }); + + it('a withheld note refreshes to the record’s new currency, and the amount stays empty', async () => { + const c = renderQuote('JPY'); + await input(c, 'description'); + await pick('product', 'Widget'); + expect((await screen.findByTestId('lookup-autofill-withheld')).textContent).toContain('here is in JPY'); + + await type(c, 'currency_code', 'GBP'); + await waitFor(() => expect(screen.getByTestId('lookup-autofill-withheld').textContent).toContain('here is in GBP')); + expect(screen.getByTestId('lookup-autofill-withheld').textContent).not.toContain('JPY'); + expect(valueOf(c, 'unit_price')).toBe(''); + }); + + it('branch B: the record turns to the picked amount’s own currency, the note stays, says so, and nothing fills until a pick again', async () => { + const c = renderQuote('EUR'); + await input(c, 'description'); + await pick('product', 'Widget'); + await screen.findByTestId('lookup-autofill-withheld'); + + await type(c, 'currency_code', 'USD'); + await waitFor(() => + expect(screen.getByTestId('lookup-autofill-withheld').textContent).toBe( + 'Unit Price was not filled when it was picked. The record is now in USD: pick again to fill $100.00.', + ), + ); + expect(valueOf(c, 'unit_price')).toBe(''); + + // Control: the pick again the note offers fills it, and nothing is left to say. + await pick('product', 'Widget'); + await waitFor(() => expect(valueOf(c, 'unit_price')).toContain('100')); + expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); + expect(screen.queryByTestId('lookup-autofill-copied')).toBeNull(); + }); + + it('branch B over a price that still holds an earlier value: the note says to clear it, then pick again', async () => { + const c = renderQuote('EUR', 'cn_ow_quote', { unit_price: 80 }); + await input(c, 'description'); + await pick('product', 'Widget'); + expect((await screen.findByTestId('lookup-autofill-withheld')).textContent).toContain('Unit Price still holds its earlier value.'); + + await type(c, 'currency_code', 'USD'); + await waitFor(() => + expect(screen.getByTestId('lookup-autofill-withheld').textContent).toBe( + '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.', + ), + ); + expect(valueOf(c, 'unit_price')).toContain('80'); + }); + + it('a hand-typed amount gets no note through a currency change, nor one typed over a copied amount', async () => { + const typed = renderQuote('USD'); + await type(typed, 'unit_price', '55'); + await type(typed, 'currency_code', 'EUR'); + expect(valueOf(typed, 'unit_price')).toContain('55'); + expect(screen.queryByTestId('lookup-autofill-copied')).toBeNull(); + expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); + cleanup(); + + const over = renderQuote('USD'); + await input(over, 'description'); + await pick('product', 'Widget'); + await waitFor(() => expect(valueOf(over, 'unit_price')).toContain('100')); + await type(over, 'unit_price', '55'); + await type(over, 'currency_code', 'EUR'); + expect(valueOf(over, 'unit_price')).toContain('55'); + expect(screen.queryByTestId('lookup-autofill-copied')).toBeNull(); + }); +});