diff --git a/.changeset/37246-related-new-dependson-seed.md b/.changeset/37246-related-new-dependson-seed.md new file mode 100644 index 00000000000..b786168ed6e --- /dev/null +++ b/.changeset/37246-related-new-dependson-seed.md @@ -0,0 +1,18 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/plugin-detail': patch +'@object-ui/console': patch +--- + +fix(console): a related tab's New keeps the parent it prefills when the child's relationship lookup declares `dependsOn` + +Clause-②: yes (widening) — one new export, `relatedCreateSeedOf`, on the published `@object-ui/plugin-detail/core` subpath; nothing is removed or renamed, and the package root exports the same names as before +Metadata-protocol: none + +On a record page's related tab, New (the header's, or the one inside the Add picker) opened the child's create form with the parent linked and nothing else. When the child's relationship lookup declares `dependsOn` (a billing milestone's order `dependsOn` the milestone's account), the form drew that lookup gated ("Select Account first") with the parent hidden, or, with a `lookupAutofill` that fills the account from the order, filled the account and then emptied the order, and Create saved the child without its parent and without an error. + +The New now opens with each `dependsOn` field of the relationship lookup seeded from the parent record — the child's field takes the parent's value, the same pairs the derived Add picker scopes its candidates by. The parent stays visible and is saved. A `dependsOn` field that is itself a lookup with a `dependsOn` and a `lookupAutofill` of its own can still be emptied by the form's dependent-lookup clear when the form opens; that clear is tracked separately. A relationship lookup without `dependsOn`, or a parent with no value for it, opens with the parent link alone, as before; the Add picker's scope is unchanged. + +- The record-form overlay's `formLink` URL parameter repeats: the parent pair first, then one `field:value` pair per seeded value, so a refresh reopens the form with all of them. +- `@object-ui/plugin-detail/core` exports `relatedCreateSeedOf(childFields, referenceField, parentRecord)`, the values a related New opens with beside the parent link. +- A custom page's related lists, which each bind a parent of their own, still open New with the parent link alone. diff --git a/ui/apps/console/vite.config.ts b/ui/apps/console/vite.config.ts index d4603ab425b..8a9d3128846 100644 --- a/ui/apps/console/vite.config.ts +++ b/ui/apps/console/vite.config.ts @@ -1577,7 +1577,7 @@ export default defineConfig({ }, { name: 'plugin-detail-core', - test: /[\\/]packages[\\/]plugin-detail[\\/]src[\\/](core|autoLayout|relatedListCompact|relatedListSort|queueClaim|ConcurrentUpdateDialog|useDetailTranslation|recordFieldAccess|useRecordEditable|useRelatedCounts|renderers[\\/]recordActivityFeed|synth[\\/](relatedListEntry|relatedArrangement|buildDefaultPageSchema))\.tsx?$/, + test: /[\\/]packages[\\/]plugin-detail[\\/]src[\\/](core|autoLayout|relatedListCompact|relatedListSort|relatedParentScope|queueClaim|ConcurrentUpdateDialog|useDetailTranslation|recordFieldAccess|useRecordEditable|useRelatedCounts|renderers[\\/]recordActivityFeed|synth[\\/](relatedListEntry|relatedArrangement|buildDefaultPageSchema))\.tsx?$/, priority: 71, includeDependenciesRecursively: false, }, diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index 30732d12a95..609ea2c619c 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -861,17 +861,25 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = // the URL means Back closes the overlay and a refresh reopens it still // correctly parent-linked — no transient component state to lose. const formObjectParam = searchParams.get(RECORD_FORM_OBJECT_PARAM); - const formLinkParam = searchParams.get(RECORD_FORM_LINK_PARAM); + // objectstack#37246 — `formLink` repeats: the parent pair first, then the + // values it seeds beside it (the relationship lookup's `dependsOn` fields). + // Keyed on the pairs' JSON text, a primitive, so the values keep their identity + // while the URL does (AGENTS.md #10). + const formLinkKey = JSON.stringify(searchParams.getAll(RECORD_FORM_LINK_PARAM)); const editingRecord = useMemo( () => (recordFormParam && recordFormParam !== 'new' ? { id: recordFormParam } : null), [recordFormParam], ); const formLinkValues = useMemo(() => { - if (!formLinkParam) return undefined; - const i = formLinkParam.indexOf(':'); - if (i <= 0) return undefined; - return { [formLinkParam.slice(0, i)]: formLinkParam.slice(i + 1) }; - }, [formLinkParam]); + const values: Record = {}; + for (const pair of JSON.parse(formLinkKey) as string[]) { + const i = pair.indexOf(':'); + const field = pair.slice(0, i); + if (i <= 0 || field in values) continue; + values[field] = pair.slice(i + 1); + } + return Object.keys(values).length > 0 ? values : undefined; + }, [formLinkKey]); const [refreshKey, setRefreshKey] = useState(0); const isDialogOpen = !!recordFormParam; diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.internalFormRetired-36425.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.internalFormRetired-36425.test.tsx index 9712db9370a..159ebe132fb 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.internalFormRetired-36425.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.internalFormRetired-36425.test.tsx @@ -22,7 +22,7 @@ import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest'; import React from 'react'; -import { render, cleanup, waitFor, screen, within } from '@testing-library/react'; +import { render, cleanup, waitFor, screen, within, fireEvent } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { registerAllFields } from '@object-ui/fields'; @@ -112,7 +112,35 @@ const AUTHORED = { }, }; const PLAIN = { name: 'crm_note', label: 'Note', fields: FIELDS, fieldGroups: FIELD_GROUPS }; -const OBJECTS = [AUTHORED, PLAIN]; + +// objectstack#37246 — a child whose relationship lookup is scoped by the +// child's own account (`dependsOn`), with and without a `lookupAutofill` that +// fills that account from the parent. +const MILESTONE = { + name: 'crm_billing_milestone', + label: 'Billing Milestone', + fields: { + name: { type: 'text', label: 'Name' }, + crm_sales_order: { + type: 'lookup', + reference: 'crm_sales_order', + label: 'Order', + dependsOn: ['crm_account'], + lookupAutofill: [{ target: 'crm_account', source: 'crm_account' }], + }, + crm_account: { type: 'lookup', reference: 'crm_account', label: 'Account' }, + }, +}; +const CONTRACT = { + name: 'crm_contract', + label: 'Contract', + fields: { + name: { type: 'text', label: 'Name' }, + crm_account: { type: 'lookup', reference: 'crm_account', label: 'Account' }, + crm_opportunity: { type: 'lookup', reference: 'crm_opportunity', label: 'Related Opportunity', dependsOn: ['crm_account'] }, + }, +}; +const OBJECTS = [AUTHORED, PLAIN, MILESTONE, CONTRACT]; const dataSourceStub = { onConnectionStateChange: () => () => {}, @@ -239,3 +267,61 @@ describe('#36425 — the New / Edit dialog reads no internal form view', () => { expect(a.fields).toEqual(b.fields); }); }); + +/** + * objectstack#37246 — a related tab's New on a child whose relationship + * lookup declares `dependsOn` (a milestone's order `dependsOn` its account): the + * pre-link carries the parent AND each `dependsOn` value the parent answers, as + * repeated `formLink` pairs (`RelatedRecordActionsBridge`). The dialog opens + * with all of them, so the lookup holds its parent in the open instead of + * behind 「Select Account first」, and Create saves the parent. + */ +describe('#37246 — a related New pre-links the parent with its dependsOn values', () => { + /** + * The relationship lookup draws its own trigger, holding the parent, and no + * gate: a lookup whose `dependsOn` field is empty draws `lookup-trigger-gated` + * (「Select Account first」) and hides the value it holds. This harness serves + * the lookups no record read, so their labels are not drawn here. + */ + async function createFrom(url: string, child: string, relationship: string) { + probe.realModal = true; + const schema = await openAt(url, child); + const dialog = await screen.findByRole('dialog', undefined, { timeout: 5000 }); + await waitFor(() => expect(within(dialog).getByTestId(`lookup-trigger-${relationship}`)).toBeInTheDocument(), { timeout: 5000 }); + expect(within(dialog).queryByTestId('lookup-trigger-gated')).toBeNull(); + fireEvent.click(within(dialog).getByRole('button', { name: 'Create' })); + await waitFor(() => expect(dataSourceStub.create).toHaveBeenCalled(), { timeout: 5000 }); + expect(dataSourceStub.create.mock.calls[0][0]).toBe(child); + return { schema, saved: dataSourceStub.create.mock.calls[0][1] }; + } + + it('with a lookupAutofill on the relationship: the order is drawn ungated, and Create saves it with its account', async () => { + const { schema, saved } = await createFrom( + '/apps/crm/crm_sales_order?form=new&formObject=crm_billing_milestone&formLink=crm_sales_order:so-1&formLink=crm_account:acc-1', + 'crm_billing_milestone', + 'crm_sales_order', + ); + expect(schema.initialValues).toStrictEqual({ crm_sales_order: 'so-1', crm_account: 'acc-1' }); + expect(saved).toMatchObject({ crm_sales_order: 'so-1', crm_account: 'acc-1' }); + }); + + it('with no lookupAutofill: the opportunity is drawn, never 「Select Account first」, and Create saves it', async () => { + const { schema, saved } = await createFrom( + '/apps/crm/crm_opportunity?form=new&formObject=crm_contract&formLink=crm_opportunity:opp-1&formLink=crm_account:acc-1', + 'crm_contract', + 'crm_opportunity', + ); + expect(schema.initialValues).toStrictEqual({ crm_opportunity: 'opp-1', crm_account: 'acc-1' }); + expect(saved).toMatchObject({ crm_opportunity: 'opp-1', crm_account: 'acc-1' }); + }); + + it('control: a lone parent pre-link still seeds just the parent', async () => { + const schema = await openAt('/apps/crm/crm_note?form=new&formObject=crm_case&formLink=account:acct-parent', 'crm_case'); + expect(schema.initialValues).toStrictEqual({ account: 'acct-parent' }); + }); + + it('the first pair of a field wins, and a malformed pair is skipped', async () => { + const schema = await openAt('/apps/crm/crm_note?form=new&formObject=crm_case&formLink=account:acct-parent&formLink=account:other&formLink=:x&formLink=status:open', 'crm_case'); + expect(schema.initialValues).toStrictEqual({ account: 'acct-parent', status: 'open' }); + }); +}); diff --git a/ui/packages/app-shell/src/urlParams.ts b/ui/packages/app-shell/src/urlParams.ts index 1e37e0ef14a..0d37e4abbe6 100644 --- a/ui/packages/app-shell/src/urlParams.ts +++ b/ui/packages/app-shell/src/urlParams.ts @@ -46,6 +46,10 @@ import { STUDIO_RETURN_PARAM } from './views/studio-design/studioAddress.js'; * | | framework#2604 D3). | | * | `formLink` | `":"` — create-mode parent | | * | | pre-link for a child task; refresh-safe. | with `form` | + * | | Repeats: further `":"` pairs are | | + * | | values seeded beside the parent (the relation- | | + * | | ship lookup's `dependsOn` fields, | | + * | | objectstack#37246). | | * | `tab` | Active record-detail tab (stable semantic | replace | * | | values: `details` / `related:` / | | * | | `related` / `activity` / `history`, | | @@ -111,7 +115,10 @@ export const RECORD_FORM_PARAM = 'form'; /** Child-task object override for the record-form overlay (objectstack-ai/objectstack#2604 D3). */ export const RECORD_FORM_OBJECT_PARAM = 'formObject'; -/** Child-task parent pre-link `":"` (objectstack-ai/objectstack#2604 D3). */ +/** + * Child-task parent pre-link `":"` (objectstack-ai/objectstack#2604 D3), + * repeated for each value seeded beside it (objectstack#37246). + */ export const RECORD_FORM_LINK_PARAM = 'formLink'; /** Active record-detail tab (objectui#2257; stable semantic values). */ diff --git a/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx b/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx index 92579741913..672ca81d008 100644 --- a/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx +++ b/ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx @@ -95,6 +95,7 @@ import { import { evalRowPredicate, isMultiValueRelationship, resolveAffordance, type ActionDef, type RowCrudPredicates } from '@object-ui/core'; import { actionRendersAt, type ActionLocation } from '@object-ui/types'; import { usePermissions } from '@object-ui/permissions'; +import { relatedCreateSeedOf } from '@object-ui/plugin-detail/core'; import { servesRecordRead, type RecordReadPrincipal } from '../utils/recordReadServed.js'; import { RECORD_FORM_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_LINK_PARAM, RECORD_TRAIL_PARAM, appendRecordTrail } from '../urlParams.js'; import { documentHref } from './documentHref.js'; @@ -460,7 +461,11 @@ export function RelatedRecordActionsBridge({ // object that is the full-page create route `AppContent`'s `handleEdit` // navigates to (`resolveRecordFormTarget`), not the overlay. const openChildForm = useCallback( - (opts: { objectName: string; recordId?: string; link?: { field: string; parentId: string | number } }) => { + (opts: { + objectName: string; + recordId?: string; + link?: { field: string; parentId: string | number; seed?: Record }; + }) => { if (opts.recordId == null && !opts.link) { const target = resolveRecordFormTarget({ objectDef: objects.find((o: any) => o?.name === opts.objectName), @@ -475,8 +480,16 @@ export function RelatedRecordActionsBridge({ const sp = new URLSearchParams(window.location.search); sp.set(RECORD_FORM_PARAM, opts.recordId ?? 'new'); sp.set(RECORD_FORM_OBJECT_PARAM, opts.objectName); - if (opts.link) sp.set(RECORD_FORM_LINK_PARAM, `${opts.link.field}:${opts.link.parentId}`); - else sp.delete(RECORD_FORM_LINK_PARAM); + sp.delete(RECORD_FORM_LINK_PARAM); + if (opts.link) { + // The parent link first, then the values it seeds beside it + // (objectstack#37246): one `formLink` pair each, all in the URL so a + // refresh reopens the form with them. + sp.append(RECORD_FORM_LINK_PARAM, `${opts.link.field}:${opts.link.parentId}`); + for (const [field, value] of Object.entries(opts.link.seed ?? {})) { + sp.append(RECORD_FORM_LINK_PARAM, `${field}:${value}`); + } + } setSearchParams(sp); // push → Back closes the overlay }, [setSearchParams, objects, base, navigate], @@ -666,10 +679,20 @@ export function RelatedRecordActionsBridge({ handlers.onCreate = () => { const canLink = relationshipField && parentId != null && parentId !== ''; + // objectstack#37246 — a relationship lookup scoped by the child's + // own fields (`dependsOn`) opens with them seeded from the parent, + // or the form gates the lookup (「Select Account first」) and its + // `lookupAutofill` empties it: the child saved without its parent. + // The parent record is this mount's own; a custom page's lists + // each name a parent of their own (`parentFromList`), which this + // bridge does not hold, so they seed the link alone. + const seed = canLink && !parentFromList && parentRecord + ? relatedCreateSeedOf(childDef.fields, relationshipField as string, parentRecord) + : undefined; openChildForm({ objectName, link: canLink - ? { field: relationshipField as string, parentId: parentId as string | number } + ? { field: relationshipField as string, parentId: parentId as string | number, seed } : undefined, }); }; diff --git a/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.createPredicates.test.tsx b/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.createPredicates.test.tsx index cd460db3dd4..b1aeea4fe44 100644 --- a/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.createPredicates.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/RelatedRecordActionsBridge.createPredicates.test.tsx @@ -23,8 +23,8 @@ */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; -import { render, cleanup } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; +import { render, cleanup, act } from '@testing-library/react'; +import { MemoryRouter, useLocation } from 'react-router-dom'; import React from 'react'; // Controllable principal verdict, keyed by action — same double the sibling @@ -46,7 +46,7 @@ vi.mock('@object-ui/permissions', async (importOriginal) => { }); import { RelatedRecordActionsBridge } from '../RelatedRecordActionsBridge'; -import { useRelatedRecordActions } from '@object-ui/react'; +import { useRelatedRecordActions, type RelatedRecordHandlers } from '@object-ui/react'; const CHILD = 'invoice'; @@ -281,3 +281,92 @@ describe('#4646 — predicates sit UNDER the object-level gates, never over them expect(h.onCreate).toBe(false); }); }); + +/** + * objectstack#37246 — "+ New" on a related list whose relationship lookup is + * scoped by the child's own fields (`dependsOn`: a milestone's order + * `dependsOn` the milestone's account) opens the form with each of those + * fields seeded from the parent, one `formLink` pair each after the parent's + * own. Without them the form gated the lookup (「Select Account first」), or + * its `lookupAutofill` filled the account and the dependent clear emptied the + * order, and the milestone saved without its order. + */ +describe('#37246 — "+ New" seeds the relationship lookup\'s dependsOn fields from the parent', () => { + const MILESTONE = 'crm_billing_milestone'; + const ORDER_PARENT = { id: 'so-1', name: 'SO-0001', crm_account: 'acc-1' }; + + function milestone(order: Record) { + return [{ + name: MILESTONE, + managedBy: 'platform', + fields: { + name: { type: 'text' }, + crm_sales_order: { type: 'lookup', reference: 'crm_sales_order', ...order }, + crm_account: { type: 'lookup', reference: 'crm_account' }, + }, + }]; + } + + /** Click "+ New" on the milestone list under `parentRecord`; the `formLink` pairs the URL then carries. */ + function newFrom(opts: { + order: Record; + parentRecord?: Record | null; + parentFromList?: boolean; + }): string[] { + let handlers: RelatedRecordHandlers = {}; + let search = ''; + function NewProbe({ onRender }: { onRender: (h: RelatedRecordHandlers, s: string) => void }) { + const resolved = useRelatedRecordActions()?.resolve({ objectName: MILESTONE, relationshipField: 'crm_sales_order', parentId: 'so-1' }) ?? {}; + onRender(resolved, useLocation().search); + return null; + } + render( + + + { handlers = h; search = s; }} /> + + , + ); + expect(typeof handlers.onCreate).toBe('function'); + act(() => handlers.onCreate!()); + const params = new URLSearchParams(search); + expect(params.get('form')).toBe('new'); + expect(params.get('formObject')).toBe(MILESTONE); + return params.getAll('formLink'); + } + + it('a bare dependsOn entry: the parent link, then the account the order names', () => { + expect(newFrom({ order: { dependsOn: ['crm_account'] } })).toEqual(['crm_sales_order:so-1', 'crm_account:acc-1']); + }); + + it('the same with a lookupAutofill beside it', () => { + const order = { dependsOn: ['crm_account'], lookupAutofill: [{ target: 'crm_account', source: 'crm_account' }] }; + expect(newFrom({ order })).toEqual(['crm_sales_order:so-1', 'crm_account:acc-1']); + }); + + it('a { field, param } entry reads the parent\'s param; an expanded reference reads as its id', () => { + const parentRecord = { id: 'so-1', customer: { id: 'acc-9', name: 'Contoso' } }; + const order = { dependsOn: [{ field: 'crm_account', param: 'customer' }] }; + expect(newFrom({ order, parentRecord })).toEqual(['crm_sales_order:so-1', 'crm_account:acc-9']); + }); + + it('control: a relationship lookup with no dependsOn links the parent alone, as before', () => { + expect(newFrom({ order: {} })).toEqual(['crm_sales_order:so-1']); + }); + + it('control: a parent that names no account seeds nothing beside the link', () => { + expect(newFrom({ order: { dependsOn: ['crm_account'] }, parentRecord: { id: 'so-1', crm_account: null } })).toEqual(['crm_sales_order:so-1']); + }); + + it('control: a custom page\'s lists name their own parents, so they seed the link alone', () => { + expect(newFrom({ order: { dependsOn: ['crm_account'] }, parentFromList: true })).toEqual(['crm_sales_order:so-1']); + }); +}); diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 8663091485c..8f2a2561675 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -112,6 +112,7 @@ import { relatedCardId } from './synth/relatedArrangement'; import { relatedTabConditionsChanged, useRelatedTabConditions } from './relatedTabConditions'; import { RelatedCardMenu, RelatedPanelHandle } from './RelatedCardMenu'; import { normalizeSortSpec } from './relatedListSort'; +import { dependsOnFromParent } from './relatedParentScope'; import { detectStatusField } from '@object-ui/types'; export interface RelatedListProps { @@ -1169,38 +1170,19 @@ export function derivedAddOf( * 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. + * Each `dependsOn` entry, read from the parent (`dependsOnFromParent`, the + * pairs a New on this tab also opens with, objectstack#37246), 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; + return dependsOnFromParent(rel.dependsOn, parentRecord)?.map( + ([field, value]): ViewFilterElement => ({ field, operator: 'equals', value }), + ); } /** Does this `lookupFilters` entry compare with a `{ $record }` value? */ 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 index c1e806c0624..69d8cae54f9 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.derivedAddScope-36707.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.derivedAddScope-36707.test.tsx @@ -18,6 +18,7 @@ import React from 'react'; import { FilterScopeProvider, RecordContextProvider } from '@object-ui/react'; import { ComponentRegistry } from '@object-ui/core'; import { RelatedList, derivedAddOf } from '../RelatedList'; +import { relatedCreateSeedOf } from '../relatedParentScope'; import { resetRelatedTabConditionsForTests } from '../relatedTabConditions'; import { RelatedListEnlargedContext } from '../relatedListCompact'; @@ -183,3 +184,56 @@ describe('the opportunity\'s 合同 tab picker (objectstack#36707)', () => { expect(headerTexts(dialog)).not.toContain('Name'); }); }); + +/** + * objectstack#37246 — the related tab's New seeds the child with what the + * relationship lookup `dependsOn`, from the parent (`relatedCreateSeedOf`): + * the picker's scope above, read as values. The derived picker is the control: + * its scope stays as #36707 set it. + */ +describe('relatedCreateSeedOf — a related New seeds the dependsOn fields from the parent (objectstack#37246)', () => { + it('each dependsOn field takes the parent\'s value: string and { field, param } entries, an expanded reference as its id', () => { + expect(relatedCreateSeedOf(CONTRACT_FIELDS, 'opportunity', { id: 'O-1', account: 'A-1' })).toEqual({ account: 'A-1' }); + const byParam = { ...CONTRACT_FIELDS, opportunity: { type: 'lookup', reference: 'opportunity', dependsOn: [{ field: 'account', param: 'customer' }] } }; + expect(relatedCreateSeedOf(byParam, 'opportunity', { id: 'O-1', customer: { id: 'A-9', name: 'Contoso' }, account: 'A-1' })).toEqual({ account: 'A-9' }); + }); + + it('a two-entry dependsOn seeds both fields; one the parent does not answer seeds neither, as the picker offers none', () => { + const twoEntries = { + ...CONTRACT_FIELDS, + opportunity: { type: 'lookup', reference: 'opportunity', dependsOn: ['account', { field: 'region', param: 'sales_region' }] }, + }; + expect(relatedCreateSeedOf(twoEntries, 'opportunity', { id: 'O-1', account: 'A-1', sales_region: 'R-1' })).toEqual({ account: 'A-1', region: 'R-1' }); + expect(relatedCreateSeedOf(twoEntries, 'opportunity', { id: 'O-1', account: 'A-1', sales_region: null })).toEqual({}); + expect(derivedAddOf(twoEntries, 'opportunity', 'contract', { id: 'O-1', account: 'A-1', sales_region: null })).toBeUndefined(); + }); + + it('a lookupFilters comparand reading $record does not stop the seed (the form still applies it)', () => { + const fields = { + ...CONTRACT_FIELDS, + opportunity: { ...CONTRACT_FIELDS.opportunity, lookupFilters: [{ field: 'region', operator: 'eq', value: { $record: 'region' } }] }, + }; + expect(relatedCreateSeedOf(fields, 'opportunity', { id: 'O-1', account: 'A-1' })).toEqual({ account: 'A-1' }); + }); + + it.each([ + ['no dependsOn', { ...CONTRACT_FIELDS, opportunity: { type: 'lookup', reference: 'opportunity' } }, { id: 'O-1', account: 'A-1' }], + ['the parent has no value for it', CONTRACT_FIELDS, { id: 'O-1', account: null }], + ['the parent record is not read', CONTRACT_FIELDS, undefined], + ['a multi-valued relationship', { ...CONTRACT_FIELDS, opportunity: { ...CONTRACT_FIELDS.opportunity, multiple: true } }, { id: 'O-1', account: 'A-1' }], + ['a value that is not text', CONTRACT_FIELDS, { id: 'O-1', account: 7 }], + ] as const)('nothing to seed: %s', (_label, fields, parent) => { + expect(relatedCreateSeedOf(fields, 'opportunity', parent as any)).toEqual({}); + }); + + it('control: the derived picker keeps its #36707 scope', () => { + expect(derivedAddOf(CONTRACT_FIELDS, 'opportunity', 'contract', { id: 'O-1', account: 'A-1' })).toEqual({ + picker: { + object: 'contract', + filter: [{ field: 'opportunity', operator: 'is_empty' }, { field: 'account', operator: 'equals', value: 'A-1' }], + }, + }); + const scoped = { ...CONTRACT_FIELDS, opportunity: { ...CONTRACT_FIELDS.opportunity, lookupFilters: [{ field: 'region', operator: 'eq', value: { $record: 'region' } }] } }; + expect(derivedAddOf(scoped, 'opportunity', 'contract', { id: 'O-1', account: 'A-1' })).toBeUndefined(); + }); +}); diff --git a/ui/packages/plugin-detail/src/core.ts b/ui/packages/plugin-detail/src/core.ts index c3ed609ae20..f476790afcf 100644 --- a/ui/packages/plugin-detail/src/core.ts +++ b/ui/packages/plugin-detail/src/core.ts @@ -16,8 +16,10 @@ * * ⛔ Nothing exported here may import a detail renderer, `./index` or a module * that registers a component, directly or through a neighbour: the subpath is - * only worth having while its closure stays these helpers. The same names are - * still exported from the package root, unchanged. A module added to this + * only worth having while its closure stays these helpers. The names this + * subpath split off the root are still exported from the package root, + * unchanged; a helper added for the console alone (`relatedCreateSeedOf`, + * objectstack#37246) is published here only. A module added to this * file's closure also joins the console's `plugin-detail-core` chunk group * (`apps/console/vite.config.ts`). * @@ -46,6 +48,7 @@ export { isWideFieldType } from './autoLayout'; export { prefetchRelatedCounts, relatedCountTargetsIn } from './useRelatedCounts'; export { COMPACT_RELATED_ROWS } from './relatedListCompact'; export { normalizeSortSpec as normalizeRelatedListSort } from './relatedListSort'; +export { relatedCreateSeedOf } from './relatedParentScope'; export { seedQueueClaimDecision } from './queueClaim'; export { seedRecordFieldAccess } from './recordFieldAccess'; export { seedRecordVerdict } from './useRecordEditable'; diff --git a/ui/packages/plugin-detail/src/relatedParentScope.ts b/ui/packages/plugin-detail/src/relatedParentScope.ts new file mode 100644 index 00000000000..571792ed453 --- /dev/null +++ b/ui/packages/plugin-detail/src/relatedParentScope.ts @@ -0,0 +1,84 @@ +/** + * 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. + */ + +import { isMultiValueRelationship, parentRelationshipFieldDef, type FieldContainerLike } from '@object-ui/core'; + +/** A parent's value a child's `dependsOn` field is compared with. */ +export type DependsOnValue = string | number | boolean; + +/** + * A relationship lookup's `dependsOn`, read from the parent's side: each + * child `field` with the parent's `param` value. `[]` when the lookup declares + * none, `undefined` when an entry cannot be resolved (malformed, or the + * parent's value is empty or not read). + * + * `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 names this parent only when its `field` equals the parent's `param`. + * The related tab reads the pairs twice: as the derived picker's scope + * (`parentScopeOf` in `RelatedList`, objectstack#36707) and as the values a + * child created there opens with (`relatedCreateSeedOf`, objectstack#37246). + */ +export function dependsOnFromParent( + dependsOn: unknown, + parentRecord: Record | undefined, +): Array<[string, DependsOnValue]> | undefined { + if (!Array.isArray(dependsOn) || dependsOn.length === 0) return []; + const pairs: Array<[string, DependsOnValue]> = []; + for (const entry of 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; + pairs.push([field, value]); + } + return pairs; +} + +/** + * The values a child created under this parent opens with beside the link + * itself (objectstack#37246): each `dependsOn` field of the relationship + * lookup takes the parent's value. A create form that opened with the parent + * alone drew its lookup gated (「Select Account first」), or emptied it the + * moment its `lookupAutofill` filled the field it depends on, and saved the + * child unlinked. Seeded, the parent is a candidate the lookup lists, and + * nothing moves under it. + * + * `{}` when there is nothing to seed: no such relationship, a multi-valued + * one, no `dependsOn`, or a `dependsOn` value the parent does not answer (no + * child could name it from there: the picker's rule). Only text values are + * seeded: the console carries them in the URL (`formLink`), where a value of + * any other type would arrive as text. + */ +export function relatedCreateSeedOf( + childFields: unknown, + referenceField: string | undefined, + parentRecord: Record | undefined, +): Record { + const fields = childFields as FieldContainerLike; + const rel = parentRelationshipFieldDef(fields, referenceField) as { type?: unknown; dependsOn?: unknown } | undefined; + if (!rel || (rel.type !== 'lookup' && rel.type !== 'master_detail') || isMultiValueRelationship(fields, referenceField)) { + return {}; + } + const seed: Record = {}; + for (const [field, value] of dependsOnFromParent(rel.dependsOn, parentRecord) ?? []) { + if (typeof value === 'string' && field !== referenceField) seed[field] = value; + } + return seed; +} + +/** A record field's value as a comparand: an expanded reference reads as its id. */ +function referenceValueOf(raw: unknown): DependsOnValue | 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; +}