Skip to content

Commit aab8b31

Browse files
feat(spec)!: a lookupFilters value may read the record being edited ($record) and an entry may match an empty column (orEmpty) (#34078)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi99sMrzgLeLs3XZDMAJhAyrC)_ Fixes #34009 Clause-②: yes (narrowing) — widened: a field's `lookupFilters` entry (a lookup, master_detail or user field) gains `orEmpty` and a declared `{ $record: "path" }` value, and `@objectstack/spec/data` gains `LookupFilterRecordReferenceSchema` / `LookupFilterRecordReference` / `LookupFilterRecordReferenceParsed`. Narrowed: an entry whose `value` is an object carrying `$record` in any other shape (two or more hops, non-snake_case names, another key beside `$record`, or operator `in` / `notIn` / `contains`), or a list value holding such an object, parsed before, as any value did, and is now refused. Metadata-protocol: narrowed Skills-docs: follow-up owed — content/docs/data-modeling/relationships.mdx, content/docs/data-modeling/fields.mdx, skills/objectstack-data/rules/field-types.md — not taught yet on purpose: the console picker resolves neither `{ $record }` nor `orEmpty` in this release (both describes carry `[PLANNED — not enforced]`); the docs move with the picker change. ## 维护者速读 1. **改了什么**:lookup 字段的 `lookupFilters` 条目可以写 `{ $record: "字段" }` 或 `{ $record: "lookup字段.字段" }`(读正在编辑的这条记录,最多跨一跳),并新增 `orEmpty: true`(候选列为空也算匹配);两者只配 eq/ne/gt/lt/gte/lte。「今天」直接用已有的 `{today}` / `{ $now: true, addDays }`,不新增写法。 2. **为什么改**:下游 CRM 报价单的价目表选择器要只列「报价日期在有效期内、市场与客户一致或为通用」的价目表,现有 `lookupFilters` 只能写字面量,做不到。 3. **风险与回滚**:本 PR 只改 spec 契约;控制台选择器尚未解析 `$record`/`orEmpty`(已标 `[PLANNED — not enforced]`,作者现在写了 `$record` 选择器会报错而不是给错结果)。唯一收窄:以前能解析但从来不能用的畸形 `$record` 值现在保存即拒,已登记语义迁移条目。回滚即撤销本 PR。 4. **先看**:`packages/spec/src/data/field.zod.ts`(`refuseMalformedLookupFilterEntry` 与 `lookupFilters` 的 describe)、`packages/spec/src/data/field.test.ts`(末尾新 describe,含 2027-01-05 报价单场景)、`.changeset/34009-lookup-filters-record-reference.md`。 5. **两分钟验证**:`pnpm --filter @objectstack/spec exec vitest run src/data/field.test.ts -t 'comparand and orEmpty'`,预期 14 个用例全绿。 6. **需要你做的**:无,席位落地。 ## What changes - **`FieldSchema.lookupFilters[]`** (`packages/spec/src/data/field.zod.ts`): each entry gains `orEmpty?: boolean` and a declared `{ $record: "path" }` value, judged by one entry-level refinement (`refuseMalformedLookupFilterEntry`): - `$record` path: a field of the record being edited, or one lookup hop (`account.cb_market`), snake_case names, at most one dot; refused at `value.$record` otherwise. - A `{ $record }` value pairs only with `eq` / `ne` / `gt` / `lt` / `gte` / `lte` (the six a filter `{ $field }` or `$now` anchor may be the whole comparand of); refused at `value` under `in` / `notIn` / `contains`, and at `value.I` as a member of a list. - `orEmpty` pairs only with the same six; refused at `orEmpty` otherwise. - The `{ $record }` object is a closed `strictObject` (`LookupFilterRecordReferenceSchema`, exported with its type so the picker and server follow-ups import one declaration): a key beside `$record` is refused with the strict-object guidance (`addDays` and `$field` carry pointed prescriptions). - The entry's strict-object aliases name `orEmpty` for `orNull` / `orBlank` / `allowEmpty` / `allowNull` / `includeEmpty` / `includeNull`. - **The rules stated in the describe and JSDoc** (the contract the ui and server follow-ups are written against): the picker sends the referenced value in place of `{ $record }`; it re-queries when a referenced field changes, the first path segment, which is implied and must not be listed in `dependsOn` for that purpose (a `dependsOn` entry also scopes the candidate query by equality, `param = value`, so `dependsOn: ['date']` would add `date = …` to the Price Book query); it leaves the entry out while the value is empty, and on a picker with no single record being edited (bulk-action bar, filter panel); a `{ $record }` that reaches a server unresolved is refused, never read as null. - **Reuse, measured**: no `$today` / `$now` twin. `'{today}'` (date macro) and `{ $now: true, addDays }` already ride a `lookupFilters` value: the picker passes the value through (`lookupFiltersToRecord`, objectui `RecordPickerDialog.tsx`) and the engine resolves both on every read (`resolveFilterTokens`, `packages/objectql/src/engine-find.ts`); `sys-approval-delegation.object.ts` already ships `{current_user_id}` in a `lookupFilters` value the same way. - **Name check**: `$record` has no meaning in the filter DSL today; it is the flow engine's variable for the record a run acts on (`flow-text-slot-template.ts`), the same idea in a different namespace. - **Narrowing, registered**: semantic entry `lookup-filter-record-reference-shape-refused` (ADR-0087), changeset `registered`. - **Ledgers**: `dropped-refinements.baseline.json` +12 sites (the new entry refinement, `lookupFilters.element` on Field and the 11 schemas that embed it; printed by the build), `liveness/field.json` `lookupFilters` row note dated (declared ahead of its reader), regenerated references, api-surface, export-origins, declaration-map, strictness-ledger counts. - No forced test edit: no existing test changed. - Not in this PR (named follow-ups, the seat files them): the console picker resolving `{ $record }` / `orEmpty` (ui lane); a server refusal of an unresolved `{ $record }` by name (server lane); the `readonlyWhen`-reads-a-related-record gap (its own card). ## Tests - `packages/spec/src/data/field.test.ts`, new top-level describe "FieldSchema.lookupFilters — { $record } comparand and orEmpty" (14 cases): the card's four-entry example parses with every key kept; controls (bare literal, `in` list, `{today}`, `$now` anchor, `{ $field }`, `{current_user_id}`) keep parsing; two hops, non-snake_case paths, `in`/`notIn`/`contains` + `$record`, a `{ $record }` member of an `in`/`notIn` list, `orEmpty` on those three, and a key beside `$record` are each refused at the named path; `orNull` is pointed at `orEmpty`; `{ $field }` and `{ $record }` stay distinct; an unresolved `{ $record }` under each of the six operators is refused by the shared filter door with `INVALID_FILTER` / 400, and the `eq` shorthand the picker sends for the market entry passes the door unchanged (pinned, refused later by the driver; flips with the server follow-up); the 2027-01-05 quote vs 2026 Q4 book fixture (what the picker is told to send) offers the 2027 export and generic books, never the Q4 one, and drops the market entry while the account has no market. - Ablation (one-shot, `scripts/ablation-replace.mjs`): removing `.superRefine(refuseMalformedLookupFilterEntry)` turns 6 of the 14 red (re-run at 3ff6dc9). ## Acceptance notes - Measured, not changed: with the eq shorthand the picker's flat lowering produces (`{ cb_market: { $record: "…" } }`) the shared spec door reads the object as filter structure and lets it through; `driver-memory` then refuses it as `Unsupported filter operator "$record"` (`INVALID_FILTER` / 400). The ordering forms are refused at the door itself. So an unresolved `{ $record }` is refused on the picker's server path either way, by a generic sentence; the by-name refusal is the server follow-up. - `@objectstack/lint` runs clean on the card's stack (tokens, preset comparands, object field refs, empty combinators: zero findings). No lint rule reads a `$record` path yet (`git grep` finds none under `packages/lint/src`), so a misspelt path such as `"acount.cb_market"` is not caught before the picker meets it: worth carrying with the picker follow-up. ## Verification Readings are in the report comment on the card; the gate list was derived after the final commit with `dispatch-gates --commands` and reconciled with `--ran`. <!-- signed: domain:spec#2 · os-steve · session_01ADHkmSBdZayQvo47yKhtGD --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a061708 commit aab8b31

16 files changed

Lines changed: 492 additions & 24 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
'@objectstack/spec': minor
3+
---
4+
5+
feat(spec)!: a `lookupFilters` value may read the record being edited (`{ $record: "path" }`) and an entry may also match an empty column (`orEmpty: true`)
6+
7+
Clause-②: yes (narrowing) — widened: a field's `lookupFilters` entry (a lookup, master_detail or user field) gains the `orEmpty` key and a declared `{ $record: "path" }` value, and `@objectstack/spec/data` gains `LookupFilterRecordReferenceSchema`, `LookupFilterRecordReference` and `LookupFilterRecordReferenceParsed`. Narrowed: an entry whose `value` is an object carrying `$record` in any other shape (a path of two or more hops or of names that are not snake_case, another key beside `$record`, or operator `in`, `notIn` or `contains`), or a list value with such an object among its members, parsed before, as any value did, and is now refused.
8+
Metadata-protocol: narrowed
9+
Skills-docs: follow-up owed — content/docs/data-modeling/relationships.mdx, content/docs/data-modeling/fields.mdx, skills/objectstack-data/rules/field-types.md — none of them teaches `{ $record }` or `orEmpty` yet, on purpose: the console picker does not resolve either in this release (both describes carry `[PLANNED — not enforced]`), so teaching them now would advertise a filter the picker does not apply; they move with the picker change.
10+
11+
<!-- adr-0087: registered lookup-filter-record-reference-shape-refused -->
12+
13+
**BREAKING** only for a `lookupFilters` entry whose `value` is an object carrying a `$record` key outside the declared shape, or a list holding one. Such an entry never worked: the console picker sent the object to the server as written, and the server refused the query (`INVALID_FILTER` / 400), so the picker showed an error instead of candidates. It is now refused where the object is written, naming `fields.NAME.lookupFilters.N.value` (or `.value.$record`, or `.value.I` for a list member) and the rule. The semantic entry `lookup-filter-record-reference-shape-refused` carries the same notice into the upgrade guide and `os migrate meta`.
14+
15+
**The remedy.** Write `{ $record: "field" }` or `{ $record: "lookup_field.field" }` with no other key, under `eq`, `ne`, `gt`, `lt`, `gte` or `lte`. A value two hops away is not reachable from a picker filter: copy it onto the record being edited, or onto the record one hop away, as a field of its own, and reference that. For a date relative to today, write the `{today}` placeholder or `{ $now: true, addDays: N }` instead of an offset beside `$record`.
16+
17+
**What is declared.** A lookup picker can now be told to offer only the candidates that fit the record being edited, e.g. a quote's Price Book picker that offers only books valid on the quote's date and in the customer's market, or in none:
18+
19+
```ts
20+
lookupFilters: [
21+
{ field: 'is_active', operator: 'eq', value: true },
22+
{ field: 'valid_from', operator: 'lte', value: { $record: 'date' }, orEmpty: true },
23+
{ field: 'valid_to', operator: 'gte', value: { $record: 'date' }, orEmpty: true },
24+
{ field: 'cb_market', operator: 'eq', value: { $record: 'account.cb_market' }, orEmpty: true },
25+
]
26+
```
27+
28+
- `{ $record: "path" }` reads a field of the record being edited, or one lookup hop from it (`account.cb_market`). It is not `{ $field }`, which names a column of the candidate row. The picker sends the referenced value in its place and re-queries when a referenced field changes. Those fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['date']` would add `date = …` to the Price Book query). 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. A `{ $record }` that reaches a server unresolved is refused, never read as null. It pairs only with the six scalar comparisons.
29+
- `orEmpty: true` also matches a candidate whose column is null ("valid from the quote date, or with no start date"). It pairs only with the six scalar comparisons.
30+
- Today's date needs nothing new: `'{today}'` and `{ $now: true, addDays: N }` already work as a `lookupFilters` value, and the engine resolves both on every read.
31+
32+
⚠ Declared ahead of its reader: in this release the console picker resolves neither `{ $record }` nor `orEmpty`. An entry that uses `{ $record }` makes the picker's query fail with `INVALID_FILTER` until the picker change ships, and `orEmpty` is ignored. The picker narrows the choice only: a rule the save must enforce still belongs in a server-side hook.

‎content/docs/references/data/field.mdx‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Field schema — Data Protocol reference
33
navTitle: Field
4-
description: "Field schemas of the ObjectStack Data Protocol: CurrencyConfig, Field and 7 more — each property with its type, default and a TypeScript example."
4+
description: "Field schemas of the ObjectStack Data Protocol: CurrencyConfig, Field and 8 more — each property with its type, default and a TypeScript example."
55
---
66

77
{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}
@@ -13,8 +13,8 @@ description: "Field schemas of the ObjectStack Data Protocol: CurrencyConfig, Fi
1313
## TypeScript Usage
1414

1515
```typescript
16-
import { CurrencyConfigSchema, FieldSchema, FieldMaskingKeepSchema, FieldMaskingRuleSchema, FieldType, InlineGridColumnSchema, LocationCoordinatesSchema, SelectOptionSchema, UniqueScopeSchema } from '@objectstack/spec/data';
17-
import type { CurrencyConfig, Field, FieldMaskingKeep, FieldMaskingRule, FieldType, InlineGridColumn, LocationCoordinates, SelectOption, UniqueScope } from '@objectstack/spec/data';
16+
import { CurrencyConfigSchema, FieldSchema, FieldMaskingKeepSchema, FieldMaskingRuleSchema, FieldType, InlineGridColumnSchema, LocationCoordinatesSchema, LookupFilterRecordReferenceSchema, SelectOptionSchema, UniqueScopeSchema } from '@objectstack/spec/data';
17+
import type { CurrencyConfig, Field, FieldMaskingKeep, FieldMaskingRule, FieldType, InlineGridColumn, LocationCoordinates, LookupFilterRecordReference, SelectOption, UniqueScope } from '@objectstack/spec/data';
1818

1919
// Validate data
2020
const result = CurrencyConfigSchema.parse(data);
@@ -93,7 +93,7 @@ const result = CurrencyConfigSchema.parse(data);
9393
| **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. |
9494
| **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. |
9595
| **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). |
96-
| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. |
96+
| **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. |
9797
| **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. |
9898
| **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. |
9999
| **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. |
@@ -236,6 +236,15 @@ const result = CurrencyConfigSchema.parse(data);
236236
| **readonlyWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is read-only when TRUE, evaluated per row against the row as `record` plus the header as `parent` (e.g. P`parent.status == 'paid'`). |
237237
| **requiredWhen** | `string \| { dialect: Enum<'cel' \| 'cron' \| 'template'>; source: string; ast?: any; meta?: object }` | optional | Predicate (CEL) — the cell is required when TRUE. Same `record` + `parent` scope as `readonlyWhen`. PRESENTATION ONLY: this flags the cell inline-invalid in the grid; nothing on the write path reads it. The server-enforced contract is the child FIELD's own `requiredWhen` — a transition gate, see `Field.requiredWhen` — which hydration copies onto an identity-only column, so declaring the requirement here alone enforces nothing. |
238238

239+
### Nested Shape: `Field.lookupFilters[number]`
240+
241+
| Property | Type | Required | Description |
242+
| :--- | :--- | :--- | :--- |
243+
| **field** | `string` | ✅ | |
244+
| **operator** | `Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>` | ✅ | |
245+
| **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. |
246+
| **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. |
247+
239248
### Nested Shape: `Field.lookupAutofill[number]`
240249

241250
| Property | Type | Required | Description |
@@ -424,6 +433,19 @@ Allowed Values: `phone`, `id_card`, `bank_account`, `email`, `name`
424433
| **accuracy** | `number` | optional | Accuracy in meters |
425434

426435

436+
---
437+
438+
## LookupFilterRecordReference
439+
440+
A lookupFilters comparand read from the record being edited: `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). The picker replaces it with that value before querying; unlike `{ $field }`, which names a column of the candidate row.
441+
442+
### Properties
443+
444+
| Property | Type | Required | Description |
445+
| :--- | :--- | :--- | :--- |
446+
| **$record** | `string` | ✅ | Path of the value on the record being edited: a field name (`quote_date`) or one lookup hop (`account.cb_market`) — at most one dot. |
447+
448+
427449
---
428450

429451
## SelectOption

0 commit comments

Comments
 (0)