diff --git a/.changeset/36412-cross-currency-pick-followups.md b/.changeset/36412-cross-currency-pick-followups.md new file mode 100644 index 00000000000..0bc13d9376f --- /dev/null +++ b/.changeset/36412-cross-currency-pick-followups.md @@ -0,0 +1,18 @@ +--- +'@object-ui/fields': patch +'@object-ui/i18n': patch +'@object-ui/plugin-form': patch +--- + +fix(fields): a lookup pick that keeps an amount says so over a filled field too, a create form's opening fill no longer waits for ever on a parent it cannot read, and a pick that fills a currency code and an amount in it copies both + +Clause-②: no +Metadata-protocol: none + +Three follow-ups to the cross-currency pick rule (a pick copies an amount only into a field in the same currency). Nothing is converted, and no metadata changes. + +- **A pick over a filled amount says why it kept it.** When a pick would replace an amount that already holds a value (a re-pick in a line-item grid, or a declared pair with `overwrite: true`) and the picked amount is in another currency, the earlier value stays and the note now shows there too, ending "Unit Price still holds its earlier value." Before, the note showed only over an empty field, so the earlier product's price sat under the new product with nothing said. The note goes away once somebody edits the field. +- **The opening fill of a create form no longer waits for ever.** A form opened with a lookup already holding a record (a related list's New, a URL prefill) fills its declared targets from it. When an amount there follows the currency of a parent the record names, the fill waited for that parent's read and never ran if the read failed, the data source cannot read single records (`findOne`), or the form names no parent object. Now the wait ends when the read answers, fails or cannot run: the other targets (a description) fill, and the amount is left empty with the note "the currency here could not be read". +- **A pick that fills a code field and its amount together copies both.** An amount that follows the record's own code field (`currencyMode: 'record'`) is now judged against the line or record with the same pick's write to that code field applied, in the line-item grid and in the record form. Picking a product that carries `currency_code: EUR` and a price in it onto a fresh line now fills the code and the price, where the price was withheld with a "no currency is chosen" note beside the code the same pick had just written. + +Also in `@object-ui/fields`: new exports `declaredPickWrites`, `judgePickWrites`, `withheldStillStands` and the type `PickWrite`; `AmountCurrency` gains the kind `unread`, `WithheldAutofill` the reason `targetCurrencyUnread` and the optional `held` (the value a target kept); `amountCurrencyOf` takes an optional third argument, the pick's own writes; `AutofillCurrencyContext.targetCurrency` is handed them as an optional second argument. In `@object-ui/i18n`: two new `lookup.*` sentences, `autofillCurrencyUnread` and `autofillKept`, in every locale pack. In `@object-ui/plugin-form`: the record-form stamp's documentation lists the hosts the rule reaches; no behaviour changes there. 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 c37de21c125..3afe0e93d1b 100644 --- a/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx @@ -411,3 +411,164 @@ describe('a pick does not copy an amount across currencies (objectstack#36249)', }); }); }); + +describe('cross-currency pick follow-ups: a re-pick over a filled cell, and a code-plus-amount pick (objectstack#36412)', () => { + const recordPrice = { type: 'currency', currencyConfig: { currencyMode: 'record' as const, currencyField: 'currency_code' } }; + const parentPrice = { type: 'currency', currencyConfig: { currencyMode: 'record' as const, currencyField: 'invoice.currency_code' } }; + + it("an amount's currency reads this pick's own write to its code field; a parent's code is not the record's to write", () => { + expect(amountCurrencyOf(recordPrice, {}, { currency_code: 'EUR' })).toEqual({ kind: 'code', code: 'EUR' }); + expect(amountCurrencyOf(recordPrice, { currency_code: 'JPY' }, { currency_code: 'EUR' })).toEqual({ kind: 'code', code: 'EUR' }); + // Control: without the write, the record as it stands. + expect(amountCurrencyOf(recordPrice, {}, {})).toEqual({ kind: 'unset' }); + expect(amountCurrencyOf(recordPrice, { currency_code: 'JPY' })).toEqual({ kind: 'code', code: 'JPY' }); + expect(amountCurrencyOf(parentPrice, {}, { 'invoice.currency_code': 'EUR', invoice: { currency_code: 'EUR' } })).toEqual({ kind: 'unset' }); + }); + + // A product carries its own code and a price in it; a line carries the same pair. + const product = { value: 'p1', currency_code: 'EUR', unit_price: 100, description: 'Euro widget' }; + const lineDefs: Record = { currency_code: { type: 'text' }, unit_price: recordPrice }; + const productDefs: Record = { currency_code: { type: 'text' }, unit_price: recordPrice }; + const context = (line: Record) => ({ + home: 'USD', + sourceCurrency: (source: string, v: unknown) => pickedAmountCurrencyOf(productDefs[source] as never, v, product), + targetCurrency: (target: string, writes?: Readonly>) => amountCurrencyOf(lineDefs[target] as never, line, writes), + }); + const codeCols = [ + { name: 'product', type: 'lookup' as const, reference: 'product' }, + { name: 'currency_code', type: 'text' as const }, + { name: 'unit_price', type: 'currency' as const }, + ]; + + it('the same-named copy writes the code and judges the price in it: both copy onto a fresh line', () => { + const plan = planLookupAutofill(codeCols, codeCols[0], product, { row: {} }, context({})); + expect(plan.patch).toEqual({ product: 'p1', currency_code: 'EUR', unit_price: 100 }); + expect(plan.withheld).toEqual([]); + // Control: a grid that draws no code column writes no code, so the line + // still holds none and the price is withheld. + const noCode = planLookupAutofill([codeCols[0], codeCols[2]], codeCols[0], product, { row: {} }, context({})); + expect(noCode.patch).toEqual({ product: 'p1' }); + expect(noCode.withheld[0]).toMatchObject({ target: 'unit_price', reason: 'noTargetCurrency', from: 'EUR' }); + }); + + it('declared pairs: a pair writing the code puts the price beside it in that code', () => { + const both = [{ target: 'currency_code', source: 'currency_code' }, { target: 'unit_price', source: 'unit_price' }]; + expect(planDeclaredLookupAutofill(both, product, {}, null, context({}))).toEqual({ + patch: { currency_code: 'EUR', unit_price: 100 }, + withheld: [], + }); + // Control: a code the record already holds is kept (no `overwrite`), and + // the price is judged in it. + const kept = planDeclaredLookupAutofill(both, product, { currency_code: 'JPY' }, null, context({ currency_code: 'JPY' })); + expect(kept.patch).toEqual({}); + expect(kept.withheld[0]).toMatchObject({ target: 'unit_price', reason: 'differs', from: 'EUR', to: 'JPY' }); + }); + + it('a value withheld over a filled target names what the target kept; one over an empty target does not', () => { + const eur = { home: 'USD', sourceCurrency: () => ({ kind: 'home' as const }), targetCurrency: (t: string) => (t === 'unit_price' ? { kind: 'code' as const, code: 'EUR' } : undefined) }; + const over = planDeclaredLookupAutofill([{ target: 'unit_price', source: 'list_price', overwrite: true }], widget, { unit_price: 80 }, null, eur); + expect(over.withheld).toEqual([{ target: 'unit_price', source: 'list_price', amount: 25, reason: 'differs', from: 'USD', to: 'EUR', held: 80 }]); + const empty = planDeclaredLookupAutofill([{ target: 'unit_price', source: 'list_price' }], widget, { unit_price: null }, null, eur); + expect(empty.withheld[0]).not.toHaveProperty('held'); + // The re-pick case: the target still holds what the earlier pick filled. + const repick = planDeclaredLookupAutofill(pairs, gadget, { unit_price: 25 }, widget, eur); + expect(repick.withheld[0]).toMatchObject({ held: 25 }); + }); + + describe('through the grid', () => { + 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 (_o: string, params?: { $filter?: { id?: { $in?: unknown[] } } }) => { + const wanted = params?.$filter?.id?.$in; + const rows = ROWS.filter((r) => !wanted || wanted.includes(r.id)); + return { 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: 'currency_code', type: 'text' as const }, + { name: 'unit_price', type: 'currency' as const, label: 'Unit Price' }, + ]; + + function Line({ columns = drawn, currency, line }: { columns?: typeof drawn; currency?: Record; line?: Record }) { + const [rows, setRows] = React.useState[]>([{ product: null, description: null, unit_price: null, ...line }]); + return ( + + + []) => setRows(next)} + field={{ columns } as never} + columnCurrencies={currency} + columnFields={{ unit_price: recordPrice }} + /> + {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); + }); + } + + it('a fresh line: the pick copies the code and the price in it, with no note', async () => { + render(); + await pickProduct(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', currency_code: 'EUR', unit_price: 100 })); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); + + it('control: a grid that draws no code column leaves the price empty and says no currency is chosen', async () => { + render( c.name !== 'currency_code')} />); + await pickProduct(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Euro widget' })); + expect(rowsNow()[0].unit_price).toBeNull(); + expect((await screen.findByTestId('line-items-autofill-withheld-0')).textContent).toContain('no currency is chosen'); + }); + + it('a pick over a filled cell in another currency keeps the earlier price and says so, until the cell is edited', async () => { + render( c.name !== 'currency_code')} currency={{ unit_price: 'JPY' }} line={{ unit_price: 80 }} />); + await pickProduct(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Euro widget' })); + expect(rowsNow()[0].unit_price).toBe(80); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.textContent).toContain('JPY'); + expect(note.textContent).toContain('Unit Price still holds its earlier value.'); + // Once somebody writes the cell, the note has said what it had to say. + fireEvent.change(screen.getAllByLabelText('Unit Price')[0], { target: { value: '9000' } }); + await waitFor(() => expect(rowsNow()[0].unit_price).toBe(9000)); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); + + it('control: a pick over an empty cell in another currency says why without the kept sentence', async () => { + render( c.name !== 'currency_code')} currency={{ unit_price: 'JPY' }} />); + await pickProduct(); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.textContent).toContain('JPY'); + expect(note.textContent).not.toContain('earlier value'); + }); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.ts b/ui/packages/fields/src/widgets/GridField.ts index 518e460231e..0f66848d5bd 100644 --- a/ui/packages/fields/src/widgets/GridField.ts +++ b/ui/packages/fields/src/widgets/GridField.ts @@ -5,12 +5,12 @@ import React from 'react'; import type { InlineGridColumn } from '@objectstack/spec/data'; import { resolveFieldCurrency, currencyFractionDigits } from '../currency.js'; import { - crossCurrencyRefusal, - planDeclaredLookupAutofill, + declaredPickWrites, + judgePickWrites, type AutofillCurrencyContext, type LookupAutofillPair, type LookupAutofillPlan, - type WithheldAutofill, + type PickWrite, } from './lookupAutofill.js'; import { fieldHelpText } from '../fieldHelpText.js'; // Type-only: erased at build, so it adds no edge to the bundle graph. The one @@ -218,7 +218,10 @@ export function evalArith(expr: string, row: Row): number | null { * `currency` is the pick's cross-currency rule (`crossCurrencyRefusal`): a * value it refuses is left out of the patch, the same-named copy and the * declared pairs alike, and listed under `withheld` so the grid says why the - * cell stayed empty. Without it every value copies as before. + * cell stayed as it was. Every value is judged against the line with all of + * this pick's writes applied (`judgePickWrites`), so a code the pick copies + * puts the amount beside it in that code. Without it every value copies as + * before. */ export function planLookupAutofill( columns: GridColumn[], @@ -227,8 +230,7 @@ export function planLookupAutofill( declared?: { pairs?: readonly LookupAutofillPair[]; row?: Row; previous?: Row | null }, currency?: AutofillCurrencyContext, ): LookupAutofillPlan { - const patch: Row = { [col.name]: record?.value ?? record?.id ?? record?._id }; - const withheld: WithheldAutofill[] = []; + const writes: PickWrite[] = []; const declaredTargets = new Set((declared?.pairs ?? []).map((p) => p.target)); if (col.autofill !== false && record && typeof record === 'object') { for (const other of columns) { @@ -236,15 +238,12 @@ export function planLookupAutofill( if (declaredTargets.has(other.name)) continue; const v = record[other.name]; if (v === undefined || v === null || v === '') continue; - const refusal = currency - ? crossCurrencyRefusal(currency.sourceCurrency(other.name, v), currency.targetCurrency(other.name), currency.home) - : undefined; - if (refusal) withheld.push({ target: other.name, source: other.name, amount: Number(v), ...refusal }); - else patch[other.name] = v; + writes.push({ target: other.name, source: other.name, value: v, held: declared?.row?.[other.name] }); } } - const pairs = planDeclaredLookupAutofill(declared?.pairs, record, declared?.row, declared?.previous, currency); - return { patch: { ...patch, ...pairs.patch }, withheld: [...withheld, ...pairs.withheld] }; + 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 }; } /** {@link planLookupAutofill}'s writes alone. */ diff --git a/ui/packages/fields/src/widgets/LookupField.tsx b/ui/packages/fields/src/widgets/LookupField.tsx index 32d98647559..4717859dc28 100644 --- a/ui/packages/fields/src/widgets/LookupField.tsx +++ b/ui/packages/fields/src/widgets/LookupField.tsx @@ -42,11 +42,12 @@ import { planDeclaredLookupAutofill, readLookupAutofillTargets, withheldAutofillMessage, + withheldStillStands, type AutofillCurrencyContext, type LookupAutofillPair, type WithheldAutofill, } from './lookupAutofill.js'; -import { useFollowedParentRecord } from './followedParentRow.js'; +import { useFollowedParentRead } from './followedParentRow.js'; import { getCellRendererResolver } from './_cell-renderer-bridge.js'; // The one place a lookup column's display value is decided — shared with the // "browse all records" picker (RecordPickerDialog) so a single `lookupColumns` @@ -1229,16 +1230,17 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro () => (autofillTargets ? Object.values(autofillTargets).find((d) => recordCurrencyPath(d as never)) : undefined), [autofillTargets], ); - const editedRecordForCurrency = useFollowedParentRecord(followingTarget as never, resolvedDependentValues, dataSource); - const followingPath = followingTarget ? recordCurrencyPath(followingTarget as never) : undefined; - const followedParentHeld = followingPath ? resolvedDependentValues?.[followingPath.via] : undefined; - // The parent read has not landed yet: the record names a parent by its id, - // and its code is not on the record the resolver reads. - const followedParentPending = - !!followingPath && - (typeof followedParentHeld === 'string' || typeof followedParentHeld === 'number') && - followedParentHeld !== '' && - !(editedRecordForCurrency?.[followingPath.via] && typeof editedRecordForCurrency[followingPath.via] === 'object'); + const { record: editedRecordForCurrency, state: followedParentState } = useFollowedParentRead( + followingTarget as never, + resolvedDependentValues, + dataSource, + ); + // The opening fill waits only while the parent read is out. A read that + // failed or cannot run ends the wait: what does not depend on the parent's + // code fills, and an amount that does is withheld with a note + // (`targetCurrencyUnread`). + const followedParentPending = followedParentState === 'pending'; + const followedParentUnread = followedParentState === 'unread'; const autofillCurrency = !!autofillTargets; /** The currency context of a pick of `row` (`crossCurrencyRefusal`), or none without stamped targets. */ const currencyFor = useCallback( @@ -1248,10 +1250,16 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro return { home: homeCurrency, sourceCurrency: (source, v) => pickedAmountCurrencyOf(sourceFields?.[source] as never, v, row), - targetCurrency: (target) => amountCurrencyOf(autofillTargets[target] as never, editedRecordForCurrency), + targetCurrency: (target, writes) => { + const def = autofillTargets[target]; + if (followedParentUnread && recordCurrencyPath(def as never)) { + return amountCurrencyOf(def as never) ? { kind: 'unread' } : undefined; + } + return amountCurrencyOf(def as never, editedRecordForCurrency, writes); + }, }; }, - [autofillTargets, refObjectSchema, homeCurrency, editedRecordForCurrency], + [autofillTargets, 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); @@ -2352,16 +2360,14 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro ); } - // objectstack#36249 — what the last fill left empty because the picked + // 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 is still empty. + // the target still holds what it held at the pick (empty, or the earlier + // value a re-pick left in place). const heldNow = normalizeId(value); const withheldShown = withheldFill && heldNow != null && String(heldNow) === withheldFill.picked - ? withheldFill.items.filter((w) => { - const held = resolvedDependentValues?.[w.target]; - return held === undefined || held === null || held === ''; - }) + ? withheldFill.items.filter((w) => withheldStillStands(w, resolvedDependentValues?.[w.target])) : []; const withheldLabel = (target: string): string => { const label = (autofillTargets?.[target] as { label?: unknown } | undefined)?.label; diff --git a/ui/packages/fields/src/widgets/followedParentRow.ts b/ui/packages/fields/src/widgets/followedParentRow.ts index 2d06b27f08b..4ef5b6dc28f 100644 --- a/ui/packages/fields/src/widgets/followedParentRow.ts +++ b/ui/packages/fields/src/widgets/followedParentRow.ts @@ -24,6 +24,18 @@ interface ParentSource { const isRow = (v: unknown): v is Record => v !== null && typeof v === 'object' && !Array.isArray(v); +/** + * Where the read of a followed parent stands: + * - `none`: the field follows no parent, or the record names none by id (no + * parent, or one already expanded on the record); + * - `pending`: the read for the parent the record names has not answered; + * - `read`: the parent row is laid on the record; + * - `unread`: the record names a parent whose code cannot be read here — the + * read failed or answered no row, the source cannot read (`findOne`), or the + * form stamped no parent object to read it from. + */ +export type FollowedParentState = 'none' | 'pending' | 'read' | 'unread'; + /** * `record` as the resolver should read it for `field`: unchanged unless the * field follows a parent the record names by a bare id, in which case the @@ -36,6 +48,19 @@ export function useFollowedParentRecord( record: Readonly> | null | undefined, dataSource: unknown, ): Readonly> | null | undefined { + return useFollowedParentRead(field, record, dataSource).record; +} + +/** + * {@link useFollowedParentRecord}, with where the read stands + * ({@link FollowedParentState}): a caller that waits for the parent's code + * waits only while the read is `pending`, never on a read that will not come. + */ +export function useFollowedParentRead( + field: { currencyConfig?: FieldCurrencyConfig } | null | undefined, + record: Readonly> | null | undefined, + dataSource: unknown, +): { record: Readonly> | null | undefined; state: FollowedParentState } { const ctx = useContext(SchemaRendererContext); const source = (dataSource ?? ctx?.dataSource) as ParentSource | null | undefined; const path = recordCurrencyPath(field); @@ -45,17 +70,20 @@ export function useFollowedParentRecord( const canRead = !!path && !!parentObject && id !== undefined && typeof source?.findOne === 'function'; const key = canRead ? `${parentObject}\u0000${id}` : ''; - const [answer, setAnswer] = useState<{ key: string; row: Record } | undefined>(undefined); + const [answer, setAnswer] = useState<{ key: string; row?: Record } | undefined>(undefined); useEffect(() => { if (!canRead || !source?.findOne) return; let current = true; source.findOne(parentObject!, id!, { $select: ['id', path!.codeField] }).then( - (row) => { if (current && isRow(row)) setAnswer({ key, row }); }, - () => { if (current) setAnswer(undefined); }, + (row) => { if (current) setAnswer(isRow(row) ? { key, row } : { key }); }, + () => { if (current) setAnswer({ key }); }, ); return () => { current = false; }; }, [canRead, source, parentObject, id, key, path?.codeField]); - if (!canRead || answer?.key !== key) return record; - return withFollowedParent(record ?? {}, field, answer.row) as Readonly>; + if (!path || id === undefined) return { record, state: 'none' }; + if (!canRead) return { record, state: 'unread' }; + if (answer?.key !== key) return { record, state: 'pending' }; + if (!answer.row) return { record, state: 'unread' }; + return { record: withFollowedParent(record ?? {}, field, answer.row) as Readonly>, state: 'read' }; } diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index 56e113e1247..424153bd951 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -27,6 +27,7 @@ import { type LookupAutofillByField, type WithheldAutofill, withheldAutofillMessage, + withheldStillStands, } from '../lookupAutofill.js'; import { FileCell } from '../FileField.js'; import { toDateInputValue, toDateTimeInputValue, fromDateTimeInputValue, isImpossibleStoredDay } from '../nativeDateValue.js'; @@ -476,7 +477,8 @@ function coerce(type: string | undefined, raw: string): any { * column whose child field definition the host handed over (`columnFields`) * is in that definition's currency, read on the line as the record form * reads it (`amountCurrencyOf`): a `fixed` code, the code a sibling field on - * the line holds, or the home currency. A `currency` column the host named + * the line holds (with this pick's own write to that code applied), or the + * home currency. A `currency` column the host named * nothing for is in the home currency. A column of any other type holds no * amount of money. A declared target that is not a drawn column is judged * by its child field the same way, and holds no amount when the host names @@ -495,7 +497,7 @@ function gridAutofillCurrency( home, sourceCurrency: (source, value) => pickedAmountCurrencyOf(sourceFields?.[source] as never, value, picked), - targetCurrency: (target): AmountCurrency | undefined => { + targetCurrency: (target, writes): AmountCurrency | undefined => { // A declared target need not be a drawn column: one that is not is // judged by its child field all the same, as the record form judges it. const c = columns.find((x) => x.name === target); @@ -505,7 +507,7 @@ function gridAutofillCurrency( return code ? { kind: 'code', code } : { kind: 'unset' }; } const def = columnFields?.[target]; - if (def && typeof def === 'object') return amountCurrencyOf(def as never, line) ?? (c ? { kind: 'home' } : undefined); + if (def && typeof def === 'object') return amountCurrencyOf(def as never, line, writes) ?? (c ? { kind: 'home' } : undefined); return c ? { kind: 'home' } : undefined; }, }; @@ -514,7 +516,9 @@ function gridAutofillCurrency( /** * What the last pick on one line did not copy (objectstack#36249): the lookup * column picked, the value it committed, and each withheld value. The note - * stands while the line still holds that pick and the withheld cell is empty. + * 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. */ interface WithheldPick { lookup: string; @@ -960,7 +964,8 @@ function GridFieldBody({ const pickedLookupRecords = useRef(new Map()); // The values the last pick on each line did not copy, because the picked // amount is in another currency than the cell (objectstack#36249): said - // under the line while that pick still stands and the cell is still empty. + // under the line while that pick still stands and the cell still holds + // what it held at the pick. const [withheldFills, setWithheldFills] = React.useState>(() => new Map()); const applyLookupSelection = useCallback( (rowIdx: number, col: GridColumn, record: any, picked?: { sourceFields?: Readonly> | null }) => { @@ -1726,11 +1731,11 @@ function GridFieldBody({ const isGhost = hasGhost && rowIdx === rows.length; const reorderable = allowReorder && !isGhost && !isList; // objectstack#36249 — the values this line's pick did not copy, - // while the pick stands and the cell is still empty. + // while the pick stands and the cell still holds what it held. const withheldPick = withheldFills.get(rowIdx); const withheldShown = withheldPick && !isList && String(row[withheldPick.lookup] ?? '') === String(withheldPick.picked ?? '') - ? withheldPick.items.filter((w) => row[w.target] == null || row[w.target] === '') + ? withheldPick.items.filter((w) => withheldStillStands(w, row[w.target])) : []; return ( diff --git a/ui/packages/fields/src/widgets/lookupAutofill.ts b/ui/packages/fields/src/widgets/lookupAutofill.ts index e38408f90c2..faf38ecb05a 100644 --- a/ui/packages/fields/src/widgets/lookupAutofill.ts +++ b/ui/packages/fields/src/widgets/lookupAutofill.ts @@ -1,5 +1,5 @@ import type { Field as SpecField } from '@objectstack/spec/data'; -import { resolveFieldCurrency, type FieldCurrencyConfig } from '@object-ui/i18n'; +import { recordCurrencyField, recordCurrencyPath, resolveFieldCurrency, type FieldCurrencyConfig } from '@object-ui/i18n'; import { formatCurrency } from './number-format.js'; import { withFollowedParentObject } from '../currency.js'; @@ -48,6 +48,9 @@ function sameValue(a: unknown, b: unknown): boolean { * an amount the pick would write into an amount in another currency is not * written; it is returned under `withheld`, so the host can say why the * target stayed as it was. Without `currency` every value copies as before. + * Each amount is judged against the record with this pick's own writes + * applied (`currency.targetCurrency`'s `writes`), so a pick that fills a code + * field and an amount in that code together copies both. */ export function planDeclaredLookupAutofill( pairs: readonly LookupAutofillPair[] | undefined, @@ -56,16 +59,61 @@ export function planDeclaredLookupAutofill( previous?: Values | null, currency?: AutofillCurrencyContext, ): LookupAutofillPlan { - const plan: LookupAutofillPlan = { patch: {}, withheld: [] }; - if (!pairs?.length || !picked || typeof picked !== 'object') return plan; + return judgePickWrites(declaredPickWrites(pairs, picked, current, previous), currency); +} + +/** + * The values the declared pairs would write on one pick, under the overwrite + * rule ({@link planDeclaredLookupAutofill}), before the cross-currency rule + * judges them. + */ +export function declaredPickWrites( + pairs: readonly LookupAutofillPair[] | undefined, + picked: Values | null | undefined, + current: Values | null | undefined, + previous?: Values | null, +): PickWrite[] { + const out: PickWrite[] = []; + if (!pairs?.length || !picked || typeof picked !== 'object') return out; for (const { target, source, overwrite } of pairs) { if (!(source in picked) || picked[source] === undefined) continue; const held = current?.[target]; const filledByEarlierPick = !!previous && source in previous && sameValue(held, previous[source]); if (!(overwrite === true || isEmptyValue(held) || filledByEarlierPick)) continue; - const refused = judgeCopy(currency, target, source, picked[source]); + out.push({ target, source, value: picked[source], held }); + } + return out; +} + +/** + * One value a pick would write: `value` from `source` into `target`, which + * held `held` at the pick. + */ +export interface PickWrite { + readonly target: string; + readonly source: string; + readonly value: unknown; + readonly held?: unknown; +} + +/** + * The cross-currency judgement of every value one pick would write. Each is + * judged against the record with all of this pick's writes applied (the + * `writes` `currency.targetCurrency` is handed), so the code a pick writes + * beside an amount is the code that amount is judged in. Without `currency` + * every value is written. + */ +export function judgePickWrites( + candidates: readonly PickWrite[], + currency: AutofillCurrencyContext | undefined, +): LookupAutofillPlan { + const plan: LookupAutofillPlan = { patch: {}, withheld: [] }; + 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); - else plan.patch[target] = picked[source]; + else plan.patch[c.target] = c.value; } return plan; } @@ -111,13 +159,17 @@ export function lookupAutofillByField(fields: Record | undefine * - `unset`: a `record`-mode amount whose record holds no code yet; * - `unknown`: a picked value whose field definition this host does not hold * (the referenced object's schema did not load), so its currency cannot be - * named. It is copied only into an amount in the home currency. + * named. It is copied only into an amount in the home currency; + * - `unread`: an amount that follows the code of a parent the record names, + * whose code this host could not read (the read failed, or cannot run), so + * nothing can be judged against it. */ export type AmountCurrency = | { readonly kind: 'home' } | { readonly kind: 'code'; readonly code: string } | { readonly kind: 'unset' } - | { readonly kind: 'unknown' }; + | { readonly kind: 'unknown' } + | { readonly kind: 'unread' }; const HOME: AmountCurrency = Object.freeze({ kind: 'home' }); const UNSET: AmountCurrency = Object.freeze({ kind: 'unset' }); @@ -147,13 +199,32 @@ function isMoneyDef(def: MoneyDef | null | undefined): def is MoneyDef { export function amountCurrencyOf( def: MoneyDef | null | undefined, record?: Readonly> | null, + writes?: Readonly> | null, ): AmountCurrency | undefined { if (!isMoneyDef(def)) return undefined; - const code = resolveFieldCurrency(def, undefined, record ?? null); + const code = resolveFieldCurrency(def, undefined, withCodeWrite(def, record, writes)); if (code) return { kind: 'code', code }; return def.currencyConfig?.currencyMode === 'record' ? UNSET : HOME; } +/** + * `record` with the write `writes` makes to `def`'s own code field applied: a + * pick that fills the code beside the amount puts the amount in that code. A + * parent's code is not the record's to write, so a parent path reads `record` + * as it stands. + */ +function withCodeWrite( + def: MoneyDef, + record: Readonly> | null | undefined, + writes: Readonly> | null | undefined, +): Readonly> | null { + const codeField = recordCurrencyField(def); + if (!writes || !codeField || recordCurrencyPath(def) || !Object.prototype.hasOwnProperty.call(writes, codeField)) { + return record ?? null; + } + return { ...(record ?? {}), [codeField]: writes[codeField] }; +} + /** * The currency of a picked value whose field definition may be missing: the * field's own answer when `def` is known, else `unknown` for a number (it may @@ -183,15 +254,21 @@ function codeOf(c: AmountCurrency, home: string | undefined): string | undefined * - `noTargetCurrency`: the amount being filled follows a record that holds * no currency yet; * - `noSourceCurrency`: the picked amount's currency cannot be named, while - * the amount being filled is in `to`. + * the amount being filled is in `to`; + * - `targetCurrencyUnread`: the amount being filled follows a parent whose + * code could not be read. + * + * `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. */ export interface WithheldAutofill { readonly target: string; readonly source: string; readonly amount: number; - readonly reason: 'differs' | 'noTargetCurrency' | 'noSourceCurrency'; + readonly reason: 'differs' | 'noTargetCurrency' | 'noSourceCurrency' | 'targetCurrencyUnread'; readonly from?: string; readonly to?: string; + readonly held?: unknown; } /** @@ -214,6 +291,7 @@ export function crossCurrencyRefusal( const from = codeOf(source, home); const to = codeOf(target, home); if (from && to && from === to) return undefined; + if (target.kind === 'unread') return { reason: 'targetCurrencyUnread', ...(from ? { from } : {}) }; if (target.kind === 'unset') return { reason: 'noTargetCurrency', ...(from ? { from } : {}) }; if (!from) return { reason: 'noSourceCurrency', ...(to ? { to } : {}) }; if (!to) return { reason: 'noTargetCurrency', from }; @@ -226,11 +304,13 @@ export function crossCurrencyRefusal( * on the picked record) and of each field of the record being edited * (`targetCurrency`, by target name), plus the organization's home currency. * A host that knows neither side passes no context, and every value copies as - * before. + * before. `targetCurrency` is handed this pick's own writes, by target name: a + * target whose code field the pick writes is in that code + * (`amountCurrencyOf`'s `writes`). */ export interface AutofillCurrencyContext { sourceCurrency: (source: string, value: unknown) => AmountCurrency | undefined; - targetCurrency: (target: string) => AmountCurrency | undefined; + targetCurrency: (target: string, writes?: Readonly) => AmountCurrency | undefined; home: string | undefined; } @@ -240,18 +320,27 @@ export interface LookupAutofillPlan { withheld: WithheldAutofill[]; } -/** `value` copied from `source` into `target`, or the reason it is not. */ +/** `write` judged against the record with this pick's `writes` applied, or the reason it is not copied. */ function judgeCopy( ctx: AutofillCurrencyContext | undefined, - target: string, - source: string, - value: unknown, + { target, source, value, held }: PickWrite, + writes: Readonly, ): WithheldAutofill | undefined { if (!ctx) return undefined; - const refusal = crossCurrencyRefusal(ctx.sourceCurrency(source, value), ctx.targetCurrency(target), ctx.home); + const refusal = crossCurrencyRefusal(ctx.sourceCurrency(source, value), ctx.targetCurrency(target, writes), ctx.home); if (!refusal) return undefined; const amount = typeof value === 'number' ? value : Number(value); - return { target, source, amount, ...refusal }; + return { target, source, amount, ...refusal, ...(isEmptyValue(held) ? {} : { held }) }; +} + +/** + * Whether the note about `item` still stands over `current`, the value its + * target holds now: the target still holds what it held at the pick (empty, + * or the earlier value a re-pick left in place). Once somebody writes the + * target, the note has said what it had to say. + */ +export function withheldStillStands(item: WithheldAutofill, current: unknown): boolean { + return item.held === undefined ? isEmptyValue(current) : sameValue(current, item.held); } /** The translation call a widget holds (`useFieldTranslation().t`). */ @@ -260,7 +349,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. + * 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. */ export function withheldAutofillMessage( item: WithheldAutofill, @@ -269,13 +359,15 @@ export function withheldAutofillMessage( locale: string | undefined, ): string { const amount = Number.isFinite(item.amount) ? formatCurrency(item.amount, item.from, locale) : String(item.amount); - if (item.reason === 'differs') { - return t('lookup.autofillCurrencyDiffers', { field: label, amount, from: item.from, to: item.to }); - } - if (item.reason === 'noSourceCurrency') { - return t('lookup.autofillSourceNoCurrency', { field: label, amount, to: item.to }); - } - return t('lookup.autofillNoCurrency', { field: label, amount }); + const why = + item.reason === 'differs' + ? t('lookup.autofillCurrencyDiffers', { field: label, amount, from: item.from, to: item.to }) + : item.reason === 'noSourceCurrency' + ? 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 })}`; } /** diff --git a/ui/packages/fields/src/widgets/useFieldTranslation.ts b/ui/packages/fields/src/widgets/useFieldTranslation.ts index e00abc8940b..6f1d5041dde 100644 --- a/ui/packages/fields/src/widgets/useFieldTranslation.ts +++ b/ui/packages/fields/src/widgets/useFieldTranslation.ts @@ -63,6 +63,8 @@ const FIELD_DEFAULTS: Record = { 'lookup.autofillCurrencyDiffers': '{{field}} was not filled: the picked amount is {{amount}} in {{from}}, but {{field}} here is in {{to}}. Enter it in {{to}}.', 'lookup.autofillSourceNoCurrency': '{{field}} was not filled: the picked amount {{amount}} names no currency, but {{field}} here is in {{to}}. Enter it in {{to}}.', '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.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 6481e93f10f..e4cbe8efe57 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -72,6 +72,8 @@ const ar = { autofillCurrencyDiffers: 'لم يُملأ {{field}}: المبلغ المختار هو {{amount}} بعملة {{from}}، لكن {{field}} هنا بعملة {{to}}. أدخله بعملة {{to}}.', autofillSourceNoCurrency: 'لم يُملأ {{field}}: المبلغ المختار {{amount}} لا يذكر عملة، لكن {{field}} هنا بعملة {{to}}. أدخله بعملة {{to}}.', autofillNoCurrency: 'لم يُملأ {{field}}: المبلغ المختار هو {{amount}}، لكن لم تُختر عملة هنا بعد. اختر العملة، ثم أدخل {{field}}.', + autofillCurrencyUnread: 'لم يُملأ {{field}}: المبلغ المختار هو {{amount}}، لكن تعذّرت قراءة العملة هنا. تحقّق من العملة، ثم أدخل {{field}}.', + autofillKept: 'يحتفظ {{field}} بقيمته السابقة.', }, 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 3618aa66269..ae8eb48860d 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -65,6 +65,8 @@ const de = { autofillCurrencyDiffers: '{{field}} wurde nicht ausgefüllt: Der gewählte Betrag ist {{amount}} in {{from}}, {{field}} ist hier aber in {{to}}. Geben Sie ihn in {{to}} ein.', autofillSourceNoCurrency: '{{field}} wurde nicht ausgefüllt: Der gewählte Betrag {{amount}} nennt keine Währung, {{field}} ist hier aber in {{to}}. Geben Sie ihn in {{to}} ein.', 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.', }, 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 c93b6f83dec..a58690aaa3c 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -73,6 +73,8 @@ const en = { autofillCurrencyDiffers: '{{field}} was not filled: the picked amount is {{amount}} in {{from}}, but {{field}} here is in {{to}}. Enter it in {{to}}.', autofillSourceNoCurrency: '{{field}} was not filled: the picked amount {{amount}} names no currency, but {{field}} here is in {{to}}. Enter it in {{to}}.', 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.', }, 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 f68c888e982..27558ece8ae 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -66,6 +66,8 @@ const es = { autofillCurrencyDiffers: 'No se rellenó {{field}}: el importe elegido es {{amount}} en {{from}}, pero aquí {{field}} está en {{to}}. Introdúzcalo en {{to}}.', autofillSourceNoCurrency: 'No se rellenó {{field}}: el importe elegido {{amount}} no indica moneda, pero aquí {{field}} está en {{to}}. Introdúzcalo en {{to}}.', 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.', }, 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 c42e540aaa9..8a5a1a6190a 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -66,6 +66,8 @@ const fr = { autofillCurrencyDiffers: '{{field}} n’a pas été rempli : le montant choisi est de {{amount}} en {{from}}, mais ici {{field}} est en {{to}}. Saisissez-le en {{to}}.', autofillSourceNoCurrency: '{{field}} n’a pas été rempli : le montant choisi {{amount}} n’indique aucune devise, mais ici {{field}} est en {{to}}. Saisissez-le en {{to}}.', 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.', }, 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 a1fdd70062b..113290b8083 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -65,6 +65,8 @@ const ja = { autofillCurrencyDiffers: '{{field}}は入力されませんでした。選択した金額は {{amount}}({{from}})ですが、ここでの{{field}}は {{to}} です。{{to}} で入力してください。', autofillSourceNoCurrency: '{{field}}は入力されませんでした。選択した金額 {{amount}} には通貨がありませんが、ここでの{{field}}は {{to}} です。{{to}} で入力してください。', autofillNoCurrency: '{{field}}は入力されませんでした。選択した金額は {{amount}} ですが、ここではまだ通貨が選択されていません。通貨を選択してから{{field}}を入力してください。', + autofillCurrencyUnread: '{{field}}は入力されませんでした。選択した金額は {{amount}} ですが、ここでの通貨を読み取れませんでした。通貨を確認してから{{field}}を入力してください。', + autofillKept: '{{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 25678dcb68a..44dd496cea6 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -65,6 +65,8 @@ const ko = { autofillCurrencyDiffers: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액은 {{amount}}({{from}})이지만 여기의 {{field}}은(는) {{to}} 기준입니다. {{to}}(으)로 직접 입력하세요.', autofillSourceNoCurrency: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액 {{amount}}에는 통화가 없지만 여기의 {{field}}은(는) {{to}} 기준입니다. {{to}}(으)로 직접 입력하세요.', autofillNoCurrency: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액은 {{amount}}이지만 여기에는 아직 통화가 선택되지 않았습니다. 통화를 선택한 후 {{field}}을(를) 입력하세요.', + autofillCurrencyUnread: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액은 {{amount}}이지만 여기의 통화를 읽을 수 없습니다. 통화를 확인한 후 {{field}}을(를) 입력하세요.', + autofillKept: '{{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 f200d78d394..3893d21b6a5 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -66,6 +66,8 @@ const pt = { autofillCurrencyDiffers: '{{field}} não foi preenchido: o valor escolhido é {{amount}} em {{from}}, mas aqui {{field}} está em {{to}}. Informe-o em {{to}}.', autofillSourceNoCurrency: '{{field}} não foi preenchido: o valor escolhido {{amount}} não indica moeda, mas aqui {{field}} está em {{to}}. Informe-o em {{to}}.', 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.', }, 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 0e654cd1e4b..f0ef5f33368 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -67,6 +67,8 @@ const ru = { autofillCurrencyDiffers: 'Поле «{{field}}» не заполнено: выбранная сумма — {{amount}} в {{from}}, а здесь «{{field}}» указывается в {{to}}. Введите её в {{to}}.', autofillSourceNoCurrency: 'Поле «{{field}}» не заполнено: у выбранной суммы {{amount}} не указана валюта, а здесь «{{field}}» указывается в {{to}}. Введите её в {{to}}.', autofillNoCurrency: 'Поле «{{field}}» не заполнено: выбранная сумма — {{amount}}, но валюта здесь ещё не выбрана. Выберите валюту, затем введите «{{field}}».', + autofillCurrencyUnread: 'Поле «{{field}}» не заполнено: выбранная сумма — {{amount}}, но валюту здесь не удалось прочитать. Проверьте валюту, затем введите «{{field}}».', + autofillKept: 'В поле «{{field}}» осталось прежнее значение.', }, 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 e7d97485756..ea2cfdc4ddf 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -74,6 +74,8 @@ const zh = { autofillCurrencyDiffers: '未填入{{field}}:所选金额为 {{amount}}({{from}}),而此处的{{field}}以 {{to}} 计。请按 {{to}} 手动填写。', autofillSourceNoCurrency: '未填入{{field}}:所选金额 {{amount}} 未注明币种,而此处的{{field}}以 {{to}} 计。请按 {{to}} 手动填写。', autofillNoCurrency: '未填入{{field}}:所选金额为 {{amount}},但此处尚未选择币种。请先选择币种,再填写{{field}}。', + autofillCurrencyUnread: '未填入{{field}}:所选金额为 {{amount}},但无法读取此处的币种。请先确认币种,再填写{{field}}。', + autofillKept: '{{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 39fba0d8405..a6820eb944e 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -74,6 +74,8 @@ const zhHant = { autofillCurrencyDiffers: '未填入{{field}}:所選金額為 {{amount}}({{from}}),而此處的{{field}}以 {{to}} 計。請按 {{to}} 手動填寫。', autofillSourceNoCurrency: '未填入{{field}}:所選金額 {{amount}} 未註明幣種,而此處的{{field}}以 {{to}} 計。請按 {{to}} 手動填寫。', autofillNoCurrency: '未填入{{field}}:所選金額為 {{amount}},但此處尚未選擇幣種。請先選擇幣種,再填寫{{field}}。', + autofillCurrencyUnread: '未填入{{field}}:所選金額為 {{amount}},但無法讀取此處的幣種。請先確認幣種,再填寫{{field}}。', + autofillKept: '{{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 635d7e01a3c..4c9648761bf 100644 --- a/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx @@ -437,3 +437,237 @@ describe('ObjectForm — a pick does not copy an amount into a field in another expect(price?.value ?? '').toBe(''); }); }); + +describe('ObjectForm — cross-currency pick follow-ups (objectstack#36412)', () => { + const recordPrice = (currencyField: string) => ({ + type: 'currency', + label: 'Unit Price', + currencyConfig: { currencyMode: 'record', currencyField }, + }); + const SCHEMAS_36412: Record = { + // A quote whose price follows its own code; a pick may write the price over a typed one. + ow_quote: { + name: 'ow_quote', + fields: { + currency_code: { type: 'text', label: 'Currency' }, + product: { + type: 'lookup', + label: 'Product', + reference: 'cc_product', + lookupAutofill: [ + { target: 'unit_price', source: 'list_price', overwrite: true }, + { target: 'description', source: 'summary' }, + ], + }, + unit_price: recordPrice('currency_code'), + description: { type: 'text', label: 'Description' }, + }, + }, + // A quote whose pick copies the product's code and its price together. + cc_quote: { + name: 'cc_quote', + fields: { + currency_code: { type: 'text', label: 'Currency' }, + product: { + type: 'lookup', + label: 'Product', + reference: 'cc_product', + lookupAutofill: [ + { target: 'currency_code', source: 'currency_code' }, + { target: 'unit_price', source: 'list_price' }, + ], + }, + unit_price: recordPrice('currency_code'), + }, + }, + // Control: the same quote, whose pick does not copy the code. + nc_quote: { + name: 'nc_quote', + fields: { + currency_code: { type: 'text', label: 'Currency' }, + product: { + type: 'lookup', + label: 'Product', + reference: 'cc_product', + lookupAutofill: [{ target: 'unit_price', source: 'list_price' }], + }, + unit_price: recordPrice('currency_code'), + }, + }, + // A line whose price follows its header's code (ADR-0144 D2 as amended). + fp_line: { + name: 'fp_line', + fields: { + invoice: { type: 'master_detail', label: 'Invoice', reference: 'fp_invoice' }, + product: { + type: 'lookup', + label: 'Product', + reference: 'fx_product', + lookupAutofill: [ + { target: 'unit_price', source: 'list_price' }, + { target: 'description', source: 'summary' }, + ], + }, + unit_price: recordPrice('invoice.currency_code'), + description: { type: 'text', label: 'Description' }, + }, + }, + fp_invoice: { name: 'fp_invoice', fields: { name: { type: 'text', label: 'Name' }, currency_code: { type: 'text', label: 'Currency' } } }, + fx_product: { + name: 'fx_product', + fields: { + name: { type: 'text', label: 'Name' }, + list_price: { type: 'currency', label: 'List Price' }, + summary: { type: 'text', label: 'Summary' }, + }, + }, + cc_product: { + name: 'cc_product', + fields: { + name: { type: 'text', label: 'Name' }, + currency_code: { type: 'text', label: 'Currency' }, + list_price: recordPrice('currency_code'), + summary: { type: 'text', label: 'Summary' }, + }, + }, + }; + const ROWS_36412: Record[]> = { + fx_product: [{ id: 'p1', name: 'Widget', list_price: 100, summary: 'A widget' }], + cc_product: [{ id: 'p1', name: 'Widget', currency_code: 'EUR', list_price: 100, summary: 'A widget' }], + fp_invoice: [{ id: 'h1', name: 'INV-1', currency_code: 'USD' }], + }; + const makeDS36412 = (parentRead: 'answers' | 'fails' | 'none' = 'answers') => { + const ds: Record = { + getObjectSchema: vi.fn(async (name: string) => SCHEMAS_36412[name]), + find: vi.fn(async (name: string, params?: { $filter?: { id?: { $in?: unknown[] } } }) => { + const wanted = params?.$filter?.id?.$in; + const rows = (ROWS_36412[name] ?? []).filter((r) => !wanted || wanted.includes(r.id)); + return { data: rows.map((r) => ({ ...r })), total: rows.length }; + }), + create: vi.fn(async (_o: string, d: Record) => ({ id: 'n1', ...d })), + update: vi.fn(), + }; + if (parentRead !== 'none') { + ds.findOne = vi.fn(async (name: string, id: string) => { + if (name === 'fp_invoice' && parentRead === 'fails') throw new Error('network down'); + const row = (ROWS_36412[name] ?? []).find((r) => r.id === id); + return row ? { ...row } : null; + }); + } + return ds; + }; + + function renderOn(objectName: string, initialValues: Record, parentRead?: 'answers' | 'fails' | 'none') { + const ds = makeDS36412(parentRead); + const view = render( + + + + + , + ); + return { ds, container: view.container }; + } + const valueOf = (c: HTMLElement, name: string) => (c.querySelector(`input[name="${name}"]`) as HTMLInputElement | null)?.value ?? ''; + + it('a pick over a filled amount in another currency keeps it and says so', async () => { + const { container } = renderOn('ow_quote', { currency_code: 'JPY', unit_price: 80 }); + await input(container, 'description'); + await pick('product', 'Widget'); + + await waitFor(() => expect(valueOf(container, 'description')).toBe('A widget')); + const note = await screen.findByTestId('lookup-autofill-withheld'); + expect(note.querySelector('[data-withheld-target="unit_price"]')?.textContent).toContain('Unit Price still holds its earlier value.'); + expect(note.textContent).toContain('JPY'); + expect(valueOf(container, 'unit_price')).toContain('80'); + }); + + it('control: the same pick over a filled amount in its own currency replaces it, with no note', async () => { + const { container } = renderOn('ow_quote', { currency_code: 'EUR', unit_price: 80 }); + await input(container, 'description'); + await pick('product', 'Widget'); + + await waitFor(() => expect(valueOf(container, 'unit_price')).toContain('100')); + expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); + }); + + it('a pick that copies the code and the price together copies both onto a quote with no code yet', async () => { + // The create form seeds a code field with the home currency: cleared here. + const { container } = renderOn('cc_quote', { currency_code: null }); + await input(container, 'currency_code'); + await pick('product', 'Widget'); + + await waitFor(() => expect(valueOf(container, 'currency_code')).toBe('EUR')); + await waitFor(() => expect(valueOf(container, 'unit_price')).toContain('100')); + expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); + }); + + it('control: a pick that does not copy the code leaves the price empty and says no currency is chosen', async () => { + const { container } = renderOn('nc_quote', { currency_code: null }); + await input(container, 'currency_code'); + await pick('product', 'Widget'); + + const note = await screen.findByTestId('lookup-autofill-withheld'); + expect(note.textContent).toContain('no currency is chosen'); + expect(valueOf(container, 'unit_price')).toBe(''); + }); + + it('the opening fill does not wait for a parent read that failed: the description fills, the price says why', async () => { + const { container } = renderOn('fp_line', { invoice: 'h1', product: 'p1' }, 'fails'); + await waitFor(() => expect(valueOf(container, 'description')).toBe('A widget')); + const note = await screen.findByTestId('lookup-autofill-withheld'); + expect(note.textContent).toContain('the currency here could not be read'); + expect(valueOf(container, 'unit_price')).toBe(''); + }); + + it('the opening fill does not wait for a parent read that cannot run (no findOne)', async () => { + const { container } = renderOn('fp_line', { invoice: 'h1', product: 'p1' }, 'none'); + await waitFor(() => expect(valueOf(container, 'description')).toBe('A widget')); + expect((await screen.findByTestId('lookup-autofill-withheld')).textContent).toContain('the currency here could not be read'); + }); + + // Every layout a record form draws through stamps the targets + // (`gateFormFields` → `stampRecordFormFields`), so the rule reaches each. + const HOST_LAYOUTS: Array<{ layout: string; schema: Record }> = [ + { layout: 'simple / flat (default arm)', schema: {} }, + { layout: 'simple / sections (default arm)', schema: { sections: [{ name: 'main', label: 'Main', fields: ['currency_code', 'product', 'unit_price'] }] } }, + { layout: 'drawer (DrawerForm)', schema: { formType: 'drawer' } }, + { layout: 'modal (ModalForm)', schema: { formType: 'modal' } }, + { layout: 'tabbed (TabbedForm)', schema: { formType: 'tabbed', sections: [{ name: 'main', label: 'Main', fields: ['currency_code', 'product', 'unit_price'] }] } }, + { layout: 'wizard (WizardForm)', schema: { formType: 'wizard', sections: [{ name: 'main', label: 'Main', fields: ['currency_code', 'product', 'unit_price'] }] } }, + ]; + for (const { layout, schema } of HOST_LAYOUTS) { + it(`every record-form host judges the pick: ${layout} withholds a EUR price from a JPY quote, and fills a EUR one`, async () => { + for (const [code, fills] of [['JPY', false], ['EUR', true]] as const) { + const ds = makeDS36412(); + const view = render( + + + + + , + ); + await input(document.body, 'currency_code'); + await pick('product', 'Widget'); + if (fills) { + await waitFor(() => expect(valueOf(document.body, 'unit_price')).toContain('100')); + expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); + } else { + expect((await screen.findByTestId('lookup-autofill-withheld')).textContent).toContain('JPY'); + expect(valueOf(document.body, 'unit_price')).toBe(''); + } + view.unmount(); + } + }); + } + + it('control: a parent read that answers fills the price in its code, with no note', async () => { + const { container } = renderOn('fp_line', { invoice: 'h1', product: 'p1' }, 'answers'); + await waitFor(() => expect(valueOf(container, 'description')).toBe('A widget')); + await waitFor(() => expect(valueOf(container, 'unit_price')).toContain('100')); + expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-form/src/recordFormStamp.ts b/ui/packages/plugin-form/src/recordFormStamp.ts index f688c4c31af..49d03fbcb6b 100644 --- a/ui/packages/plugin-form/src/recordFormStamp.ts +++ b/ui/packages/plugin-form/src/recordFormStamp.ts @@ -32,6 +32,13 @@ * (objectstack#36249), and a target's currency is its definition's. A * target the form draws carries the name the form shows for it, so the * note about a target it did not fill names it the same way. + * - The hosts this reaches are every record-form layout: `ObjectForm`'s + * simple and sectioned arms, `TabbedForm`, `WizardForm`, `ModalForm` and + * `DrawerForm`, and the forms drawn through `ObjectForm` (`MasterDetailForm`'s + * header and line form, `EmbeddableForm`). A line-item grid judges its own + * picks (`GridField`). A standalone `form` node drawn outside these hosts + * holds no object field map, is not stamped, and its lookup copies as it + * always did. */ import { RECORD_BEING_EDITED_KEY, withLookupAutofillTargets, withRecordBeingEdited } from '@object-ui/fields';