Skip to content

Commit fa345c4

Browse files
fix(console): a parent's whole-record hand lock locks its inline master-detail lines in the edit form (#38388)
Fixes #38249 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:对象上写了「整单人手锁定」条件的单据(如已确认的订单),在控制台编辑对话框里,明细行也一并锁住:不能加行、复制行、删行、拖动排序或改单元格;明细字段自己写了「始终可改」的那一列仍可编辑;整单与明细都没有可改之处时,记录页的「编辑」按钮置灰并说明原因。 - 为什么做:对象级整单锁定上线后,表头字段锁住了,明细行却还能手改,与「整单人手锁定」的承诺不符,维护者裁定按字面先落地、再立此跟进卡补上明细这一半。 - 出错会怎样:漏锁时用户仍能手改明细行,服务端校验照常兜底;误锁时只影响手工编辑,按钮、接口、导入、流程照常写入;去掉对象上的锁定条件即可撤回。 - 要你做什么:无。 ## What changes Governing ruling: the maintainer on PR #38169 (the object-level hand lock), 「本 PR 按字面落地+立跟进卡」; this card is that follow-up. The opt-out reads the existing override rule of the two-tier lock model (ruling on #36806, Q1 = B on #37402): a field that declares a hand lock of its own — `uiReadonly: true` or a `uiReadonlyWhen` — is judged by it instead of any object-level default, and `uiReadonly: false` is not such a declaration. No key, value or schema property is added. **`@object-ui/plugin-form`** - `MasterDetailForm.tsx` (the edit dialog's line grids): the header record feed also lands the parent object's `uiReadonlyWhen` with its field names. On an EDIT form the lines judge it over the live header record (every header field seeded `null`, the stored row as `previous`, the host's predicate scope) through the one hand-lock verdict (`fieldReadOnlyByHand` of a field that declares nothing, i.e. the object lock itself, failing closed). While it holds: no Add, Duplicate, Remove or drag-reorder, no per-row editor, and every line column whose child field owns no hand lock is locked on every row. A create is not judged. - `deriveMasterDetail.ts`: derived and hydrated line columns carry an in-memory mark when their child field owns a hand lock (`childFieldOwnsHandLock`, which asks `effectiveUiReadonlyWhen` itself rather than restating the rule). `lockColumnsByParentHandLock` locks every unmarked column. `childLinesOpenUnderParentHandLock` answers whether some child field owns a non-static hand lock (exported from the root and from `/core`). **`@object-ui/app-shell`** - `editFormLockedByState.ts`: an object that places an inline child collection no longer keeps Edit live unconditionally. It greys Edit when the object's own `uiReadonlyWhen` holds over the record, every drawn header field is read-only, and no placed child object has a field that could open a line cell. That needs the child definitions, through a new optional `childObjectDef` argument; without it, or for a child it cannot answer, Edit stays live (fail open, as before). - `RecordDetailView.tsx`: passes the served object list as that resolver. Declared writes (REST, import, actions, flows) are untouched: nothing on the server reads either key (ruling on #36806). Published surface, both additive (a non-protocol widening, so `patch`): `@object-ui/plugin-form` exports `childLinesOpenUnderParentHandLock` from its `.` and `./core` entries, and the exported `editFormLockedByState` of `@object-ui/app-shell` takes an optional fourth argument, `childObjectDef`; a caller that omits it behaves as before. ## Why PR #38169's acceptance notes recorded that a parent's object lock did not reach its line rows, and its contract review (record 7236877945) escalated it. The maintainer summary of #37402 promises 「整单人手锁定」 for a confirmed order, while a person could still edit its lines. ## Tests - New `MasterDetailForm.parentHandLock-38249.test.tsx` (real `MasterDetailForm` and `GridField`): a locked parent offers no add / duplicate / remove / reorder and locks a line cell; a child field with its own `uiReadonlyWhen: 'false'` stays editable while its sibling is locked; `uiReadonly: true` stays locked; a fully configured entry (no child schema read) locks every cell; CONTROL draft parent edits as before; CONTROL a create is not judged. - `__tests__/dialogHandLock-36806.test.ts`, new top-level describe: `childFieldOwnsHandLock` over each spelling (`uiReadonly: false` and a server lock are not ownership); derived and authored (typed and untyped) columns; an unmarked column fails closed; `childLinesOpenUnderParentHandLock`. - `editFormLockedByState.test.ts`, new describe: true when the lock holds and no child field can open; false with a `'false'` child override; true with only a static child lock; false when the predicate does not hold; false when the header is locked field by field only; fail-open without child definitions. - `RecordDetailView.editLockedByState-32756.test.tsx`, new top-level describe: Edit disabled with the state reason on a locked document with lines; CONTROL a `'false'` child override and a draft record keep it live. ## Acceptance notes - Measured on `main` first: the new rendered pin against the unfixed code, 4 failed / 2 passed (a confirmed parent's line cell was editable; both controls green). - Precedence, as the existing override rule gives it: a child field with its own conditional `uiReadonlyWhen` (say over the line's own columns) is judged by that predicate, so the parent's lock does not reach that cell. Its default (no declaration) is now the child object's lock OR the parent's. - A row-level opt-out for adding or removing lines does not exist: under a locked parent no line is added, duplicated, removed or reordered, whatever the child fields declare. A field-level declaration opens only that field's cell on stored lines. - The per-row editor is not offered under a locked parent, because it edits every child field. So in a form-factor collection (`inlineEdit: 'form'`, lines shown as a list) a child field's own opt-out has no surface while the parent is locked: that collection reads fully locked. - A fully configured entry (typed columns and the relationship field) reads no child schema, so its columns carry no ownership mark and all lock under the parent lock (the hand lock fails closed). - Before the header record lands, the parent predicate is judged over `null`-seeded header fields; a predicate such as `record.status == 'confirmed'` then reads open until the record lands. This is the same window as the grid's own object-definition read noted on PR #38169. - Scope: the console edit form and the record page's Edit state. The record page's own line-items panel (`LineItemsPanel` / the record body table editor) is not changed here; whether it should follow the parent's lock is for its own card. - The four commits' `Claude-Session:` trailers name the dispatching seat's session (`session_017xRBcSAaBEfQpU2yJexSJ8`) instead of this dev session (`session_017xRBcSPkRxFWubkD5XfiDh`), a transcription slip; the history is left as pushed. - File surface beyond the two claimed files, each `check-handover.mjs --inflight` clear: `MasterDetailForm.tsx` (the line grid), `RecordDetailView.tsx` (the Edit state's caller), `core.ts` and `index.tsx` (one export each). ## Verification Patch round (seat claim amendment 7247687945, head `1933251b`): `Clause-②` corrected to `yes (widening)` here and in both changesets (still `patch`, `Metadata-protocol: none`); `origin/main` merged twice (`212babcf`, `1933251b`), no incoming commit touching this diff's files. On `1933251b`: the four pin files 4/4 files, 42/42 tests; `dispatch-gates.mjs --commands` 38 families, all run, all exit 0 (the ui `scripts/` suite 172 files passed, 2 skipped / 5,159 tests); `--ran`: "38 run, 0 NOT-MEASURED"; `overlap-check.mjs` VERDICT clean exit 0; `check:nul-bytes` OK. The readings below are the first round's. Two-minute check: `cd ui && pnpm exec vitest run packages/plugin-form/src/MasterDetailForm.parentHandLock-38249.test.tsx` — expect 6 passed. First files to read (by risk): `ui/packages/plugin-form/src/MasterDetailForm.tsx` (the `parentHandLocked` verdict and the three grid props it gates); `ui/packages/plugin-form/src/deriveMasterDetail.ts` (`childFieldOwnsHandLock` and the mark); `ui/packages/app-shell/src/utils/editFormLockedByState.ts` (the subform branch). Readings on `objectstack-ai/objectstack`, head `9166fa40` (the gate union on `81f9ef2c`; the one later commit adds only the record-page test describe, and the derived list on `9166fa40` is byte-identical). <details><summary>Tests</summary> - `@object-ui/plugin-form` full suite: 249 files / 2,816 passed, 1 skipped. - `@object-ui/plugin-form` and `@object-ui/app-shell` `type-check` (both `tsc --noEmit` and the test tsconfig): exit 0. - app-shell targeted: `RecordDetailView.editLockedByState-32756.test.tsx` + `editFormLockedByState.test.ts` 27/27. The app-shell full suite is not run locally (CI `Test UI` runs it). - New and extended pins together (plugin-form + app-shell utils): 35/35. </details> <details><summary>Shown red without the fix (scripts/ablation-replace.mjs, restored to HEAD each time, blob equal and git diff HEAD empty)</summary> - `MasterDetailForm.tsx` parent verdict forced `false`: rendered pin 4 failed / 2 passed (controls green). - `editFormLockedByState.ts` back to returning false for any subform: 2 failed / 18 passed (the two "is true" cases). - `deriveMasterDetail.ts` ownership mark removed: 3 failed (derived and authored column cases, and the rendered `'false'` override case). - `RecordDetailView.tsx` resolver dropped: 1 failed / 6 passed (the Edit-disabled case). </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 38 families, all run on `81f9ef2c`; 37 exit 0. `pnpm --dir ui exec vitest run scripts/` exit 1: SIGKILLed by the container's memory limit while the plugin-form suite ran beside it, so not measured on that run. Rerun alone under the verify lock with `--maxWorkers=2`: 172 files passed, 2 skipped / 5,159 tests, exit 0. - `dispatch-gates.mjs --ran`: "38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED" over the raw record (the exit 1 above as recorded). - `overlap-check.mjs` before every push: VERDICT clean exit 0. - `pnpm check:nul-bytes`: OK. - Full dogfood battery: n/a (no `!`, no `(narrowing)` arm). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (CI). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017xRBcSPkRxFWubkD5XfiDh --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcSPkRxFWubkD5XfiDh)_ <!-- signed: repo:objectstack#8 · sunhaolin · session_017xRBcSPkRxFWubkD5XfiDh --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ec087c2 commit fa345c4

12 files changed

Lines changed: 518 additions & 22 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(app-shell): the record page greys Edit on a hand-locked document whose inline lines are locked too
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/plugin-form': patch
3+
---
4+
5+
fix(plugin-form): a parent's whole-record hand lock locks its inline master-detail lines in the edit form
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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).

‎ui/packages/app-shell/src/utils/editFormLockedByState.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,54 @@ describe('editFormLockedByState reads the object-level uiReadonlyWhen (#37402)',
118118
expect(editFormLockedByState(order({}), { ...CONFIRMED, status: 'draft' })).toBe(false);
119119
});
120120
});
121+
122+
/**
123+
* #38249 — an object's whole-record hand lock locks its inline lines too, so
124+
* an object that places a child collection greys Edit when the lock holds and
125+
* no field of the child can open a line cell. Without the child's definition,
126+
* or when a child field owns a lock that could open, Edit stays live.
127+
*/
128+
describe('editFormLockedByState with inline lines under the object-level uiReadonlyWhen (#38249)', () => {
129+
const CONFIRMED = { id: 'o1', status: 'confirmed', amount: 1 };
130+
const order = {
131+
name: 'order',
132+
uiReadonlyWhen: "record.status == 'confirmed'",
133+
fields: { status: { type: 'text' }, amount: { type: 'number' } },
134+
groupSubforms: [{ childObject: 'order_line', relationshipField: 'order' }],
135+
};
136+
const line = (qty: Record<string, unknown> = {}) => ({
137+
name: 'order_line',
138+
fields: { order: { type: 'master_detail', reference: 'order' }, qty: { type: 'number', ...qty } },
139+
});
140+
const defs = (child: unknown) => (name: string) => (name === 'order_line' ? (child as any) : undefined);
141+
142+
it('is true when the object lock holds and no child field can open a line cell', () => {
143+
expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line()))).toBe(true);
144+
});
145+
146+
it("is false when a child field keeps its cell editable with its own uiReadonlyWhen 'false'", () => {
147+
expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonlyWhen: 'false' })))).toBe(false);
148+
});
149+
150+
it('is true when the child field owns only a static lock', () => {
151+
expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonly: true })))).toBe(true);
152+
});
153+
154+
it('is false while the object predicate does not hold', () => {
155+
expect(editFormLockedByState(order, { ...CONFIRMED, status: 'draft' }, undefined, defs(line()))).toBe(false);
156+
});
157+
158+
it('is false when the header is locked only field by field: that leaves the lines open', () => {
159+
const { uiReadonlyWhen: _drop, ...plain } = order;
160+
const byField = {
161+
...plain,
162+
fields: { status: { type: 'text', readonlyWhen: "record.status == 'confirmed'" }, amount: { type: 'number', readonlyWhen: "record.status == 'confirmed'" } },
163+
};
164+
expect(editFormLockedByState(byField, CONFIRMED, undefined, defs(line()))).toBe(false);
165+
});
166+
167+
it("fails open without the child object's definition", () => {
168+
expect(editFormLockedByState(order, CONFIRMED)).toBe(false);
169+
expect(editFormLockedByState(order, CONFIRMED, undefined, () => undefined)).toBe(false);
170+
});
171+
});

‎ui/packages/app-shell/src/utils/editFormLockedByState.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,20 @@
2929
* so a writable field anywhere keeps Edit live;
3030
* - the object's field groups place no inline child collection
3131
* (`recordFormSubforms`, objectstack-ai/objectstack#36425), whose rows the
32-
* form still edits whatever the header fields say.
32+
* form still edits whatever the header fields say — unless the object's
33+
* whole-record hand lock (`uiReadonlyWhen`) holds over the record, which
34+
* locks those rows too (objectstack#38249), and no field of any placed
35+
* child object owns a hand lock that could open a line cell
36+
* (`childLinesOpenUnderParentHandLock`). That needs each child object's
37+
* definition, from `childObjectDef`; without it, or for a child it cannot
38+
* answer, Edit stays live.
3339
*
3440
* A predicate that faults resolves to its fail-open verdict (writable), as in
3541
* the form, so a broken rule never greys Edit.
3642
*/
3743

38-
import { effectiveUiReadonlyWhen, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core';
39-
import { filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core';
44+
import { effectiveUiReadonlyWhen, fieldReadOnlyByHand, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core';
45+
import { childLinesOpenUnderParentHandLock, filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core';
4046
import type { FormField } from '@object-ui/types';
4147
import { recordFormSubforms, type ObjectDefinitionForRecordForm } from './recordFormNavigation.js';
4248

@@ -66,9 +72,11 @@ export function editFormLockedByState(
6672
objectDef: EditFormLockObject | null | undefined,
6773
record: Record<string, unknown> | null | undefined,
6874
scope?: Record<string, unknown>,
75+
childObjectDef?: (name: string) => { fields?: Record<string, any> } | null | undefined,
6976
): boolean {
7077
if (!objectDef || !record) return false;
71-
if (recordFormSubforms(objectDef)) return false;
78+
const subforms = recordFormSubforms(objectDef);
79+
if (subforms && !childObjectDef) return false;
7280

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

98+
if (subforms) {
99+
// objectstack#38249 — the lines are locked only by the object's own
100+
// whole-record hand lock (a field-level lock on the header leaves them
101+
// open), judged by the one hand-lock verdict over the stored row.
102+
const objectLockHolds = fieldReadOnlyByHand({}, ruleRecord, {
103+
object: objectDef,
104+
previous: ruleRecord,
105+
scope,
106+
fieldContext: 'object uiReadonlyWhen',
107+
});
108+
if (!objectLockHolds) return false;
109+
for (const subform of subforms) {
110+
const childObject = typeof subform?.childObject === 'string' ? subform.childObject : undefined;
111+
const child = childObject ? childObjectDef?.(childObject) : undefined;
112+
if (!child || childLinesOpenUnderParentHandLock(child)) return false;
113+
}
114+
}
115+
90116
let shown = 0;
91117
let lockedByRule = 0;
92118
for (const { name, def } of entries) {

‎ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,8 @@ function stateLockBadge(): HTMLElement | null {
133133
}
134134

135135
/** Mount the console record page and wait for the record read and the header. */
136-
async function mountRecordPage(record: Record<string, unknown>, fields: Record<string, unknown>) {
137-
const objects = [objectDef(fields)];
136+
async function mountRecordPage(record: Record<string, unknown>, fields: Record<string, unknown>, served?: any[]) {
137+
const objects = served ?? [objectDef(fields)];
138138
const dataSource = makeDataSource(record);
139139
render(
140140
<MemoryRouter initialEntries={[`/apps/fin/${OBJECT_NAME}/${RECORD_ID}`]}>
@@ -245,3 +245,48 @@ describe('console record header — a record whose state locks every edit-form f
245245
expect(stateLockBadge()).toBeNull();
246246
});
247247
});
248+
249+
/**
250+
* objectstack#38249 — an object whose whole-record hand lock (`uiReadonlyWhen`)
251+
* holds locks its inline lines in the edit form too, so the record page greys
252+
* Edit even though its field groups place a child collection — unless a child
253+
* field owns a hand lock that could open a line cell.
254+
*/
255+
describe('console record header — a hand-locked document with inline lines (objectstack#38249)', () => {
256+
const LINE_OBJECT = 'ebqu_claim_line';
257+
const parent = {
258+
...objectDef({
259+
id: { type: 'text', label: 'Id' },
260+
name: { type: 'text', label: 'Title' },
261+
status: { type: 'text', label: 'Status' },
262+
}),
263+
uiReadonlyWhen: "record.status == 'approved'",
264+
groupSubforms: [{ childObject: LINE_OBJECT, relationshipField: 'claim' }],
265+
};
266+
const line = (amount: Record<string, unknown> = {}) => ({
267+
name: LINE_OBJECT,
268+
label: 'Claim line',
269+
fields: {
270+
claim: { type: 'master_detail', label: 'Claim', reference: OBJECT_NAME },
271+
amount: { type: 'currency', label: 'Amount', ...amount },
272+
},
273+
});
274+
275+
it('draws Edit disabled when the object lock holds and no line cell can open', async () => {
276+
await mountRecordPage(APPROVED, {}, [parent, line()]);
277+
await waitFor(() => expect(headerEditButton()).toBeDisabled());
278+
expect(stateLockBadge()).toBeInTheDocument();
279+
});
280+
281+
it("CONTROL: a child field whose own uiReadonlyWhen is 'false' keeps Edit enabled", async () => {
282+
await mountRecordPage(APPROVED, {}, [parent, line({ uiReadonlyWhen: 'false' })]);
283+
expect(headerEditButton()).not.toBeDisabled();
284+
expect(stateLockBadge()).toBeNull();
285+
});
286+
287+
it('CONTROL: a state the object lock does not hold keeps Edit enabled', async () => {
288+
await mountRecordPage(DRAFT, {}, [parent, line()]);
289+
expect(headerEditButton()).not.toBeDisabled();
290+
expect(stateLockBadge()).toBeNull();
291+
});
292+
});

‎ui/packages/app-shell/src/views/RecordDetailView.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3108,8 +3108,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
31083108
// goes off exactly when the form would open with no control.
31093109
const predicateScope = usePredicateScope();
31103110
const editLockedByState = useMemo(
3111-
() => editFormLockedByState(objectDef as any, pageRecord as Record<string, unknown> | null | undefined, predicateScope),
3112-
[objectDef, pageRecord, predicateScope],
3111+
() => editFormLockedByState(
3112+
objectDef as any,
3113+
pageRecord as Record<string, unknown> | null | undefined,
3114+
predicateScope,
3115+
// The placed child objects' definitions: a parent's whole-record hand
3116+
// lock locks its inline lines too, unless a child field owns a lock
3117+
// that could open one (objectstack#38249).
3118+
(name) => objects.find((o: any) => o?.name === name),
3119+
),
3120+
[objectDef, pageRecord, predicateScope, objects],
31133121
);
31143122

31153123
// ── Audit history fetch ────────────────────────────────────────────
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#38249 — a parent's whole-record hand lock (object-level
11+
* `uiReadonlyWhen`) covers its inline master-detail lines in the edit form.
12+
*
13+
* While the predicate holds over the parent record, a person adds,
14+
* duplicates, removes, reorders and edits no line by hand. A child field that
15+
* declares a hand lock of its own (`uiReadonly: true` or a `uiReadonlyWhen`)
16+
* is judged by that declaration instead, the same override the object level
17+
* reads (`effectiveUiReadonlyWhen`): `uiReadonlyWhen: 'false'` keeps that one
18+
* cell editable on a locked document. A create is not judged.
19+
*
20+
* Measured through the REAL `MasterDetailForm` and `GridField`.
21+
*/
22+
import { describe, it, expect, vi, afterEach } from 'vitest';
23+
import { render, screen, waitFor, cleanup } from '@testing-library/react';
24+
import React from 'react';
25+
26+
import { registerAllFields } from '@object-ui/fields';
27+
import { MasterDetailForm } from './MasterDetailForm';
28+
29+
registerAllFields();
30+
afterEach(cleanup);
31+
32+
const PARENT = 'sales_order';
33+
const CHILD = 'sales_order_line';
34+
const LINE = { id: 'L1', order: 'SO1', qty: 3, note: 'gift wrap' };
35+
36+
const PARENT_SCHEMA = {
37+
name: PARENT,
38+
uiReadonlyWhen: "record.status == 'confirmed'",
39+
fields: { ref: { type: 'text', label: 'Ref' }, status: { type: 'text', label: 'Status' } },
40+
};
41+
42+
const childSchema = (note: Record<string, unknown>) => ({
43+
name: CHILD,
44+
fields: {
45+
order: { type: 'master_detail', reference: PARENT, label: 'Order' },
46+
qty: { type: 'number', label: 'Qty' },
47+
note: { type: 'text', label: 'Note', ...note },
48+
},
49+
});
50+
51+
function makeDS(status: string, note: Record<string, unknown> = {}) {
52+
return {
53+
getObjectSchema: vi.fn(async (obj: string) =>
54+
obj === PARENT ? PARENT_SCHEMA : obj === CHILD ? childSchema(note) : null,
55+
),
56+
findOne: vi.fn().mockResolvedValue({ id: 'SO1', ref: 'SO-1', status }),
57+
find: vi.fn().mockResolvedValue({ data: [LINE] }),
58+
create: vi.fn(),
59+
update: vi.fn(),
60+
delete: vi.fn(),
61+
batchTransaction: vi.fn().mockResolvedValue({ results: [] }),
62+
};
63+
}
64+
65+
/** Untyped authored columns: the child schema is read and each column hydrated from its field. */
66+
const DERIVED = [{ childObject: CHILD, relationshipField: 'order', columns: [{ name: 'qty', label: 'Qty' }, { name: 'note', label: 'Note' }] }];
67+
/** A fully configured entry: typed columns and the FK, so no child schema is read. */
68+
const CONFIGURED = [{ childObject: CHILD, relationshipField: 'order', columns: [{ name: 'qty', label: 'Qty', type: 'number' }] }];
69+
70+
function mount(ds: ReturnType<typeof makeDS>, details = DERIVED, mode: 'edit' | 'create' = 'edit') {
71+
return render(
72+
<MasterDetailForm
73+
schema={{
74+
objectName: PARENT,
75+
mode,
76+
...(mode === 'edit' ? { recordId: 'SO1' } : {}),
77+
fields: ['ref', 'status'],
78+
details,
79+
} as any}
80+
dataSource={ds as any}
81+
/>,
82+
);
83+
}
84+
85+
const offered = () => ({
86+
add: screen.queryByTestId('line-items-add') !== null,
87+
duplicate: screen.queryAllByRole('button', { name: 'Duplicate row' }).length > 0,
88+
remove: screen.queryAllByRole('button', { name: 'Remove row' }).length > 0,
89+
reorder: screen.queryByTestId('line-items-drag-0') !== null,
90+
});
91+
92+
/** Wait until the stored line is drawn and the header record has landed. */
93+
async function lineLoaded(ds: ReturnType<typeof makeDS>) {
94+
await waitFor(() => expect(screen.getByDisplayValue('3')).toBeTruthy());
95+
await waitFor(() => expect(ds.findOne).toHaveBeenCalled());
96+
// A locked header field draws its read face, an open one its input.
97+
await waitFor(() => expect(screen.queryByDisplayValue('SO-1') ?? screen.queryByText('SO-1')).toBeTruthy());
98+
}
99+
100+
const qtyCell = () => screen.getByDisplayValue('3') as HTMLInputElement;
101+
const noteCell = () => screen.getByDisplayValue('gift wrap') as HTMLInputElement;
102+
103+
describe('MasterDetailForm: the parent object\'s uiReadonlyWhen hand-locks its inline lines (objectstack#38249)', () => {
104+
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 () => {
105+
const ds = makeDS('confirmed');
106+
mount(ds);
107+
await lineLoaded(ds);
108+
await waitFor(() => expect(qtyCell().disabled).toBe(true));
109+
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
110+
});
111+
112+
it("a child field whose own uiReadonlyWhen is 'false' stays editable on a locked parent; its siblings stay locked", async () => {
113+
const ds = makeDS('confirmed', { uiReadonlyWhen: 'false' });
114+
mount(ds);
115+
await lineLoaded(ds);
116+
await waitFor(() => expect(qtyCell().disabled).toBe(true));
117+
expect(noteCell().disabled).toBe(false);
118+
expect(offered().add).toBe(false);
119+
});
120+
121+
it('a child field with uiReadonly: true stays locked on a locked parent (its own declaration locks it)', async () => {
122+
const ds = makeDS('confirmed', { uiReadonly: true });
123+
mount(ds);
124+
await lineLoaded(ds);
125+
await waitFor(() => expect(qtyCell().disabled).toBe(true));
126+
expect(noteCell().disabled).toBe(true);
127+
});
128+
129+
it('a fully configured entry (no child schema read) locks every line cell on a locked parent', async () => {
130+
const ds = makeDS('confirmed');
131+
mount(ds, CONFIGURED);
132+
await lineLoaded(ds);
133+
await waitFor(() => expect(qtyCell().disabled).toBe(true));
134+
expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false });
135+
});
136+
137+
it('CONTROL: while the parent predicate does not hold, the lines are edited as before', async () => {
138+
const ds = makeDS('draft');
139+
mount(ds);
140+
await lineLoaded(ds);
141+
expect(qtyCell().disabled).toBe(false);
142+
expect(noteCell().disabled).toBe(false);
143+
expect(offered()).toEqual({ add: true, duplicate: true, remove: true, reorder: true });
144+
});
145+
146+
it('CONTROL: a create form is not judged — lines are added on an object that carries the lock', async () => {
147+
const ds = makeDS('confirmed');
148+
mount(ds, DERIVED, 'create');
149+
await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy());
150+
});
151+
});

0 commit comments

Comments
 (0)