Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/37246-related-new-dependson-seed.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion ui/apps/console/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down
20 changes: 14 additions & 6 deletions ui/packages/app-shell/src/console/AppContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {};
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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: () => () => {},
Expand Down Expand Up @@ -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' });
});
});
9 changes: 8 additions & 1 deletion ui/packages/app-shell/src/urlParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ import { STUDIO_RETURN_PARAM } from './views/studio-design/studioAddress.js';
* | | framework#2604 D3). | |
* | `formLink` | `"<fkField>:<parentId>"` — create-mode parent | |
* | | pre-link for a child task; refresh-safe. | with `form` |
* | | Repeats: further `"<field>:<value>"` 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:<child>` / | |
* | | `related` / `activity` / `history`, | |
Expand Down Expand Up @@ -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 `"<fkField>:<parentId>"` (objectstack-ai/objectstack#2604 D3). */
/**
* Child-task parent pre-link `"<fkField>:<parentId>"` (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). */
Expand Down
31 changes: 27 additions & 4 deletions ui/packages/app-shell/src/views/RelatedRecordActionsBridge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, string> };
}) => {
if (opts.recordId == null && !opts.link) {
const target = resolveRecordFormTarget({
objectDef: objects.find((o: any) => o?.name === opts.objectName),
Expand All @@ -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],
Expand Down Expand Up @@ -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,
});
};
Expand Down
Loading
Loading