Skip to content

Commit 571b494

Browse files
fix(console): the record page's edit-state save writes a closing header after its lines (ADR-0162 D4) (#39007)
Part of #38997 Clause-②: no Metadata-protocol: none ## 维护者速读 - 控制台记录页进入编辑状态后,同时改明细行并把单据改成关闭状态(如“已付款”)的一次保存,会先写明细、最后写单据头,整单保存成功;以前这样的保存会被整单拒绝。不关单的保存与今天一样。 - 属于“记录关闭态锁”这一组工作,替记录页编辑状态补上主从表单已有的“关单写在最后”的顺序。 - 出错时,编辑状态下改明细并关单的保存可能仍被整单拒绝,或不关单的保存顺序变了;改动只在控制台,可直接撤回。 - 无 ## What changes Item 1 of the card (the edit-state save order). Item 2, the full-record edit dialog's closed lock, waits on the record-page lock work of #37773 (branch `claude/issue-37773-record-page-lock`), which adds the data-layer lock to the record approvals hook; this PR adds no lock read of its own and touches no file of that work. - **Batch builder** (`ui/packages/plugin-form/src/RecordBodyTableEditor.tsx`, `buildRecordEditBatch`): takes the object's `closedStates` as a new optional fifth argument, the `MasterDetailEditOptions` that `buildMasterDetailEditBatch` takes. When the field draft sets a value the object lists in `closedStates` (judged by the shared `closesRecord`), the record's update is written after every line write and owned as `{ kind: 'parent' }` at the end. Otherwise the record's update stays op 0. Callers that pass nothing get the old order. ADR-0162 D4. - **Edit-state controller** (`ui/packages/app-shell/src/views/recordEditState.tsx`): reads `closedStates` off the object definition the page's `RecordContextProvider` already carries (no request), hands it to the builder, and drops an empty draft's record update by its owner instead of slicing index 0. - Changeset: `.changeset/38997-edit-state-closing-order.md` (`@object-ui/plugin-form` and `@object-ui/app-shell`, patch). ## Tests - `RecordBodyTableEditor.recordEditBatch-35599.test.ts`, new describe: a closing draft puts the record update last with its owner last, and a refusal is still placed on the record field and on the line; CONTROL: a non-closing value, a non-state field, and no `closedStates` keep the record first. - `RecordDetailView.harness.test.tsx`, `recordEditState-35599` block: two new cases drive the real record page. Edit lines, pick the closing status, Save: the one batch ends with the record update. CONTROL: the same edits with a status the object does not close on keep the record first. <details><summary>Ablations (each restored, blob equal to HEAD)</summary> - Controller: passing `{}` instead of `{ closedStates }` turns the closing harness case red (record update not last); its control and the other 9 cases stay green. - Builder: forcing `closing = false` turns the closing unit case red; the other 9 in the file stay green. </details> ## Acceptance notes - Request count: unchanged. The controller reads the object definition the page already holds; the record page's one-request record open is not touched. - Item 2 (the edit dialog opens locked with the closed wording on a closed record) is not in this PR. It builds on the record-page lock work of #37773, once that lands. - `closesRecord` judges only the edited keys of the draft, as the master-detail form does: a save that edits lines on a record that is already closed is still refused by the server (that is the lock the dialog and the page should show, item 2). ## Verification Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts` (from the repo root): 10 passed, including the closing describe. Read first: `recordEditState.tsx` (the owner-based drop of the record op), then `buildRecordEditBatch`. <details><summary>Local readings, head 79b7870</summary> - plugin-form full suite: 255 files, 2,842 passed, 1 skipped. - app-shell: `RecordDetailView.harness.test.tsx` and `recordEditState.helpers-35599.test.ts`: 98 passed. - `type-check`: plugin-form exit 0, app-shell exit 0. eslint on the four touched source and test files: 0 errors. - `dispatch-gates --ran` (taken at 23ace6e): 39 derived, 39 run, 0 NOT-MEASURED. The set is unchanged at 79b7870; the ratchet families (type-check coverage and debt, test-source-alias, cross-package-test-inputs, nul-bytes, undeclared-dep-imports) re-run there: all exit 0. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3c3a154 commit 571b494

5 files changed

Lines changed: 163 additions & 13 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/plugin-form': patch
3+
'@object-ui/app-shell': patch
4+
---
5+
6+
fix(console): the record page's edit-state save writes a closing header after its lines
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
On a record page in its edit state, a Save that edits the body-table lines and also sets the record to a state its object lists in `closedStates` now writes every line first and the record's update last, in the same one batch. Before, the record's update went first, the line writes then met a closed record, and the whole save was refused. A Save that does not close the record keeps the record's update first, as before. This is the order the master-detail form already uses (ADR-0162 D4).
12+
13+
`buildRecordEditBatch` takes the object's `closedStates` as a new optional fifth argument (`{ closedStates }`), the same option `buildMasterDetailEditBatch` takes. Callers that pass nothing get the old order. Find the record's operation by its owner (`{ kind: 'parent' }`), not by index 0: a closing update is the last operation.

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

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,7 +2906,8 @@ describe('RecordDetailView.recordEditState-35599', () => {
29062906
const RECORD_ID = 'q-1';
29072907
const fk = { type: 'master_detail', reference: PARENT, label: 'Quote' };
29082908

2909-
const objectsWith = ({ lineEnable }: { lineEnable?: Record<string, unknown> } = {}) => [
2909+
/** `closedStates`: the quote declares a `status` select and closes on the values listed (ADR-0162 D1). */
2910+
const objectsWith = ({ lineEnable, closedStates }: { lineEnable?: Record<string, unknown>; closedStates?: Record<string, string[]> } = {}) => [
29102911
{
29112912
name: PARENT,
29122913
label: 'Quote',
@@ -2915,7 +2916,22 @@ describe('RecordDetailView.recordEditState-35599', () => {
29152916
id: { type: 'text', label: 'Id', group: 'basic' },
29162917
name: { type: 'text', label: 'Name', group: 'basic' },
29172918
summary: { type: 'text', label: 'Summary', group: 'basic' },
2919+
...(closedStates
2920+
? {
2921+
status: {
2922+
type: 'select',
2923+
label: 'Status',
2924+
group: 'basic',
2925+
options: [
2926+
{ value: 'draft', label: 'Draft' },
2927+
{ value: 'sent', label: 'Sent' },
2928+
{ value: 'accepted', label: 'Accepted' },
2929+
],
2930+
},
2931+
}
2932+
: {}),
29182933
},
2934+
...(closedStates ? { closedStates } : {}),
29192935
// objectstack#35889: a master-detail child is a body table only where a
29202936
// field group of the parent names it.
29212937
fieldGroups: [
@@ -2966,7 +2982,7 @@ describe('RecordDetailView.recordEditState-35599', () => {
29662982
return { data, total: data.length };
29672983
}),
29682984
create: vi.fn(async (_o: string, row: unknown) => row),
2969-
findOne: vi.fn(async (_o: string, recordId: string) => ({ id: recordId, name: `Quote ${recordId}`, summary: 'First' })),
2985+
findOne: vi.fn(async (_o: string, recordId: string) => ({ id: recordId, name: `Quote ${recordId}`, summary: 'First', status: 'draft' })),
29702986
update: vi.fn(async () => ({})),
29712987
delete: vi.fn(async () => ({})),
29722988
getObjectSchema: vi.fn(async (o: string) => objects.find((d) => d.name === o) ?? null),
@@ -3170,6 +3186,50 @@ describe('RecordDetailView.recordEditState-35599', () => {
31703186
expect(editor(view.container, 'showcase_line.quote')).toBeNull();
31713187
});
31723188

3189+
/** Pick `label` on the record's Status select, in the details column (not a body table's). */
3190+
async function pickStatus(container: HTMLElement, label: string) {
3191+
const details = container.querySelector('[data-record-column="details"]') as HTMLElement;
3192+
let trigger: HTMLElement | undefined;
3193+
await waitFor(() => {
3194+
trigger = (Array.from(details.querySelectorAll('[role="combobox"]')) as HTMLElement[])
3195+
.find((el) => !el.closest('[data-body-table-editor]'));
3196+
expect(trigger).toBeDefined();
3197+
}, { timeout: 5000 });
3198+
fireEvent.keyDown(trigger!, { key: 'ArrowDown' });
3199+
fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: label }));
3200+
}
3201+
3202+
it('ADR-0162 D4 (objectstack#38997): a Save that sets a closing state writes every line first and the record last', async () => {
3203+
const view = renderPage(objectsWith({ closedStates: { status: ['accepted'] } }));
3204+
await enterEditState(view);
3205+
editEverything(view.container);
3206+
await pickStatus(view.container, 'Accepted');
3207+
await act(async () => { fireEvent.click(headerButton('Save')!); });
3208+
await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 });
3209+
const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array<Record<string, any>>;
3210+
expect(ops).toHaveLength(5);
3211+
expect(ops[ops.length - 1]).toEqual({ object: PARENT, action: 'update', id: RECORD_ID, data: { summary: 'Second', status: 'accepted' } });
3212+
expect(ops.slice(0, -1).map((o) => [o.object, o.action, o.id ?? null])).toEqual(expect.arrayContaining([
3213+
['showcase_line', 'create', null],
3214+
['showcase_line', 'update', 'l1'],
3215+
['showcase_line', 'delete', 'l2'],
3216+
['showcase_task', 'update', 't1'],
3217+
]));
3218+
await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 });
3219+
});
3220+
3221+
it('CONTROL — on the same object, a Save that sets a state it does not close on keeps the record first', async () => {
3222+
const view = renderPage(objectsWith({ closedStates: { status: ['accepted'] } }));
3223+
await enterEditState(view);
3224+
editEverything(view.container);
3225+
await pickStatus(view.container, 'Sent');
3226+
await act(async () => { fireEvent.click(headerButton('Save')!); });
3227+
await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 });
3228+
const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array<Record<string, any>>;
3229+
expect(ops).toHaveLength(5);
3230+
expect(ops[0]).toEqual({ object: PARENT, action: 'update', id: RECORD_ID, data: { summary: 'Second', status: 'sent' } });
3231+
});
3232+
31733233
it('a refused batch keeps every edit and places the reason on its line; Cancel then restores', async () => {
31743234
const view = renderPage(objectsWith());
31753235
await enterEditState(view);

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

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@
2929
* tables at all (the card's item 5, see there).
3030
* - {@link withDetailWritesWithheld} — ruling A's client half: a locked
3131
* record's master-detail children draw no New / Edit / Delete.
32+
*
33+
* [ADR-0162 D4] A Save whose field draft puts the record into one of its
34+
* object's `closedStates` writes the record's update after every line write
35+
* (`buildRecordEditBatch`), so the lines never meet a closed record. The
36+
* declaration is read off the object definition the page hands its
37+
* `RecordContextProvider`: no request.
3238
*/
3339

3440
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -53,7 +59,7 @@ import {
5359
AlertDialogTitle,
5460
toast,
5561
} from '@object-ui/components';
56-
import { useInlineEdit, type RelatedRecordActionsValue } from '@object-ui/react';
62+
import { useInlineEdit, useRecordContext, type RelatedRecordActionsValue } from '@object-ui/react';
5763
import { RecordBodyTableEditorSlotContext, type RecordBodyTableEditorSlot } from '@object-ui/plugin-detail';
5864
import { canServeApiOperation } from '@objectstack/spec/data';
5965
import { useRegisterUnsavedEdits } from '../chrome/unsavedEdits.js';
@@ -209,6 +215,9 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
209215
children,
210216
}) => {
211217
const inline = useInlineEdit();
218+
// [ADR-0162 D4] The object's `closedStates`, as the page's own object
219+
// definition carries it (the `RecordContextProvider` above this controller).
220+
const closedStates = (useRecordContext()?.objectSchema as { closedStates?: unknown } | undefined)?.closedStates;
212221
const tablesRef = useRef(new Map<string, BodyTableEditHandle>());
213222
const [dirtyTables, setDirtyTables] = useState<ReadonlySet<string>>(() => new Set());
214223
const [saving, setSaving] = useState(false);
@@ -301,17 +310,20 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
301310
return snap ? [{ id: h.id, ...snap }] : [];
302311
})
303312
: [];
304-
const built = buildRecordEditBatch(objectName, String(recordId), draft, tables);
313+
const built = buildRecordEditBatch(objectName, String(recordId), draft, tables, { closedStates });
305314
// objectstack#35940 — the lines the batch skips untouched: never written,
306315
// and said so once the save has landed (or had nothing else to write).
307316
const skipped = tables.reduce((n, table) => n + table.rows.filter(isUntouchedNewRow).length, 0);
308317
const sayWhatWasSkipped = () => {
309318
if (skipped > 0) toast.info(untouchedNotSaved(skipped));
310319
};
311-
// An untouched record writes no update of its own: op 0 goes when the draft is empty.
320+
// An untouched record writes no update of its own: the record's op goes
321+
// when the draft is empty. Found by its owner, not by its index: a closing
322+
// update is the last op, not op 0.
312323
const hasDraft = Object.keys(draft).length > 0;
313-
const ops = hasDraft ? built.ops : built.ops.slice(1);
314-
const owners = hasDraft ? built.owners : built.owners.slice(1);
324+
const kept = built.owners.map((owner) => hasDraft || owner.kind !== 'parent');
325+
const ops = built.ops.filter((_, i) => kept[i]);
326+
const owners = built.owners.filter((_, i) => kept[i]);
315327
if (ops.length === 0) {
316328
await finish();
317329
sayWhatWasSkipped();
@@ -339,7 +351,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
339351
inline.setSaving(false);
340352
setSaving(false);
341353
}
342-
}, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish, untouchedNotSaved]);
354+
}, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, closedStates, finish, untouchedNotSaved]);
343355

344356
const cancel = useCallback(() => {
345357
inline?.cancel();

‎ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import { describe, it, expect } from 'vitest';
1616
import { UNTOUCHED_NEW_ROW } from '@object-ui/fields';
17+
import type { BatchTransactionOperation } from '@object-ui/types';
1718
import { attributeRecordEditRefusal, buildRecordEditBatch } from './RecordBodyTableEditor';
1819

1920
const childSchema = {
@@ -171,3 +172,52 @@ describe('attributeRecordEditRefusal — a refused batch is placed where it belo
171172
expect(r.message).toBe('This Order is locked while an approval is in progress');
172173
});
173174
});
175+
176+
describe('buildRecordEditBatch — a save that closes the record writes its lines first (ADR-0162 D4, objectstack#38997)', () => {
177+
// The object's declaration as its served definition carries it.
178+
const CLOSED_STATES = { status: ['paid', 'void'] };
179+
const order = (ops: ReadonlyArray<BatchTransactionOperation>) =>
180+
ops.map((o) => [o.object, o.action, o.id ?? null]);
181+
182+
it('a draft that sets a closing state puts the record update after every line write, owned as the record', () => {
183+
const { ops, owners } = buildRecordEditBatch('order', 'o1', { status: 'paid' }, [lines, notes], {
184+
closedStates: CLOSED_STATES,
185+
});
186+
expect(order(ops)).toEqual([
187+
['order_line', 'create', null],
188+
['order_line', 'update', 'l1'],
189+
['order_line', 'delete', 'l2'],
190+
['order_note', 'create', null],
191+
['order', 'update', 'o1'],
192+
]);
193+
expect(ops[4].data).toEqual({ status: 'paid' });
194+
expect(owners).toEqual([
195+
{ kind: 'row', table: 'order_line.order', row: 2 },
196+
{ kind: 'row', table: 'order_line.order', row: 0 },
197+
{ kind: 'row', table: 'order_line.order', row: -1 },
198+
{ kind: 'row', table: 'order_note.order', row: 0 },
199+
{ kind: 'parent' },
200+
]);
201+
// A refusal still lands where it belongs, whatever the record op's index.
202+
const refused = Object.assign(new Error('Validation failed'), {
203+
details: { error: 'Validation failed', fields: [{ field: 'status', message: 'Not allowed' }, { field: 'body', message: 'Required' }] },
204+
});
205+
const r = attributeRecordEditRefusal(refused, ops, owners);
206+
expect(r.fieldErrors).toEqual({ status: 'Not allowed' });
207+
expect(r.rowErrors).toEqual({ 'order_note.order': [{ row: 0, field: 'body', message: 'Required' }] });
208+
});
209+
210+
it('CONTROL — a draft that does not close keeps the record update first', () => {
211+
for (const [draft, options] of [
212+
[{ status: 'sent' }, { closedStates: CLOSED_STATES }],
213+
[{ name: 'paid' }, { closedStates: CLOSED_STATES }],
214+
[{ status: 'paid' }, {}],
215+
[{ status: 'paid' }, undefined],
216+
] as const) {
217+
const { ops, owners } = buildRecordEditBatch('order', 'o1', { ...draft }, [lines, notes], options);
218+
expect(order(ops)[0]).toEqual(['order', 'update', 'o1']);
219+
expect(owners[0]).toEqual({ kind: 'parent' });
220+
expect(ops).toHaveLength(5);
221+
}
222+
});
223+
});

‎ui/packages/plugin-form/src/RecordBodyTableEditor.tsx‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import {
4848
usePredicateScope,
4949
useRecordContext,
5050
} from '@object-ui/react';
51-
import { buildMasterDetailEditBatch, idOf, isBlankRow, type ChildSchema } from './masterDetailTx';
51+
import { buildMasterDetailEditBatch, closesRecord, idOf, isBlankRow, type ChildSchema, type MasterDetailEditOptions } from './masterDetailTx';
5252
import { applyColumnPermissions } from './fieldWriteGate';
5353
import { deriveDetail, lockColumnsByParentHandLock, parentHandLockHolds } from './deriveMasterDetail';
5454
import { schemaDefaultValues } from './schemaDefaults';
@@ -99,19 +99,30 @@ export const RecordEditSessionContext = React.createContext<RecordEditSession |
9999
export type RecordEditOpOwner = { kind: 'parent' } | { kind: 'row'; table: string; row: number };
100100

101101
/**
102-
* The ONE batch of a record-page save: the record's field draft (op 0, an
103-
* update of only the edited keys) and every body table's lines diffed into
102+
* The ONE batch of a record-page save: the record's field draft (an update of
103+
* only the edited keys) and every body table's lines diffed into
104104
* create / update / delete — `buildMasterDetailEditBatch`, table by table, so
105105
* each op can be traced back to the line it came from ({@link RecordEditOpOwner}).
106+
*
107+
* The record's update is op 0, unless the draft puts the record into one of
108+
* its object's closed states (`options.closedStates`, judged by `closesRecord`
109+
* as the master-detail form judges it): then it is the LAST op, after every
110+
* line write. [ADR-0162 D4] Inside the batch's one transaction each write meets
111+
* the record as stored when it arrives, so a line write after the closing
112+
* update would meet a closed record and the whole save would be refused. Read
113+
* the record's op by its owner (`{ kind: 'parent' }`), never by its index.
106114
*/
107115
export function buildRecordEditBatch(
108116
parentObject: string,
109117
parentId: string,
110118
parentDraft: Record<string, any>,
111119
tables: ReadonlyArray<{ id: string } & BodyTableSnapshot>,
120+
options: MasterDetailEditOptions = {},
112121
): { ops: BatchTransactionOperation[]; owners: RecordEditOpOwner[] } {
113-
const ops: BatchTransactionOperation[] = [buildMasterDetailEditBatch(parentObject, parentId, parentDraft, [])[0]];
114-
const owners: RecordEditOpOwner[] = [{ kind: 'parent' }];
122+
const parentOp: BatchTransactionOperation = buildMasterDetailEditBatch(parentObject, parentId, parentDraft, [])[0];
123+
const closing = closesRecord(parentDraft, options.closedStates);
124+
const ops: BatchTransactionOperation[] = closing ? [] : [parentOp];
125+
const owners: RecordEditOpOwner[] = closing ? [] : [{ kind: 'parent' }];
115126
for (const t of tables) {
116127
const tableOps = buildMasterDetailEditBatch(parentObject, parentId, {}, [t]).slice(1);
117128
// Rows are traced back by id (update / delete) or by position among the
@@ -132,6 +143,10 @@ export function buildRecordEditBatch(
132143
owners.push({ kind: 'row', table: t.id, row });
133144
}
134145
}
146+
if (closing) {
147+
ops.push(parentOp);
148+
owners.push({ kind: 'parent' });
149+
}
135150
return { ops, owners };
136151
}
137152

0 commit comments

Comments
 (0)