diff --git a/.changeset/36249-cross-currency-pick.md b/.changeset/36249-cross-currency-pick.md new file mode 100644 index 00000000000..d7f2f7efad7 --- /dev/null +++ b/.changeset/36249-cross-currency-pick.md @@ -0,0 +1,32 @@ +--- +'@objectstack/spec': minor +'@object-ui/fields': minor +'@object-ui/i18n': minor +'@object-ui/plugin-form': minor +--- + +fix(fields): a lookup pick no longer copies an amount into a field in another currency; the field stays empty and the form says why + +Clause-②: yes (narrowing) — a cross-currency price copy that happens today stops and the line is left empty with a stated reason (ruled B); widened: three new `@object-ui/i18n` `lookup.autofill*` keys in every locale pack, new `@object-ui/fields` exports from `lookupAutofill.ts` (`planDeclaredLookupAutofill`, `crossCurrencyRefusal`, `amountCurrencyOf`, `pickedAmountCurrencyOf`, `withheldAutofillMessage`, `withLookupAutofillTargets`, `readLookupAutofillTargets`, `LOOKUP_AUTOFILL_TARGETS_KEY` and their types), an optional second argument on `onSelectRecord`, an optional trailing `currency` parameter on `declaredLookupAutofillPatch` and `lookupAutofillPatch`, and the optional `columnFields` prop on `GridField` +Metadata-protocol: semantic + + + +**BREAKING** for forms and line-item grids that relied on a pick copying an amount across currencies. On a EUR invoice, picking a product whose price is in the home currency used to copy the number as euros (a $100 product became a €100 line). Nothing converted it. Now the price is not copied: the cell or field stays empty, and a note under the line (in a grid) or under the lookup (in a form) names the picked amount with its currency and the currency of the field, so the price can be entered by hand. The other fields of the same pick (a description) still fill. + +**The rule.** It applies to the grid's same-named copy (the column key `autofill`), to the grid's declared `lookupAutofill` pairs, and to the record form's declared pairs, on a pick and on a create form's opening fill: + +- an amount is a `currency` field or a `formula` returning `currency`; a `number` carries no currency and copies as before; +- both sides in the home currency (neither declares one) copy as before, also when no home currency is configured; +- otherwise the value copies only when both sides name the same known code: a `fixed` code, the code the record holds, or the code its `master_detail` parent holds (ADR-0144 D2 as amended), with the home currency counting as its configured code; +- a field that follows a record's currency while that record holds none yet is not filled, and the note says no currency is chosen yet. + +Nothing is converted at any rate, and no build-time check is added: the line's currency is known only while the form is open. + +**`@objectstack/spec`.** The describes of `FieldSchema.lookupAutofill` and of the inline grid column key `autofill` state the rule. + +**`@object-ui/fields`.** `planDeclaredLookupAutofill` returns the writes and the withheld values of a pick; `declaredLookupAutofillPatch` and `lookupAutofillPatch` keep returning the writes alone. `LookupField` hands a host that owns the pick (`onSelectRecord`) the referenced object's field map as a second argument. `GridField` takes `columnFields`, the child field behind each currency column, so a `fixed` code or a code on the line decides that column's currency as on the record form. + +**`@object-ui/plugin-form`.** The record form stamps the definitions of a lookup's `lookupAutofill` targets on the lookup's field metadata, each with the name the form shows for it, so the lookup can read each target's currency and names it as the form does. The line-item hosts hand their grid each currency column's child field. + +**`@object-ui/i18n`.** Three new `lookup.autofill*` sentences, in every locale pack. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 7e7509c9e49..1a4a8ef7103 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -296,6 +296,13 @@ product's `list_price`. - **Overwrite rule.** By default a pick never replaces a value somebody wrote: the target is filled only while it is empty or still holds the value an earlier pick filled in. A pair with `overwrite: true` replaces the target on every pick. +- **Currency rule.** An amount of money (a `currency` field, or a `formula` returning + `currency`) is copied only into a target in the same currency: both in the home + currency, or both naming the same code (a `fixed` code, or the code the record or + its `master_detail` parent holds). Otherwise the target is left as it is and the + form says why, naming both currencies and the picked amount so the price can be + entered by hand. Nothing is converted. A `number` carries no currency and copies + as before. The grid's same-named copy follows the same rule. - **Client-side only.** The fill edits the form, and the filled value is saved as an ordinary write. Nothing on the write path reads the key: an import or an API write that sets the lookup fills nothing. diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index cd4a0964fae..a4b20e52381 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -96,7 +96,7 @@ const result = CurrencyConfigSchema.parse(data); | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | -| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | +| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | | **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | @@ -233,7 +233,7 @@ const result = CurrencyConfigSchema.parse(data); | **computed** | `boolean` | optional | Read-only computed column, recomputed live from sibling cells via `expr` and written back into the row. | | **expr** | `string` | optional | Arithmetic expression for a computed column — a BARE string over `+ - * / %`, parentheses, numeric literals and field refs (`record.qty` or `qty`), evaluated by the grid's own safe evaluator. Deliberately NOT a CEL Expression envelope; `{ dialect, source }` is refused here. | | **scale** | `integer` | optional | Decimal places to round a computed numeric result to (integer 0-100). REFUSED on a column declaring `type: 'currency'` — delete it there: the currency's CLDR fraction digits decide. The upper bound is the renderer's: the grid rounds with `toFixed`, which throws a RangeError above 100. | -| **autofill** | `boolean` | optional | For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. | +| **autofill** | `boolean` | optional | For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. An amount of money is copied only into a cell in the same currency: a picked amount in another currency than its cell (its child field's: a `fixed` code, the code the line or its header holds, or the home currency) is not copied, the cell stays empty and the grid says why. Nothing is converted. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is read-only when TRUE, evaluated per row against the row as `record` plus the header as `parent` (e.g. P`parent.status == 'paid'`). | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is required when TRUE. Same `record` + `parent` scope as `readonlyWhen`. PRESENTATION ONLY: this flags the cell inline-invalid in the grid; nothing on the write path reads it. The server-enforced contract is the child FIELD's own `requiredWhen` — a transition gate, see `Field.requiredWhen` — which hydration copies onto an identity-only column, so declaring the requirement here alone enforces nothing. | @@ -430,7 +430,7 @@ Allowed Values: `phone`, `id_card`, `bank_account`, `email`, `name` | **computed** | `boolean` | optional | Read-only computed column, recomputed live from sibling cells via `expr` and written back into the row. | | **expr** | `string` | optional | Arithmetic expression for a computed column — a BARE string over `+ - * / %`, parentheses, numeric literals and field refs (`record.qty` or `qty`), evaluated by the grid's own safe evaluator. Deliberately NOT a CEL Expression envelope; `{ dialect, source }` is refused here. | | **scale** | `integer` | optional | Decimal places to round a computed numeric result to (integer 0-100). REFUSED on a column declaring `type: 'currency'` — delete it there: the currency's CLDR fraction digits decide. The upper bound is the renderer's: the grid rounds with `toFixed`, which throws a RangeError above 100. | -| **autofill** | `boolean` | optional | For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. | +| **autofill** | `boolean` | optional | For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. An amount of money is copied only into a cell in the same currency: a picked amount in another currency than its cell (its child field's: a `fixed` code, the code the line or its header holds, or the home currency) is not copied, the cell stays empty and the grid says why. Nothing is converted. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is read-only when TRUE, evaluated per row against the row as `record` plus the header as `parent` (e.g. P`parent.status == 'paid'`). | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is required when TRUE. Same `record` + `parent` scope as `readonlyWhen`. PRESENTATION ONLY: this flags the cell inline-invalid in the grid; nothing on the write path reads it. The server-enforced contract is the child FIELD's own `requiredWhen` — a transition gate, see `Field.requiredWhen` — which hydration copies onto an identity-only column, so declaring the requirement here alone enforces nothing. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index f695bda288c..a176d62b56b 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -276,7 +276,7 @@ const result = ApiMethod.parse(data); | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | -| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | +| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | | **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | @@ -667,7 +667,7 @@ const result = ApiMethod.parse(data); | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | -| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | +| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | | **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 3827a1a5a5f..b99826ac04a 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -99,7 +99,7 @@ Add a new field to an existing object | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | -| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | +| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | | **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | @@ -537,7 +537,7 @@ Add a new field to an existing object | **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | -| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | +| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy. | | **expression** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | CEL expression the field's value is computed from, e.g. F`record.amount * 0.1`. On a `formula` field: computed on read, no column. On any other (stored) field: computed by the engine from the row the write stores and stored, so a client-sent value never stands and a `summary` can roll the column up — on every insert and every update by id (the stored row merged with the patch), and on a predicate update only when the patch moves an input (one value for every matched row, else the update is refused). | | **returnType** | `Enum<'number' \| 'text' \| 'boolean' \| 'date' \| 'currency' \| 'percent'>` | optional | Value type of a formula field (number/text/boolean/date/currency/percent). Authoring stamps `number`, `text`, `boolean` or `date` from the expression's inferred type and leaves it absent when none is proven; `percent` is declared by the author, and a verdict that proves no other type (`number`, or none) keeps it, as does a money verdict: a declared `percent` is never re-stamped `currency`. Otherwise `currency` is stamped when the expression provably computes money, and withdrawn for `number` (its `currencyConfig` dropped) when an edit leaves it a plain number; an unproven verdict keeps it. `currency`: an amount of money, in the currency the formula's own `currencyConfig` declares, as a currency field declares it (no `currencyConfig`: dynamic, the tenant default currency). `percent`: a ratio, read and displayed as a `percent` field reads its stored value — a fraction (0.25 shows 25%, so the expression divides and does not multiply by 100) unless the formula declares a `max` above 1, then percentage points; its `scale` is the decimal places of the displayed percentage (absent: 0), and its `percentDisplay` picks the bar or the plain face. | | **summaryOperations** | `{ object: string; field?: string; function: Enum<'count' \| 'sum' \| 'min' \| 'max' \| 'avg'>; relationshipField?: string; … }` | optional | Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted. | diff --git a/content/docs/references/ui/component.mdx b/content/docs/references/ui/component.mdx index 22cc601e118..1dae4fbdb30 100644 --- a/content/docs/references/ui/component.mdx +++ b/content/docs/references/ui/component.mdx @@ -1923,7 +1923,7 @@ Type: `string` | **computed** | `boolean` | optional | Read-only computed column, recomputed live from sibling cells via `expr` and written back into the row. | | **expr** | `string` | optional | Arithmetic expression for a computed column — a BARE string over `+ - * / %`, parentheses, numeric literals and field refs (`record.qty` or `qty`), evaluated by the grid's own safe evaluator. Deliberately NOT a CEL Expression envelope; `{ dialect, source }` is refused here. | | **scale** | `integer` | optional | Decimal places to round a computed numeric result to (integer 0-100). REFUSED on a column declaring `type: 'currency'` — delete it there: the currency's CLDR fraction digits decide. The upper bound is the renderer's: the grid rounds with `toFixed`, which throws a RangeError above 100. | -| **autofill** | `boolean` | optional | For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. | +| **autofill** | `boolean` | optional | For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. An amount of money is copied only into a cell in the same currency: a picked amount in another currency than its cell (its child field's: a `fixed` code, the code the line or its header holds, or the home currency) is not copied, the cell stays empty and the grid says why. Nothing is converted. | | **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is read-only when TRUE, evaluated per row against the row as `record` plus the header as `parent` (e.g. P`parent.status == 'paid'`). | | **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is required when TRUE. Same `record` + `parent` scope as `readonlyWhen`. PRESENTATION ONLY: this flags the cell inline-invalid in the grid; nothing on the write path reads it. The server-enforced contract is the child FIELD's own `requiredWhen` — a transition gate, see `Field.requiredWhen` — which hydration copies onto an identity-only column, so declaring the requirement here alone enforces nothing. | diff --git a/examples/app-showcase/src/data/objects/invoice.object.ts b/examples/app-showcase/src/data/objects/invoice.object.ts index 0c93cb88d1c..f2090016a2e 100644 --- a/examples/app-showcase/src/data/objects/invoice.object.ts +++ b/examples/app-showcase/src/data/objects/invoice.object.ts @@ -5,10 +5,13 @@ import { cel, P } from '@objectstack/spec'; /** * Product — a small price-book / catalog. The invoice line's `product` lookup - * points here; selecting a product auto-fills the line's `description` and - * `unit_price` (the line-item grid copies matching field names from the chosen - * record — the catalog typeahead every invoicing tool has: QuickBooks - * "Product/Service", Stripe price catalog, NetSuite item column). + * points here; selecting a product auto-fills the line's `description` and, + * when the currencies match, its `unit_price` (the line-item grid copies + * matching field names from the chosen record — the catalog typeahead every + * invoicing tool has: QuickBooks "Product/Service", Stripe price catalog, + * NetSuite item column). The catalog price is in the home currency; on an + * invoice in another currency the line's price stays empty and the grid says + * why, since nothing converts it. */ export const Product = ObjectSchema.create({ name: 'showcase_product', @@ -374,8 +377,10 @@ export const InvoiceLine = ObjectSchema.create({ { name: 'amount' }, ], }), - // Catalog lookup. Picking a product auto-fills `description` + `unit_price` - // (the grid copies same-named fields from the selected product record). + // Catalog lookup. Picking a product auto-fills `description`, and + // `unit_price` when the currencies match (the grid copies same-named + // fields from the selected product record; a home-currency price is not + // copied onto a line in another currency). // Line sort position — stamped by the grid on drag-reorder so the order // persists. Excluded from the editable columns (it's not hand-entered). position: Field.number({ label: 'Position', defaultValue: 0 }), diff --git a/examples/app-showcase/src/data/seed/index.ts b/examples/app-showcase/src/data/seed/index.ts index e6b06f6b0cc..964a25eefde 100644 --- a/examples/app-showcase/src/data/seed/index.ts +++ b/examples/app-showcase/src/data/seed/index.ts @@ -273,7 +273,8 @@ const teams = defineSeed(Team, { }); // Catalog products the invoice line's `product` lookup picks from. Selecting -// one auto-fills the line's description + unit_price (matching field names). +// one auto-fills the line's description, and its unit_price when the +// currencies match (matching field names). const products = defineSeed(Product, { externalId: 'sku', records: [ diff --git a/packages/spec/src/data/field-lookup-autofill.test.ts b/packages/spec/src/data/field-lookup-autofill.test.ts index e912265adf7..a078b47980b 100644 --- a/packages/spec/src/data/field-lookup-autofill.test.ts +++ b/packages/spec/src/data/field-lookup-autofill.test.ts @@ -256,14 +256,14 @@ describe('`lookupAutofill` — source half (defineStack cross-reference)', () => }); describe('control: the grid column key `autofill` keeps its contract', () => { - it('a lookup column still takes `autofill` on and off, and its describe is unchanged', () => { + it('a lookup column still takes `autofill` on and off, and its describe states the currency rule', () => { for (const autofill of [true, false]) { expect(InlineGridColumnSchema.safeParse({ name: 'crm_product', type: 'lookup', reference: 'crm_product', autofill }).success).toBe(true); } expect(InlineGridColumnSchema.safeParse({ name: 'crm_product' }).success).toBe(true); const shape = (InlineGridColumnSchema as unknown as { shape: Record }).shape; expect(shape.autofill!.description).toBe( - "For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable.", + "For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. An amount of money is copied only into a cell in the same currency: a picked amount in another currency than its cell (its child field's: a `fixed` code, the code the line or its header holds, or the home currency) is not copied, the cell stays empty and the grid says why. Nothing is converted.", ); }); diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index ef388203f56..01e90177610 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -1397,7 +1397,7 @@ export const InlineGridColumnSchema = lazySchema(() => strictObject({ // mirror); the describe names the one type set it still applies to. scale: z.number().int().nonnegative().max(MAX_RENDERABLE_SCALE, { message: SCALE_UPPER_BOUND_MESSAGE }).optional() .describe('Decimal places to round a computed numeric result to (integer 0-100). REFUSED on a column declaring `type: \'currency\'` — delete it there: the currency\'s CLDR fraction digits decide. The upper bound is the renderer\'s: the grid rounds with `toFixed`, which throws a RangeError above 100.').meta({ title: 'Scale' }), - autofill: z.boolean().optional().describe("For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable.").meta({ title: 'Autofill' }), + autofill: z.boolean().optional().describe("For `lookup` columns: picking a record copies its same-named fields into sibling columns (a product's unit_price/description). On by default; set false to disable. An amount of money is copied only into a cell in the same currency: a picked amount in another currency than its cell (its child field's: a `fixed` code, the code the line or its header holds, or the home currency) is not copied, the cell stays empty and the grid says why. Nothing is converted.").meta({ title: 'Autofill' }), readonlyWhen: EvaluatedExpressionInputSchema.optional().describe("Predicate (CEL) — the cell is read-only when TRUE, evaluated per row against the row as `record` plus the header as `parent` (e.g. P`parent.status == 'paid'`).").meta({ title: 'Read-only When' }), requiredWhen: EvaluatedExpressionInputSchema.optional().describe('Predicate (CEL) — the cell is required when TRUE. Same `record` + `parent` scope as `readonlyWhen`. PRESENTATION ONLY: this flags the cell inline-invalid in the grid; nothing on the write path reads it. The server-enforced contract is the child FIELD\'s own `requiredWhen` — a transition gate, see `Field.requiredWhen` — which hydration copies onto an identity-only column, so declaring the requirement here alone enforces nothing.').meta({ title: 'Required When' }), }).superRefine((column, ctx) => { @@ -2566,11 +2566,18 @@ export const FieldSchema = lazySchema(() => { * pick never replaces a value somebody wrote unless the pair says * `overwrite: true`. * - * ⭐ Relation to the grid column key `autofill` (`InlineGridColumnSchema`), - * which is unchanged: that key governs only the grid's implicit SAME-NAMED - * copy (on by default, overwriting). A declared pair applies in the grid too, - * under this key's own overwrite rule, and takes its target out of the - * same-named copy, so one target never has two writers on one pick. + * ⭐ Relation to the grid column key `autofill` (`InlineGridColumnSchema`): + * that key governs only the grid's implicit SAME-NAMED copy (on by default, + * overwriting). A declared pair applies in the grid too, under this key's + * own overwrite rule, and takes its target out of the same-named copy, so + * one target never has two writers on one pick. + * + * ⭐ The currency rule binds both copies (maintainer ruling 「B 币种不同就不填并说明」, + * record 7075336705 on objectstack-ai/objectstack#36249): an amount of money + * is copied only into a target in the same currency, else the target is left + * as it is and the form says why. Nothing is converted (ADR-0144 D5 refuses + * an implied rate of 1). The rule is the client's, like the fill itself: the + * line's currency is known only at run time, so no build-time door judges it. * * Three doors judge it: the parse (this field's superRefine — a single-value * relationship only), the object's parse (`refuseDishonestLookupAutofill` in @@ -2594,8 +2601,9 @@ export const FieldSchema = lazySchema(() => { })).min(1).optional().describe( "Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. " + "OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. " + + "CURRENCY RULE: an amount of money (a `currency` field, or a `formula` returning `currency`) is copied only into a target in the same currency, both in the home currency or both naming the same ISO 4217 code (a `fixed` code, or the code the record or its `master_detail` parent holds). Otherwise the target is left as it is and the form says why, naming both currencies and the picked amount; nothing is converted. A `number` carries no currency and copies as before. " + 'Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. ' - + "Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy.", + + "Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy, under the same currency rule; a declared pair takes its target out of that copy.", ), /** 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 085d34a3c1a..c37de21c125 100644 --- a/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx @@ -21,13 +21,21 @@ */ import * as React from 'react'; -import { describe, it, expect, vi, afterEach } from 'vitest'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; import { render, screen, cleanup, waitFor, act, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; import { SchemaRendererContext } from '@object-ui/react'; +import { LocalizationProvider } from '@object-ui/i18n'; import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; -import { lookupAutofillPatch } from './GridField'; -import { declaredLookupAutofillPatch, lookupAutofillByField } from './lookupAutofill'; +import { lookupAutofillPatch, planLookupAutofill } from './GridField'; +import { + amountCurrencyOf, + crossCurrencyRefusal, + declaredLookupAutofillPatch, + lookupAutofillByField, + pickedAmountCurrencyOf, + planDeclaredLookupAutofill, +} from './lookupAutofill'; afterEach(cleanup); @@ -181,3 +189,225 @@ describe('GridField — a lookup cell pick fills the declared targets (objectsta expect(rowsNow()[0].unit_price).toBe(19); }); }); + +describe('a pick does not copy an amount across currencies (objectstack#36249)', () => { + const HOME = { kind: 'home' } as const; + const eur = { kind: 'code', code: 'EUR' } as const; + const usd = { kind: 'code', code: 'USD' } as const; + + it('the rule: same currency copies, another currency or none is withheld, a number copies', () => { + expect(crossCurrencyRefusal(HOME, HOME, 'USD')).toBeUndefined(); + expect(crossCurrencyRefusal(HOME, HOME, undefined)).toBeUndefined(); + expect(crossCurrencyRefusal(undefined, eur, 'USD')).toBeUndefined(); + expect(crossCurrencyRefusal(HOME, undefined, 'USD')).toBeUndefined(); + expect(crossCurrencyRefusal(usd, HOME, 'USD')).toBeUndefined(); + expect(crossCurrencyRefusal(HOME, eur, 'EUR')).toBeUndefined(); + expect(crossCurrencyRefusal({ kind: 'unknown' }, HOME, 'USD')).toBeUndefined(); + expect(crossCurrencyRefusal(HOME, eur, 'USD')).toEqual({ reason: 'differs', from: 'USD', to: 'EUR' }); + expect(crossCurrencyRefusal(eur, HOME, 'USD')).toEqual({ reason: 'differs', from: 'EUR', to: 'USD' }); + expect(crossCurrencyRefusal(HOME, { kind: 'unset' }, 'USD')).toEqual({ reason: 'noTargetCurrency', from: 'USD' }); + expect(crossCurrencyRefusal({ kind: 'unknown' }, eur, 'USD')).toEqual({ reason: 'noSourceCurrency', to: 'EUR' }); + expect(crossCurrencyRefusal(HOME, eur, undefined)).toEqual({ reason: 'noSourceCurrency', to: 'EUR' }); + }); + + it("an amount's currency is its field's: home, fixed, the record's code, or none for a number", () => { + expect(amountCurrencyOf({ type: 'currency' })).toEqual(HOME); + expect(amountCurrencyOf({ type: 'currency', currencyConfig: { currencyMode: 'dynamic' } })).toEqual(HOME); + expect(amountCurrencyOf({ type: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'JPY' } })).toEqual({ kind: 'code', code: 'JPY' }); + const record = { type: 'currency', currencyConfig: { currencyMode: 'record' as const, currencyField: 'currency_code' } }; + expect(amountCurrencyOf(record, { currency_code: 'EUR' })).toEqual(eur); + expect(amountCurrencyOf(record, {})).toEqual({ kind: 'unset' }); + expect(amountCurrencyOf({ type: 'number' })).toBeUndefined(); + expect(amountCurrencyOf({ type: 'formula', returnType: 'currency' })).toEqual(HOME); + }); + + const productFields = { unit_price: { type: 'currency' }, list_price: { type: 'currency' }, description: { type: 'text' } }; + const homeContext = (lineCurrency: string | undefined | null) => ({ + home: 'USD', + sourceCurrency: (source: string, v: unknown) => pickedAmountCurrencyOf((productFields as Record)[source], v, widget), + targetCurrency: (target: string) => + target !== 'unit_price' ? undefined : lineCurrency === null ? HOME : lineCurrency ? { kind: 'code' as const, code: lineCurrency } : { kind: 'unset' as const }, + }); + + it('the same-named copy: a EUR line keeps its price empty and lists why; a USD line fills', () => { + const eurPlan = planLookupAutofill(cols, cols[0], widget, undefined, homeContext('EUR')); + expect(eurPlan.patch).toEqual({ product: 'p1', description: 'Standard widget' }); + expect(eurPlan.withheld).toEqual([ + { target: 'unit_price', source: 'unit_price', amount: 29.99, reason: 'differs', from: 'USD', to: 'EUR' }, + ]); + const usdPlan = planLookupAutofill(cols, cols[0], widget, undefined, homeContext(null)); + expect(usdPlan.patch).toEqual({ product: 'p1', description: 'Standard widget', unit_price: 29.99 }); + expect(usdPlan.withheld).toEqual([]); + }); + + it('a declared pair: a EUR line keeps its price empty and lists why; a USD line fills', () => { + const eurPlan = planLookupAutofill(cols, cols[0], widget, { pairs, row: { unit_price: null } }, homeContext('EUR')); + expect(eurPlan.patch).toEqual({ product: 'p1', description: 'Standard widget' }); + expect(eurPlan.withheld).toEqual([ + { target: 'unit_price', source: 'list_price', amount: 25, reason: 'differs', from: 'USD', to: 'EUR' }, + ]); + const usdPlan = planLookupAutofill(cols, cols[0], widget, { pairs, row: { unit_price: null } }, homeContext(null)); + expect(usdPlan.patch).toEqual({ product: 'p1', description: 'Standard widget', unit_price: 25 }); + expect(planDeclaredLookupAutofill(pairs, widget, { unit_price: null }, null, homeContext('EUR')).patch).toEqual({}); + }); + + it('a line whose header holds no currency yet fills no price', () => { + const plan = planLookupAutofill(cols, cols[0], widget, undefined, homeContext(undefined)); + expect(plan.patch).not.toHaveProperty('unit_price'); + expect(plan.withheld[0]).toMatchObject({ target: 'unit_price', reason: 'noTargetCurrency', from: 'USD' }); + }); + + describe('through the grid', () => { + const ROWS = [{ id: 'p1', name: 'Widget', description: 'Standard widget', unit_price: 100 }]; + // The product's price field; a test may give it a `fixed` code. + let productPrice: Record = { type: 'currency', label: 'Unit Price' }; + beforeEach(() => { + productPrice = { type: 'currency', label: 'Unit Price' }; + }); + const ds = { + getObjectSchema: vi.fn(async () => ({ name: 'product', fields: { name: { type: 'text' }, description: { type: 'text' }, unit_price: productPrice } })), + 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 lineColumns = [ + { 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({ + currency, + columnFields, + home = 'USD', + line, + lookupAutofill, + }: { + currency?: Record; + columnFields?: Record; + home?: string; + line?: Record; + lookupAutofill?: Record; + }) { + const [rows, setRows] = React.useState[]>([{ product: null, description: null, unit_price: null, ...line }]); + return ( + + + []) => setRows(next)} + field={{ columns: lineColumns } as never} + columnCurrencies={currency} + columnFields={columnFields} + lookupAutofill={lookupAutofill} + /> + {JSON.stringify(rows)} + + + ); + } + + const rowsNow = () => JSON.parse(screen.getByTestId('rows').textContent || '[]'); + + async function pickWidget(): Promise { + // The cell's lookup reads the product schema first: the pick judges the + // price by its field. + 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('Widget')); + if (!el) throw new Error('Widget not offered'); + return el; + }, { timeout: 3000 }); + await act(async () => { + fireEvent.click(option); + }); + } + + it('a EUR line: the price stays empty and the line says why, naming both currencies and the price', async () => { + render(); + await pickWidget(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Standard widget' })); + expect(rowsNow()[0].unit_price).toBeNull(); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.textContent).toContain('Unit Price was not filled'); + expect(note.textContent).toContain('$100.00'); + expect(note.textContent).toContain('EUR'); + }); + + it('a USD line: the price fills as before, with no note', async () => { + render(); + await pickWidget(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Standard widget', unit_price: 100 })); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); + + // A line column carries no `currencyConfig`: the host hands the grid the + // child field behind it (`columnFields`), and the column is in that + // field's currency, as on the record form. + const FIXED_EUR = { unit_price: { type: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } } }; + + it('a fixed EUR price into a fixed EUR column fills, under a USD home currency', async () => { + productPrice = { type: 'currency', label: 'Unit Price', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } }; + render(); + await pickWidget(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', unit_price: 100 })); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); + + it('a fixed EUR price into a fixed EUR column fills with no home currency configured', async () => { + productPrice = { type: 'currency', label: 'Unit Price', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'EUR' } }; + render(); + await pickWidget(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', unit_price: 100 })); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); + + it('a home-currency price into a fixed EUR column is withheld, and the line says why', async () => { + render(); + await pickWidget(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Standard widget' })); + expect(rowsNow()[0].unit_price).toBeNull(); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.textContent).toContain('$100.00'); + expect(note.textContent).toContain('EUR'); + }); + + it('a declared target that is not a drawn column is judged by its child field: a home price into a fixed EUR field is withheld', async () => { + render( + , + ); + await pickWidget(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Standard widget' })); + expect(rowsNow()[0].net_price ?? null).toBeNull(); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.querySelector('[data-withheld-target="net_price"]')).not.toBeNull(); + }); + + it("a home-currency price onto a line whose own code is JPY is withheld", async () => { + render( + , + ); + await pickWidget(); + await waitFor(() => expect(rowsNow()[0]).toMatchObject({ product: 'p1', description: 'Standard widget' })); + expect(rowsNow()[0].unit_price).toBeNull(); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.textContent).toContain('JPY'); + }); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.ts b/ui/packages/fields/src/widgets/GridField.ts index 2e286b33ebd..ee12433323e 100644 --- a/ui/packages/fields/src/widgets/GridField.ts +++ b/ui/packages/fields/src/widgets/GridField.ts @@ -4,7 +4,14 @@ import React from 'react'; import type { InlineGridColumn } from '@objectstack/spec/data'; import { resolveFieldCurrency, currencyFractionDigits } from '../currency.js'; -import { declaredLookupAutofillPatch, type LookupAutofillPair } from './lookupAutofill.js'; +import { + crossCurrencyRefusal, + planDeclaredLookupAutofill, + type AutofillCurrencyContext, + type LookupAutofillPair, + type LookupAutofillPlan, + type WithheldAutofill, +} from './lookupAutofill.js'; import { fieldHelpText } from '../fieldHelpText.js'; // Type-only: erased at build, so it adds no edge to the bundle graph. The one // RUNTIME edge to the widget body is the `import()` in `loadGridFieldWidget`. @@ -207,24 +214,48 @@ export function evalArith(expr: string, row: Row): number | null { * (`declaredLookupAutofillPatch`), whatever the column's `autofill` says, and * a declared target is taken out of the same-named copy, so one target never * has two writers on one pick. + * + * `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. */ -export function lookupAutofillPatch( +export function planLookupAutofill( columns: GridColumn[], col: GridColumn, record: any, declared?: { pairs?: readonly LookupAutofillPair[]; row?: Row; previous?: Row | null }, -): Row { + currency?: AutofillCurrencyContext, +): LookupAutofillPlan { const patch: Row = { [col.name]: record?.value ?? record?.id ?? record?._id }; + const withheld: WithheldAutofill[] = []; 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 !== '') patch[other.name] = v; + 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; } } - return { ...patch, ...declaredLookupAutofillPatch(declared?.pairs, record, declared?.row, declared?.previous) }; + const pairs = planDeclaredLookupAutofill(declared?.pairs, record, declared?.row, declared?.previous, currency); + return { patch: { ...patch, ...pairs.patch }, withheld: [...withheld, ...pairs.withheld] }; +} + +/** {@link planLookupAutofill}'s writes alone. */ +export function lookupAutofillPatch( + columns: GridColumn[], + col: GridColumn, + record: any, + declared?: { pairs?: readonly LookupAutofillPair[]; row?: Row; previous?: Row | null }, + currency?: AutofillCurrencyContext, +): Row { + return planLookupAutofill(columns, col, record, declared, currency).patch; } /** diff --git a/ui/packages/fields/src/widgets/LookupField.tsx b/ui/packages/fields/src/widgets/LookupField.tsx index e581dccfde9..46cad38be7e 100644 --- a/ui/packages/fields/src/widgets/LookupField.tsx +++ b/ui/packages/fields/src/widgets/LookupField.tsx @@ -31,7 +31,17 @@ import { buildExpandFields, declaredNameField, getRecordDisplayName, mergeFilter import { getRecentLookupIds, pushRecentLookupId } from './recentLookups.js'; import { getPersonInitials } from './personDisplay.js'; import { rememberPickedRecords } from './referenceRecordCache.js'; -import { declaredLookupAutofillPatch, type LookupAutofillPair } from './lookupAutofill.js'; +import { + amountCurrencyOf, + pickedAmountCurrencyOf, + planDeclaredLookupAutofill, + readLookupAutofillTargets, + withheldAutofillMessage, + type AutofillCurrencyContext, + type LookupAutofillPair, + type WithheldAutofill, +} from './lookupAutofill.js'; +import { useFollowedParentRecord } 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` @@ -42,7 +52,7 @@ import { buildLookupColumnDescriptors, renderLookupColumnValue, } from './lookupColumnDisplay.js'; -import { useSafeFieldLabel, useDisplayLocale } from '@object-ui/i18n'; +import { useSafeFieldLabel, useDisplayLocale, useLocalization, recordCurrencyPath } from '@object-ui/i18n'; import { SchemaRendererContext as ImportedSchemaRendererContext, useAction, useHasActionProvider } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { useFieldTranslation } from './useFieldTranslation.js'; @@ -638,6 +648,12 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro // `recordToOption`, ADR-0079). Without this the label fell back to a // non-existent `name` field and ultimately to the raw record id. const [refObjectSchema, setRefObjectSchema] = useState(null); + // Whether that read has answered (or failed): the opening fill waits for it + // when it would copy an amount, since the amount's currency is its field's + // on the referenced object (objectstack#36249). A host that cannot read the + // schema has nothing to wait for. + const refSchemaReadable = !!dataSource && !!referenceTo && typeof (dataSource as any).getObjectSchema === 'function'; + const [refSchemaAnswered, setRefSchemaAnswered] = useState(false); useEffect(() => { if (!dataSource || !referenceTo) return; const getSchema = (dataSource as any).getObjectSchema; @@ -645,9 +661,11 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro let alive = true; Promise.resolve(getSchema.call(dataSource, referenceTo)) .then((s: any) => { if (alive) setRefObjectSchema(s); }) - .catch(() => { /* fall back to displayField chain */ }); + .catch(() => { /* fall back to displayField chain */ }) + .finally(() => { if (alive) setRefSchemaAnswered(true); }); return () => { alive = false; }; }, [dataSource, referenceTo]); + const refSchemaSettled = !refSchemaReadable || refSchemaAnswered; /** * Picker columns. Honour explicit `lookupColumns` when authored; otherwise @@ -1186,6 +1204,52 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro !multiple && !onSelectRecord && props.onAutofill ? fieldMeta?.lookupAutofill : undefined; const onAutofill = props.onAutofill; + /** + * The cross-currency rule of a pick in a record form (objectstack#36249): + * an amount is copied only into a target in the same currency + * (`crossCurrencyRefusal`). The picked amount's currency is its field's on + * the referenced object (`refObjectSchema`), read on the picked row; the + * target's is its definition's, which the record form stamps on this field + * (`withLookupAutofillTargets`), read on the record being edited. A target + * that follows its parent's currency reads the parent's code, read once + * for the parent the record holds, as the amount box itself does. + */ + const { currency: homeCurrency } = useLocalization(); + const autofillTargets = autofillPairs?.length ? readLookupAutofillTargets(fieldMeta) : undefined; + const followingTarget = useMemo( + () => (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 autofillCurrency = !!autofillTargets; + /** The currency context of a pick of `row` (`crossCurrencyRefusal`), or none without stamped targets. */ + const currencyFor = useCallback( + (row: Record): AutofillCurrencyContext | undefined => { + if (!autofillTargets) return undefined; + const sourceFields = (refObjectSchema as { fields?: Record } | null)?.fields; + return { + home: homeCurrency, + sourceCurrency: (source, v) => pickedAmountCurrencyOf(sourceFields?.[source] as never, v, row), + targetCurrency: (target) => amountCurrencyOf(autofillTargets[target] as never, editedRecordForCurrency), + }; + }, + [autofillTargets, refObjectSchema, homeCurrency, editedRecordForCurrency], + ); + /** 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); + }, []); + /** * Fill the declared targets from the picked `row`. The current values are * the host's live record (`dependentValues`). "An earlier pick filled it" is @@ -1202,10 +1266,11 @@ 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 = declaredLookupAutofillPatch(autofillPairs, row, resolvedDependentValues, previous); + const { patch, withheld } = planDeclaredLookupAutofill(autofillPairs, row, resolvedDependentValues, previous, currencyFor(row)); + noteWithheld(recordValue(row, idField), withheld); if (Object.keys(patch).length > 0) onAutofill(patch); }, - [autofillPairs, onAutofill, normalizeId, value, pickedRecords, idField, resolvedDependentValues], + [autofillPairs, onAutofill, normalizeId, value, pickedRecords, idField, resolvedDependentValues, currencyFor, noteWithheld], ); /** @@ -1241,16 +1306,22 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro const row: Record | undefined = expanded ?? hydratedRecords.find((r) => String(recordValue(r, idField)) === key); if (!row) return; + // objectstack#36249 — an amount's currency is read off the referenced + // object's schema and the parent the record follows: the opening fill + // waits for both reads, so it judges the copy once, on the answer. + if (autofillCurrency && (!refSchemaSettled || followedParentPending)) return; openingFilledRef.current = key; setPickedRecords((prev) => mergeRowsByValue(prev, [row], idField)); - const patch = declaredLookupAutofillPatch( + const { patch, withheld } = planDeclaredLookupAutofill( autofillPairs.map(({ target, source }) => ({ target, source })), row, resolvedDependentValues, null, + currencyFor(row), ); + noteWithheld(key, withheld); if (Object.keys(patch).length > 0) onAutofill(patch, { opening: true }); - }, [autofillPairs, onAutofill, openingValue, value, normalizeId, hydratedRecords, idField, resolvedDependentValues]); + }, [autofillPairs, onAutofill, openingValue, value, normalizeId, hydratedRecords, idField, resolvedDependentValues, autofillCurrency, refSchemaSettled, followedParentPending, currencyFor, noteWithheld]); /** * Commit a pick. `row` is the record `option` was built from. @@ -1289,7 +1360,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro } } else { if (referenceTo) pushRecentLookupId(referenceTo, option.value, perms.userId); - if (onSelectRecord) onSelectRecord(option); + if (onSelectRecord) onSelectRecord(option, { sourceFields: refObjectSchema?.fields ?? null }); else { onChange(option.value); fillDeclaredTargets(row); @@ -1363,7 +1434,10 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro if (referenceTo) pushRecentLookupId(referenceTo, recordValue(row, idField) as string | number | undefined, perms.userId); setPickedRecords(records); rememberPickedRecords(referenceTo, records, idField, refObjectSchema ?? undefined); - onSelectRecord(recordToOption(row, declaredDisplayField, idField, effectiveDescriptionField, refObjectSchema, perms, referenceTo)); + onSelectRecord( + recordToOption(row, declaredDisplayField, idField, effectiveDescriptionField, refObjectSchema, perms, referenceTo), + { sourceFields: refObjectSchema?.fields ?? null }, + ); if (commitsCell) onCommit?.(); }, [multiple, onSelectRecord, handlePickerSelectRecords, referenceTo, idField, declaredDisplayField, effectiveDescriptionField, refObjectSchema, perms, inCell, onCommit], @@ -2230,6 +2304,22 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro ); } + // objectstack#36249 — what the last fill left empty because the picked + // amount is in another currency, while the field still holds that pick and + // the target is still empty. + 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 === ''; + }) + : []; + const withheldLabel = (target: string): string => { + const label = (autofillTargets?.[target] as { label?: unknown } | undefined)?.label; + return typeof label === 'string' && label !== '' ? label : target; + }; + return (
{/* Selected values display — a multi-select field's chips (full mode @@ -2380,6 +2470,16 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro
)} + {withheldShown.length > 0 && ( +
+ {withheldShown.map((w) => ( +

+ {withheldAutofillMessage(w, withheldLabel(w.target), t, displayLocale)} +

+ ))} +
+ )} + {recordPickerDialog} ); diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index e23f10e5198..555338a6095 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -19,7 +19,15 @@ import { formatDate, formatDateTime, resolveFieldRuleState, toDisplayDate } from import { useDisplayLocale, useLocalization, formatDisplayNumber } from '@object-ui/i18n'; import { currencySymbol } from '../../currency.js'; import { LookupField } from '../LookupField.js'; -import type { LookupAutofillByField } from '../lookupAutofill.js'; +import { + amountCurrencyOf, + pickedAmountCurrencyOf, + type AmountCurrency, + type AutofillCurrencyContext, + type LookupAutofillByField, + type WithheldAutofill, + withheldAutofillMessage, +} from '../lookupAutofill.js'; import { FileCell } from '../FileField.js'; import { toDateInputValue, toDateTimeInputValue, fromDateTimeInputValue, isImpossibleStoredDay } from '../nativeDateValue.js'; import { useFieldTranslation } from '../useFieldTranslation.js'; @@ -38,7 +46,7 @@ import { currencyOfColumn, currencyWidth, isUntouchedNewRow, - lookupAutofillPatch, + planLookupAutofill, sumColumn, UNTOUCHED_NEW_ROW, type ColumnCurrencies, @@ -390,6 +398,65 @@ function coerce(type: string | undefined, raw: string): any { if (type === 'datetime') return fromDateTimeInputValue(raw); return raw; } +/** + * The cross-currency context of a pick in this grid (`crossCurrencyRefusal`). + * + * - A picked value's currency is its field's on the referenced object + * (`sourceFields`, the schema the lookup cell read for its labels), read on + * the picked record. A value whose field the cell does not know is a value + * of unknown currency when it is a number. + * - A cell's currency is its column's: a `currency` column the host resolved + * (`columnCurrencies`, a line amount following its header's currency) is in + * that code, or in none while the header holds no code. Any other `currency` + * 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 + * 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 + * none. + */ +function gridAutofillCurrency( + columns: readonly GridColumn[], + sourceFields: Readonly> | null | undefined, + picked: Row | null | undefined, + columnCurrencies: ColumnCurrencies | undefined, + home: string | undefined, + columnFields?: Readonly>, + line?: Row, +): AutofillCurrencyContext { + return { + home, + sourceCurrency: (source, value) => + pickedAmountCurrencyOf(sourceFields?.[source] as never, value, picked), + targetCurrency: (target): 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); + if (c && c.type !== 'currency') return undefined; + if (columnCurrencies && Object.prototype.hasOwnProperty.call(columnCurrencies, target)) { + const code = columnCurrencies[target]; + 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); + return c ? { kind: 'home' } : undefined; + }, + }; +} + +/** + * 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. + */ +interface WithheldPick { + lookup: string; + picked: unknown; + items: readonly WithheldAutofill[]; +} + export type GridFieldWidgetProps = FieldWidgetComponentProps & { /** When provided, each row shows an "expand" button that opens the row in a * full form (the host — e.g. MasterDetailForm — renders the drawer/modal and @@ -417,6 +484,15 @@ export type GridFieldWidgetProps = FieldWidgetComponentProps & { * so the master-detail host that holds the header and the child schema * hands it over. A column it does not name is in the tenant currency. */ columnCurrencies?: ColumnCurrencies; + /** The child field definition behind each `currency` column, by column + * name (objectstack#36249): a grid column carries no `currencyConfig`, so + * the host that holds the child schema hands the definitions over. A pick + * copies an amount into a column only in the same currency, and a column + * named here is in its definition's currency (a `fixed` code, or the code + * a sibling field on the line holds), read as the record form reads it. + * {@link columnCurrencies} still decides a column it names. Absent: such a + * column counts as being in the tenant currency, as before. */ + columnFields?: Readonly>; /** The values a new line starts with (objectstack#35816): the child * object's static field defaults, by field name. A grid column carries no * default (the spec's inline column refuses `defaultValue`), so the host @@ -572,6 +648,7 @@ function GridFieldBody({ onAdd, lookupAutofill, columnCurrencies, + columnFields, newRowValues, newRowRequiredShown, columnHelp, @@ -774,19 +851,31 @@ function GridFieldBody({ * than its index, so adding, removing or reordering rows cannot misattribute it. */ 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. + const [withheldFills, setWithheldFills] = React.useState>(() => new Map()); const applyLookupSelection = useCallback( - (rowIdx: number, col: GridColumn, record: any) => { + (rowIdx: number, col: GridColumn, record: any, picked?: { sourceFields?: Readonly> | null }) => { const row = rows[rowIdx] ?? blankRow(); const pickKey = (id: unknown) => `${col.name}\u0000${String(id)}`; const heldId = row[col.name]; const previous = heldId == null || heldId === '' ? null : pickedLookupRecords.current.get(pickKey(heldId)) ?? null; - const patch = lookupAutofillPatch(columns, col, record, { pairs: lookupAutofill?.[col.name], row, previous }); + const currency = gridAutofillCurrency(columns, picked?.sourceFields, record, columnCurrencies, tenantCurrency, columnFields, row); + const { patch, withheld } = planLookupAutofill(columns, col, record, { pairs: lookupAutofill?.[col.name], row, previous }, currency); if (record && typeof record === 'object' && patch[col.name] != null) { pickedLookupRecords.current.set(pickKey(patch[col.name]), record); } + setWithheldFills((prev) => { + if (withheld.length === 0 && !prev.has(rowIdx)) return prev; + const next = new Map(prev); + if (withheld.length === 0) next.delete(rowIdx); + else next.set(rowIdx, { lookup: col.name, picked: patch[col.name], items: withheld }); + return next; + }); applyPatch(rowIdx, patch); }, - [columns, rows, blankRow, lookupAutofill, applyPatch], + [columns, rows, blankRow, lookupAutofill, applyPatch, columnCurrencies, tenantCurrency, columnFields], ); /** Set a cell to an already-typed value (lookup ids, etc.) without coercion. */ @@ -1218,7 +1307,7 @@ function GridFieldBody({ setCellValue(rowIdx, c.name, v)} - onSelectRecord={(rec: any) => applyLookupSelection(rowIdx, c, rec)} + onSelectRecord={(rec: any, picked?: { sourceFields?: Readonly> | null }) => applyLookupSelection(rowIdx, c, rec, picked)} compact field={{ reference: c.reference, displayField: c.displayField, idField: c.idField, multiple: c.multiple, options: c.options, placeholder: '—' } as any} disabled={locked} @@ -1417,9 +1506,16 @@ function GridFieldBody({ displayRows.map((row, rowIdx) => { 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. + 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] === '') + : []; return ( + )} + {withheldShown.length > 0 && ( + + + + {withheldShown.map((w) => { + const target = columns.find((x) => x.name === w.target); + return ( +

+ {withheldAutofillMessage(w, target?.label || w.target, t, displayLocale)} +

+ ); + })} + + + )} +
); }) )} diff --git a/ui/packages/fields/src/widgets/lookupAutofill.ts b/ui/packages/fields/src/widgets/lookupAutofill.ts index 71d2e0fa16d..e38408f90c2 100644 --- a/ui/packages/fields/src/widgets/lookupAutofill.ts +++ b/ui/packages/fields/src/widgets/lookupAutofill.ts @@ -1,4 +1,7 @@ import type { Field as SpecField } from '@objectstack/spec/data'; +import { resolveFieldCurrency, type FieldCurrencyConfig } from '@object-ui/i18n'; +import { formatCurrency } from './number-format.js'; +import { withFollowedParentObject } from '../currency.js'; /** * One declared `{ target, source, overwrite? }` pair of `@objectstack/spec`'s @@ -40,22 +43,42 @@ function sameValue(a: unknown, b: unknown): boolean { * * A `source` the picked record does not carry (a field the reader may not * read is not served) writes nothing: a missing key is not a value. + * + * The cross-currency rule (`crossCurrencyRefusal`, read through `currency`): + * 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. */ -export function declaredLookupAutofillPatch( +export function planDeclaredLookupAutofill( pairs: readonly LookupAutofillPair[] | undefined, picked: Values | null | undefined, current: Values | null | undefined, previous?: Values | null, -): Values { - const patch: Values = {}; - if (!pairs?.length || !picked || typeof picked !== 'object') return patch; + currency?: AutofillCurrencyContext, +): LookupAutofillPlan { + const plan: LookupAutofillPlan = { patch: {}, withheld: [] }; + if (!pairs?.length || !picked || typeof picked !== 'object') return plan; 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) patch[target] = picked[source]; + if (!(overwrite === true || isEmptyValue(held) || filledByEarlierPick)) continue; + const refused = judgeCopy(currency, target, source, picked[source]); + if (refused) plan.withheld.push(refused); + else plan.patch[target] = picked[source]; } - return patch; + return plan; +} + +/** {@link planDeclaredLookupAutofill}'s writes alone. */ +export function declaredLookupAutofillPatch( + pairs: readonly LookupAutofillPair[] | undefined, + picked: Values | null | undefined, + current: Values | null | undefined, + previous?: Values | null, + currency?: AutofillCurrencyContext, +): Values { + return planDeclaredLookupAutofill(pairs, picked, current, previous, currency).patch; } /** @@ -75,3 +98,225 @@ export function lookupAutofillByField(fields: Record | undefine } return out; } + +/** + * The currency one amount of a pick is in, for the cross-currency rule a pick + * follows (the maintainer's ruling on objectstack-ai/objectstack#36249: when + * the two currencies differ, the value is not copied and the form says why). + * + * - `home`: the amount declares no currency of its own (no `currencyConfig`, + * or `dynamic`), so it is in the organization's home currency (ADR-0144 D2); + * - `code`: the amount is in a known ISO 4217 code, a `fixed` code or the + * code its record holds (`record` mode, the parent's code included); + * - `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. + */ +export type AmountCurrency = + | { readonly kind: 'home' } + | { readonly kind: 'code'; readonly code: string } + | { readonly kind: 'unset' } + | { readonly kind: 'unknown' }; + +const HOME: AmountCurrency = Object.freeze({ kind: 'home' }); +const UNSET: AmountCurrency = Object.freeze({ kind: 'unset' }); +const UNKNOWN: AmountCurrency = Object.freeze({ kind: 'unknown' }); + +interface MoneyDef { + type?: unknown; + returnType?: unknown; + currencyConfig?: FieldCurrencyConfig; +} + +/** Is `def` an amount of money: a `currency` field, or a `formula` returning one. */ +function isMoneyDef(def: MoneyDef | null | undefined): def is MoneyDef { + if (!def || typeof def !== 'object') return false; + return def.type === 'currency' || (def.type === 'formula' && def.returnType === 'currency'); +} + +/** + * The currency of the amount `def` declares, read on `record` (the row the + * amount sits in), or `undefined` when `def` is no amount of money: a + * `number` carries no currency and copies as before. + * + * Read through `resolveFieldCurrency`, the one resolver every currency face + * shares, handed no tenant default: a field it answers no code for declares + * none of its own, so it is in the home currency. + */ +export function amountCurrencyOf( + def: MoneyDef | null | undefined, + record?: Readonly> | null, +): AmountCurrency | undefined { + if (!isMoneyDef(def)) return undefined; + const code = resolveFieldCurrency(def, undefined, record ?? null); + if (code) return { kind: 'code', code }; + return def.currencyConfig?.currencyMode === 'record' ? UNSET : HOME; +} + +/** + * 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 + * be an amount) and `undefined` for anything else. + */ +export function pickedAmountCurrencyOf( + def: MoneyDef | null | undefined, + value: unknown, + picked: Readonly> | null | undefined, +): AmountCurrency | undefined { + if (def && typeof def === 'object') return amountCurrencyOf(def, picked); + return typeof value === 'number' ? UNKNOWN : undefined; +} + +/** The code `c` names, the home currency read as `home` when one is configured. */ +function codeOf(c: AmountCurrency, home: string | undefined): string | undefined { + if (c.kind === 'code') return c.code; + if (c.kind === 'home') return home || undefined; + return undefined; +} + +/** + * Why a pick did not copy one value: the picked `amount` and the two + * currencies, so the form can say so and a person can price it by hand. + * + * - `differs`: both currencies are known and differ (`from` → `to`); + * - `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`. + */ +export interface WithheldAutofill { + readonly target: string; + readonly source: string; + readonly amount: number; + readonly reason: 'differs' | 'noTargetCurrency' | 'noSourceCurrency'; + readonly from?: string; + readonly to?: string; +} + +/** + * The cross-currency rule of a pick, as one predicate: `undefined` when the + * value copies, else why it does not. + * + * A value copies as before when either side is no amount of money, and when + * both amounts are in the home currency (an organization with no home + * currency configured included). Otherwise it copies only when both sides + * name the same known code: the home currency counts as its configured code. + * Nothing is converted, and nothing is copied at an implied rate of 1. + */ +export function crossCurrencyRefusal( + source: AmountCurrency | undefined, + target: AmountCurrency | undefined, + home: string | undefined, +): Pick | undefined { + if (!source || !target) return undefined; + if (target.kind === 'home' && (source.kind === 'home' || source.kind === 'unknown')) return undefined; + const from = codeOf(source, home); + const to = codeOf(target, home); + if (from && to && from === to) return undefined; + if (target.kind === 'unset') return { reason: 'noTargetCurrency', ...(from ? { from } : {}) }; + if (!from) return { reason: 'noSourceCurrency', ...(to ? { to } : {}) }; + if (!to) return { reason: 'noTargetCurrency', from }; + return { reason: 'differs', from, to }; +} + +/** + * What a host knows about the currencies of one pick: the currency of each + * value the picked record offers (`sourceCurrency`, by source field name, read + * 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. + */ +export interface AutofillCurrencyContext { + sourceCurrency: (source: string, value: unknown) => AmountCurrency | undefined; + targetCurrency: (target: string) => AmountCurrency | undefined; + home: string | undefined; +} + +/** The writes and the withheld values of one pick. */ +export interface LookupAutofillPlan { + patch: Values; + withheld: WithheldAutofill[]; +} + +/** `value` copied from `source` into `target`, or the reason it is not. */ +function judgeCopy( + ctx: AutofillCurrencyContext | undefined, + target: string, + source: string, + value: unknown, +): WithheldAutofill | undefined { + if (!ctx) return undefined; + const refusal = crossCurrencyRefusal(ctx.sourceCurrency(source, value), ctx.targetCurrency(target), ctx.home); + if (!refusal) return undefined; + const amount = typeof value === 'number' ? value : Number(value); + return { target, source, amount, ...refusal }; +} + +/** The translation call a widget holds (`useFieldTranslation().t`). */ +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. + */ +export function withheldAutofillMessage( + item: WithheldAutofill, + label: string, + t: Translate, + 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 }); +} + +/** + * The key a record form stamps the definitions of a lookup's `lookupAutofill` + * targets under, on the lookup's own field metadata: the widget receives one + * field, not the object, and a target's currency is its definition's. The + * same hand-off shape as `FOLLOWED_PARENT_OBJECT_KEY` (`currency.ts`). + */ +export const LOOKUP_AUTOFILL_TARGETS_KEY = 'lookupAutofillTargets'; + +/** + * `def` with the definitions of its `lookupAutofill` targets stamped, read + * off `fields` (the edited object's field map), each carrying the parent + * object it follows when its currency follows a parent (ADR-0144 D2 as + * amended). `labels` names each field as the form shows it (translated); + * a target the form draws carries that name as its `label`, so a note about + * it names the field the way the form does. `def` itself when it declares no + * pairs or `fields` names none of its targets. + */ +export function withLookupAutofillTargets( + def: T, + fields: Readonly> | null | undefined, + labels?: Readonly>, +): T { + const pairs = (def as { lookupAutofill?: unknown }).lookupAutofill; + if (!Array.isArray(pairs) || pairs.length === 0 || !fields) return def; + const targets: Record = {}; + for (const pair of pairs as LookupAutofillPair[]) { + const target = fields[pair?.target]; + if (!target || typeof target !== 'object') continue; + const stamped = withFollowedParentObject(target, fields); + const shown = labels?.[pair.target]; + targets[pair.target] = typeof shown === 'string' && shown !== '' ? { ...stamped, label: shown } : stamped; + } + return Object.keys(targets).length > 0 ? { ...def, [LOOKUP_AUTOFILL_TARGETS_KEY]: targets } : def; +} + +/** The target definitions a form stamped on `field`, or `undefined`. */ +export function readLookupAutofillTargets(field: unknown): Readonly>> | undefined { + const value = (field as Record | null | undefined)?.[LOOKUP_AUTOFILL_TARGETS_KEY]; + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record>) + : undefined; +} diff --git a/ui/packages/fields/src/widgets/types.ts b/ui/packages/fields/src/widgets/types.ts index c10d47e31d9..1900e9cfa61 100644 --- a/ui/packages/fields/src/widgets/types.ts +++ b/ui/packages/fields/src/widgets/types.ts @@ -271,8 +271,13 @@ export type FieldWidgetComponentProps = { * Receive the FULL selected record rather than just its id, so a host can * auto-fill sibling fields from it (a line-item grid copying a product's * price). When provided, the host owns the resulting value change. + * + * `picked.sourceFields` is the referenced object's field map, as the widget + * read it for its labels (`null` before it loads or when it cannot be read): + * a host copying an amount judges its currency by its field + * (objectstack#36249). */ - onSelectRecord?: (record: Record) => void; + onSelectRecord?: (record: Record, picked?: { sourceFields?: Readonly> | null }) => void; /** * Write sibling fields of the record being edited: the targets a pick in a * lookup fills under its declared `lookupAutofill` pairs, as one patch of diff --git a/ui/packages/fields/src/widgets/useFieldTranslation.ts b/ui/packages/fields/src/widgets/useFieldTranslation.ts index 237a63e572e..e00abc8940b 100644 --- a/ui/packages/fields/src/widgets/useFieldTranslation.ts +++ b/ui/packages/fields/src/widgets/useFieldTranslation.ts @@ -58,6 +58,11 @@ const FIELD_DEFAULTS: Record = { // row for a numeric `count`, as i18next reads the `en` pack. 'lookup.recordCount_one': '{{count}} record', 'lookup.recordCount_other': '{{count}} records', + // objectstack#36249 — why a pick left an amount empty (`withheldAutofillMessage`). + // Same values as the `en` pack. + '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.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 c3010486d99..cdec4d4f853 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -69,6 +69,9 @@ const ar = { loading: 'جارٍ التحميل…', noOptions: 'لا توجد خيارات', noRecords: 'لا توجد سجلات', + autofillCurrencyDiffers: 'لم يُملأ {{field}}: المبلغ المختار هو {{amount}} بعملة {{from}}، لكن {{field}} هنا بعملة {{to}}. أدخله بعملة {{to}}.', + autofillSourceNoCurrency: 'لم يُملأ {{field}}: المبلغ المختار {{amount}} لا يذكر عملة، لكن {{field}} هنا بعملة {{to}}. أدخله بعملة {{to}}.', + autofillNoCurrency: 'لم يُملأ {{field}}: المبلغ المختار هو {{amount}}، لكن لم تُختر عملة هنا بعد. اختر العملة، ثم أدخل {{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 ffedd874ffd..5227738003c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -62,6 +62,9 @@ const de = { loading: 'Wird geladen…', noOptions: 'Keine Optionen gefunden', noRecords: 'Keine Datensätze gefunden', + 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.', }, 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 bc51e535396..43443bc9856 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -68,6 +68,11 @@ const en = { nextPage: 'Next page', jumpToPage: 'Jump to page', retry: 'Retry', + // objectstack#36249 — why a pick left an amount empty: the picked amount is + // in another currency than the field it would fill (nothing is converted). + 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}}.', }, 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 4eb1416c2e9..879876d4b00 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -63,6 +63,9 @@ const es = { loading: 'Cargando…', noOptions: 'No se encontraron opciones', noRecords: 'No se encontraron registros', + 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}}.', }, 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 2897ba30a6d..818581671e2 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -63,6 +63,9 @@ const fr = { loading: 'Chargement…', noOptions: 'Aucune option trouvée', noRecords: 'Aucun enregistrement trouvé', + 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}}.', }, 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 8e905217048..d29ce59f214 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -62,6 +62,9 @@ const ja = { loading: '読み込み中…', noOptions: 'オプションが見つかりません', noRecords: 'レコードが見つかりません', + autofillCurrencyDiffers: '{{field}}は入力されませんでした。選択した金額は {{amount}}({{from}})ですが、ここでの{{field}}は {{to}} です。{{to}} で入力してください。', + autofillSourceNoCurrency: '{{field}}は入力されませんでした。選択した金額 {{amount}} には通貨がありませんが、ここでの{{field}}は {{to}} です。{{to}} で入力してください。', + autofillNoCurrency: '{{field}}は入力されませんでした。選択した金額は {{amount}} ですが、ここではまだ通貨が選択されていません。通貨を選択してから{{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 0b863615fd9..2d925a0975b 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -62,6 +62,9 @@ const ko = { loading: '로딩 중…', noOptions: '옵션을 찾을 수 없습니다', noRecords: '레코드를 찾을 수 없습니다', + autofillCurrencyDiffers: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액은 {{amount}}({{from}})이지만 여기의 {{field}}은(는) {{to}} 기준입니다. {{to}}(으)로 직접 입력하세요.', + autofillSourceNoCurrency: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액 {{amount}}에는 통화가 없지만 여기의 {{field}}은(는) {{to}} 기준입니다. {{to}}(으)로 직접 입력하세요.', + autofillNoCurrency: '{{field}}이(가) 입력되지 않았습니다. 선택한 금액은 {{amount}}이지만 여기에는 아직 통화가 선택되지 않았습니다. 통화를 선택한 후 {{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 fa337da7bd4..eff4cdfed00 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -63,6 +63,9 @@ const pt = { loading: 'Carregando…', noOptions: 'Nenhuma opção encontrada', noRecords: 'Nenhum registro encontrado', + 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}}.', }, 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 22a331c1f3b..9fce522e130 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -64,6 +64,9 @@ const ru = { loading: 'Загрузка…', noOptions: 'Варианты не найдены', noRecords: 'Записи не найдены', + autofillCurrencyDiffers: 'Поле «{{field}}» не заполнено: выбранная сумма — {{amount}} в {{from}}, а здесь «{{field}}» указывается в {{to}}. Введите её в {{to}}.', + autofillSourceNoCurrency: 'Поле «{{field}}» не заполнено: у выбранной суммы {{amount}} не указана валюта, а здесь «{{field}}» указывается в {{to}}. Введите её в {{to}}.', + autofillNoCurrency: 'Поле «{{field}}» не заполнено: выбранная сумма — {{amount}}, но валюта здесь ещё не выбрана. Выберите валюту, затем введите «{{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 3937118eb1a..eee22c9302a 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -71,6 +71,9 @@ const zh = { nextPage: '下一页', jumpToPage: '跳转到指定页', retry: '重试', + autofillCurrencyDiffers: '未填入{{field}}:所选金额为 {{amount}}({{from}}),而此处的{{field}}以 {{to}} 计。请按 {{to}} 手动填写。', + autofillSourceNoCurrency: '未填入{{field}}:所选金额 {{amount}} 未注明币种,而此处的{{field}}以 {{to}} 计。请按 {{to}} 手动填写。', + autofillNoCurrency: '未填入{{field}}:所选金额为 {{amount}},但此处尚未选择币种。请先选择币种,再填写{{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 e27f1bad492..b605faeccb2 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -71,6 +71,9 @@ const zhHant = { nextPage: '下一頁', jumpToPage: '跳轉到指定頁', retry: '重試', + autofillCurrencyDiffers: '未填入{{field}}:所選金額為 {{amount}}({{from}}),而此處的{{field}}以 {{to}} 計。請按 {{to}} 手動填寫。', + autofillSourceNoCurrency: '未填入{{field}}:所選金額 {{amount}} 未註明幣種,而此處的{{field}}以 {{to}} 計。請按 {{to}} 手動填寫。', + autofillNoCurrency: '未填入{{field}}:所選金額為 {{amount}},但此處尚未選擇幣種。請先選擇幣種,再填寫{{field}}。', }, common: { // objectui#13461 — a disclosure toggle's name (the tree-view node toggle). diff --git a/ui/packages/plugin-form/src/LineItemsPanel.tsx b/ui/packages/plugin-form/src/LineItemsPanel.tsx index e7f78d96360..2a6eb09ddb7 100644 --- a/ui/packages/plugin-form/src/LineItemsPanel.tsx +++ b/ui/packages/plugin-form/src/LineItemsPanel.tsx @@ -34,7 +34,7 @@ import { usePermissions } from '@object-ui/permissions'; import { buildMasterDetailEditBatch, sumRows } from './masterDetailTx'; import { applyColumnPermissions } from './fieldWriteGate'; import { hydrateColumns } from './deriveMasterDetail'; -import { parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns'; +import { currencyFieldDefsOf, parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns'; import { runBatchTransaction, mergeFilterNodes, @@ -764,6 +764,12 @@ export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ sch ), [childSchema, schema.relationshipField, parentRow, tenantCurrency], ); + // Each currency column's child field, so a pick copies an amount only into + // a column in the same currency (objectstack#36249). + const lineCurrencyFields = useMemo( + () => currencyFieldDefsOf(childSchema?.fields as Record | undefined), + [childSchema], + ); const lineLookupAutofill = useMemo( () => lookupAutofillByField(childSchema?.fields as Record | undefined), [childSchema], @@ -921,6 +927,7 @@ export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ sch // targets in the row. Empty until that schema arrives. lookupAutofill={lineLookupAutofill} columnCurrencies={lineColumnCurrencies} + columnFields={lineCurrencyFields} columnHelp={lineColumnHelp} readonly={schema.readonly} // No input while the save is in flight (objectui#10631): `save` diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 84579653bf1..94027885ddc 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -67,7 +67,7 @@ import { resolveInitialRecord } from './initialRecord'; import { sectionEntryName } from './sectionFields'; import { deriveDetail } from './deriveMasterDetail'; import { schemaDefaultValues } from './schemaDefaults'; -import { parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns'; +import { currencyFieldDefsOf, parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns'; // objectui#11428 — the per-row form's offer test is the spec's rule. import { isInlineRowFormOffered } from '@objectstack/spec/data'; // objectui#11396 — one `details` entry, by reference: the spec's own type for @@ -455,6 +455,12 @@ interface DetailEntry { * currency. Internal state, never authored. */ parentCurrencyFields?: ReturnType; + /** + * The child fields that hold an amount of money, by name + * (`currencyFieldDefsOf`): a pick copies an amount into a line column only + * in the same currency (objectstack#36249). Internal state, never authored. + */ + currencyFields?: ReturnType; } /** The field shape `resolveFieldCurrency` reads — the one currency resolver. */ @@ -1263,6 +1269,9 @@ const MasterDetailLines: React.FC = ({ // The columns whose amount follows this header's currency // (ADR-0144 D2 as amended), in the header's live code. columnCurrencies={followedColumnCurrencies(entry.parentCurrencyFields, parentRecord, tenantCurrency)} + // Each currency column's own currency (a `fixed` code, a code on + // the line), for a pick's cross-currency rule (objectstack#36249). + columnFields={entry.currencyFields} // objectstack#35940 — a new line starts on the child's defaults, // and its empty required cell reads red once a save was tried, // as on the record page's edit state. @@ -1569,6 +1578,7 @@ export const MasterDetailForm: React.FC = ({ lookupAutofill: lookupAutofillByField(childSchema?.fields as Record | undefined), columnHelp: columnHelpByField(childSchema?.fields as Record | undefined), parentCurrencyFields: parentCurrencyFieldsOf(childSchema?.fields as Record | undefined, d.relationshipField), + currencyFields: currencyFieldDefsOf(childSchema?.fields as Record | undefined), }; } return { @@ -1588,6 +1598,7 @@ export const MasterDetailForm: React.FC = ({ lookupAutofill: lookupAutofillByField(childSchema?.fields as Record | undefined), columnHelp: columnHelpByField(childSchema?.fields as Record | undefined), parentCurrencyFields: parentCurrencyFieldsOf(childSchema?.fields as Record | undefined, derived.relationshipField), + currencyFields: currencyFieldDefsOf(childSchema?.fields as Record | undefined), }; } catch (err) { // THE DERIVE FAILED, on a schema that loaded fine — almost always 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 0aa0f034d27..635d7e01a3c 100644 --- a/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx @@ -25,6 +25,7 @@ import { ObjectForm } from './ObjectForm'; import { ModalForm } from './ModalForm'; import { registerAllFields } from '@object-ui/fields'; import { SchemaRendererContext } from '@object-ui/react'; +import { createI18n, I18nProvider, LocalizationProvider } from '@object-ui/i18n'; registerAllFields(); @@ -316,3 +317,123 @@ describe('ObjectForm — a create form opened with a lookup value fills its decl expect(valueOf(container, 'note')).toBe(''); }); }); + +describe('ObjectForm — a pick does not copy an amount into a field in another currency (objectstack#36249)', () => { + // A quote whose price follows its own currency code (ADR-0144 D2), and a + // catalog whose price is in the home currency (USD here). + const CURRENCY_SCHEMAS: Record = { + fx_quote: { + name: 'fx_quote', + fields: { + currency_code: { type: 'text', label: 'Currency' }, + product: { + type: 'lookup', + label: 'Product', + reference: 'fx_product', + lookupAutofill: [ + { target: 'unit_price', source: 'list_price' }, + { target: 'description', source: 'summary' }, + ], + }, + unit_price: { + type: 'currency', + label: 'Unit Price', + currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' }, + }, + description: { type: 'text', label: 'Description' }, + }, + }, + fx_product: { + name: 'fx_product', + fields: { + name: { type: 'text', label: 'Name' }, + list_price: { type: 'currency', label: 'List Price' }, + summary: { type: 'text', label: 'Summary' }, + }, + }, + }; + const CURRENCY_ROWS: Record[]> = { + fx_product: [{ id: 'p1', name: 'Widget', list_price: 100, summary: 'A widget' }], + }; + const makeCurrencyDS = () => ({ + getObjectSchema: vi.fn(async (name: string) => CURRENCY_SCHEMAS[name]), + find: vi.fn(async (name: string, params?: { $filter?: { id?: { $in?: unknown[] } } }) => { + const wanted = params?.$filter?.id?.$in; + const rows = (CURRENCY_ROWS[name] ?? []).filter((r) => !wanted || wanted.includes(r.id)); + return { data: rows.map((r) => ({ ...r })), total: rows.length }; + }), + findOne: vi.fn(async (name: string, id: string) => { + const row = (CURRENCY_ROWS[name] ?? []).find((r) => r.id === id); + return row ? { ...row } : null; + }), + create: vi.fn(async (_o: string, d: Record) => ({ id: 'q1', ...d })), + update: vi.fn(), + }); + + function renderQuote(initialValues: Record, i18n?: ReturnType) { + const ds = makeCurrencyDS(); + const form = ( + + + + + + ); + const view = render(i18n ? {form} : form); + return { ds, container: view.container }; + } + + it('a EUR quote: the price stays empty and the form says why; the description still fills', async () => { + const { container } = renderQuote({ currency_code: 'EUR' }); + await input(container, 'description'); + await pick('product', 'Widget'); + + await waitFor(() => expect((container.querySelector('input[name="description"]') as HTMLInputElement).value).toBe('A widget')); + const note = await screen.findByTestId('lookup-autofill-withheld'); + expect(note.querySelector('[data-withheld-target="unit_price"]')).not.toBeNull(); + expect(note.textContent).toContain('$100.00'); + expect(note.textContent).toContain('USD'); + expect(note.textContent).toContain('EUR'); + const price = container.querySelector('input[name="unit_price"]') as HTMLInputElement | null; + expect(price?.value ?? '').toBe(''); + }); + + it('the note names the field as the form shows it: the translated label, not the authored one', async () => { + const i18n = createI18n({ + defaultLanguage: 'zh', + detectBrowserLanguage: false, + resources: { zh: { app: { fields: { fx_quote: { unit_price: '单价' } } } } }, + }); + const { container } = renderQuote({ currency_code: 'EUR' }, i18n); + await input(container, 'description'); + await screen.findByText('单价'); + await pick('product', 'Widget'); + + const note = await screen.findByTestId('lookup-autofill-withheld'); + const line = note.querySelector('[data-withheld-target="unit_price"]'); + expect(line?.textContent).toContain('单价'); + expect(line?.textContent).not.toContain('Unit Price'); + expect(line?.textContent).not.toContain('unit_price'); + }); + + it('a USD quote: the price fills as before, with no note', async () => { + const { container } = renderQuote({ currency_code: 'USD' }); + await input(container, 'description'); + await pick('product', 'Widget'); + + await waitFor(() => expect((container.querySelector('input[name="description"]') as HTMLInputElement).value).toBe('A widget')); + await waitFor(() => expect((container.querySelector('input[name="unit_price"]') as HTMLInputElement).value).toBe('100')); + expect(screen.queryByTestId('lookup-autofill-withheld')).toBeNull(); + }); + + it('the opening fill follows the same rule: a EUR quote opened with a product fills no price', async () => { + const { container } = renderQuote({ currency_code: 'EUR', product: 'p1' }); + await waitFor(() => expect((container.querySelector('input[name="description"]') as HTMLInputElement).value).toBe('A widget')); + await screen.findByTestId('lookup-autofill-withheld'); + const price = container.querySelector('input[name="unit_price"]') as HTMLInputElement | null; + expect(price?.value ?? '').toBe(''); + }); +}); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.crossCurrency-36249.test.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.crossCurrency-36249.test.tsx new file mode 100644 index 00000000000..314be354e73 --- /dev/null +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.crossCurrency-36249.test.tsx @@ -0,0 +1,197 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * The record page's body-table editor, the third host of the line grid, + * judges a pick's amount by each line column's own currency, as the other + * hosts do (objectstack#36249): a line price following a EUR invoice withholds + * a home-currency price, and a pick between two amounts in the same currency + * fills as before. The record is judged as the user has it in the open edit: + * a currency code staged in the inline draft, not yet saved, is the code the + * new lines are saved under. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { InlineEditProvider, RecordContextProvider, SchemaRendererContext, useInlineEdit } from '@object-ui/react'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { registerAllFields } from '@object-ui/fields'; +import { + RecordBodyTableEditor, + RecordEditSessionContext, + type BodyTableEditHandle, + type RecordEditSession, +} from './RecordBodyTableEditor'; + +registerAllFields(); +afterEach(() => cleanup()); + +const LINE_SCHEMA = { + name: 'fx_line', + fields: { + invoice: { type: 'master_detail', label: 'Invoice', reference: 'fx_invoice' }, + product: { type: 'lookup', label: 'Product', reference: 'fx_product' }, + description: { type: 'text', label: 'Description' }, + unit_price: { + type: 'currency', + label: 'Unit Price', + currencyConfig: { currencyMode: 'record', currencyField: 'invoice.currency_code' }, + }, + }, +}; +const PRODUCT_SCHEMA = { + name: 'fx_product', + fields: { + name: { type: 'text', label: 'Name' }, + description: { type: 'text', label: 'Description' }, + unit_price: { type: 'currency', label: 'Unit Price' }, + }, +}; +const PRODUCTS = [{ id: 'p1', name: 'Widget', description: 'A widget', unit_price: 100 }]; + +const FIXED_EUR = { currencyMode: 'fixed', defaultCurrency: 'EUR' } as const; +const withPrice = (schema: typeof LINE_SCHEMA | typeof PRODUCT_SCHEMA, price: Record) => ({ + ...schema, + fields: { ...schema.fields, unit_price: price }, +}); + +/** Stages the record's currency in the inline draft, as the record page's edit does. */ +function StageCurrency({ code }: { code: string }) { + const inline = useInlineEdit(); + const setField = inline?.setField; + React.useEffect(() => { + setField?.('currency_code', code); + }, [setField, code]); + return null; +} + +function mount( + invoiceCurrency: string, + schemas: { line?: Record; product?: Record } = {}, + draftCurrency?: string, +) { + const lineSchema = schemas.line ?? LINE_SCHEMA; + const productSchema = schemas.product ?? PRODUCT_SCHEMA; + const ds = { + getObjectSchema: vi.fn(async (name: string) => (name === 'fx_product' ? productSchema : lineSchema)), + find: vi.fn(async (name: string, params?: { $filter?: { id?: { $in?: unknown[] } } }) => { + if (name !== 'fx_product') { + return { data: [{ id: 'l1', invoice: 'i1', product: null, description: null, unit_price: null }] }; + } + const wanted = params?.$filter?.id?.$in; + const rows = PRODUCTS.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 = PRODUCTS.find((r) => r.id === id); + return row ? { ...row } : null; + }), + onMutation: () => () => {}, + }; + let handle: BodyTableEditHandle | null = null; + const session: RecordEditSession = { + register: (h) => { + handle = h; + return () => { handle = null; }; + }, + reportDirty: () => {}, + saving: false, + }; + render( + + + + + {draftCurrency ? : null} + + + + + + + , + ); + return { ds, rows: () => (handle as BodyTableEditHandle | null)?.snapshot()?.rows ?? null }; +} + +async function pickWidget(ds: { getObjectSchema: ReturnType }): Promise { + const trigger = await screen.findByTestId('lookup-trigger'); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith('fx_product')); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); + await act(async () => { + fireEvent.click(trigger); + }); + const option = await waitFor(() => { + const el = screen.getAllByRole('option').find((o) => (o.getAttribute('title') ?? o.textContent ?? '').includes('Widget')); + if (!el) throw new Error('Widget not offered'); + return el; + }, { timeout: 3000 }); + await act(async () => { + fireEvent.click(option); + }); +} + +describe('RecordBodyTableEditor — a pick does not copy an amount across currencies (objectstack#36249)', () => { + it('a line following a EUR invoice: the home price is withheld and the line says why', async () => { + const { ds, rows } = mount('EUR'); + await pickWidget(ds); + await waitFor(() => expect(rows()?.[0]).toMatchObject({ product: 'p1', description: 'A widget' })); + expect(rows()![0].unit_price ?? null).toBeNull(); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.textContent).toContain('$100.00'); + expect(note.textContent).toContain('EUR'); + }); + + it('a fixed EUR line price: a fixed EUR product price fills under a USD home currency', async () => { + const { ds, rows } = mount('USD', { + line: withPrice(LINE_SCHEMA, { type: 'currency', label: 'Unit Price', currencyConfig: FIXED_EUR }), + product: withPrice(PRODUCT_SCHEMA, { type: 'currency', label: 'Unit Price', currencyConfig: FIXED_EUR }), + }); + await pickWidget(ds); + await waitFor(() => expect(rows()?.[0]).toMatchObject({ product: 'p1', unit_price: 100 })); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); + + it('a fixed EUR line price: a home-currency product price is withheld', async () => { + const { ds, rows } = mount('USD', { + line: withPrice(LINE_SCHEMA, { type: 'currency', label: 'Unit Price', currencyConfig: FIXED_EUR }), + }); + await pickWidget(ds); + await waitFor(() => expect(rows()?.[0]).toMatchObject({ product: 'p1', description: 'A widget' })); + expect(rows()![0].unit_price ?? null).toBeNull(); + expect((await screen.findByTestId('line-items-autofill-withheld-0')).textContent).toContain('EUR'); + }); + + it('a line following a USD invoice: the home price fills as before, with no note', async () => { + const { ds, rows } = mount('USD'); + await pickWidget(ds); + await waitFor(() => expect(rows()?.[0]).toMatchObject({ product: 'p1', description: 'A widget', unit_price: 100 })); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); + + it('an invoice stored in USD with EUR staged in the open edit: the home price is withheld', async () => { + const { ds, rows } = mount('USD', {}, 'EUR'); + await pickWidget(ds); + await waitFor(() => expect(rows()?.[0]).toMatchObject({ product: 'p1', description: 'A widget' })); + expect(rows()![0].unit_price ?? null).toBeNull(); + const note = await screen.findByTestId('line-items-autofill-withheld-0'); + expect(note.textContent).toContain('$100.00'); + expect(note.textContent).toContain('EUR'); + }); + + it('an invoice stored in EUR with USD staged in the open edit: the home price fills, with no note', async () => { + const { ds, rows } = mount('EUR', {}, 'USD'); + await pickWidget(ds); + await waitFor(() => expect(rows()?.[0]).toMatchObject({ product: 'p1', description: 'A widget', unit_price: 100 })); + expect(screen.queryByTestId('line-items-autofill-withheld-0')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 65da6f35ba3..bcb2b156903 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -44,12 +44,14 @@ import { usePermissions } from '@object-ui/permissions'; import { extractFieldErrors, extractWriteErrorMessage, + useInlineEdit, useRecordContext, } from '@object-ui/react'; import { buildMasterDetailEditBatch, idOf, isBlankRow, type ChildSchema } from './masterDetailTx'; import { applyColumnPermissions } from './fieldWriteGate'; import { deriveDetail } from './deriveMasterDetail'; import { schemaDefaultValues } from './schemaDefaults'; +import { currencyFieldDefsOf, followedColumnCurrencies, parentCurrencyFieldsOf } from './parentCurrencyColumns'; import { useFormChromeTranslation } from './formChrome'; /** One reason the server gave about one line of a body table. */ @@ -290,6 +292,37 @@ export const RecordBodyTableEditor: React.FC = ({ ob [childSchema, perms.userId, homeCurrency, homeTimeZone], ); + // objectstack#36249 — the currency of each money column, as the record form + // and the other line hosts hand it to the grid: a line amount that follows + // this record through `relationshipField` is in this record's code + // (`columnCurrencies`), and any other money column is in its own field's + // currency (`columnFields`). A pick copies an amount only into a column in + // the same currency. + // + // The record is read as the user has it in the open edit, not as stored: + // the edit state saves a code change on the record and its new lines in one + // batch, so a code staged in the inline draft is the code the lines are + // saved under. A live value is `{ ...data, ...draft }` (InlineEditContext). + const inline = useInlineEdit(); + const savedRow = record?.data as Record | undefined; + const draftRow = inline?.draft; + const headerRow = useMemo | undefined>( + () => (draftRow && Object.keys(draftRow).length > 0 ? { ...(savedRow ?? {}), ...draftRow } : savedRow), + [savedRow, draftRow], + ); + const lineColumnCurrencies = useMemo( + () => followedColumnCurrencies( + parentCurrencyFieldsOf(childSchema?.fields as Record | undefined, relationshipField), + headerRow, + homeCurrency, + ), + [childSchema, relationshipField, headerRow, homeCurrency], + ); + const lineCurrencyFields = useMemo( + () => currencyFieldDefsOf(childSchema?.fields as Record | undefined), + [childSchema], + ); + const snapshotRef = useRef(null); snapshotRef.current = rows && derived ? { childObject: objectName, relationshipField, rows, original, childSchema } @@ -341,6 +374,8 @@ export const RecordBodyTableEditor: React.FC = ({ ob disabled={session.saving} contextRecord={record?.data as Record | undefined} lookupAutofill={lookupAutofillByField(childSchema?.fields as Record | undefined)} + columnCurrencies={lineColumnCurrencies} + columnFields={lineCurrencyFields} // Each child field's help, on its column header (objectstack#35804). columnHelp={columnHelpByField(childSchema?.fields as Record | undefined)} newRowValues={newRowValues} diff --git a/ui/packages/plugin-form/src/parentCurrencyColumns.ts b/ui/packages/plugin-form/src/parentCurrencyColumns.ts index 12a33160f21..333f25db700 100644 --- a/ui/packages/plugin-form/src/parentCurrencyColumns.ts +++ b/ui/packages/plugin-form/src/parentCurrencyColumns.ts @@ -38,6 +38,25 @@ export function parentCurrencyFieldsOf( return out; } +/** + * The child fields that hold an amount of money (`currency`, or a `formula` + * returning `currency`), by name, or `undefined` when none does. The line grid + * reads a pick's target currency off these (`GridField`'s `columnFields`), as + * the record form does (objectstack#36249). + */ +export function currencyFieldDefsOf( + childFields: Readonly> | null | undefined, +): Readonly> | undefined { + if (!childFields || typeof childFields !== 'object') return undefined; + let out: Record | undefined; + for (const [name, def] of Object.entries(childFields)) { + const d = def as { type?: unknown; returnType?: unknown } | null; + if (!d || typeof d !== 'object') continue; + if (d.type === 'currency' || (d.type === 'formula' && d.returnType === 'currency')) (out ??= {})[name] = def; + } + return out; +} + /** * The currency of each following column, read off the live header record. A * header with no code yet maps the column to `undefined`: no symbol, never the diff --git a/ui/packages/plugin-form/src/recordFormStamp.ts b/ui/packages/plugin-form/src/recordFormStamp.ts index 545b94ee4a7..f688c4c31af 100644 --- a/ui/packages/plugin-form/src/recordFormStamp.ts +++ b/ui/packages/plugin-form/src/recordFormStamp.ts @@ -26,21 +26,31 @@ * `lookupFilters`, so the face the widget reads carries its own stamp. * - A field whose faces neither read `{ $record }` nor carry the key comes * back as the same object. + * - A lookup declaring `lookupAutofill` also carries the definitions of its + * targets (`withLookupAutofillTargets`), read off the same field map: a + * pick copies an amount only into a target in the same currency + * (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. */ -import { RECORD_BEING_EDITED_KEY, withRecordBeingEdited } from '@object-ui/fields'; +import { RECORD_BEING_EDITED_KEY, withLookupAutofillTargets, withRecordBeingEdited } from '@object-ui/fields'; type Def = Record; const isDef = (v: unknown): v is Def => !!v && typeof v === 'object' && !Array.isArray(v); /** `face` without an authored stamp, then stamped by the form. */ -function restamp(face: Def, objectFields: Readonly> | null | undefined): Def { +function restamp( + face: Def, + objectFields: Readonly> | null | undefined, + labels: Readonly>, +): Def { let clean = face; if (Object.prototype.hasOwnProperty.call(face, RECORD_BEING_EDITED_KEY)) { const { [RECORD_BEING_EDITED_KEY]: _authored, ...rest } = face; clean = rest; } - return withRecordBeingEdited(clean, objectFields); + return withLookupAutofillTargets(withRecordBeingEdited(clean, objectFields), objectFields, labels); } /** @@ -55,11 +65,17 @@ export function stampRecordFormFields>( objectFields: Readonly> | null | undefined, ): T[] | undefined { if (!Array.isArray(fields)) return fields; + // Each drawn field's name as the form shows it (already translated), for a + // lookup's note about a target it did not fill (objectstack#36249). + const labels: Record = {}; + for (const f of fields) { + if (isDef(f) && typeof f.name === 'string' && typeof f.label === 'string' && f.label !== '') labels[f.name] = f.label; + } return fields.map((f) => { if (!isDef(f)) return f; - const outer = restamp(f, objectFields); + const outer = restamp(f, objectFields, labels); const inner = outer.field; - const field = isDef(inner) ? restamp(inner, objectFields) : inner; + const field = isDef(inner) ? restamp(inner, objectFields, labels) : inner; if (outer === f && field === inner) return f; return (field === inner ? outer : { ...outer, field }) as T; });