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
17 changes: 17 additions & 0 deletions .changeset/36412-currency-change-notes.md
Original file line number Diff line number Diff line change
@@ -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.
150 changes: 150 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 @@ -35,6 +35,8 @@ import {
lookupAutofillByField,
pickedAmountCurrencyOf,
planDeclaredLookupAutofill,
copiedAutofillNow,
withheldAutofillNow,
} from './lookupAutofill';

afterEach(cleanup);
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<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: drawn } as never} columnCurrencies={{ unit_price: header }} />
<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);
});
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(<Line header="EUR" />);
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(<Line header="USD" />);
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(<Line header="EUR" />);
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(<Line header="JPY" />);
await pickProduct();
expect(withheldNote()?.textContent).toContain('here is in JPY');

view.rerender(<Line header="GBP" />);
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(<Line header="USD" />);
await pickProduct();
expect(withheldNote()?.textContent).toContain('here is in USD');

view.rerender(<Line header="EUR" />);
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(<Line header="USD" line={{ unit_price: 80 }} />);
await pickProduct();
expect(withheldNote()?.textContent).toContain('Unit Price still holds its earlier value.');

view.rerender(<Line header="EUR" />);
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(<Line header="EUR" />);
fireEvent.change(screen.getAllByLabelText('Unit Price')[0], { target: { value: '70' } });
await waitFor(() => expect(rowsNow()[0].unit_price).toBe(70));
view.rerender(<Line header="USD" />);
expect(rowsNow()[0].unit_price).toBe(70);
expect(copiedNote()).toBeNull();
expect(withheldNote()).toBeNull();

cleanup();

const over = render(<Line header="EUR" />);
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(<Line header="USD" />);
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');
});
});
2 changes: 1 addition & 1 deletion ui/packages/fields/src/widgets/GridField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
60 changes: 47 additions & 13 deletions ui/packages/fields/src/widgets/LookupField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,12 @@ import {
planDeclaredLookupAutofill,
readLookupAutofillTargets,
withheldAutofillMessage,
withheldAutofillNow,
withheldStillStands,
copiedAutofillMessage,
copiedAutofillNow,
type AutofillCurrencyContext,
type CopiedAutofill,
type LookupAutofillPair,
type WithheldAutofill,
} from './lookupAutofill.js';
Expand Down Expand Up @@ -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);
}, []);

/**
Expand All @@ -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],
Expand Down Expand Up @@ -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]);

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -2665,6 +2690,15 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
))}
</div>
)}
{copiedShown.length > 0 && (
<div className="text-xs text-muted-foreground" role="status" data-testid="lookup-autofill-copied">
{copiedShown.map(({ item, now }) => (
<p key={item.target} data-copied-target={item.target}>
{copiedAutofillMessage(item, now, withheldLabel(item.target), t, displayLocale)}
</p>
))}
</div>
)}

{recordPickerDialog}
</div>
Expand Down
Loading
Loading