From d7bceceba2f8bd253d4d4f7a24f36254ce5bdf0a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 13:47:40 +0000 Subject: [PATCH] =?UTF-8?q?fix(plugin-detail):=20a=20related=20tab's=20?= =?UTF-8?q?=E3=80=8C+=20=E6=B7=BB=E5=8A=A0=E3=80=8D=20picker=20keeps=20to?= =?UTF-8?q?=20the=20parent's=20own=20records=20and=20names=20them=20by=20t?= =?UTF-8?q?heir=20name=20field=20(#36707)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbYmr1N6x5nuafz67fw --- .../36707-related-tab-lookup-picker-scope.md | 12 ++ ui/packages/plugin-detail/src/RelatedList.tsx | 79 +++++++- ...RelatedList.derivedAddScope-36707.test.tsx | 185 ++++++++++++++++++ ...RelatedList.enlargedToolbar-27524.test.tsx | 6 +- 4 files changed, 269 insertions(+), 13 deletions(-) create mode 100644 .changeset/36707-related-tab-lookup-picker-scope.md create mode 100644 ui/packages/plugin-detail/src/__tests__/RelatedList.derivedAddScope-36707.test.tsx diff --git a/.changeset/36707-related-tab-lookup-picker-scope.md b/.changeset/36707-related-tab-lookup-picker-scope.md new file mode 100644 index 00000000000..f3242a2ac10 --- /dev/null +++ b/.changeset/36707-related-tab-lookup-picker-scope.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-detail': patch +--- + +fix(plugin-detail): a related tab's 「+ 添加」 picker keeps to the parent's own records and names them by their name field + +Clause-②: no +Metadata-protocol: none + +On a record page's related tab whose child is linked by a plain `lookup`, the derived 「+ 添加」 picker listed the unlinked children of every parent's scope. An opportunity's 合同 (contracts) tab listed unlinked contracts of every account, although a contract's opportunity lookup `dependsOn` the contract's account; a pick linked another customer's contract to the opportunity. The picker now applies that lookup's `dependsOn` from the parent record: each named child field must equal the parent's value (here, only contracts of the opportunity's own account). When the parent has no value for it, or the lookup's `lookupFilters` compare with `$record`, the tab offers no picker and 「+ 添加」 creates a record directly. + +The picker's label column is the picked object's name field (its declared `nameField`, else the derived title field) when the add names no `labelField`, under that field's label. It was a hard-coded `name`: on contracts, whose name field is `contract_number`, the first column was an empty 「NAME」. diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 4aabb7cd0a3..ed61cbcb75f 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -1089,7 +1089,15 @@ function relationFieldEntries(fields: unknown): Array<[string, RelationFieldDef] * lists only UNLINKED children (this relationship empty): a row already * here would be a no-op pick, and a row under another parent would move * silently. Moving a child between parents stays on the child's own - * form, where the change is visible (seat ruling on L1-a S1, #35725); + * form, where the change is visible (seat ruling on L1-a S1, #35725). + * When the relationship lookup is scoped by the child's own fields + * (`dependsOn`: a contract's opportunity `dependsOn` the contract's + * account), the picker lists only children that lookup could name this + * parent from: each `dependsOn` field equal to the parent's value + * (objectstack#36707 — the opportunity's 合同 tab listed every account's + * unlinked contracts, and a pick linked another customer's contract). + * A scope it cannot resolve (the parent's value is empty or not read, or + * a `lookupFilters` comparand reads `$record`) offers no picker; * - `master_detail` with a source catalog: the picker lists the catalog and * a pick creates a row of this list naming it (`linkField`). The catalog * is the child's one other REQUIRED single-valued `lookup` (a line's @@ -1120,12 +1128,17 @@ export function derivedAddOf( childFields: unknown, referenceField: string | undefined, childObject: string | undefined, + parentRecord?: Record, ): RelatedListAdd | undefined { if (!referenceField || !childObject) return undefined; const entries = relationFieldEntries(childFields); const rel = entries.find(([name]) => name === referenceField)?.[1]; if (!rel || rel.multiple === true) return undefined; - if (rel.type === 'lookup') return { picker: { object: childObject, filter: [{ field: referenceField, operator: 'is_empty' }] } }; + if (rel.type === 'lookup') { + const scope = parentScopeOf(rel, parentRecord); + if (!scope) return undefined; + return { picker: { object: childObject, filter: [{ field: referenceField, operator: 'is_empty' }, ...scope] } }; + } if (rel.type !== 'master_detail') return undefined; const catalogs = entries.filter(([name, def]) => name !== referenceField @@ -1149,6 +1162,51 @@ export function derivedAddOf( return { picker: { object: catalogDef.reference as string }, linkField: catalogField }; } +/** + * The candidate rules a `lookup` relationship's own scope adds to the derived + * picker of children (`derivedAddOf`), seen from the parent: `[]` when the + * lookup is unscoped, `undefined` when the scope cannot be resolved here. + * + * `dependsOn` scopes the lookup's candidates by equality — a `{ field, param }` + * entry (a bare string names both) sends the child's `field` value as the + * parent object's `param` (`LookupField`'s `dependentFilter`). Reversed, a + * child can name this parent only when its `field` equals the parent's + * `param`, so each entry becomes `field equals `. With the + * parent's value empty or not read yet no child could name it: no picker, + * never an unscoped one. A `lookupFilters` comparand reading `$record` relates + * the parent's columns to the child's by any operator, and this side does not + * invert it: no picker either. + */ +function parentScopeOf(rel: RelationFieldDef, parentRecord: Record | undefined): ViewFilterElement[] | undefined { + if (Array.isArray(rel.lookupFilters) && rel.lookupFilters.some(readsRecord)) return undefined; + if (!Array.isArray(rel.dependsOn) || rel.dependsOn.length === 0) return []; + const rules: ViewFilterElement[] = []; + for (const entry of rel.dependsOn) { + const field = typeof entry === 'string' ? entry : (entry as { field?: unknown } | null)?.field; + const param = typeof entry === 'string' ? entry : ((entry as { param?: unknown }).param ?? field); + if (typeof field !== 'string' || field === '' || typeof param !== 'string' || param === '') return undefined; + const value = referenceValueOf(parentRecord?.[param]); + if (value === undefined) return undefined; + rules.push({ field, operator: 'equals', value }); + } + return rules; +} + +/** A record field's value as a filter comparand: an expanded reference reads as its id. */ +function referenceValueOf(raw: unknown): string | number | boolean | undefined { + const value = raw && typeof raw === 'object' && !Array.isArray(raw) + ? ((raw as { id?: unknown; _id?: unknown }).id ?? (raw as { _id?: unknown })._id) + : raw; + if (typeof value === 'number' || typeof value === 'boolean') return value; + return typeof value === 'string' && value !== '' ? value : undefined; +} + +/** Does this `lookupFilters` entry compare with a `{ $record }` value? */ +function readsRecord(entry: unknown): boolean { + const value = (entry as { value?: unknown } | null)?.value; + return !!value && typeof value === 'object' && '$record' in (value as object); +} + /** * Does the insert fill this field when a create omits it — the engine's * `applyFieldDefaults`: a non-null `defaultValue`, else a select option marked @@ -1166,11 +1224,7 @@ function insertDefaults(def: RelationFieldDef): boolean { */ function scopedByRow(def: RelationFieldDef): boolean { if (Array.isArray(def.dependsOn) && def.dependsOn.length > 0) return true; - if (!Array.isArray(def.lookupFilters)) return false; - return def.lookupFilters.some((entry) => { - const value = (entry as { value?: unknown } | null)?.value; - return !!value && typeof value === 'object' && '$record' in (value as object); - }); + return Array.isArray(def.lookupFilters) && def.lookupFilters.some(readsRecord); } /** One group of a stateful child list (`statusGroupsOf`). */ @@ -1544,8 +1598,8 @@ export const RelatedList: React.FC = ({ // when the page authored none (`derivedAddOf`). The rest of this component // reads `add` alone, so a derived add takes the authored one's path. const derivedAdd = React.useMemo( - () => (enlargedFace && !authoredAdd && !schema ? derivedAddOf(objectSchema?.fields, referenceField, api) : undefined), - [enlargedFace, authoredAdd, schema, objectSchema, referenceField, api], + () => (enlargedFace && !authoredAdd && !schema ? derivedAddOf(objectSchema?.fields, referenceField, api, parentRecord) : undefined), + [enlargedFace, authoredAdd, schema, objectSchema, referenceField, api, parentRecord], ); const add = authoredAdd ?? derivedAdd; // objectstack#27056 — the card's count, asked up front with the column's @@ -2118,7 +2172,12 @@ export const RelatedList: React.FC = ({ }); return () => { cancelled = true; }; }, [pickerOpen, pickerObject, pickerSchema, dataSource]); - const pickerDisplayField = add?.picker?.labelField || 'name'; + // The label column is the picked object's name field (ADR-0079: declared + // `nameField`, else derived) when the add names no `labelField` — a derived + // add never does (objectstack#36707: a contract's 合同 tab picker led with an + // empty 「NAME」, the contract's name being `contract_number`). `name` only + // until the schema is read. + const pickerDisplayField = add?.picker?.labelField || resolveNameField(pickerSchema) || 'name'; const pickerColumns = React.useMemo(() => { const derived = deriveLookupColumns(pickerSchema, { displayField: pickerDisplayField }); return derived.length > 0 ? derived : undefined; diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.derivedAddScope-36707.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.derivedAddScope-36707.test.tsx new file mode 100644 index 00000000000..c1e806c0624 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.derivedAddScope-36707.test.tsx @@ -0,0 +1,185 @@ +/** + * objectstack#36707 — the related tab's derived 「+ 添加」 on a `lookup` + * relationship (`derivedAddOf`, the lookup arm): + * + * 1. the relationship lookup's `dependsOn` scopes the picker from the parent + * record. An opportunity's 合同 tab: `contract.opportunity` `dependsOn` + * the contract's account, so the picker lists only unlinked contracts of + * the opportunity's own account — never another customer's, which a pick + * would have linked here. A scope it cannot resolve offers no picker; + * 2. the picker's label column is the picked object's name field, not a + * hard-coded `name` (an empty 「NAME」 column on contracts, whose name + * field is `contract_number`). + */ +import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { FilterScopeProvider, RecordContextProvider } from '@object-ui/react'; +import { ComponentRegistry } from '@object-ui/core'; +import { RelatedList, derivedAddOf } from '../RelatedList'; +import { resetRelatedTabConditionsForTests } from '../relatedTabConditions'; +import { RelatedListEnlargedContext } from '../relatedListCompact'; + +afterEach(() => resetRelatedTabConditionsForTests()); + +/** `object-grid` lives in `plugin-grid`, which this package cannot import. */ +function ObjectGridStandIn({ schema }: { schema: any }) { + const rows: any[] = schema?.data?.items ?? []; + return
    {rows.map((row) =>
  • {String(row.subject ?? row.contract_number ?? row.id)}
  • )}
; +} + +beforeAll(() => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); + ComponentRegistry.register('object-grid', ObjectGridStandIn as never); +}); + +const CONTRACT_FIELDS = { + contract_number: { type: 'autonumber', label: 'Contract Number' }, + account: { type: 'master_detail', reference: 'account', label: 'Account', required: true }, + opportunity: { type: 'lookup', reference: 'opportunity', label: 'Opportunity', dependsOn: ['account'] }, + status: { type: 'text', label: 'Status' }, +}; +const CONTRACT_SCHEMA = { name: 'contract', nameField: 'contract_number', fields: CONTRACT_FIELDS }; + +/** The unlinked contracts of two accounts; the stand-in server honours equality on `account`. */ +const POOL = [ + { id: 'k-own', contract_number: 'CTR-0003', account: 'A-1', opportunity: null, status: 'Draft' }, + { id: 'k-other', contract_number: 'CTR-0004', account: 'A-2', opportunity: null, status: 'Draft' }, +]; +const LINKED = [{ id: 'k-here', contract_number: 'CTR-0001', account: 'A-1', opportunity: 'O-1', status: 'Active' }]; + +function dataSourceFor(schema: Record = CONTRACT_SCHEMA) { + return { + find: vi.fn(async (resource: string, params?: any) => { + const filter = JSON.stringify(params?.$filter ?? []); + if (resource === 'contract' && JSON.stringify(params ?? {}).includes('O-1')) return { data: LINKED, total: LINKED.length }; + const data = POOL.filter((r) => !filter.includes('"account"') || filter.includes(`"${r.account}"`)); + return { data, total: data.length }; + }), + getObjectSchema: vi.fn(async () => schema), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + batchTransaction: vi.fn(async (ops: unknown[]) => ({ results: ops.map(() => ({})) })), + }; +} + +function renderTab(parent: Record, { onNew = vi.fn(), schema }: { onNew?: () => void; schema?: Record } = {}) { + const dataSource = dataSourceFor(schema); + render( + + + + + + + , + ); + return { dataSource }; +} + +/** The picker's column headers that carry a name, in order (the select-all column has none). */ +const headerTexts = (dialog: HTMLElement) => + Array.from(within(dialog).getByTestId('record-picker-sticky-header').querySelectorAll('th')) + .map((th) => th.textContent?.trim() ?? '') + .filter((text) => text !== ''); +const addButton = () => document.querySelector('[data-related-enlarged-toolbar] [data-related-add]') as HTMLElement; +const pickerReads = (ds: ReturnType) => + ds.find.mock.calls.filter(([r, p]) => r === 'contract' && !JSON.stringify(p ?? {}).includes('O-1')); + +describe('derivedAddOf — a lookup relationship scoped by dependsOn (objectstack#36707)', () => { + const unlinked = { field: 'opportunity', operator: 'is_empty' }; + + it('each dependsOn field must equal the parent\'s value: string and { field, param } entries', () => { + expect(derivedAddOf(CONTRACT_FIELDS, 'opportunity', 'contract', { id: 'O-1', account: 'A-1' })).toEqual({ + picker: { object: 'contract', filter: [unlinked, { field: 'account', operator: 'equals', value: 'A-1' }] }, + }); + const byParam = { ...CONTRACT_FIELDS, opportunity: { type: 'lookup', reference: 'opportunity', dependsOn: [{ field: 'account', param: 'customer' }] } }; + expect(derivedAddOf(byParam, 'opportunity', 'contract', { id: 'O-1', customer: 'A-9', account: 'A-1' })?.picker.filter).toEqual([ + unlinked, + { field: 'account', operator: 'equals', value: 'A-9' }, + ]); + }); + + it('an expanded reference on the parent reads as its id', () => { + expect(derivedAddOf(CONTRACT_FIELDS, 'opportunity', 'contract', { id: 'O-1', account: { id: 'A-1', name: 'Initech' } })?.picker.filter).toEqual([ + unlinked, + { field: 'account', operator: 'equals', value: 'A-1' }, + ]); + }); + + it.each([ + ['the parent has no value for it', { id: 'O-1', account: null }], + ['the parent record is not read', undefined], + ] as const)('no picker when the scope cannot be resolved: %s', (_label, parent) => { + expect(derivedAddOf(CONTRACT_FIELDS, 'opportunity', 'contract', parent as any)).toBeUndefined(); + }); + + it('no picker when a lookupFilters comparand on the relationship reads $record', () => { + const fields = { + ...CONTRACT_FIELDS, + opportunity: { type: 'lookup', reference: 'opportunity', lookupFilters: [{ field: 'region', operator: 'eq', value: { $record: 'region' } }] }, + }; + expect(derivedAddOf(fields, 'opportunity', 'contract', { id: 'O-1', region: 'east' })).toBeUndefined(); + }); + + it('control: an unscoped lookup (static lookupFilters included) keeps the unlinked-only picker, parent read or not', () => { + const fields = { + ...CONTRACT_FIELDS, + opportunity: { type: 'lookup', reference: 'opportunity', lookupFilters: [{ field: 'is_active', operator: 'eq', value: true }] }, + }; + expect(derivedAddOf(fields, 'opportunity', 'contract')).toEqual({ picker: { object: 'contract', filter: [unlinked] } }); + }); +}); + +describe('the opportunity\'s 合同 tab picker (objectstack#36707)', () => { + it('lists only the account\'s own unlinked contracts, led by the contract number under its label', async () => { + const { dataSource } = renderTab({ id: 'O-1', name: 'Initech Cloud Migration', account: 'A-1' }); + await waitFor(() => expect(screen.getByText('CTR-0001')).toBeInTheDocument()); + fireEvent.click(addButton()); + const dialog = await screen.findByTestId('record-picker-dialog'); + expect(await within(dialog).findByTestId('record-row-k-own')).toHaveTextContent('CTR-0003'); + expect(within(dialog).queryByTestId('record-row-k-other')).toBeNull(); + const reads = pickerReads(dataSource); + expect(reads.length).toBeGreaterThan(0); + for (const [, params] of reads) { + const filter = JSON.stringify((params as any)?.$filter ?? []); + expect(filter).toContain('"A-1"'); + expect(filter).toContain('is_empty'); + } + const headers = headerTexts(dialog); + expect(headers[0]).toBe('Contract Number'); + expect(headers).not.toContain('Name'); + }); + + it('a parent with no account offers no picker: 「+ 添加」 creates a contract', async () => { + const onNew = vi.fn(); + const { dataSource } = renderTab({ id: 'O-1', name: 'Initech Cloud Migration', account: null }, { onNew }); + await waitFor(() => expect(screen.getByText('CTR-0001')).toBeInTheDocument()); + fireEvent.click(addButton()); + expect(onNew).toHaveBeenCalledTimes(1); + expect(screen.queryByTestId('record-picker-dialog')).toBeNull(); + expect(pickerReads(dataSource)).toHaveLength(0); + }); + + it('with no declared nameField the label column is the derived title field, still never an empty 「NAME」', async () => { + const { nameField: _drop, ...undeclared } = CONTRACT_SCHEMA; + renderTab({ id: 'O-1', account: 'A-1' }, { schema: undeclared }); + await waitFor(() => expect(screen.getByText('CTR-0001')).toBeInTheDocument()); + fireEvent.click(addButton()); + const dialog = await screen.findByTestId('record-picker-dialog'); + await within(dialog).findByTestId('record-row-k-own'); + expect(headerTexts(dialog)).not.toContain('Name'); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx index 80affd61baf..11acc3a2e1b 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx @@ -76,9 +76,9 @@ const ROWS = [ { id: 't2', subject: 'Call back', lead: 'L-1', owner_id: 'u-2', due_date: '2026-11-04' }, ]; const CANDIDATES = [ - { id: 'c1', name: 'Alpha' }, - { id: 'c2', name: 'Bravo' }, - { id: 'c3', name: 'Charlie' }, + { id: 'c1', name: 'Alpha', subject: 'Alpha' }, + { id: 'c2', name: 'Bravo', subject: 'Bravo' }, + { id: 'c3', name: 'Charlie', subject: 'Charlie' }, ]; interface Harness {