Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/36412-cross-currency-pick-followups.md
Original file line number Diff line number Diff line change
@@ -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.
161 changes: 161 additions & 0 deletions ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> = { currency_code: { type: 'text' }, unit_price: recordPrice };
const productDefs: Record<string, unknown> = { currency_code: { type: 'text' }, unit_price: recordPrice };
const context = (line: Record<string, unknown>) => ({
home: 'USD',
sourceCurrency: (source: string, v: unknown) => pickedAmountCurrencyOf(productDefs[source] as never, v, product),
targetCurrency: (target: string, writes?: Readonly<Record<string, unknown>>) => 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<string, string | undefined>; line?: Record<string, unknown> }) {
const [rows, setRows] = React.useState<Record<string, unknown>[]>([{ product: null, description: null, unit_price: null, ...line }]);
return (
<LocalizationProvider value={{ currency: 'USD' }}>
<SchemaRendererContext.Provider value={{ dataSource: ds } as never}>
<GridField
value={rows}
onChange={(next: Record<string, unknown>[]) => setRows(next)}
field={{ columns } as never}
columnCurrencies={currency}
columnFields={{ unit_price: recordPrice }}
/>
<output data-testid="rows">{JSON.stringify(rows)}</output>
</SchemaRendererContext.Provider>
</LocalizationProvider>
);
}
const rowsNow = () => JSON.parse(screen.getByTestId('rows').textContent || '[]');

async function pickProduct(): Promise<void> {
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(<Line />);
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(<Line columns={drawn.filter((c) => 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(<Line columns={drawn.filter((c) => 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(<Line columns={drawn.filter((c) => 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');
});
});
});
25 changes: 12 additions & 13 deletions ui/packages/fields/src/widgets/GridField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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[],
Expand All @@ -227,24 +230,20 @@ 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) {
if (other.name === col.name || other.computed || other.type === 'lookup') continue;
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. */
Expand Down
Loading
Loading