Skip to content
12 changes: 12 additions & 0 deletions .changeset/38249-inline-lines-hand-lock-edit-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/app-shell': patch
---

fix(app-shell): the record page greys Edit on a hand-locked document whose inline lines are locked too

Clause-②: yes (widening)
Metadata-protocol: none

The record page's Edit was always live on an object whose field groups place an inline child collection, because the edit form still edited its lines. Now that a parent's whole-record hand lock (`uiReadonlyWhen`) locks those lines as well, Edit goes off with the state-lock reason when the lock holds over the record, every header field the form draws is read-only, and no field of any placed child object owns a hand lock that could open a line cell. Without a child object's definition, or when a child field declares a `uiReadonlyWhen` of its own, Edit stays live as before.

Additive: the exported `editFormLockedByState` takes an optional fourth argument, `childObjectDef` (a child object name to its served definition); callers that omit it behave as before.
12 changes: 12 additions & 0 deletions .changeset/38249-inline-lines-hand-lock-form.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/plugin-form': patch
---

fix(plugin-form): a parent's whole-record hand lock locks its inline master-detail lines in the edit form

Clause-②: yes (widening)
Metadata-protocol: none

The master-detail edit form now reads the parent object's `uiReadonlyWhen` (the whole-record hand lock) over its lines too. While it holds over the parent record, a person adds, duplicates, removes or reorders no line, the per-row editor is not offered, 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 — the same override the object level already reads. 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. A create is not judged. A fully configured entry (typed columns and the relationship field, so no child schema is read) has every line cell locked while the parent lock holds. REST, import, action and flow writes are unchanged: nothing on the server reads either key.

New export `childLinesOpenUnderParentHandLock`, from the package root and from `@object-ui/plugin-form/core`: whether a child object's lines can still be edited under a locked parent (some child field owns a hand lock that is not static).
51 changes: 51 additions & 0 deletions ui/packages/app-shell/src/utils/editFormLockedByState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,54 @@ describe('editFormLockedByState reads the object-level uiReadonlyWhen (#37402)',
expect(editFormLockedByState(order({}), { ...CONFIRMED, status: 'draft' })).toBe(false);
});
});

/**
* #38249 — an object's whole-record hand lock locks its inline lines too, so
* an object that places a child collection greys Edit when the lock holds and
* no field of the child can open a line cell. Without the child's definition,
* or when a child field owns a lock that could open, Edit stays live.
*/
describe('editFormLockedByState with inline lines under the object-level uiReadonlyWhen (#38249)', () => {
const CONFIRMED = { id: 'o1', status: 'confirmed', amount: 1 };
const order = {
name: 'order',
uiReadonlyWhen: "record.status == 'confirmed'",
fields: { status: { type: 'text' }, amount: { type: 'number' } },
groupSubforms: [{ childObject: 'order_line', relationshipField: 'order' }],
};
const line = (qty: Record<string, unknown> = {}) => ({
name: 'order_line',
fields: { order: { type: 'master_detail', reference: 'order' }, qty: { type: 'number', ...qty } },
});
const defs = (child: unknown) => (name: string) => (name === 'order_line' ? (child as any) : undefined);

it('is true when the object lock holds and no child field can open a line cell', () => {
expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line()))).toBe(true);
});

it("is false when a child field keeps its cell editable with its own uiReadonlyWhen 'false'", () => {
expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonlyWhen: 'false' })))).toBe(false);
});

it('is true when the child field owns only a static lock', () => {
expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonly: true })))).toBe(true);
});

it('is false while the object predicate does not hold', () => {
expect(editFormLockedByState(order, { ...CONFIRMED, status: 'draft' }, undefined, defs(line()))).toBe(false);
});

it('is false when the header is locked only field by field: that leaves the lines open', () => {
const { uiReadonlyWhen: _drop, ...plain } = order;
const byField = {
...plain,
fields: { status: { type: 'text', readonlyWhen: "record.status == 'confirmed'" }, amount: { type: 'number', readonlyWhen: "record.status == 'confirmed'" } },
};
expect(editFormLockedByState(byField, CONFIRMED, undefined, defs(line()))).toBe(false);
});

it("fails open without the child object's definition", () => {
expect(editFormLockedByState(order, CONFIRMED)).toBe(false);
expect(editFormLockedByState(order, CONFIRMED, undefined, () => undefined)).toBe(false);
});
});
34 changes: 30 additions & 4 deletions ui/packages/app-shell/src/utils/editFormLockedByState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,20 @@
* so a writable field anywhere keeps Edit live;
* - the object's field groups place no inline child collection
* (`recordFormSubforms`, objectstack-ai/objectstack#36425), whose rows the
* form still edits whatever the header fields say.
* form still edits whatever the header fields say — unless the object's
* whole-record hand lock (`uiReadonlyWhen`) holds over the record, which
* locks those rows too (objectstack#38249), and no field of any placed
* child object owns a hand lock that could open a line cell
* (`childLinesOpenUnderParentHandLock`). That needs each child object's
* definition, from `childObjectDef`; without it, or for a child it cannot
* answer, Edit stays live.
*
* A predicate that faults resolves to its fail-open verdict (writable), as in
* the form, so a broken rule never greys Edit.
*/

import { effectiveUiReadonlyWhen, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core';
import { filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core';
import { effectiveUiReadonlyWhen, fieldReadOnlyByHand, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core';
import { childLinesOpenUnderParentHandLock, filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core';
import type { FormField } from '@object-ui/types';
import { recordFormSubforms, type ObjectDefinitionForRecordForm } from './recordFormNavigation.js';

Expand Down Expand Up @@ -66,9 +72,11 @@ export function editFormLockedByState(
objectDef: EditFormLockObject | null | undefined,
record: Record<string, unknown> | null | undefined,
scope?: Record<string, unknown>,
childObjectDef?: (name: string) => { fields?: Record<string, any> } | null | undefined,
): boolean {
if (!objectDef || !record) return false;
if (recordFormSubforms(objectDef)) return false;
const subforms = recordFormSubforms(objectDef);
if (subforms && !childObjectDef) return false;

const declared = fieldEntries(objectDef.fields);
// The fields the form draws: the form's own system-field pass drops the
Expand All @@ -87,6 +95,24 @@ export function editFormLockedByState(
for (const { name } of declared) ruleRecord[name] = null;
for (const [k, v] of Object.entries(record)) if (v !== undefined) ruleRecord[k] = v;

if (subforms) {
// objectstack#38249 — the lines are locked only by the object's own
// whole-record hand lock (a field-level lock on the header leaves them
// open), judged by the one hand-lock verdict over the stored row.
const objectLockHolds = fieldReadOnlyByHand({}, ruleRecord, {
object: objectDef,
previous: ruleRecord,
scope,
fieldContext: 'object uiReadonlyWhen',
});
if (!objectLockHolds) return false;
for (const subform of subforms) {
const childObject = typeof subform?.childObject === 'string' ? subform.childObject : undefined;
const child = childObject ? childObjectDef?.(childObject) : undefined;
if (!child || childLinesOpenUnderParentHandLock(child)) return false;
}
}

let shown = 0;
let lockedByRule = 0;
for (const { name, def } of entries) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ function stateLockBadge(): HTMLElement | null {
}

/** Mount the console record page and wait for the record read and the header. */
async function mountRecordPage(record: Record<string, unknown>, fields: Record<string, unknown>) {
const objects = [objectDef(fields)];
async function mountRecordPage(record: Record<string, unknown>, fields: Record<string, unknown>, served?: any[]) {
const objects = served ?? [objectDef(fields)];
const dataSource = makeDataSource(record);
render(
<MemoryRouter initialEntries={[`/apps/fin/${OBJECT_NAME}/${RECORD_ID}`]}>
Expand Down Expand Up @@ -245,3 +245,48 @@ describe('console record header — a record whose state locks every edit-form f
expect(stateLockBadge()).toBeNull();
});
});

/**
* objectstack#38249 — an object whose whole-record hand lock (`uiReadonlyWhen`)
* holds locks its inline lines in the edit form too, so the record page greys
* Edit even though its field groups place a child collection — unless a child
* field owns a hand lock that could open a line cell.
*/
describe('console record header — a hand-locked document with inline lines (objectstack#38249)', () => {
const LINE_OBJECT = 'ebqu_claim_line';
const parent = {
...objectDef({
id: { type: 'text', label: 'Id' },
name: { type: 'text', label: 'Title' },
status: { type: 'text', label: 'Status' },
}),
uiReadonlyWhen: "record.status == 'approved'",
groupSubforms: [{ childObject: LINE_OBJECT, relationshipField: 'claim' }],
};
const line = (amount: Record<string, unknown> = {}) => ({
name: LINE_OBJECT,
label: 'Claim line',
fields: {
claim: { type: 'master_detail', label: 'Claim', reference: OBJECT_NAME },
amount: { type: 'currency', label: 'Amount', ...amount },
},
});

it('draws Edit disabled when the object lock holds and no line cell can open', async () => {
await mountRecordPage(APPROVED, {}, [parent, line()]);
await waitFor(() => expect(headerEditButton()).toBeDisabled());
expect(stateLockBadge()).toBeInTheDocument();
});

it("CONTROL: a child field whose own uiReadonlyWhen is 'false' keeps Edit enabled", async () => {
await mountRecordPage(APPROVED, {}, [parent, line({ uiReadonlyWhen: 'false' })]);
expect(headerEditButton()).not.toBeDisabled();
expect(stateLockBadge()).toBeNull();
});

it('CONTROL: a state the object lock does not hold keeps Edit enabled', async () => {
await mountRecordPage(DRAFT, {}, [parent, line()]);
expect(headerEditButton()).not.toBeDisabled();
expect(stateLockBadge()).toBeNull();
});
});
12 changes: 10 additions & 2 deletions ui/packages/app-shell/src/views/RecordDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3108,8 +3108,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
// goes off exactly when the form would open with no control.
const predicateScope = usePredicateScope();
const editLockedByState = useMemo(
() => editFormLockedByState(objectDef as any, pageRecord as Record<string, unknown> | null | undefined, predicateScope),
[objectDef, pageRecord, predicateScope],
() => editFormLockedByState(
objectDef as any,
pageRecord as Record<string, unknown> | null | undefined,
predicateScope,
// The placed child objects' definitions: a parent's whole-record hand
// lock locks its inline lines too, unless a child field owns a lock
// that could open one (objectstack#38249).
(name) => objects.find((o: any) => o?.name === name),
),
[objectDef, pageRecord, predicateScope, objects],
);

// ── Audit history fetch ────────────────────────────────────────────
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/**
* 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#38249 — a parent's whole-record hand lock (object-level
* `uiReadonlyWhen`) covers its inline master-detail lines in the edit form.
*
* While the predicate holds over the parent 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 instead, the same override the object level
* reads (`effectiveUiReadonlyWhen`): `uiReadonlyWhen: 'false'` keeps that one
* cell editable on a locked document. A create is not judged.
*
* Measured through the REAL `MasterDetailForm` 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 { MasterDetailForm } from './MasterDetailForm';

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 makeDS(status: string, note: Record<string, unknown> = {}) {
return {
getObjectSchema: vi.fn(async (obj: string) =>
obj === PARENT ? PARENT_SCHEMA : obj === CHILD ? childSchema(note) : null,
),
findOne: vi.fn().mockResolvedValue({ id: 'SO1', ref: 'SO-1', status }),
find: vi.fn().mockResolvedValue({ data: [LINE] }),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
batchTransaction: vi.fn().mockResolvedValue({ results: [] }),
};
}

/** Untyped authored columns: the child schema is read and each column hydrated from its field. */
const DERIVED = [{ childObject: CHILD, relationshipField: 'order', columns: [{ name: 'qty', label: 'Qty' }, { name: 'note', label: 'Note' }] }];
/** A fully configured entry: typed columns and the FK, so no child schema is read. */
const CONFIGURED = [{ childObject: CHILD, relationshipField: 'order', columns: [{ name: 'qty', label: 'Qty', type: 'number' }] }];

function mount(ds: ReturnType<typeof makeDS>, details = DERIVED, mode: 'edit' | 'create' = 'edit') {
return render(
<MasterDetailForm
schema={{
objectName: PARENT,
mode,
...(mode === 'edit' ? { recordId: 'SO1' } : {}),
fields: ['ref', 'status'],
details,
} as any}
dataSource={ds as any}
/>,
);
}

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 and the header record has landed. */
async function lineLoaded(ds: ReturnType<typeof makeDS>) {
await waitFor(() => expect(screen.getByDisplayValue('3')).toBeTruthy());
await waitFor(() => expect(ds.findOne).toHaveBeenCalled());
// A locked header field draws its read face, an open one its input.
await waitFor(() => expect(screen.queryByDisplayValue('SO-1') ?? screen.queryByText('SO-1')).toBeTruthy());
}

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

describe('MasterDetailForm: the parent object\'s uiReadonlyWhen hand-locks its inline lines (objectstack#38249)', () => {
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 = makeDS('confirmed');
mount(ds);
await lineLoaded(ds);
await waitFor(() => expect(qtyCell().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 = makeDS('confirmed', { uiReadonlyWhen: 'false' });
mount(ds);
await lineLoaded(ds);
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(noteCell().disabled).toBe(false);
expect(offered().add).toBe(false);
});

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

it('a fully configured entry (no child schema read) locks every line cell on a locked parent', async () => {
const ds = makeDS('confirmed');
mount(ds, CONFIGURED);
await lineLoaded(ds);
await waitFor(() => expect(qtyCell().disabled).toBe(true));
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
});

it('CONTROL: while the parent predicate does not hold, the lines are edited as before', async () => {
const ds = makeDS('draft');
mount(ds);
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('CONTROL: a create form is not judged — lines are added on an object that carries the lock', async () => {
const ds = makeDS('confirmed');
mount(ds, DERIVED, 'create');
await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy());
});
});
Loading
Loading