Skip to content

Commit be29e2d

Browse files
committed
wip(fields): cross-currency pick follow-ups — re-pick note, bounded wait, code-plus-amount pick
Claude-Session: https://claude.ai/code/session_01WGufzhoBbwh8URjwQHde8v Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 7a5ae65 commit be29e2d

17 files changed

Lines changed: 224 additions & 70 deletions

File tree

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

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ import React from 'react';
55
import type { InlineGridColumn } from '@objectstack/spec/data';
66
import { resolveFieldCurrency, currencyFractionDigits } from '../currency.js';
77
import {
8-
crossCurrencyRefusal,
9-
planDeclaredLookupAutofill,
8+
declaredPickWrites,
9+
judgePickWrites,
1010
type AutofillCurrencyContext,
1111
type LookupAutofillPair,
1212
type LookupAutofillPlan,
13-
type WithheldAutofill,
13+
type PickWrite,
1414
} from './lookupAutofill.js';
1515
import { fieldHelpText } from '../fieldHelpText.js';
1616
// 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 {
218218
* `currency` is the pick's cross-currency rule (`crossCurrencyRefusal`): a
219219
* value it refuses is left out of the patch, the same-named copy and the
220220
* declared pairs alike, and listed under `withheld` so the grid says why the
221-
* cell stayed empty. Without it every value copies as before.
221+
* cell stayed as it was. Every value is judged against the line with all of
222+
* this pick's writes applied (`judgePickWrites`), so a code the pick copies
223+
* puts the amount beside it in that code. Without it every value copies as
224+
* before.
222225
*/
223226
export function planLookupAutofill(
224227
columns: GridColumn[],
@@ -227,24 +230,20 @@ export function planLookupAutofill(
227230
declared?: { pairs?: readonly LookupAutofillPair[]; row?: Row; previous?: Row | null },
228231
currency?: AutofillCurrencyContext,
229232
): LookupAutofillPlan {
230-
const patch: Row = { [col.name]: record?.value ?? record?.id ?? record?._id };
231-
const withheld: WithheldAutofill[] = [];
233+
const writes: PickWrite[] = [];
232234
const declaredTargets = new Set((declared?.pairs ?? []).map((p) => p.target));
233235
if (col.autofill !== false && record && typeof record === 'object') {
234236
for (const other of columns) {
235237
if (other.name === col.name || other.computed || other.type === 'lookup') continue;
236238
if (declaredTargets.has(other.name)) continue;
237239
const v = record[other.name];
238240
if (v === undefined || v === null || v === '') continue;
239-
const refusal = currency
240-
? crossCurrencyRefusal(currency.sourceCurrency(other.name, v), currency.targetCurrency(other.name), currency.home)
241-
: undefined;
242-
if (refusal) withheld.push({ target: other.name, source: other.name, amount: Number(v), ...refusal });
243-
else patch[other.name] = v;
241+
writes.push({ target: other.name, source: other.name, value: v, held: declared?.row?.[other.name] });
244242
}
245243
}
246-
const pairs = planDeclaredLookupAutofill(declared?.pairs, record, declared?.row, declared?.previous, currency);
247-
return { patch: { ...patch, ...pairs.patch }, withheld: [...withheld, ...pairs.withheld] };
244+
writes.push(...declaredPickWrites(declared?.pairs, record, declared?.row, declared?.previous));
245+
const plan = judgePickWrites(writes, currency);
246+
return { patch: { [col.name]: record?.value ?? record?.id ?? record?._id, ...plan.patch }, withheld: plan.withheld };
248247
}
249248

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

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

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,12 @@ import {
4242
planDeclaredLookupAutofill,
4343
readLookupAutofillTargets,
4444
withheldAutofillMessage,
45+
withheldStillStands,
4546
type AutofillCurrencyContext,
4647
type LookupAutofillPair,
4748
type WithheldAutofill,
4849
} from './lookupAutofill.js';
49-
import { useFollowedParentRecord } from './followedParentRow.js';
50+
import { useFollowedParentRead } from './followedParentRow.js';
5051
import { getCellRendererResolver } from './_cell-renderer-bridge.js';
5152
// The one place a lookup column's display value is decided — shared with the
5253
// "browse all records" picker (RecordPickerDialog) so a single `lookupColumns`
@@ -1229,16 +1230,17 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
12291230
() => (autofillTargets ? Object.values(autofillTargets).find((d) => recordCurrencyPath(d as never)) : undefined),
12301231
[autofillTargets],
12311232
);
1232-
const editedRecordForCurrency = useFollowedParentRecord(followingTarget as never, resolvedDependentValues, dataSource);
1233-
const followingPath = followingTarget ? recordCurrencyPath(followingTarget as never) : undefined;
1234-
const followedParentHeld = followingPath ? resolvedDependentValues?.[followingPath.via] : undefined;
1235-
// The parent read has not landed yet: the record names a parent by its id,
1236-
// and its code is not on the record the resolver reads.
1237-
const followedParentPending =
1238-
!!followingPath &&
1239-
(typeof followedParentHeld === 'string' || typeof followedParentHeld === 'number') &&
1240-
followedParentHeld !== '' &&
1241-
!(editedRecordForCurrency?.[followingPath.via] && typeof editedRecordForCurrency[followingPath.via] === 'object');
1233+
const { record: editedRecordForCurrency, state: followedParentState } = useFollowedParentRead(
1234+
followingTarget as never,
1235+
resolvedDependentValues,
1236+
dataSource,
1237+
);
1238+
// The opening fill waits only while the parent read is out. A read that
1239+
// failed or cannot run ends the wait: what does not depend on the parent's
1240+
// code fills, and an amount that does is withheld with a note
1241+
// (`targetCurrencyUnread`).
1242+
const followedParentPending = followedParentState === 'pending';
1243+
const followedParentUnread = followedParentState === 'unread';
12421244
const autofillCurrency = !!autofillTargets;
12431245
/** The currency context of a pick of `row` (`crossCurrencyRefusal`), or none without stamped targets. */
12441246
const currencyFor = useCallback(
@@ -1248,10 +1250,16 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
12481250
return {
12491251
home: homeCurrency,
12501252
sourceCurrency: (source, v) => pickedAmountCurrencyOf(sourceFields?.[source] as never, v, row),
1251-
targetCurrency: (target) => amountCurrencyOf(autofillTargets[target] as never, editedRecordForCurrency),
1253+
targetCurrency: (target, writes) => {
1254+
const def = autofillTargets[target];
1255+
if (followedParentUnread && recordCurrencyPath(def as never)) {
1256+
return amountCurrencyOf(def as never) ? { kind: 'unread' } : undefined;
1257+
}
1258+
return amountCurrencyOf(def as never, editedRecordForCurrency, writes);
1259+
},
12521260
};
12531261
},
1254-
[autofillTargets, refObjectSchema, homeCurrency, editedRecordForCurrency],
1262+
[autofillTargets, refObjectSchema, homeCurrency, editedRecordForCurrency, followedParentUnread],
12551263
);
12561264
/** What the last fill left empty, for the record it picked; said under the field. */
12571265
const [withheldFill, setWithheldFill] = useState<{ picked: string; items: readonly WithheldAutofill[] } | null>(null);
@@ -2352,16 +2360,14 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
23522360
);
23532361
}
23542362

2355-
// objectstack#36249 — what the last fill left empty because the picked
2363+
// objectstack#36249 — what the last fill did not copy because the picked
23562364
// amount is in another currency, while the field still holds that pick and
2357-
// the target is still empty.
2365+
// the target still holds what it held at the pick (empty, or the earlier
2366+
// value a re-pick left in place).
23582367
const heldNow = normalizeId(value);
23592368
const withheldShown =
23602369
withheldFill && heldNow != null && String(heldNow) === withheldFill.picked
2361-
? withheldFill.items.filter((w) => {
2362-
const held = resolvedDependentValues?.[w.target];
2363-
return held === undefined || held === null || held === '';
2364-
})
2370+
? withheldFill.items.filter((w) => withheldStillStands(w, resolvedDependentValues?.[w.target]))
23652371
: [];
23662372
const withheldLabel = (target: string): string => {
23672373
const label = (autofillTargets?.[target] as { label?: unknown } | undefined)?.label;

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

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ interface ParentSource {
2424

2525
const isRow = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);
2626

27+
/**
28+
* Where the read of a followed parent stands:
29+
* - `none`: the field follows no parent, or the record names none by id (no
30+
* parent, or one already expanded on the record);
31+
* - `pending`: the read for the parent the record names has not answered;
32+
* - `read`: the parent row is laid on the record;
33+
* - `unread`: the record names a parent whose code cannot be read here — the
34+
* read failed or answered no row, the source cannot read (`findOne`), or the
35+
* form stamped no parent object to read it from.
36+
*/
37+
export type FollowedParentState = 'none' | 'pending' | 'read' | 'unread';
38+
2739
/**
2840
* `record` as the resolver should read it for `field`: unchanged unless the
2941
* field follows a parent the record names by a bare id, in which case the
@@ -36,6 +48,19 @@ export function useFollowedParentRecord(
3648
record: Readonly<Record<string, unknown>> | null | undefined,
3749
dataSource: unknown,
3850
): Readonly<Record<string, unknown>> | null | undefined {
51+
return useFollowedParentRead(field, record, dataSource).record;
52+
}
53+
54+
/**
55+
* {@link useFollowedParentRecord}, with where the read stands
56+
* ({@link FollowedParentState}): a caller that waits for the parent's code
57+
* waits only while the read is `pending`, never on a read that will not come.
58+
*/
59+
export function useFollowedParentRead(
60+
field: { currencyConfig?: FieldCurrencyConfig } | null | undefined,
61+
record: Readonly<Record<string, unknown>> | null | undefined,
62+
dataSource: unknown,
63+
): { record: Readonly<Record<string, unknown>> | null | undefined; state: FollowedParentState } {
3964
const ctx = useContext(SchemaRendererContext);
4065
const source = (dataSource ?? ctx?.dataSource) as ParentSource | null | undefined;
4166
const path = recordCurrencyPath(field);
@@ -45,17 +70,20 @@ export function useFollowedParentRecord(
4570
const canRead = !!path && !!parentObject && id !== undefined && typeof source?.findOne === 'function';
4671
const key = canRead ? `${parentObject}\u0000${id}` : '';
4772

48-
const [answer, setAnswer] = useState<{ key: string; row: Record<string, unknown> } | undefined>(undefined);
73+
const [answer, setAnswer] = useState<{ key: string; row?: Record<string, unknown> } | undefined>(undefined);
4974
useEffect(() => {
5075
if (!canRead || !source?.findOne) return;
5176
let current = true;
5277
source.findOne(parentObject!, id!, { $select: ['id', path!.codeField] }).then(
53-
(row) => { if (current && isRow(row)) setAnswer({ key, row }); },
54-
() => { if (current) setAnswer(undefined); },
78+
(row) => { if (current) setAnswer(isRow(row) ? { key, row } : { key }); },
79+
() => { if (current) setAnswer({ key }); },
5580
);
5681
return () => { current = false; };
5782
}, [canRead, source, parentObject, id, key, path?.codeField]);
5883

59-
if (!canRead || answer?.key !== key) return record;
60-
return withFollowedParent(record ?? {}, field, answer.row) as Readonly<Record<string, unknown>>;
84+
if (!path || id === undefined) return { record, state: 'none' };
85+
if (!canRead) return { record, state: 'unread' };
86+
if (answer?.key !== key) return { record, state: 'pending' };
87+
if (!answer.row) return { record, state: 'unread' };
88+
return { record: withFollowedParent(record ?? {}, field, answer.row) as Readonly<Record<string, unknown>>, state: 'read' };
6189
}

‎ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
type LookupAutofillByField,
2828
type WithheldAutofill,
2929
withheldAutofillMessage,
30+
withheldStillStands,
3031
} from '../lookupAutofill.js';
3132
import { FileCell } from '../FileField.js';
3233
import { toDateInputValue, toDateTimeInputValue, fromDateTimeInputValue, isImpossibleStoredDay } from '../nativeDateValue.js';
@@ -476,7 +477,8 @@ function coerce(type: string | undefined, raw: string): any {
476477
* column whose child field definition the host handed over (`columnFields`)
477478
* is in that definition's currency, read on the line as the record form
478479
* reads it (`amountCurrencyOf`): a `fixed` code, the code a sibling field on
479-
* the line holds, or the home currency. A `currency` column the host named
480+
* the line holds (with this pick's own write to that code applied), or the
481+
* home currency. A `currency` column the host named
480482
* nothing for is in the home currency. A column of any other type holds no
481483
* amount of money. A declared target that is not a drawn column is judged
482484
* by its child field the same way, and holds no amount when the host names
@@ -495,7 +497,7 @@ function gridAutofillCurrency(
495497
home,
496498
sourceCurrency: (source, value) =>
497499
pickedAmountCurrencyOf(sourceFields?.[source] as never, value, picked),
498-
targetCurrency: (target): AmountCurrency | undefined => {
500+
targetCurrency: (target, writes): AmountCurrency | undefined => {
499501
// A declared target need not be a drawn column: one that is not is
500502
// judged by its child field all the same, as the record form judges it.
501503
const c = columns.find((x) => x.name === target);
@@ -505,7 +507,7 @@ function gridAutofillCurrency(
505507
return code ? { kind: 'code', code } : { kind: 'unset' };
506508
}
507509
const def = columnFields?.[target];
508-
if (def && typeof def === 'object') return amountCurrencyOf(def as never, line) ?? (c ? { kind: 'home' } : undefined);
510+
if (def && typeof def === 'object') return amountCurrencyOf(def as never, line, writes) ?? (c ? { kind: 'home' } : undefined);
509511
return c ? { kind: 'home' } : undefined;
510512
},
511513
};
@@ -514,7 +516,9 @@ function gridAutofillCurrency(
514516
/**
515517
* What the last pick on one line did not copy (objectstack#36249): the lookup
516518
* column picked, the value it committed, and each withheld value. The note
517-
* stands while the line still holds that pick and the withheld cell is empty.
519+
* stands while the line still holds that pick and the withheld cell still
520+
* holds what it held at the pick (`withheldStillStands`): empty, or the
521+
* earlier value a re-pick left in place.
518522
*/
519523
interface WithheldPick {
520524
lookup: string;
@@ -960,7 +964,8 @@ function GridFieldBody({
960964
const pickedLookupRecords = useRef(new Map<string, Row>());
961965
// The values the last pick on each line did not copy, because the picked
962966
// amount is in another currency than the cell (objectstack#36249): said
963-
// under the line while that pick still stands and the cell is still empty.
967+
// under the line while that pick still stands and the cell still holds
968+
// what it held at the pick.
964969
const [withheldFills, setWithheldFills] = React.useState<ReadonlyMap<number, WithheldPick>>(() => new Map());
965970
const applyLookupSelection = useCallback(
966971
(rowIdx: number, col: GridColumn, record: any, picked?: { sourceFields?: Readonly<Record<string, unknown>> | null }) => {
@@ -1726,11 +1731,11 @@ function GridFieldBody({
17261731
const isGhost = hasGhost && rowIdx === rows.length;
17271732
const reorderable = allowReorder && !isGhost && !isList;
17281733
// objectstack#36249 — the values this line's pick did not copy,
1729-
// while the pick stands and the cell is still empty.
1734+
// while the pick stands and the cell still holds what it held.
17301735
const withheldPick = withheldFills.get(rowIdx);
17311736
const withheldShown =
17321737
withheldPick && !isList && String(row[withheldPick.lookup] ?? '') === String(withheldPick.picked ?? '')
1733-
? withheldPick.items.filter((w) => row[w.target] == null || row[w.target] === '')
1738+
? withheldPick.items.filter((w) => withheldStillStands(w, row[w.target]))
17341739
: [];
17351740
return (
17361741
<React.Fragment key={rowIdx}>

0 commit comments

Comments
 (0)