From ddcd812a240bc60f6e6ce84cb843ecf51a4273e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 22:32:03 +0000 Subject: [PATCH 1/4] fix(console): the record page's edit-state save writes a closing header after its lines (ADR-0162 D4) buildRecordEditBatch takes the object's closedStates and, when the field draft sets a closing value, puts the record's update after every line write, as buildMasterDetailEditBatch does. The edit-state controller reads closedStates off the object definition the page's RecordContextProvider carries, and drops an empty draft's update by its owner, not by index 0. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --- .../app-shell/src/views/recordEditState.tsx | 24 ++++++--- ...yTableEditor.recordEditBatch-35599.test.ts | 49 +++++++++++++++++++ .../plugin-form/src/RecordBodyTableEditor.tsx | 25 ++++++++-- 3 files changed, 87 insertions(+), 11 deletions(-) diff --git a/ui/packages/app-shell/src/views/recordEditState.tsx b/ui/packages/app-shell/src/views/recordEditState.tsx index 66011b45294..38f52744c37 100644 --- a/ui/packages/app-shell/src/views/recordEditState.tsx +++ b/ui/packages/app-shell/src/views/recordEditState.tsx @@ -29,6 +29,12 @@ * tables at all (the card's item 5, see there). * - {@link withDetailWritesWithheld} — ruling A's client half: a locked * record's master-detail children draw no New / Edit / Delete. + * + * [ADR-0162 D4] A Save whose field draft puts the record into one of its + * object's `closedStates` writes the record's update after every line write + * (`buildRecordEditBatch`), so the lines never meet a closed record. The + * declaration is read off the object definition the page hands its + * `RecordContextProvider`: no request. */ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; @@ -53,7 +59,7 @@ import { AlertDialogTitle, toast, } from '@object-ui/components'; -import { useInlineEdit, type RelatedRecordActionsValue } from '@object-ui/react'; +import { useInlineEdit, useRecordContext, type RelatedRecordActionsValue } from '@object-ui/react'; import { RecordBodyTableEditorSlotContext, type RecordBodyTableEditorSlot } from '@object-ui/plugin-detail'; import { canServeApiOperation } from '@objectstack/spec/data'; import { useRegisterUnsavedEdits } from '../chrome/unsavedEdits.js'; @@ -209,6 +215,9 @@ export const RecordEditStateController: React.FC children, }) => { const inline = useInlineEdit(); + // [ADR-0162 D4] The object's `closedStates`, as the page's own object + // definition carries it (the `RecordContextProvider` above this controller). + const closedStates = (useRecordContext()?.objectSchema as { closedStates?: unknown } | undefined)?.closedStates; const tablesRef = useRef(new Map()); const [dirtyTables, setDirtyTables] = useState>(() => new Set()); const [saving, setSaving] = useState(false); @@ -301,17 +310,20 @@ export const RecordEditStateController: React.FC return snap ? [{ id: h.id, ...snap }] : []; }) : []; - const built = buildRecordEditBatch(objectName, String(recordId), draft, tables); + const built = buildRecordEditBatch(objectName, String(recordId), draft, tables, { closedStates }); // objectstack#35940 — the lines the batch skips untouched: never written, // and said so once the save has landed (or had nothing else to write). const skipped = tables.reduce((n, table) => n + table.rows.filter(isUntouchedNewRow).length, 0); const sayWhatWasSkipped = () => { if (skipped > 0) toast.info(untouchedNotSaved(skipped)); }; - // An untouched record writes no update of its own: op 0 goes when the draft is empty. + // An untouched record writes no update of its own: the record's op goes + // when the draft is empty. Found by its owner, not by its index: a closing + // update is the last op, not op 0. const hasDraft = Object.keys(draft).length > 0; - const ops = hasDraft ? built.ops : built.ops.slice(1); - const owners = hasDraft ? built.owners : built.owners.slice(1); + const kept = built.owners.map((owner) => hasDraft || owner.kind !== 'parent'); + const ops = built.ops.filter((_, i) => kept[i]); + const owners = built.owners.filter((_, i) => kept[i]); if (ops.length === 0) { await finish(); sayWhatWasSkipped(); @@ -339,7 +351,7 @@ export const RecordEditStateController: React.FC inline.setSaving(false); setSaving(false); } - }, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish, untouchedNotSaved]); + }, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, closedStates, finish, untouchedNotSaved]); const cancel = useCallback(() => { inline?.cancel(); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts index 5c7144bf554..6ff41b7eefc 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts @@ -171,3 +171,52 @@ describe('attributeRecordEditRefusal — a refused batch is placed where it belo expect(r.message).toBe('This Order is locked while an approval is in progress'); }); }); + +describe('buildRecordEditBatch — a save that closes the record writes its lines first (ADR-0162 D4, objectstack#38997)', () => { + // The object's declaration as its served definition carries it. + const CLOSED_STATES = { status: ['paid', 'void'] }; + const order = (ops: ReadonlyArray<{ object: string; action: string; id?: unknown }>) => + ops.map((o) => [o.object, o.action, o.id ?? null]); + + it('a draft that sets a closing state puts the record update after every line write, owned as the record', () => { + const { ops, owners } = buildRecordEditBatch('order', 'o1', { status: 'paid' }, [lines, notes], { + closedStates: CLOSED_STATES, + }); + expect(order(ops)).toEqual([ + ['order_line', 'create', null], + ['order_line', 'update', 'l1'], + ['order_line', 'delete', 'l2'], + ['order_note', 'create', null], + ['order', 'update', 'o1'], + ]); + expect(ops[4].data).toEqual({ status: 'paid' }); + expect(owners).toEqual([ + { kind: 'row', table: 'order_line.order', row: 2 }, + { kind: 'row', table: 'order_line.order', row: 0 }, + { kind: 'row', table: 'order_line.order', row: -1 }, + { kind: 'row', table: 'order_note.order', row: 0 }, + { kind: 'parent' }, + ]); + // A refusal still lands where it belongs, whatever the record op's index. + const refused = Object.assign(new Error('Validation failed'), { + details: { error: 'Validation failed', fields: [{ field: 'status', message: 'Not allowed' }, { field: 'body', message: 'Required' }] }, + }); + const r = attributeRecordEditRefusal(refused, ops, owners); + expect(r.fieldErrors).toEqual({ status: 'Not allowed' }); + expect(r.rowErrors).toEqual({ 'order_note.order': [{ row: 0, field: 'body', message: 'Required' }] }); + }); + + it('CONTROL — a draft that does not close keeps the record update first', () => { + for (const [draft, options] of [ + [{ status: 'sent' }, { closedStates: CLOSED_STATES }], + [{ name: 'paid' }, { closedStates: CLOSED_STATES }], + [{ status: 'paid' }, {}], + [{ status: 'paid' }, undefined], + ] as const) { + const { ops, owners } = buildRecordEditBatch('order', 'o1', { ...draft }, [lines, notes], options); + expect(order(ops)[0]).toEqual(['order', 'update', 'o1']); + expect(owners[0]).toEqual({ kind: 'parent' }); + expect(ops).toHaveLength(5); + } + }); +}); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index d5346b79940..910f2bc4a41 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -48,7 +48,7 @@ import { usePredicateScope, useRecordContext, } from '@object-ui/react'; -import { buildMasterDetailEditBatch, idOf, isBlankRow, type ChildSchema } from './masterDetailTx'; +import { buildMasterDetailEditBatch, closesRecord, idOf, isBlankRow, type ChildSchema, type MasterDetailEditOptions } from './masterDetailTx'; import { applyColumnPermissions } from './fieldWriteGate'; import { deriveDetail, lockColumnsByParentHandLock, parentHandLockHolds } from './deriveMasterDetail'; import { schemaDefaultValues } from './schemaDefaults'; @@ -99,19 +99,30 @@ export const RecordEditSessionContext = React.createContext, tables: ReadonlyArray<{ id: string } & BodyTableSnapshot>, + options: MasterDetailEditOptions = {}, ): { ops: BatchTransactionOperation[]; owners: RecordEditOpOwner[] } { - const ops: BatchTransactionOperation[] = [buildMasterDetailEditBatch(parentObject, parentId, parentDraft, [])[0]]; - const owners: RecordEditOpOwner[] = [{ kind: 'parent' }]; + const parentOp: BatchTransactionOperation = buildMasterDetailEditBatch(parentObject, parentId, parentDraft, [])[0]; + const closing = closesRecord(parentDraft, options.closedStates); + const ops: BatchTransactionOperation[] = closing ? [] : [parentOp]; + const owners: RecordEditOpOwner[] = closing ? [] : [{ kind: 'parent' }]; for (const t of tables) { const tableOps = buildMasterDetailEditBatch(parentObject, parentId, {}, [t]).slice(1); // Rows are traced back by id (update / delete) or by position among the @@ -132,6 +143,10 @@ export function buildRecordEditBatch( owners.push({ kind: 'row', table: t.id, row }); } } + if (closing) { + ops.push(parentOp); + owners.push({ kind: 'parent' }); + } return { ops, owners }; } From 3855d73718c861730865d1d13b5997810d38d4cf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 22:33:22 +0000 Subject: [PATCH 2/4] test(console): drive the edit-state save of a closing record through the record page A Save that picks a closing status and edits the lines sends the lines first and the record last; the control picks a status the object does not close on and keeps the record first. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --- .../views/RecordDetailView.harness.test.tsx | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 1604a941ff4..fff71b50151 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -2906,7 +2906,8 @@ describe('RecordDetailView.recordEditState-35599', () => { const RECORD_ID = 'q-1'; const fk = { type: 'master_detail', reference: PARENT, label: 'Quote' }; - const objectsWith = ({ lineEnable }: { lineEnable?: Record } = {}) => [ + /** `closedStates`: the quote declares a `status` select and closes on the values listed (ADR-0162 D1). */ + const objectsWith = ({ lineEnable, closedStates }: { lineEnable?: Record; closedStates?: Record } = {}) => [ { name: PARENT, label: 'Quote', @@ -2915,7 +2916,22 @@ describe('RecordDetailView.recordEditState-35599', () => { id: { type: 'text', label: 'Id', group: 'basic' }, name: { type: 'text', label: 'Name', group: 'basic' }, summary: { type: 'text', label: 'Summary', group: 'basic' }, + ...(closedStates + ? { + status: { + type: 'select', + label: 'Status', + group: 'basic', + options: [ + { value: 'draft', label: 'Draft' }, + { value: 'sent', label: 'Sent' }, + { value: 'accepted', label: 'Accepted' }, + ], + }, + } + : {}), }, + ...(closedStates ? { closedStates } : {}), // objectstack#35889: a master-detail child is a body table only where a // field group of the parent names it. fieldGroups: [ @@ -2966,7 +2982,7 @@ describe('RecordDetailView.recordEditState-35599', () => { return { data, total: data.length }; }), create: vi.fn(async (_o: string, row: unknown) => row), - findOne: vi.fn(async (_o: string, recordId: string) => ({ id: recordId, name: `Quote ${recordId}`, summary: 'First' })), + findOne: vi.fn(async (_o: string, recordId: string) => ({ id: recordId, name: `Quote ${recordId}`, summary: 'First', status: 'draft' })), update: vi.fn(async () => ({})), delete: vi.fn(async () => ({})), getObjectSchema: vi.fn(async (o: string) => objects.find((d) => d.name === o) ?? null), @@ -3170,6 +3186,50 @@ describe('RecordDetailView.recordEditState-35599', () => { expect(editor(view.container, 'showcase_line.quote')).toBeNull(); }); + /** Pick `label` on the record's Status select, in the details column (not a body table's). */ + async function pickStatus(container: HTMLElement, label: string) { + const details = container.querySelector('[data-record-column="details"]') as HTMLElement; + let trigger: HTMLElement | undefined; + await waitFor(() => { + trigger = (Array.from(details.querySelectorAll('[role="combobox"]')) as HTMLElement[]) + .find((el) => !el.closest('[data-body-table-editor]')); + expect(trigger).toBeDefined(); + }, { timeout: 5000 }); + fireEvent.keyDown(trigger!, { key: 'ArrowDown' }); + fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: label })); + } + + it('ADR-0162 D4 (objectstack#38997): a Save that sets a closing state writes every line first and the record last', async () => { + const view = renderPage(objectsWith({ closedStates: { status: ['accepted'] } })); + await enterEditState(view); + editEverything(view.container); + await pickStatus(view.container, 'Accepted'); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 }); + const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array>; + expect(ops).toHaveLength(5); + expect(ops[ops.length - 1]).toEqual({ object: PARENT, action: 'update', id: RECORD_ID, data: { summary: 'Second', status: 'accepted' } }); + expect(ops.slice(0, -1).map((o) => [o.object, o.action, o.id ?? null])).toEqual(expect.arrayContaining([ + ['showcase_line', 'create', null], + ['showcase_line', 'update', 'l1'], + ['showcase_line', 'delete', 'l2'], + ['showcase_task', 'update', 't1'], + ])); + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + }); + + it('CONTROL — on the same object, a Save that sets a state it does not close on keeps the record first', async () => { + const view = renderPage(objectsWith({ closedStates: { status: ['accepted'] } })); + await enterEditState(view); + editEverything(view.container); + await pickStatus(view.container, 'Sent'); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 }); + const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array>; + expect(ops).toHaveLength(5); + expect(ops[0]).toEqual({ object: PARENT, action: 'update', id: RECORD_ID, data: { summary: 'Second', status: 'sent' } }); + }); + it('a refused batch keeps every edit and places the reason on its line; Cancel then restores', async () => { const view = renderPage(objectsWith()); await enterEditState(view); From 23ace6e38ba80fec1d228996a2daef59580c5422 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 22:34:26 +0000 Subject: [PATCH 3/4] chore(changeset): the edit-state save writes a closing header last Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --- .changeset/38997-edit-state-closing-order.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .changeset/38997-edit-state-closing-order.md diff --git a/.changeset/38997-edit-state-closing-order.md b/.changeset/38997-edit-state-closing-order.md new file mode 100644 index 00000000000..cb01d0aeb00 --- /dev/null +++ b/.changeset/38997-edit-state-closing-order.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-form': patch +'@object-ui/app-shell': patch +--- + +fix(console): the record page's edit-state save writes a closing header after its lines + +Clause-②: no +Metadata-protocol: none + +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). + +`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. From 79b787018d9d8aa85a7cc2f5a1c9294f165395e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:00:24 +0000 Subject: [PATCH 4/4] test(plugin-form): type the closing-save pin's order helper by the batch operation type Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ --- .../src/RecordBodyTableEditor.recordEditBatch-35599.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts index 6ff41b7eefc..339ff8c4a61 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts @@ -14,6 +14,7 @@ import { describe, it, expect } from 'vitest'; import { UNTOUCHED_NEW_ROW } from '@object-ui/fields'; +import type { BatchTransactionOperation } from '@object-ui/types'; import { attributeRecordEditRefusal, buildRecordEditBatch } from './RecordBodyTableEditor'; const childSchema = { @@ -175,7 +176,7 @@ describe('attributeRecordEditRefusal — a refused batch is placed where it belo describe('buildRecordEditBatch — a save that closes the record writes its lines first (ADR-0162 D4, objectstack#38997)', () => { // The object's declaration as its served definition carries it. const CLOSED_STATES = { status: ['paid', 'void'] }; - const order = (ops: ReadonlyArray<{ object: string; action: string; id?: unknown }>) => + const order = (ops: ReadonlyArray) => ops.map((o) => [o.object, o.action, o.id ?? null]); it('a draft that sets a closing state puts the record update after every line write, owned as the record', () => {