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
10 changes: 10 additions & 0 deletions .changeset/38521-line-panels-parent-hand-lock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/plugin-form': patch
---

fix(plugin-form): a parent's whole-record hand lock locks the record page's line panels too

Clause-②: no
Metadata-protocol: none

The record page has two hand surfaces over a document's lines besides the edit form: the `record:line_items` panel, and the body-table editor its edit state draws. Both now read the parent object's `uiReadonlyWhen` (the whole-record hand lock), as the edit form already does. While it holds over the parent record, a person adds, duplicates, removes or reorders no line there, and every line cell is locked unless its child field declares a hand lock of its own (`uiReadonly: true` or a `uiReadonlyWhen`), which then judges that cell instead. So a child field whose own `uiReadonlyWhen` is the constant `false` keeps that one cell editable on a confirmed order; `uiReadonly: false` is not such a declaration. The panel judges the lock when the record page it sits on is its parent; until that record's row has loaded, its lines stay locked. The edit state judges the record as the user has it in the open edit. REST, import, action and flow writes are unchanged: nothing on the server reads either key.
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/**
* 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#38521 — a record page's `record:line_items` panel under its
* parent's whole-record hand lock (object-level `uiReadonlyWhen`), the rule the
* edit form follows (`MasterDetailForm.parentHandLock-38249.test.tsx`).
*
* The panel sits on the parent's record page, whose record context carries the
* parent row and its object definition. While the parent's predicate holds over
* that row, a person adds, duplicates, removes, reorders and edits no line by
* hand. A child field that declares a hand lock of its own (`uiReadonly: true`
* or a `uiReadonlyWhen`) is judged by that declaration instead:
* `uiReadonlyWhen: 'false'` keeps that one cell editable on a locked document.
*
* Measured through the REAL `LineItemsPanel` and `GridField`.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup } from '@testing-library/react';
import React from 'react';

import { registerAllFields } from '@object-ui/fields';
import { RecordContextProvider, SchemaRendererProvider } from '@object-ui/react';
import { LineItemsPanel } from './LineItemsPanel';

registerAllFields();
afterEach(cleanup);

const PARENT = 'sales_order';
const CHILD = 'sales_order_line';
const LINE = { id: 'L1', order: 'SO1', qty: 3, note: 'gift wrap' };

const PARENT_SCHEMA = {
name: PARENT,
uiReadonlyWhen: "record.status == 'confirmed'",
fields: { ref: { type: 'text', label: 'Ref' }, status: { type: 'text', label: 'Status' } },
};

const childSchema = (note: Record<string, unknown>) => ({
name: CHILD,
fields: {
order: { type: 'master_detail', reference: PARENT, label: 'Order' },
qty: { type: 'number', label: 'Qty' },
note: { type: 'text', label: 'Note', ...note },
},
});

/** Untyped authored columns: each is hydrated from its child field. */
const PANEL = {
childObject: CHILD,
relationshipField: 'order',
columns: [{ name: 'qty', label: 'Qty' }, { name: 'note', label: 'Note' }],
} as any;

function mount(
status: string,
note: Record<string, unknown> = {},
parentSchema: unknown = PARENT_SCHEMA,
opts: { rowLoaded?: boolean; panel?: Record<string, unknown> } = {},
) {
const ds = {
getObjectSchema: vi.fn(async (obj: string) => (obj === CHILD ? childSchema(note) : null)),
find: vi.fn().mockResolvedValue({ data: [LINE] }),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
};
render(
<SchemaRendererProvider dataSource={ds as any}>
<RecordContextProvider
objectName={PARENT}
recordId="SO1"
data={opts.rowLoaded === false ? undefined : { id: 'SO1', ref: 'SO-1', status }}
objectSchema={parentSchema}
dataSource={ds as any}
>
<LineItemsPanel schema={{ ...PANEL, ...opts.panel }} />
</RecordContextProvider>
</SchemaRendererProvider>,
);
return ds;
}

const offered = () => ({
add: screen.queryByTestId('line-items-add') !== null,
duplicate: screen.queryAllByRole('button', { name: 'Duplicate row' }).length > 0,
remove: screen.queryAllByRole('button', { name: 'Remove row' }).length > 0,
reorder: screen.queryByTestId('line-items-drag-0') !== null,
});

/** Wait until the stored line is drawn over the hydrated (child-schema) columns. */
async function lineLoaded(ds: ReturnType<typeof mount>) {
await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith(CHILD));
await waitFor(() => expect(screen.getByDisplayValue('3')).toBeTruthy());
}

const qtyCell = () => screen.getByDisplayValue('3') as HTMLInputElement;
const noteCell = () => screen.getByDisplayValue('gift wrap') as HTMLInputElement;

describe("LineItemsPanel: the parent object's uiReadonlyWhen hand-locks the record page's lines (objectstack#38521)", () => {
it('a locked parent offers no add, duplicate, remove or reorder of a line, and locks a line cell that declares no hand lock of its own', async () => {
const ds = mount('confirmed');
await lineLoaded(ds);
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(noteCell().disabled).toBe(true);
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
});

it("a child field whose own uiReadonlyWhen is 'false' stays editable on a locked parent; its siblings stay locked", async () => {
const ds = mount('confirmed', { uiReadonlyWhen: 'false' });
await lineLoaded(ds);
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(noteCell().disabled).toBe(false);
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
});

it('a child field with uiReadonly: true stays locked on a locked parent (its own declaration locks it)', async () => {
const ds = mount('confirmed', { uiReadonly: true });
await lineLoaded(ds);
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(noteCell().disabled).toBe(true);
});

it('CONTROL: while the parent predicate does not hold, the lines are edited as before', async () => {
const ds = mount('draft');
await lineLoaded(ds);
expect(qtyCell().disabled).toBe(false);
expect(noteCell().disabled).toBe(false);
expect(offered()).toEqual({ add: true, duplicate: true, remove: true, reorder: true });
});

it('a parent row the record context has not loaded yet locks the lines (the hand lock fails closed)', async () => {
const ds = mount('draft', {}, PARENT_SCHEMA, { rowLoaded: false });
await lineLoaded(ds);
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
});

it("CONTROL: a panel bound to another parent than the record context's is not judged by that record", async () => {
const ds = mount('confirmed', {}, PARENT_SCHEMA, { panel: { parentObject: PARENT, parentId: 'SO2' } });
await lineLoaded(ds);
expect(qtyCell().disabled).toBe(false);
expect(offered().add).toBe(true);
});

it('CONTROL: a parent object that declares no uiReadonlyWhen leaves the lines open', async () => {
const { uiReadonlyWhen: _drop, ...plain } = PARENT_SCHEMA;
const ds = mount('confirmed', {}, plain);
await lineLoaded(ds);
expect(qtyCell().disabled).toBe(false);
expect(offered()).toEqual({ add: true, duplicate: true, remove: true, reorder: true });
});
});
50 changes: 41 additions & 9 deletions ui/packages/plugin-form/src/LineItemsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ import {
import { LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields';
import type { GridFieldMetadata } from '@object-ui/types';
import { createSafeTranslation, useLocalization } from '@object-ui/i18n';
import { useSchemaContext, useRecordContext, useFilterScope, useResolvedFilter, useDataInvalidation, usePrintPage, NonGridRowCeilingNote } from '@object-ui/react';
import { useSchemaContext, useRecordContext, useFilterScope, useResolvedFilter, useDataInvalidation, usePrintPage, usePredicateScope, NonGridRowCeilingNote } from '@object-ui/react';
import { usePermissions } from '@object-ui/permissions';
import { buildMasterDetailEditBatch, sumRows } from './masterDetailTx';
import { applyColumnPermissions } from './fieldWriteGate';
import { hydrateColumns } from './deriveMasterDetail';
import { hydrateColumns, lockColumnsByParentHandLock, parentHandLockHolds } from './deriveMasterDetail';
import { currencyFieldDefsOf, parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns';
import {
runBatchTransaction,
Expand Down Expand Up @@ -770,6 +770,28 @@ export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ sch
() => currencyFieldDefsOf(childSchema?.fields as Record<string, unknown> | undefined),
[childSchema],
);

// objectstack#38521 — the PARENT's whole-record hand lock covers its lines
// here as in the edit form (objectstack#38249). Judged when the record
// context is this panel's parent (the record page the panel sits on), whose
// served definition carries the lock and whose row it is judged over
// (`parentHandLockHolds`). While it holds, no line is added, duplicated,
// removed or reordered, and every cell whose child field owns no hand lock
// is locked (`lockColumnsByParentHandLock`); a child field's own
// `uiReadonlyWhen` / `uiReadonly: true` judges its cell instead. Declared
// writes are untouched: nothing on the server reads either key.
const predicateScope = usePredicateScope();
const recordIsParent = record?.recordId != null
&& String(record.recordId) === String(parentId)
&& record.objectName === parentObject;
const parentSchema = recordIsParent
? (record?.objectSchema as { uiReadonlyWhen?: unknown; fields?: unknown } | undefined)
: undefined;
const parentLockRow = recordIsParent ? (record?.data as Record<string, unknown> | undefined) : undefined;
const parentHandLocked = useMemo(
() => parentHandLockHolds(parentSchema, parentLockRow, { scope: predicateScope, parentObjectName: parentObject }),
[parentSchema, parentLockRow, predicateScope, parentObject],
);
const lineLookupAutofill = useMemo(
() => lookupAutofillByField(childSchema?.fields as Record<string, unknown> | undefined),
[childSchema],
Expand Down Expand Up @@ -801,10 +823,17 @@ export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ sch
// master-detail grid's does. An authored `label` or `type` still wins,
// and a column whose field the child does not declare is kept as
// written. Until the schema arrives the columns render as authored.
columns: applyColumnPermissions(hydrateColumns(schema.columns, childSchema ?? undefined, { booleanLabel }), {
perms,
objectName: schema.childObject,
}),
//
// Under the parent's hand lock (objectstack#38521) each hydrated
// column whose child field owns no hand lock is locked before that
// pass; an authored column no child schema has answered for carries
// no mark yet and is locked too (the hand lock fails closed).
columns: applyColumnPermissions(
parentHandLocked
? lockColumnsByParentHandLock(hydrateColumns(schema.columns, childSchema ?? undefined, { booleanLabel }))
: hydrateColumns(schema.columns, childSchema ?? undefined, { booleanLabel }),
{ perms, objectName: schema.childObject },
),
// The grid's `totalField` is the CHILD column summed (this block's
// `amountField`), shown whenever one is named, exactly as
// `MasterDetailForm` maps it. This block's own `totalField` is only
Expand All @@ -813,14 +842,17 @@ export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ sch
totalField: schema.amountField || (schema.totalField ? 'amount' : undefined),
minRows: schema.minRows,
maxRows: schema.maxRows,
allowAdd: !schema.readonly && lineAddGranted,
allowDelete: !schema.readonly && lineRemoveGranted,
// The parent's hand lock withholds add (and Duplicate), remove and
// reorder (objectstack#38521).
allowAdd: !schema.readonly && lineAddGranted && !parentHandLocked,
allowDelete: !schema.readonly && lineRemoveGranted && !parentHandLocked,
...(parentHandLocked ? { allowReorder: false } : {}),
// Checked against the grid's published type (objectui#11610), so a key
// the grid does not declare, or one of its retired snake_case
// spellings, fails to compile here.
} satisfies Partial<GridFieldMetadata>) as GridFieldMetadata,
// eslint-disable-next-line react-hooks/exhaustive-deps -- `booleanLabel` keyed on its WORDS, see above
[schema, childSchema, perms, lineAddGranted, lineRemoveGranted, booleanTrueWord, booleanFalseWord],
[schema, childSchema, perms, lineAddGranted, lineRemoveGranted, parentHandLocked, booleanTrueWord, booleanFalseWord],
);

// The config hint names the property to set as code, and the property name
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/**
* 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#38521 — the record page's body-table editor (its edit state)
* under the parent's whole-record hand lock (object-level `uiReadonlyWhen`),
* the rule the edit form follows (`MasterDetailForm.parentHandLock-38249.test.tsx`).
*
* The record page keeps Edit live on a locked document when a header field or
* a child field owns a hand lock that can still open (objectstack#38249), so
* the edit state opens and draws this editor. While the parent's predicate
* holds over the record, a person adds, duplicates, removes, reorders and edits
* no line by hand; a child field that declares a hand lock of its own
* (`uiReadonly: true` or a `uiReadonlyWhen`) is judged by that declaration:
* `uiReadonlyWhen: 'false'` keeps that one cell editable.
*
* Measured through the REAL `RecordBodyTableEditor` and `GridField`.
*/
import * as React from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import { RecordContextProvider } from '@object-ui/react';
import { registerAllFields } from '@object-ui/fields';
import { RecordBodyTableEditor, RecordEditSessionContext, type RecordEditSession } from './RecordBodyTableEditor';

registerAllFields();
afterEach(() => cleanup());

const PARENT = 'sales_order';
const CHILD = 'sales_order_line';
const LINE = { id: 'L1', order: 'SO1', qty: 3, note: 'gift wrap' };

const PARENT_SCHEMA = {
name: PARENT,
uiReadonlyWhen: "record.status == 'confirmed'",
fields: { ref: { type: 'text', label: 'Ref' }, status: { type: 'text', label: 'Status' } },
};

const childSchema = (note: Record<string, unknown>) => ({
name: CHILD,
fields: {
order: { type: 'master_detail', reference: PARENT, label: 'Order' },
qty: { type: 'number', label: 'Qty' },
note: { type: 'text', label: 'Note', ...note },
},
});

function mount(status: string, note: Record<string, unknown> = {}, parentSchema: unknown = PARENT_SCHEMA) {
const ds = {
getObjectSchema: vi.fn(async (obj: string) => (obj === CHILD ? childSchema(note) : null)),
find: vi.fn(async () => ({ data: [LINE] })),
onMutation: () => () => {},
};
const session: RecordEditSession = { register: () => () => {}, reportDirty: () => {}, saving: false };
render(
<RecordContextProvider
objectName={PARENT}
recordId="SO1"
data={{ id: 'SO1', ref: 'SO-1', status }}
objectSchema={parentSchema}
dataSource={ds as never}
>
<RecordEditSessionContext.Provider value={session}>
<RecordBodyTableEditor objectName={CHILD} relationshipField="order" />
</RecordEditSessionContext.Provider>
</RecordContextProvider>,
);
return ds;
}

const offered = () => ({
add: screen.queryByTestId('line-items-add') !== null,
duplicate: screen.queryAllByRole('button', { name: 'Duplicate row' }).length > 0,
remove: screen.queryAllByRole('button', { name: 'Remove row' }).length > 0,
reorder: screen.queryByTestId('line-items-drag-0') !== null,
});

const qtyCell = () => screen.getByDisplayValue('3') as HTMLInputElement;
const noteCell = () => screen.getByDisplayValue('gift wrap') as HTMLInputElement;
/** Whether an input a person can type in holds the note. */
const noteOpen = () => {
const input = screen.queryByDisplayValue('gift wrap') as HTMLInputElement | null;
return input !== null && !input.disabled;
};
const lineLoaded = () => waitFor(() => expect(screen.getByDisplayValue('3')).toBeTruthy());

describe("RecordBodyTableEditor: the parent object's uiReadonlyWhen hand-locks the edit state's lines (objectstack#38521)", () => {
it('a locked parent offers no add, duplicate, remove or reorder of a line, and locks a line cell that declares no hand lock of its own', async () => {
mount('confirmed');
await lineLoaded();
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(noteCell().disabled).toBe(true);
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
});

it("a child field whose own uiReadonlyWhen is 'false' stays editable on a locked parent; its siblings stay locked", async () => {
mount('confirmed', { uiReadonlyWhen: 'false' });
await lineLoaded();
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(noteCell().disabled).toBe(false);
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
});

it('a child field with uiReadonly: true stays locked on a locked parent (its own declaration locks it)', async () => {
mount('confirmed', { uiReadonly: true });
await lineLoaded();
await waitFor(() => expect(qtyCell().disabled).toBe(true));
// The derived columns never list a `uiReadonly: true` child field
// (`deriveInlineGridColumns`), so the note is drawn in no input at all.
expect(noteOpen()).toBe(false);
});

it('CONTROL: while the parent predicate does not hold, the lines are edited as before', async () => {
mount('draft');
await lineLoaded();
expect(qtyCell().disabled).toBe(false);
expect(noteCell().disabled).toBe(false);
expect(offered()).toEqual({ add: true, duplicate: true, remove: true, reorder: true });
});

it('CONTROL: a parent object that declares no uiReadonlyWhen leaves the lines open', async () => {
const { uiReadonlyWhen: _drop, ...plain } = PARENT_SCHEMA;
mount('confirmed', {}, plain);
await lineLoaded();
expect(qtyCell().disabled).toBe(false);
expect(offered()).toEqual({ add: true, duplicate: true, remove: true, reorder: true });
});
});
Loading
Loading