diff --git a/.changeset/34197-lookup-record-reference.md b/.changeset/34197-lookup-record-reference.md new file mode 100644 index 00000000000..52d4ddc02d3 --- /dev/null +++ b/.changeset/34197-lookup-record-reference.md @@ -0,0 +1,22 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-form': patch +'@object-ui/plugin-grid': patch +'@objectstack/spec': patch +--- + +feat(fields): the lookup picker reads `{ $record }` lookupFilters values from the record being edited and sends `orEmpty` + +Clause-②: no +Metadata-protocol: none + +A `lookupFilters` entry may compare a candidate column with a value of the record being edited, written `{ $record: 'quote_date' }` or, one lookup hop away, `{ $record: 'account.cb_market' }`, and may add `orEmpty: true` so a candidate whose column is null also matches. The schema has accepted both since the previous release; the lookup picker now honours them. + +- **The value.** Before the candidate query leaves the browser, the picker puts the value the reference names in its place: the quick-select popover, the table picker and the search-first people picker all send it. A one-hop path reads the lookup's target row once per id, its hop fields alone, unless the record already holds that row expanded. The query waits for that read and goes out once, with the value in it. +- **An empty value.** While the referenced value is empty (null, unset, an empty string, or an unset hop lookup) 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, the rule an unset `dependsOn` parent follows. A reference that was never resolved is never sent. +- **Re-query.** Changing a referenced field re-queries the open picker once, with the new value. Changing any other field of the record does not. +- **orEmpty.** An entry with `orEmpty: true` is sent as an `$or` of its comparison and a null match on the same column. Several such entries each keep their own alternative. +- **Record forms opt in.** `ObjectForm` and authored form sections stamp such a lookup as drawn for a single record being edited, naming the object each hop's lookup points at (`withRecordBeingEdited`, exported from `@object-ui/fields`), through the spec's `referenceTargetOf`, so a hop through a `user` field, whose target the type fixes, resolves too. The picker resolves `{ $record }` only on that stamp. Any other host, such as a bulk action dialog that hands the widget its sibling parameters, leaves every `{ $record }` entry out. A bulk action parameter cannot claim the stamp by writing it: the bulk dialog never carries `recordBeingEdited` from a parameter onto its widget. +- **Spec.** The `value`, `orEmpty` and `lookupFilters` describes on `FieldSchema` lose their `[PLANNED — not enforced]` markers and say what the picker does. The no-record example now names a bulk action over selected rows in place of a filter panel, which reads no `lookupFilters`. + +Literal entries and `dependsOn` query exactly as before. diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index bb7336bbe6b..88817c90f0d 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -93,7 +93,7 @@ const result = CurrencyConfigSchema.parse(data); | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **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): the picker sends that value in its place and re-queries whenever a referenced field changes. Those 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, and on a picker with no single record being edited (a bulk-action bar, a filter panel), 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, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. [PLANNED — not enforced] `{ $record }` and orEmpty are declared ahead of the picker that resolves them. | +| **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, never read as null. 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. | @@ -242,8 +242,8 @@ const result = CurrencyConfigSchema.parse(data); | :--- | :--- | :--- | :--- | | **field** | `string` | ✅ | | | **operator** | `Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>` | ✅ | | -| **value** | `any` | ✅ | The comparand: a literal (an array for `in` / `notIn`), a date placeholder such as `{today}` or a `{ $now: true, addDays }` comparand for a date relative to today, or a `{ $record: "path" }` reference to the record being edited — a field of it, or one lookup hop ("account.cb_market"); a `{ $record }` value pairs only with eq, ne, gt, lt, gte or lte. [PLANNED — not enforced] The picker does not resolve `{ $record }` yet. | -| **orEmpty** | `boolean` | optional | [PLANNED — not enforced] TRUE: the entry also matches a candidate whose column is null — "valid from the quote date, or with no start date". Only with eq, ne, gt, lt, gte or lte. The picker does not read it yet. | +| **value** | `any` | ✅ | The comparand: a literal (an array for `in` / `notIn`), a date placeholder such as `{today}` or a `{ $now: true, addDays }` comparand for a date relative to today, or a `{ $record: "path" }` reference to the record being edited — a field of it, or one lookup hop ("account.cb_market"); a `{ $record }` value pairs only with eq, ne, gt, lt, gte or lte. In a record form, whatever its layout, the picker sends the referenced value in place of the reference; every other picker host leaves the entry out. | +| **orEmpty** | `boolean` | optional | TRUE: the entry also matches a candidate whose column is null — "valid from the quote date, or with no start date". Only with eq, ne, gt, lt, gte or lte. The picker sends the comparison or a null match on the same column. | ### Nested Shape: `Field.lookupAutofill[number]` diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index c571b0fe6bf..8b5c26a2024 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -270,7 +270,7 @@ const result = ApiMethod.parse(data); | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **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): the picker sends that value in its place and re-queries whenever a referenced field changes. Those 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, and on a picker with no single record being edited (a bulk-action bar, a filter panel), 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, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. [PLANNED — not enforced] `{ $record }` and orEmpty are declared ahead of the picker that resolves them. | +| **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, never read as null. 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. | @@ -647,7 +647,7 @@ const result = ApiMethod.parse(data); | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **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): the picker sends that value in its place and re-queries whenever a referenced field changes. Those 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, and on a picker with no single record being edited (a bulk-action bar, a filter panel), 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, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. [PLANNED — not enforced] `{ $record }` and orEmpty are declared ahead of the picker that resolves them. | +| **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, never read as null. 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. | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 138a99c90d1..43c5323cd6f 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -96,7 +96,7 @@ Add a new field to an existing object | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **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): the picker sends that value in its place and re-queries whenever a referenced field changes. Those 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, and on a picker with no single record being edited (a bulk-action bar, a filter panel), 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, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. [PLANNED — not enforced] `{ $record }` and orEmpty are declared ahead of the picker that resolves them. | +| **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, never read as null. 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. | @@ -532,7 +532,7 @@ Add a new field to an existing object | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **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): the picker sends that value in its place and re-queries whenever a referenced field changes. Those 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, and on a picker with no single record being edited (a bulk-action bar, a filter panel), 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, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. [PLANNED — not enforced] `{ $record }` and orEmpty are declared ahead of the picker that resolves them. | +| **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, never read as null. 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. | diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index c55f515c24b..6525313fff9 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -381,8 +381,8 @@ }, "lookupFilters": { "status": "live", - "verifiedAt": "2026-10-16", - "note": "objectui LookupField + RecordPickerDialog — base scoping filters honoured by BOTH popover and dialog; structured supported form of referenceFilters. The picker reads it camelCase-only at objectui @daeb77fc84: packages/fields/src/widgets/LookupField.tsx#lookupFilters. Outside the picker, two readers keep a snake leg behind the declared key: objectui @daeb77fc84: packages/fields/src/resolveActionParams.ts#resolveActionParam reads `lookupFilters ?? lookup_filters` when it builds a lookup action param, and objectui @daeb77fc84: packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx#readLookupFilters reads `lookupFilters ?? lookup_filters` from a stored document. Declared ahead of its reader on 2026-11-15 (#34009): an entry's `{ $record: \"path\" }` value (the record being edited, at most one lookup hop) and its `orEmpty` key are parsed and refused by shape here, but the picker at objectui @daeb77fc84 resolves neither — `lookupFiltersToRecord` (packages/fields/src/widgets/RecordPickerDialog.tsx) sends the value as written and drops `orEmpty` — so both carry `[PLANNED — not enforced]` in their describe until the ui-lane follow-up lands; an unresolved `$record` reaching the server is refused there (INVALID_FILTER), never answered." + "verifiedAt": "2026-11-16", + "note": "objectui LookupField + RecordPickerDialog — base scoping filters honoured by BOTH popover and dialog; structured supported form of referenceFilters. The picker reads it camelCase-only at objectui @daeb77fc84: packages/fields/src/widgets/LookupField.tsx#lookupFilters. Outside the picker, two readers keep a snake leg behind the declared key: objectui @daeb77fc84: packages/fields/src/resolveActionParams.ts#resolveActionParam reads `lookupFilters ?? lookup_filters` when it builds a lookup action param, and objectui @daeb77fc84: packages/app-shell/src/views/metadata-admin/inspectors/ObjectFieldInspector.tsx#readLookupFilters reads `lookupFilters ?? lookup_filters` from a stored document. `{ $record: \"path\" }` values and `orEmpty` (#34009, declared 2026-11-15) are read since #34197: ui/packages/fields/src/widgets/lookupRecordReference.ts#resolveLookupFilters puts the value of the record being edited in place of each reference, only on a field a record form stamped through `withRecordBeingEdited` in the same file (record forms only, whatever their layout; the host's `dependentValues`; a one-hop path reads the lookup's target row the stamp names; any other host leaves every reference out) and leaves out an entry whose value is empty or cannot be read, before ui/packages/fields/src/widgets/LookupField.tsx#queryLookupFilters feeds the popover, the table picker and PeoplePicker; ui/packages/fields/src/widgets/RecordPickerDialog.tsx#lookupFiltersToRecord sends `orEmpty: true` as an `$or` with a `$null` match on the same column and leaves out any reference that was never resolved. The server's refusal of an unresolved `$record` by name is not measured yet; its carrier is #34199." }, "dependsOn": { "status": "live", diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 08db72289f4..d52a8651c37 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -1318,12 +1318,19 @@ const LOOKUP_FILTER_RECORD_PATH_RE = /^[a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)?$/ * - **Operator.** Only the six scalar comparisons * ({@link LOOKUP_FILTER_SCALAR_COMPARISONS}), and the reference is the whole * value: never a member of an `in` / `notIn` list. + * - **Where it resolves.** In a record form only, whatever its layout (the + * auto layout, authored or field-group sections, a modal, drawer, tabbed or + * wizard form, a master-detail header form). 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). * - **An empty value.** When the referenced value is empty (null, unset, an - * empty string, or a hop whose lookup is unset), the entry is left out of - * the candidate query, so a quote whose account has no market is offered - * every book the other entries admit. A picker with no single record being - * edited (a bulk-action selection bar, a filter panel) has no value to read - * and leaves every `{ $record }` entry out by the same rule. + * empty string, or a hop whose lookup is unset) 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 of the + * candidate query, so a quote whose account has no market is offered + * every book the other entries admit. * - **Re-query.** The picker re-queries its candidates whenever a referenced * field changes — the first segment of the path (`quote_date`, `account`). * Those fields are implied by the `$record` paths. Do NOT list them in @@ -2254,24 +2261,27 @@ export const FieldSchema = lazySchema(() => { 'The comparand: a literal (an array for `in` / `notIn`), a date placeholder such as `{today}` or a ' + '{ $now: true, addDays } comparand for a date relative to today, or a { $record: "path" } reference to the ' + 'record being edited — a field of it, or one lookup hop ("account.cb_market"); a { $record } value pairs ' - + 'only with eq, ne, gt, lt, gte or lte. [PLANNED — not enforced] The picker does not resolve { $record } yet.', + + 'only with eq, ne, gt, lt, gte or lte. In a record form, whatever its layout, the picker sends the referenced ' + + 'value in place of the reference; every other picker host leaves the entry out.', ), orEmpty: z.boolean().optional().describe( - '[PLANNED — not enforced] TRUE: the entry also matches a candidate whose column is null — "valid from the ' - + 'quote date, or with no start date". Only with eq, ne, gt, lt, gte or lte. The picker does not read it yet.', + 'TRUE: the entry also matches a candidate whose column is null — "valid from the quote date, or with no ' + + 'start date". Only with eq, ne, gt, lt, gte or lte. The picker sends the comparison or a null match on the same column.', ), }).superRefine(refuseMalformedLookupFilterEntry)).optional().describe( '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): the picker sends that value in its place and re-queries whenever a referenced field changes. Those fields ' + + '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, and on a picker with no single record being edited (a bulk-action bar, a filter panel), 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 ' + + '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, never read as null. The picker narrows the choice only: a rule the save must ' - + 'enforce belongs on the server too. [PLANNED — not enforced] { $record } and orEmpty are declared ahead of the ' - + 'picker that resolves them.', + + 'enforce belongs on the server too.', ), dependsOn: z.array(z.union([z.string(), strictObject({ surface: 'this dependsOn entry', diff --git a/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx b/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx index 41fe72358aa..dc5b1c9f3b7 100644 --- a/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx +++ b/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx @@ -331,6 +331,15 @@ const LEDGER: Readonly> = { why: 'RUNTIME-ONLY (objectstack#28245) — object-field metadata (the spec\'s `FieldSchema.lookupAutofill`) read off the ' + 'resolved `field` stash: which fields a pick fills is a fact about the object, not about one form.', }, + recordBeingEdited: { + readers: ['entry@fields/src/widgets/lookupRecordReference.ts'], + why: 'RUNTIME-ONLY (objectstack#34197) — stamped by `ObjectForm` and `buildSectionFields` (`withRecordBeingEdited`) on ' + + 'a lookup whose `lookupFilters` read `{ $record }`: the record form\'s statement that one record is being edited, ' + + 'with the object each hop points at. A host that edits no single record must not be able to claim it. The ' + + 'invariant is held by the two builders and by the closed spec shapes (the published `customFields` member and ' + + 'action params refuse the key); this face\'s loose `FormFieldSchema`, which can author it on an inline form ' + + 'field, is tracked by objectstack#34344.', + }, homeAmountSource: { readers: [CURRENCY], why: 'RUNTIME-ONLY (objectstack#27196) — the producers stamp the home-amount source onto the resolved field ' diff --git a/ui/packages/app-shell/src/views/ActionParamDialog.recordReference-34197.test.tsx b/ui/packages/app-shell/src/views/ActionParamDialog.recordReference-34197.test.tsx new file mode 100644 index 00000000000..73d845f3fba --- /dev/null +++ b/ui/packages/app-shell/src/views/ActionParamDialog.recordReference-34197.test.tsx @@ -0,0 +1,99 @@ +/** + * 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. + */ + +/** + * objectstack#34197 — an action's parameter dialog is not a record form, so a + * lookup param whose `lookupFilters` read `{ $record }` leaves that entry out, + * even when a SIBLING param carries a value of the same name. + * + * The dialog hands every picker its own in-progress values as + * `dependentValues` (objectui#8672 ruling A), and those values are not the + * record a `{ $record: 'quote_date' }` path names. The picker resolves a + * reference only on a field a record form stamped (`withRecordBeingEdited`); + * `paramToField` builds the widget field from enumerated keys and stamps + * nothing, so a param that writes `recordBeingEdited` itself is not let opt + * in either. Driven through the real `ActionParamDialog`. + * + * CONTROL: the literal entry beside it reaches the candidate query, so the + * dialog does forward `lookupFilters` — the missing entry is left out, not + * lost with the rest. + */ +import { describe, it, expect, vi, beforeAll } from 'vitest'; +import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import type { ActionParamDef } from '@object-ui/core'; +import { SchemaRendererProvider } from '@object-ui/react'; +// Module scope, per AGENTS.md 测试纪律: the picker sits behind `React.lazy`. +import '@object-ui/fields'; +import { ActionParamDialog } from './ActionParamDialog'; + +beforeAll(() => { + if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = vi.fn() as never; +}); + +const QUOTE_DATE: ActionParamDef = { name: 'quote_date', label: 'Quote date', type: 'text' }; +const PRICE_BOOK: ActionParamDef = { + name: 'price_book', + label: 'Price Book', + type: 'lookup', + referenceTo: 'price_book', + lookupFilters: [ + { field: 'is_active', operator: 'eq', value: true }, + { field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' }, orEmpty: true }, + ], +} as ActionParamDef; + +async function pickerQueries(priceBook: ActionParamDef) { + const ds = { + find: vi.fn(async () => ({ data: [{ id: 'b1', name: 'Standard 2026' }], total: 1 })), + findOne: vi.fn(async () => null), + }; + render( + + {} }} onOpenChange={() => {}} /> + , + ); + fireEvent.change(await screen.findByLabelText('Quote date'), { target: { value: '2026-11-01' } }); + const trigger = await screen.findByTestId('lookup-trigger-price_book'); + await act(async () => { + fireEvent.click(trigger); + }); + const queries = () => ds.find.mock.calls.filter((c: any[]) => c[0] === 'price_book').map((c: any[]) => c[1]?.$filter); + await waitFor(() => expect(queries().length).toBeGreaterThan(0)); + return { queries: queries(), ds }; +} + +describe('ActionParamDialog — a { $record } lookup filter is left out (objectstack#34197)', () => { + it('a param that writes the record-form stamp itself gains nothing: the entry is still left out', async () => { + const { queries, ds } = await pickerQueries({ ...PRICE_BOOK, recordBeingEdited: { hopObjects: {} } } as ActionParamDef); + for (const filter of queries) expect(filter).toEqual({ is_active: true }); + expect(ds.findOne).not.toHaveBeenCalled(); + }); + + it('leaves the entry out although a sibling param holds a value of that name', async () => { + const ds = { + find: vi.fn(async () => ({ data: [{ id: 'b1', name: 'Standard 2026' }], total: 1 })), + findOne: vi.fn(async () => null), + }; + render( + + {} }} onOpenChange={() => {}} /> + , + ); + fireEvent.change(await screen.findByLabelText('Quote date'), { target: { value: '2026-11-01' } }); + + const trigger = await screen.findByTestId('lookup-trigger-price_book'); + await act(async () => { + fireEvent.click(trigger); + }); + const queries = () => ds.find.mock.calls.filter((c: any[]) => c[0] === 'price_book').map((c: any[]) => c[1]?.$filter); + await waitFor(() => expect(queries().length).toBeGreaterThan(0)); + for (const filter of queries()) expect(filter).toEqual({ is_active: true }); + expect(ds.findOne).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 037a90b6116..bdd79a03160 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5382,6 +5382,9 @@ export { PERMISSION_SET_GRANT_COLUMNS } from './widgets/permissionSetHolders.js' // `permission-ref` field's definition, so the widget recognises the grant's // name column by its object and its column, not by its column name alone. export { FORM_OBJECT_KEY, withFormObject } from './widgets/permissionSetHolders.js'; +// A record form stamps any lookup whose `lookupFilters` read `{ $record }`: one record is being edited here, +// with the object each hop points at. Only a field carrying the stamp resolves a `{ $record }`. +export { RECORD_BEING_EDITED_KEY, withRecordBeingEdited } from './widgets/lookupRecordReference.js'; // New widgets according to @objectstack/spec export * from './widgets/ColorField.js'; export * from './widgets/SliderField.js'; diff --git a/ui/packages/fields/src/widgets/LookupField.recordReference-34197.test.tsx b/ui/packages/fields/src/widgets/LookupField.recordReference-34197.test.tsx new file mode 100644 index 00000000000..f8a28947a23 --- /dev/null +++ b/ui/packages/fields/src/widgets/LookupField.recordReference-34197.test.tsx @@ -0,0 +1,304 @@ +/** + * 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. + */ + +/** + * `lookupFilters` values that read the record being edited — `{ $record }` — + * and the `orEmpty` flag (`@objectstack/spec` `field.zod.ts`, + * `LookupFilterRecordReferenceSchema`). + * + * The picker sends the referenced value in place of the reference, reads a + * one-hop path off the lookup's target row, leaves an entry out while its + * value is empty, re-queries when a referenced field changes, and sends + * `orEmpty: true` as an `$or` with a null match on the same column. Literal + * entries and `dependsOn` query exactly as before. + * + * Resolution is opt-in by the host: only a field a record form stamped + * (`withRecordBeingEdited`) reads the values it is handed. A host that edits + * no single record — a bulk action dialog handing the widget its sibling + * parameters — leaves every `{ $record }` entry out. + */ + +import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { LookupField } from './LookupField'; +import { lookupFiltersToRecord } from './RecordPickerDialog'; +import { RECORD_BEING_EDITED_KEY, resolveLookupFilters, withRecordBeingEdited } from './lookupRecordReference'; + +const books = [{ id: 'b1', name: 'Standard 2026' }]; + +function makeDataSource(hopRows: Record> = {}) { + const find = vi.fn(async () => ({ data: books, total: books.length })); + const findOne = vi.fn(async (object: string, id: string) => hopRows[`${object}:${id}`] ?? null); + return { find, findOne } as any; +} + +/** The `$filter` of every candidate query sent to `price_book`, in order. */ +function candidateFilters(ds: { find: { mock: { calls: any[][] } } }): unknown[] { + return ds.find.mock.calls.filter((c) => c[0] === 'price_book').map((c) => c[1]?.$filter); +} + +function priceBookField(lookupFilters: unknown[], extra: Record = {}) { + return { name: 'price_book', label: 'Price Book', reference: 'price_book', lookupFilters, ...extra } as any; +} + +/** The field as a record form hands it: stamped as drawn for a single record being edited. */ +function formField(lookupFilters: unknown[], objectFields: Record = {}) { + return withRecordBeingEdited(priceBookField(lookupFilters), objectFields); +} + +async function openPopover() { + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: /select/i })); + }); +} + +beforeEach(() => { + try { + localStorage.clear(); + } catch { + /* jsdom */ + } +}); + +describe('LookupField — { $record } lookupFilters values (#34197)', () => { + it('sends a field of the record being edited in place of the reference', async () => { + const ds = makeDataSource(); + render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(candidateFilters(ds)[0]).toEqual({ valid_from: { $lte: '2026-11-01' } }); + }); + + it('reads a one-hop path off the row the lookup points at, and queries once with its value', async () => { + const ds = makeDataSource({ 'account:a1': { id: 'a1', cb_market: 'm9' } }); + const field = formField( + [{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }], + { account: { type: 'lookup', reference: 'account' } }, + ); + render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(ds.findOne).toHaveBeenCalledWith('account', 'a1', { $select: ['id', 'cb_market'] }); + expect(candidateFilters(ds)).toEqual([{ cb_market: 'm9' }]); + }); + + it('reads a hop the record already holds expanded without another request', async () => { + const ds = makeDataSource(); + render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(candidateFilters(ds)[0]).toEqual({ cb_market: 'm7' }); + expect(ds.findOne).not.toHaveBeenCalled(); + }); + + it('leaves an entry out while the referenced value is empty, and on a picker given no record', async () => { + const filters = [ + { field: 'is_active', operator: 'eq', value: true }, + { field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }, + { field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }, + ]; + const ds = makeDataSource(); + const { unmount } = render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(candidateFilters(ds)[0]).toEqual({ is_active: true }); + unmount(); + + const bare = makeDataSource(); + render(); + await openPopover(); + await waitFor(() => expect(candidateFilters(bare)).toHaveLength(1)); + expect(candidateFilters(bare)[0]).toEqual({ is_active: true }); + }); + + it('re-queries once when a referenced field changes, and not when another field does', async () => { + const ds = makeDataSource(); + const field = formField([{ field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }]); + const { rerender } = render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + + rerender( + , + ); + await act(async () => { await Promise.resolve(); }); + expect(candidateFilters(ds)).toHaveLength(1); + + rerender( + , + ); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(2)); + await act(async () => { await Promise.resolve(); }); + expect(candidateFilters(ds)).toEqual([ + { valid_from: { $lte: '2026-11-01' } }, + { valid_from: { $lte: '2026-12-01' } }, + ]); + }); + + it('sends orEmpty as an $or with a null match on the same column', async () => { + const ds = makeDataSource(); + render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(candidateFilters(ds)[0]).toEqual({ + is_active: true, + $and: [ + { $or: [{ valid_from: { $lte: '2026-11-01' } }, { valid_from: { $null: true } }] }, + { $or: [{ valid_to: { $gte: '2026-11-01' } }, { valid_to: { $null: true } }] }, + ], + }); + }); + + it('hands the table picker the resolved values', async () => { + const ds = makeDataSource(); + render( + , + ); + await act(async () => { + fireEvent.click(screen.getByTestId('browse-all-records')); + }); + await waitFor(() => expect(candidateFilters(ds).length).toBeGreaterThan(0)); + for (const filter of candidateFilters(ds)) { + expect(filter).toEqual({ + $and: [{ $or: [{ valid_from: { $lte: '2026-11-01' } }, { valid_from: { $null: true } }] }], + }); + } + }); + + it('a host that does not say a record is being edited leaves every { $record } entry out, even when its values hold one of that name', async () => { + // The bulk action dialog's shape: the widget is handed the dialog's sibling + // parameter values, and its field carries no record-form stamp. + const filters = [ + { field: 'is_active', operator: 'eq', value: true }, + { field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }, + { field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }, + ]; + const ds = makeDataSource({ 'account:a1': { id: 'a1', cb_market: 'm9' } }); + render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(candidateFilters(ds)[0]).toEqual({ is_active: true }); + expect(ds.findOne).not.toHaveBeenCalled(); + }); + + it('CONTROL: the same field and values on a record-form host resolve', async () => { + const filters = [ + { field: 'is_active', operator: 'eq', value: true }, + { field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }, + { field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' } }, + ]; + const ds = makeDataSource(); + const field = formField(filters, { account: { type: 'lookup', reference: 'account' } }); + expect(field[RECORD_BEING_EDITED_KEY]).toEqual({ hopObjects: { account: 'account' } }); + render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(candidateFilters(ds)[0]).toEqual({ is_active: true, valid_from: { $lte: '2026-11-01' }, cb_market: 'm7' }); + }); + + it('CONTROL: a literal entry and a dependsOn entry query exactly as before', async () => { + const ds = makeDataSource(); + render( + , + ); + await openPopover(); + await waitFor(() => expect(candidateFilters(ds)).toHaveLength(1)); + expect(candidateFilters(ds)[0]).toEqual({ is_active: true, account: 'a1' }); + expect(ds.findOne).not.toHaveBeenCalled(); + }); +}); + +describe('lookupFiltersToRecord — an unresolved { $record } never reaches the wire (#34197)', () => { + it('leaves out an entry still carrying a reference, and keeps the literal ones', () => { + expect( + lookupFiltersToRecord([ + { field: 'is_active', operator: 'eq', value: true }, + { field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' }, orEmpty: true }, + ]), + ).toEqual({ is_active: true }); + }); + + it('resolveLookupFilters keeps literal entries, in order, as the same objects', () => { + const literal = { field: 'is_active', operator: 'eq' as const, value: true }; + const out = resolveLookupFilters( + [literal, { field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' } }], + { quote_date: '2026-11-01' }, + ); + expect(out[0]).toBe(literal); + expect(out[1]).toEqual({ field: 'valid_from', operator: 'lte', value: '2026-11-01' }); + }); +}); diff --git a/ui/packages/fields/src/widgets/LookupField.tsx b/ui/packages/fields/src/widgets/LookupField.tsx index a833611d9c8..8e81575ee06 100644 --- a/ui/packages/fields/src/widgets/LookupField.tsx +++ b/ui/packages/fields/src/widgets/LookupField.tsx @@ -15,6 +15,13 @@ import { toDomProps } from './toDomProps.js'; import { PHONE_TOUCH_HEIGHT, PHONE_TOUCH_SQUARE } from './touchTarget.js'; import type { DataSource, FormField, QueryParams, LookupColumnDef, LookupFieldMetadata } from '@object-ui/types'; import { RecordPickerDialog, lookupFiltersToRecord } from './RecordPickerDialog.js'; +import { + readRecordBeingEdited, + readsRecord, + resolveLookupFilters, + useRecordHopRows, + type LookupFilterEntry, +} from './lookupRecordReference.js'; import type { RecordPickerFilterColumn } from './RecordPickerDialog.js'; import { PeoplePicker } from './PeoplePicker.js'; import { useRecordQuery } from './useRecordQuery.js'; @@ -40,6 +47,9 @@ import { usePermissions } from '@object-ui/permissions'; import { useFieldTranslation } from './useFieldTranslation.js'; import { ScanFieldButton, useFieldScanOffered } from './ScanFieldButton.js'; +/** The record a host that edits none hands `{ $record }` resolution: nothing to read. */ +const NO_EDITED_RECORD: Readonly> = Object.freeze({}); + export interface LookupOption { value: string | number; label: string; @@ -408,7 +418,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro // Enterprise Record Picker configuration const lookupColumns: Array | undefined = fieldMeta?.lookupColumns; const lookupPageSize: number | undefined = fieldMeta?.lookupPageSize; - const lookupFilters: import('@object-ui/types').LookupFilterDef[] | undefined = fieldMeta?.lookupFilters; + const lookupFilters: LookupFilterEntry[] | undefined = fieldMeta?.lookupFilters; // Search-first PeoplePicker opt-in (user fields). When `picker === 'search'` // the Level-2 picker is the rich PeoplePicker (avatar rows + selection tray) @@ -529,6 +539,47 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro }); }, [dependsOn, resolvedDependentValues]); + /** + * `lookupFilters` as the candidate queries send them: every `{ $record }` + * value replaced by the value it names on the record being edited — the + * same host record `dependsOn` reads — and every entry whose value is empty + * left out (`resolveLookupFilters`). A one-hop path (`account.cb_market`) + * reads the lookup's target row once per id, unless the record already + * holds it expanded; the queries wait for that read and go out once, with + * the value in them. + * + * The referenced fields are not `dependsOn` parents and gate nothing. A + * change to one changes the resolved values, and the queries key on those + * values, so the candidates re-query; a change to any other field of the + * record leaves the resolved list, and so every query, as it was. + * + * Opt-in by the host: only a field a record form stamped + * (`withRecordBeingEdited`) resolves against the values it is handed. On any + * other host — a bulk action over selected rows, an action's parameter + * dialog — those values are not the record the path names, so every + * `{ $record }` entry is left out, as on a picker given no record at all. + * + * Filters that read no record pass through as authored, the same array. + */ + const filtersReadRecord = readsRecord(lookupFilters); + const recordBeingEdited = readRecordBeingEdited(fieldMeta); + const editedRecord = recordBeingEdited ? resolvedDependentValues : NO_EDITED_RECORD; + const recordHops = useRecordHopRows( + filtersReadRecord ? lookupFilters : undefined, + editedRecord, + recordBeingEdited?.hopObjects, + dataSource, + ); + const recordReadsPending = recordHops.pending; + const resolvedFiltersKey = filtersReadRecord && lookupFilters + ? JSON.stringify(resolveLookupFilters(lookupFilters, editedRecord, recordHops.rows)) + : ''; + const resolvedRecordFilters = useMemo( + () => (resolvedFiltersKey ? (JSON.parse(resolvedFiltersKey) as LookupFilterEntry[]) : undefined), + [resolvedFiltersKey], + ); + const queryLookupFilters = filtersReadRecord ? resolvedRecordFilters : lookupFilters; + const hasDataSource = dataSource != null && typeof dataSource.find === 'function' && !!referenceTo; // Fetch the referenced object's schema so option labels resolve through its @@ -748,16 +799,16 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro // + base lookupFilters, so the popover matches the full picker. const popoverFilter = useMemo | undefined>(() => { const f: Record = { - ...(lookupFilters && lookupFilters.length > 0 ? lookupFiltersToRecord(lookupFilters) : {}), + ...(queryLookupFilters && queryLookupFilters.length > 0 ? lookupFiltersToRecord(queryLookupFilters) : {}), ...(dependentFilter ?? {}), }; return Object.keys(f).length > 0 ? f : undefined; - }, [dependentFilter, lookupFilters]); + }, [dependentFilter, queryLookupFilters]); const popoverQuery = useRecordQuery({ dataSource, objectName: referenceTo, - enabled: isOpen && hasDataSource && !dependenciesMissing, + enabled: isOpen && hasDataSource && !dependenciesMissing && !recordReadsPending, pageSize: LOOKUP_PAGE_SIZE, filter: popoverFilter, expand: candidateExpand, @@ -1247,6 +1298,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro useEffect(() => { if (!isOpen || !hasDataSource || !dataSource || !referenceTo || searchQuery) return; if (dependenciesMissing) { setRecentRows([]); return; } + if (recordReadsPending) return; const ids = getRecentLookupIds(referenceTo); if (!ids.length) { setRecentRows([]); return; } let cancelled = false; @@ -1277,7 +1329,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro })(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isOpen, hasDataSource, referenceTo, searchQuery, dependenciesMissing, popoverFilter, idField, candidateExpandKey]); + }, [isOpen, hasDataSource, referenceTo, searchQuery, dependenciesMissing, recordReadsPending, popoverFilter, idField, candidateExpandKey]); const recentOptions = useMemo( () => recentRows.map((r) => @@ -1793,7 +1845,8 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro { setIsPickerOpen(o); if (!o) setPickerInitialSearch(undefined); @@ -1811,7 +1864,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro value={pickerValue} onSelect={onChange} onSelectRecords={handlePickerSelectRecords} - lookupFilters={lookupFilters} + lookupFilters={queryLookupFilters} baseFilter={dependentFilter} /> {lookupScan} @@ -2032,7 +2085,8 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro {/* Level 2: classic table picker — search fields use the inline combobox above. */} {hasDataSource && dataSource && referenceTo && pickerVariant !== 'search' && ( compatible with + * The comparisons `orEmpty` pairs with — the spec's six scalar orderings and + * equalities (`LOOKUP_FILTER_SCALAR_COMPARISONS` in `field.zod.ts`, which + * refuses the flag on any other operator). + */ +const OR_EMPTY_OPERATORS: ReadonlySet = new Set(['eq', 'ne', 'gt', 'lt', 'gte', 'lte']); + +/** No condition: an operator outside the nine, which adds nothing to the filter. */ +const NO_CONDITION = Symbol('no-condition'); + +/** One entry's condition on its column, in the `$filter` record form. */ +function lookupFilterCondition(f: LookupFilterEntry): unknown { + switch (f.operator) { + case 'eq': return f.value; + case 'ne': return { $ne: f.value }; + case 'gt': return { $gt: f.value }; + case 'lt': return { $lt: f.value }; + case 'gte': return { $gte: f.value }; + case 'lte': return { $lte: f.value }; + case 'contains': return { $contains: f.value }; + case 'in': return { $in: f.value }; + case 'notIn': return { $nin: f.value }; + default: return NO_CONDITION; + } +} + +/** + * Convert `lookupFilters` entries to a Record compatible with * QueryParams.$filter. Supports operator mapping for eq/ne/gt/lt/gte/lte/ * contains/in/notIn. + * + * An entry with `orEmpty: true` also matches a candidate whose column is null: + * it is sent as `{ $or: [condition, { column: { $null: true } }] }`, one member + * of a `$and` list, so two such entries — or one beside a plain entry on the + * same column — each keep their own alternative. + * + * ⛔ A `{ $record }` comparand is the picker's to replace with a value of the + * record being edited (`resolveLookupFilters`, which LookupField runs before + * calling this). An entry still carrying one here was never resolved and is + * left out: the server knows no record being edited, and refuses the + * reference rather than read it. */ export function lookupFiltersToRecord( - filters: LookupFilterDef[], + filters: readonly LookupFilterEntry[], ): Record { const result: Record = {}; + const orEmpty: Record[] = []; for (const f of filters) { - switch (f.operator) { - case 'eq': - result[f.field] = f.value; - break; - case 'ne': - result[f.field] = { $ne: f.value }; - break; - case 'gt': - result[f.field] = { $gt: f.value }; - break; - case 'lt': - result[f.field] = { $lt: f.value }; - break; - case 'gte': - result[f.field] = { $gte: f.value }; - break; - case 'lte': - result[f.field] = { $lte: f.value }; - break; - case 'contains': - result[f.field] = { $contains: f.value }; - break; - case 'in': - result[f.field] = { $in: f.value }; - break; - case 'notIn': - result[f.field] = { $nin: f.value }; - break; + if (isRecordReference(f.value)) continue; + const condition = lookupFilterCondition(f); + if (condition === NO_CONDITION) continue; + if (f.orEmpty === true && OR_EMPTY_OPERATORS.has(f.operator)) { + orEmpty.push({ $or: [{ [f.field]: condition }, { [f.field]: { $null: true } }] }); + } else { + result[f.field] = condition; } } + if (orEmpty.length > 0) result.$and = orEmpty; return result; } @@ -404,8 +423,10 @@ export interface RecordPickerDialogProps { * Base filters applied to every query. * Converted from LookupFieldMetadata.lookupFilters. * Restricts which records are selectable (e.g. only active records). + * `{ $record }` values arrive already resolved (LookupField); one that did + * not is left out of the query by `lookupFiltersToRecord`. */ - lookupFilters?: LookupFilterDef[]; + lookupFilters?: readonly LookupFilterEntry[]; /** * Hard filter constraint applied to every query. Unlike `lookupFilters`, diff --git a/ui/packages/fields/src/widgets/lookupRecordReference.ts b/ui/packages/fields/src/widgets/lookupRecordReference.ts new file mode 100644 index 00000000000..17e5815c245 --- /dev/null +++ b/ui/packages/fields/src/widgets/lookupRecordReference.ts @@ -0,0 +1,314 @@ +/** + * 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 picker half of `@objectstack/spec`'s `lookupFilters` comparand + * `{ $record: 'path' }` — a value of the RECORD BEING EDITED, which the picker + * puts in place of the reference before the candidate query leaves the + * browser (`LookupFilterRecordReferenceSchema` in `field.zod.ts` states the + * contract; this module is its one reader). + * + * Invariants: + * - A path is a field of the edited record (`quote_date`) or one lookup hop + * from it (`account.cb_market`). + * - The picker resolves a reference only where its host SAYS a single record + * is being edited: a record form stamps that on the field it hands the + * widget (`withRecordBeingEdited`). Every other host — a bulk action over + * selected rows, an action's parameter dialog, inline edit on a record + * page — leaves every `{ $record }` entry out, whatever values it passes the widget: the values + * such a host passes are not the record the author's path names. + * - An entry whose referenced value is empty — null, unset, `''`, an empty + * list, a hop whose lookup is unset — is left out of the query, the rule an + * unset `dependsOn` parent follows. + * - A hop whose row cannot be read is left out the same way: the picker + * narrows the choice only, and the save is the server's to judge. + * - ⛔ No `{ $record }` value ever reaches the wire: `lookupFiltersToRecord` + * drops one that was never resolved. + */ +import { useContext, useEffect, useMemo, useRef, useState } from 'react'; +import { SchemaRendererContext } from '@object-ui/react'; +import { referenceTargetOf } from '@objectstack/spec/data'; +import type { Field as SpecField, LookupFilterRecordReference } from '@objectstack/spec/data'; + +/** One authored `lookupFilters` entry, typed by reference to the spec row. */ +export type LookupFilterEntry = NonNullable[number]; + +/** + * The key a record form stamps on a lookup field whose `lookupFilters` read + * `{ $record }`, the host's statement that a single record is being edited + * here. Its value names the object each hop's lookup points at + * (`{ hopObjects: { account: 'account' } }`): a widget receives one field, + * not the object it is drawn for, so it could not otherwise name the object + * to read `account`'s row from. The same hand-off shape as + * `FOLLOWED_PARENT_OBJECT_KEY` (`currency.ts`) and `FORM_OBJECT_KEY`. + * + * ⛔ Opt-in: a widget whose field carries no stamp resolves no `{ $record }`. + */ +export const RECORD_BEING_EDITED_KEY = 'recordBeingEdited'; + +/** What a record form stamps under {@link RECORD_BEING_EDITED_KEY}. */ +export interface RecordBeingEdited { + hopObjects: Readonly>; +} + +/** One `{ $record }` hop: the lookup on the edited record and the field read on its target. */ +export interface RecordReferenceHop { + via: string; + field: string; +} + +/** Is `value` a `{ $record: path }` comparand? Shape only, as the spec's refinement reads it. */ +export function isRecordReference(value: unknown): value is LookupFilterRecordReference { + return !!value && typeof value === 'object' && !Array.isArray(value) + && Object.prototype.hasOwnProperty.call(value, '$record'); +} + +function recordPath(value: unknown): string | undefined { + if (!isRecordReference(value)) return undefined; + const path = (value as { $record?: unknown }).$record; + return typeof path === 'string' && path !== '' ? path : undefined; +} + +/** Does any entry read the edited record? */ +export function readsRecord(filters: readonly LookupFilterEntry[] | undefined): boolean { + return !!filters?.some((f) => isRecordReference(f?.value)); +} + +/** The one-hop paths the entries name, one per distinct `via.field`. */ +export function recordReferenceHops(filters: readonly LookupFilterEntry[] | undefined): RecordReferenceHop[] { + const hops: RecordReferenceHop[] = []; + const seen = new Set(); + for (const f of filters ?? []) { + const path = recordPath(f?.value); + const dot = path ? path.indexOf('.') : -1; + if (!path || dot < 0 || seen.has(path)) continue; + seen.add(path); + hops.push({ via: path.slice(0, dot), field: path.slice(dot + 1) }); + } + return hops; +} + +const isRow = (v: unknown): v is Record => + v !== null && typeof v === 'object' && !Array.isArray(v); + +/** Empty by the `dependsOn` gate's own test. */ +function isEmptyValue(v: unknown): boolean { + return v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0); +} + +/** A related record as the query compares it: an expanded row collapses to its id. */ +function collapseReference(v: unknown): unknown { + if (!isRow(v) || v instanceof Date) return v; + return v.id ?? v._id ?? v; +} + +/** The id a record's lookup holds — bare, or under an expanded row. */ +function referencedId(v: unknown): string | undefined { + const id = collapseReference(v); + if (typeof id === 'string' && id !== '') return id; + if (typeof id === 'number') return String(id); + return undefined; +} + +/** + * `def` stamped under {@link RECORD_BEING_EDITED_KEY}: the record form's + * statement that the widget is drawn for a single record being edited, with + * the object each `{ $record }` hop's lookup references (read off `fields`, + * the edited object's field map). `def` itself when its filters read no + * record. Only a host that edits one record calls this. + * + * A hop's object is the spec's `referenceTargetOf` — the one arbiter the + * `$record` path rule of the object linter also asks — so a hop through a + * field whose target the type fixes (`user` → `sys_user`, with no + * `reference` written) is named like one through a `lookup`. + */ +export function withRecordBeingEdited( + def: T, + fields: Readonly> | null | undefined, +): T { + const filters = (def as { lookupFilters?: LookupFilterEntry[] }).lookupFilters; + if (!readsRecord(filters)) return def; + const hopObjects: Record = {}; + for (const { via } of recordReferenceHops(filters)) { + const target = referenceTargetOf(fields?.[via]); + if (target) hopObjects[via] = target; + } + const stamp: RecordBeingEdited = { hopObjects }; + return { ...def, [RECORD_BEING_EDITED_KEY]: stamp }; +} + +/** The record-being-edited stamp a form put on `field`, or `undefined` when none did. */ +export function readRecordBeingEdited(field: unknown): RecordBeingEdited | undefined { + const value = (field as Record | null | undefined)?.[RECORD_BEING_EDITED_KEY]; + if (!isRow(value)) return undefined; + const hopObjects = isRow(value.hopObjects) ? (value.hopObjects as Record) : {}; + return { hopObjects }; +} + +/** + * The value a `{ $record }` path names, or `undefined` when it is empty or + * cannot be read. `hopRows` holds the rows read for each hop's lookup, by + * `via`; an expanded row on the record itself is read first, so a host that + * already holds the related record costs no request. + */ +function readRecordPath( + path: string, + record: Readonly>, + hopRows: Readonly | undefined>>, +): unknown { + const dot = path.indexOf('.'); + if (dot < 0) { + const v = collapseReference(record[path]); + return isEmptyValue(v) ? undefined : v; + } + const via = path.slice(0, dot); + const field = path.slice(dot + 1); + const held = record[via]; + if (isEmptyValue(held)) return undefined; + const row = isRow(held) && Object.prototype.hasOwnProperty.call(held, field) ? held : hopRows[via]; + if (!row) return undefined; + const v = collapseReference(row[field]); + return isEmptyValue(v) ? undefined : v; +} + +/** + * `filters` with every `{ $record }` value replaced by the value it names on + * `record`, and every entry whose value is empty or unreadable left out. + * Literal entries pass through untouched, in order. + */ +export function resolveLookupFilters( + filters: readonly LookupFilterEntry[], + record: Readonly>, + hopRows: Readonly | undefined>> = {}, +): LookupFilterEntry[] { + const out: LookupFilterEntry[] = []; + for (const f of filters) { + if (!isRecordReference(f.value)) { + out.push(f); + continue; + } + const path = recordPath(f.value); + const value = path ? readRecordPath(path, record, hopRows) : undefined; + if (value !== undefined) out.push({ ...f, value }); + } + return out; +} + +const warnedHops = new Set(); + +/** + * Said once per hop: the entry is left out, so the picker offers more than the + * author wrote — visible here rather than only as a wider list. + */ +function warnUnreadableHop(via: string, field: string, object: string | undefined): void { + if ((globalThis as { process?: { env?: { NODE_ENV?: string } } }).process?.env?.NODE_ENV === 'production') return; + const key = `${via}.${field}`; + if (warnedHops.has(key)) return; + warnedHops.add(key); + console.warn( + `[LookupField] lookupFilters { $record: "${key}" } is left out of the candidate query: ` + + (object + ? `no data source here can read ${object} rows.` + : `the record holds "${via}" as an id, and this host did not name the object it points at ` + + `(a record form stamps it with withRecordBeingEdited).`), + ); +} + +interface HopSource { + findOne?: (resource: string, id: string, params?: Record) => Promise; +} + +/** One hop read the record currently calls for: the row of `object` with id `id`. */ +interface HopRead { + via: string; + object: string; + id: string; + fields: string[]; + key: string; +} + +/** + * Read the rows the `{ $record }` hops of `filters` need, once per lookup id: + * the target's hop fields alone. A hop the record already holds expanded, an + * unset lookup, and a hop whose object no form stamped are not read. + * + * `pending` is true while a read the record calls for has not landed, so the + * caller holds its candidate query and sends it once, with the value in it. + */ +export function useRecordHopRows( + filters: readonly LookupFilterEntry[] | undefined, + record: Readonly>, + hopObjects: Readonly> | undefined, + dataSource: unknown, +): { rows: Readonly | undefined>>; pending: boolean } { + const ctx = useContext(SchemaRendererContext); + const source = (dataSource ?? ctx?.dataSource) as HopSource | null | undefined; + const canRead = typeof source?.findOne === 'function'; + + const reads: HopRead[] = []; + const byVia = new Map(); + for (const { via, field } of recordReferenceHops(filters)) { + const held = record[via]; + if (isRow(held) && Object.prototype.hasOwnProperty.call(held, field)) continue; + const object = hopObjects?.[via]; + const id = referencedId(held); + if (id !== undefined && (!object || !canRead)) warnUnreadableHop(via, field, object); + if (!object || id === undefined || !canRead) continue; + const existing = byVia.get(via); + if (existing) { + existing.fields.push(field); + continue; + } + const read: HopRead = { via, object, id, fields: [field], key: '' }; + byVia.set(via, read); + reads.push(read); + } + for (const read of reads) read.key = `${read.object}\u0000${read.id}\u0000${read.fields.join(',')}`; + // The reads as one primitive: the effect below keys on it, never on an array identity. + const readsKey = reads.map((r) => `${r.via}\u0001${r.key}`).join('\u0002'); + + // Answers are keyed by object, id and fields, so one that lands after the + // record moved on is kept for that key and never read for another. + const [answers, setAnswers] = useState | null>>({}); + const requested = useRef(new Set()); + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { mounted.current = false; }; + }, []); + useEffect(() => { + if (!readsKey || !source?.findOne) return; + for (const entry of readsKey.split('\u0002')) { + const [, key] = entry.split('\u0001'); + if (requested.current.has(key)) continue; + requested.current.add(key); + const [object, id, fields] = key.split('\u0000'); + const settle = (row: Record | null) => { + if (mounted.current) setAnswers((a) => ({ ...a, [key]: row })); + }; + source.findOne(object, id, { $select: ['id', ...fields.split(',')] }).then( + (row) => settle(isRow(row) ? row : null), + () => settle(null), + ); + } + }, [readsKey, source]); + + const rows: Record | undefined> = {}; + let pending = false; + for (const read of reads) { + if (!(read.key in answers)) { + pending = true; + continue; + } + rows[read.via] = answers[read.key] ?? undefined; + } + const rowsKey = JSON.stringify(rows); + // Stable across renders that read the same rows (AGENTS.md #10: keyed on the payload). + const stableRows = useMemo(() => JSON.parse(rowsKey) as typeof rows, [rowsKey]); + return { rows: stableRows, pending }; +} diff --git a/ui/packages/plugin-form/src/ObjectForm.tsx b/ui/packages/plugin-form/src/ObjectForm.tsx index 606cc60f86d..930ef89f1dc 100644 --- a/ui/packages/plugin-form/src/ObjectForm.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.tsx @@ -18,7 +18,7 @@ import type { ObjectFormSchema, FormField, FormSchema, DataSource } from '@objec import { SchemaRenderer, useSafeFieldLabel } from '@object-ui/react'; import { pickLocalized, useObjectTranslation, useLocalization, withHomeAmountSource } from '@object-ui/i18n'; import { useRecordInvalidation } from './recordInvalidation'; -import { mapFieldTypeToFormType, buildValidationRules, formatFileSize, fieldHelpText, withFollowedParentObject, withFormObject, PERMISSION_SET_GRANT_COLUMNS } from '@object-ui/fields'; +import { mapFieldTypeToFormType, buildValidationRules, formatFileSize, fieldHelpText, withFollowedParentObject, withFormObject, withRecordBeingEdited, PERMISSION_SET_GRANT_COLUMNS } from '@object-ui/fields'; import { isExpressionComputedField } from '@object-ui/core'; import { useIsMobile, toast } from '@object-ui/components'; import { resolveSuccessNavigate } from './successBehavior'; @@ -1021,8 +1021,16 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource // A `permission-ref` field also carries the object this form edits // (objectstack#32795), so the widget tells the grant's name column // from a column of the same name on another object. + // A lookup whose `lookupFilters` read `{ $record }` also carries the + // form's statement that one record is being edited here, with the + // object each hop's lookup points at: its picker resolves the + // references only on that stamp, and reads a hop for the id the + // form holds. field: withFormObject( - withFollowedParentObject(withHomeAmountSource(field, objectSchema.fields, name), objectSchema.fields), + withRecordBeingEdited( + withFollowedParentObject(withHomeAmountSource(field, objectSchema.fields, name), objectSchema.fields), + objectSchema.fields, + ), schema.objectName, ), // A per-field widget override. `form.tsx` resolves `widget || type`, so this makes the diff --git a/ui/packages/plugin-form/src/__tests__/lookupRecordHop-34197.test.tsx b/ui/packages/plugin-form/src/__tests__/lookupRecordHop-34197.test.tsx new file mode 100644 index 00000000000..8a8a6af7315 --- /dev/null +++ b/ui/packages/plugin-form/src/__tests__/lookupRecordHop-34197.test.tsx @@ -0,0 +1,193 @@ +/** + * 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. + */ + +/** + * A record form stamps, on a lookup it draws whose `lookupFilters` read + * `{ $record }`, that one record is being edited here, with the object each + * hop's lookup points at (`withRecordBeingEdited`). The picker resolves the + * references only on that stamp, and reads `account.cb_market` for the + * account id the form holds. Both field builders stamp it: the auto-layout + * `ObjectForm` and the authored sections (`buildSectionFields`, through + * `ModalForm`). + */ +import { describe, it, expect, afterEach } from 'vitest'; +import { render, waitFor, cleanup, fireEvent, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { registerAllFields } from '@object-ui/fields'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { ObjectForm } from '../ObjectForm'; +import { ModalForm } from '../ModalForm'; + +registerAllFields(); +afterEach(cleanup); + +const QUOTE = { + name: 'quote', + fields: { + subject: { type: 'text', label: 'Subject' }, + quote_date: { type: 'date', label: 'Quote date' }, + account: { type: 'lookup', label: 'Account', reference: 'account' }, + price_book: { + type: 'lookup', + label: 'Price Book', + reference: 'price_book', + lookupFilters: [ + { field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' }, orEmpty: true }, + { field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' }, orEmpty: true }, + ], + }, + }, +}; +const ROW = { id: 'q1', subject: 'Q', quote_date: '2026-11-01', account: 'a1', price_book: null }; + +function dataSource() { + const priceBookFilters: unknown[] = []; + const ds = { + getObjectSchema: async (name: string) => (name === 'quote' ? QUOTE : { name, fields: { name: { type: 'text' } } }), + findOne: async (object: string) => (object === 'account' ? { id: 'a1', name: 'Acme', cb_market: 'm9' } : ROW), + find: async (object: string, params: any) => { + if (object === 'price_book') priceBookFilters.push(params?.$filter); + return { data: [], total: 0 }; + }, + create: async () => ROW, + update: async () => ROW, + }; + return { ds, priceBookFilters }; +} + +const EXPECTED = { + $and: [ + { $or: [{ valid_from: { $lte: '2026-11-01' } }, { valid_from: { $null: true } }] }, + { $or: [{ cb_market: 'm9' }, { cb_market: { $null: true } }] }, + ], +}; + +async function openPriceBook() { + let trigger: HTMLElement | null = null; + await waitFor(() => { + trigger = document.querySelector('[data-testid="lookup-trigger-price_book"]'); + if (!trigger) throw new Error('form not ready'); + }, { timeout: 5000 }); + await act(async () => { + fireEvent.click(trigger!); + }); +} + +describe('record forms say a record is being edited, and name the object a { $record } hop reads (#34197)', () => { + it('auto-layout ObjectForm: the picker queries with the hop value read for the account the form holds', async () => { + const { ds, priceBookFilters } = dataSource(); + render( + + + , + ); + await openPriceBook(); + await waitFor(() => expect(priceBookFilters.length).toBeGreaterThan(0), { timeout: 5000 }); + expect(priceBookFilters).toEqual([EXPECTED]); + }); + + it('authored sections (ModalForm): the same hop value reaches the query', async () => { + const { ds, priceBookFilters } = dataSource(); + render( + + + , + ); + await openPriceBook(); + await waitFor(() => expect(priceBookFilters.length).toBeGreaterThan(0), { timeout: 5000 }); + expect(priceBookFilters).toEqual([EXPECTED]); + }); +}); + +/** + * A hop through a `user` field: its target is fixed by the type (`sys_user`), + * with no `reference` written, so the form names it through the spec's + * `referenceTargetOf` — the arbiter the object linter's `$record` rule asks. + */ +const TASK = { + name: 'task', + fields: { + subject: { type: 'text', label: 'Subject' }, + owner: { type: 'user', label: 'Owner' }, + territory: { + type: 'lookup', + label: 'Territory', + reference: 'territory', + lookupFilters: [{ field: 'region', operator: 'eq', value: { $record: 'owner.region' } }], + }, + }, +}; + +function userHopDataSource(owner: unknown) { + const territoryFilters: unknown[] = []; + const userReads: unknown[] = []; + const row = { id: 't1', subject: 'T', owner, territory: null }; + const ds = { + getObjectSchema: async (name: string) => (name === 'task' ? TASK : { name, fields: { name: { type: 'text' } } }), + findOne: async (object: string, id: string, params: unknown) => { + if (object === 'sys_user') { + userReads.push([id, params]); + return { id: 'u1', name: 'Ann', region: 'emea' }; + } + return row; + }, + find: async (object: string, params: any) => { + if (object === 'territory') territoryFilters.push(params?.$filter); + return { data: [], total: 0 }; + }, + create: async () => row, + update: async () => row, + }; + return { ds, territoryFilters, userReads }; +} + +async function openTerritory() { + let trigger: HTMLElement | null = null; + await waitFor(() => { + trigger = document.querySelector('[data-testid="lookup-trigger-territory"]'); + if (!trigger) throw new Error('form not ready'); + }, { timeout: 5000 }); + await act(async () => { + fireEvent.click(trigger!); + }); +} + +describe('a { $record } hop through a user field resolves in a record form (#34197)', () => { + it('the user held as an id: the form names sys_user, the picker reads the hop and sends its value', async () => { + const { ds, territoryFilters, userReads } = userHopDataSource('u1'); + render( + + + , + ); + await openTerritory(); + await waitFor(() => expect(territoryFilters.length).toBeGreaterThan(0), { timeout: 5000 }); + expect(territoryFilters).toEqual([{ region: 'emea' }]); + expect(userReads).toEqual([['u1', { $select: ['id', 'region'] }]]); + }); + + it('the user held as an expanded row: the value is read off it, with no request', async () => { + const { ds, territoryFilters, userReads } = userHopDataSource({ id: 'u1', name: 'Ann', region: 'apac' }); + render( + + + , + ); + await openTerritory(); + await waitFor(() => expect(territoryFilters.length).toBeGreaterThan(0), { timeout: 5000 }); + expect(territoryFilters).toEqual([{ region: 'apac' }]); + expect(userReads).toEqual([]); + }); +}); diff --git a/ui/packages/plugin-form/src/sectionFields.ts b/ui/packages/plugin-form/src/sectionFields.ts index 5a26fcf5ffb..7de6051fb25 100644 --- a/ui/packages/plugin-form/src/sectionFields.ts +++ b/ui/packages/plugin-form/src/sectionFields.ts @@ -42,7 +42,7 @@ import type { FormField } from '@object-ui/types'; import { evalFieldPredicate, isBlankPredicateText, isExpressionComputedField, type FieldRulePredicate } from '@object-ui/core'; -import { mapFieldTypeToFormType, buildValidationRules, fieldHelpText, withFollowedParentObject, withFormObject } from '@object-ui/fields'; +import { mapFieldTypeToFormType, buildValidationRules, fieldHelpText, withFollowedParentObject, withFormObject, withRecordBeingEdited } from '@object-ui/fields'; import { withHomeAmountSource } from '@object-ui/i18n'; import { isCreateFormMode, isRequiredInForm } from './schemaDefaults'; import { findCustomFieldMember } from './customFieldsMerge'; @@ -350,8 +350,15 @@ export function fromObjectSchema(fieldName: string, ctx: SectionFieldsContext): // ... and a `permission-ref` field carries the object this form edits // (objectstack#32795), so the widget recognises the grant's name column by // its object and its column. + // ... and a lookup whose `lookupFilters` read `{ $record }` carries the + // form's statement that one record is being edited here (with the object + // each hop's lookup points at): the picker resolves the references only + // on that stamp. field: withFormObject( - withFollowedParentObject(withHomeAmountSource(field, ctx.objectSchema?.fields, fieldName), ctx.objectSchema?.fields), + withRecordBeingEdited( + withFollowedParentObject(withHomeAmountSource(field, ctx.objectSchema?.fields, fieldName), ctx.objectSchema?.fields), + ctx.objectSchema?.fields, + ), ctx.objectName, ), options: field.options, diff --git a/ui/packages/plugin-grid/src/__tests__/bulkActionDialogRecordReference-34197.test.tsx b/ui/packages/plugin-grid/src/__tests__/bulkActionDialogRecordReference-34197.test.tsx new file mode 100644 index 00000000000..3a5215df486 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/bulkActionDialogRecordReference-34197.test.tsx @@ -0,0 +1,123 @@ +/** + * 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. + */ + +/** + * objectstack#34197 — a bulk action dialog edits no single record, so a + * lookup param whose `lookupFilters` read `{ $record }` leaves that entry out, + * even when a SIBLING param carries a value of the same name. + * + * The dialog hands every picker its own in-progress values as + * `dependentValues` (objectui#8755), and those values are not the record a + * `{ $record: 'quote_date' }` path names. The picker resolves a reference + * only on a field a record form stamped (`withRecordBeingEdited`); this + * dialog stamps nothing. Driven through the real `BulkActionDialog`, because + * the hand-off of the sibling values IS the hazard. + * + * A param that writes `recordBeingEdited` itself is not let opt in: + * `bulkParamToField` never carries the key from a param. + * + * CONTROL: the literal entry beside it reaches the candidate query, so the + * dialog does forward `lookupFilters` — the missing entry is left out, not + * lost with the rest. + */ +import { describe, it, expect, vi, beforeAll } from 'vitest'; +import React from 'react'; +import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +// Module scope, per AGENTS.md §测试纪律: the picker sits behind `React.lazy`. +import '@object-ui/fields'; +import { BulkActionDialog } from '../components/BulkActionDialog'; + +beforeAll(() => { + if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = vi.fn() as any; +}); + +function makeDataSource() { + return { + find: vi.fn(async () => ({ data: [{ id: 'b1', name: 'Standard 2026' }], total: 1 })), + findOne: vi.fn(async () => null), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + } as any; +} + +const QUOTE_DATE = { name: 'quote_date', label: 'Quote date', type: 'text' }; +const PRICE_BOOK = { + name: 'price_book', + label: 'Price Book', + type: 'lookup', + object: 'price_book', + lookupFilters: [ + { field: 'is_active', operator: 'eq', value: true }, + { field: 'valid_from', operator: 'lte', value: { $record: 'quote_date' }, orEmpty: true }, + ], +}; + +async function pickerQueries(priceBook: Record) { + const ds = makeDataSource(); + render( + {}} + />, + ); + const dateInput = await waitFor(() => { + const el = document.getElementById('bulk-param-quote_date'); + if (!el) throw new Error('dialog not ready'); + return el; + }); + fireEvent.change(dateInput, { target: { value: '2026-11-01' } }); + const trigger = await screen.findByTestId('lookup-trigger-price_book'); + await act(async () => { + fireEvent.click(trigger); + }); + const queries = () => ds.find.mock.calls.filter((c: any[]) => c[0] === 'price_book').map((c: any[]) => c[1]?.$filter); + await waitFor(() => expect(queries().length).toBeGreaterThan(0)); + return { queries: queries(), ds }; +} + +describe('BulkActionDialog — a { $record } lookup filter is left out (objectstack#34197)', () => { + it('a param that writes the record-form stamp itself gains nothing: the entry is still left out', async () => { + const { queries, ds } = await pickerQueries({ ...PRICE_BOOK, recordBeingEdited: { hopObjects: {} } }); + for (const filter of queries) expect(filter).toEqual({ is_active: true }); + expect(ds.findOne).not.toHaveBeenCalled(); + }); + + it('leaves the entry out although a sibling param holds a value of that name', async () => { + const ds = makeDataSource(); + render( + {}} + />, + ); + const dateInput = await waitFor(() => { + const el = document.getElementById('bulk-param-quote_date'); + if (!el) throw new Error('dialog not ready'); + return el; + }); + fireEvent.change(dateInput, { target: { value: '2026-11-01' } }); + + const trigger = await screen.findByTestId('lookup-trigger-price_book'); + await act(async () => { + fireEvent.click(trigger); + }); + const queries = () => ds.find.mock.calls.filter((c: any[]) => c[0] === 'price_book').map((c: any[]) => c[1]?.$filter); + await waitFor(() => expect(queries().length).toBeGreaterThan(0)); + for (const filter of queries()) expect(filter).toEqual({ is_active: true }); + expect(ds.findOne).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/plugin-grid/src/components/bulkParamToField.ts b/ui/packages/plugin-grid/src/components/bulkParamToField.ts index cfab4e4665d..1a4531bd010 100644 --- a/ui/packages/plugin-grid/src/components/bulkParamToField.ts +++ b/ui/packages/plugin-grid/src/components/bulkParamToField.ts @@ -22,7 +22,7 @@ * `paramToField`). */ import { EXPANDABLE_FIELD_TYPES } from '@object-ui/core'; -import { resolveFormWidgetType } from '@object-ui/fields'; +import { RECORD_BEING_EDITED_KEY, resolveFormWidgetType } from '@object-ui/fields'; import type { BulkActionParam } from '@object-ui/types'; /** @@ -123,7 +123,10 @@ export function lookupTargetObject(param: BulkActionParam): string | undefined { * bulk person params get the exact PeoplePicker the form's user fields use * (search-first, avatar + department·email rows, banned users excluded). * - `BulkActionParam`'s documented catch-all keys (min/max/step/format/…) are - * forwarded to the widget as-is. + * forwarded to the widget as-is — except `recordBeingEdited`, which only a + * record form may stamp (`withRecordBeingEdited`): this dialog edits no + * single record, so a param that writes the key itself is not let opt its + * lookup into `{ $record }` resolution against the sibling params. */ export function bulkParamToField( param: BulkActionParam, @@ -160,8 +163,11 @@ export function bulkParamToField( object, labelField, placeholder, + // Never carried: the host's statement that one record is being edited, + // which this dialog cannot make (objectstack#34197). + [RECORD_BEING_EDITED_KEY]: _recordBeingEdited, ...extra - } = param; + } = param as BulkActionParam & { [RECORD_BEING_EDITED_KEY]?: unknown }; const field: Record = { ...extra,