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
13 changes: 13 additions & 0 deletions .changeset/38997-edit-state-closing-order.md
Original file line number Diff line number Diff line change
@@ -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.
64 changes: 62 additions & 2 deletions ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> } = {}) => [
/** `closedStates`: the quote declares a `status` select and closes on the values listed (ADR-0162 D1). */
const objectsWith = ({ lineEnable, closedStates }: { lineEnable?: Record<string, unknown>; closedStates?: Record<string, string[]> } = {}) => [
{
name: PARENT,
label: 'Quote',
Expand All @@ -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: [
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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<Record<string, any>>;
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<Record<string, any>>;
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);
Expand Down
24 changes: 18 additions & 6 deletions ui/packages/app-shell/src/views/recordEditState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand Down Expand Up @@ -209,6 +215,9 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
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<string, BodyTableEditHandle>());
const [dirtyTables, setDirtyTables] = useState<ReadonlySet<string>>(() => new Set());
const [saving, setSaving] = useState(false);
Expand Down Expand Up @@ -301,17 +310,20 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
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();
Expand Down Expand Up @@ -339,7 +351,7 @@ export const RecordEditStateController: React.FC<RecordEditStateControllerProps>
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -171,3 +172,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<BatchTransactionOperation>) =>
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);
}
});
});
25 changes: 20 additions & 5 deletions ui/packages/plugin-form/src/RecordBodyTableEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -99,19 +99,30 @@ export const RecordEditSessionContext = React.createContext<RecordEditSession |
export type RecordEditOpOwner = { kind: 'parent' } | { kind: 'row'; table: string; row: number };

/**
* The ONE batch of a record-page save: the record's field draft (op 0, an
* update of only the edited keys) and every body table's lines diffed into
* The ONE batch of a record-page save: the record's field draft (an update of
* only the edited keys) and every body table's lines diffed into
* create / update / delete — `buildMasterDetailEditBatch`, table by table, so
* each op can be traced back to the line it came from ({@link RecordEditOpOwner}).
*
* The record's update is op 0, unless the draft puts the record into one of
* its object's closed states (`options.closedStates`, judged by `closesRecord`
* as the master-detail form judges it): then it is the LAST op, after every
* line write. [ADR-0162 D4] Inside the batch's one transaction each write meets
* the record as stored when it arrives, so a line write after the closing
* update would meet a closed record and the whole save would be refused. Read
* the record's op by its owner (`{ kind: 'parent' }`), never by its index.
*/
export function buildRecordEditBatch(
parentObject: string,
parentId: string,
parentDraft: Record<string, any>,
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
Expand All @@ -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 };
}

Expand Down
Loading