diff --git a/.changeset/37773-console-closed-lock.md b/.changeset/37773-console-closed-lock.md new file mode 100644 index 00000000000..eb966e48d46 --- /dev/null +++ b/.changeset/37773-console-closed-lock.md @@ -0,0 +1,20 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/plugin-form': patch +'@object-ui/i18n': patch +--- + +fix(console): a closed row in a grid reads as closed, not as in approval, and a save that closes a master writes its lines first + +Clause-②: no +Metadata-protocol: none + +The grid and the line grid now ask the data layer's one lock read (`POST /api/v1/data/{object}/locks`, on the first cell or row selection) for the edit and delete affordances of a row, and word the reason from its `lockReason`. They no longer ask the approvals lock read for this. + +- A closed row (`lockReason: 'closed_state'`, its own state or its master's) opens no cell editor, and the cell says "This record is closed, so it can't be changed." Its row menu offers neither Edit nor Delete, for either `lockSource`. A row that is closed and also held by an approval reads as closed. +- A row held by an approval behaves as before: its own approval keeps Delete, and a line of a held master does not. +- The answer is read above the caller's field permissions, so a reader who may not see the state field still gets the closed wording. +- A master-detail edit save that sets a closing state on the header (a value its object lists in `closedStates`) writes every line first and the header last, in one batch, so the save is not refused against the record it is closing. A save that does not close keeps the header first. +- New string `grid.readOnlyReason.closedLocked` in every console locale. + +The grid's lock read is gated on the `data` route in discovery, not on the approvals service, and makes the same number of requests as before. The record page is unchanged here. diff --git a/content/docs/data-modeling/closed-states.mdx b/content/docs/data-modeling/closed-states.mdx index b22d5de04bd..d4b41915e6e 100644 --- a/content/docs/data-modeling/closed-states.mdx +++ b/content/docs/data-modeling/closed-states.mdx @@ -308,9 +308,10 @@ app that reassigns closed documents ships an action for it. Once the write that closes a document has landed, a later write in the same unit of work meets a closed record. So when line edits and the closing write travel in one save, the lines are written first and the header that closes the document -last. The console's master-detail form saves the header before its lines, in one -transaction, so a save there that both closes the document and changes a line is -refused whole: change the lines, then close the document in a save of its own. +last. The console's master-detail form follows this order: when a save sets a +value the header object lists in `closedStates`, it writes every line first and +the header last, in one transaction, so a save that changes lines and closes the +document lands whole. A create has no such order. A caller cannot create a document that is already closed together with its lines, because each line would be added under a closed diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index c5a7f4ded6a..6e4cd350570 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -621,6 +621,7 @@ const ar = { viewOff: "التحرير في القائمة متوقف لهذا العرض.", objectReadOnly: "لا يمكن تحرير هذه السجلات هنا.", noPermission: "ليس لديك إذن بتحرير هذه السجلات.", + closedLocked: "هذا السجل مغلق ولا يمكن تغييره.", approvalLocked: "هذا السجل مقفل أثناء الموافقة عليه.", checking: "جارٍ التحقق مما إذا كان يمكن تعديل هذا السجل…", noRecordPermission: "ليس لديك إذن بتحرير هذا السجل.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index d87ac0943a5..fb4788529c3 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -587,6 +587,7 @@ const de = { viewOff: "Das Bearbeiten in der Liste ist für diese Ansicht ausgeschaltet.", objectReadOnly: "Diese Datensätze können hier nicht bearbeitet werden.", noPermission: "Sie haben keine Berechtigung, diese Datensätze zu bearbeiten.", + closedLocked: "Dieser Datensatz ist abgeschlossen und kann nicht mehr geändert werden.", approvalLocked: "Dieser Datensatz ist während der Genehmigung gesperrt.", checking: "Es wird geprüft, ob dieser Datensatz bearbeitet werden kann…", noRecordPermission: "Sie haben keine Berechtigung, diesen Datensatz zu bearbeiten.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 83a496784a7..b44a80af555 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -866,6 +866,7 @@ const en = { viewOff: 'Editing in the list is turned off for this view.', objectReadOnly: 'These records can\'t be edited here.', noPermission: 'You don\'t have permission to edit these records.', + closedLocked: 'This record is closed, so it can\'t be changed.', approvalLocked: 'This record is locked while it\'s in approval.', checking: 'Checking whether this record can be edited…', noRecordPermission: 'You don\'t have permission to edit this record.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 39c54f6adfb..8538f879c1f 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -599,6 +599,7 @@ const es = { viewOff: "La edición en la lista está desactivada para esta vista.", objectReadOnly: "Estos registros no se pueden editar aquí.", noPermission: "No tiene permiso para editar estos registros.", + closedLocked: "Este registro está cerrado y ya no se puede modificar.", approvalLocked: "Este registro está bloqueado mientras está en aprobación.", checking: "Comprobando si este registro se puede editar…", noRecordPermission: "No tiene permiso para editar este registro.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 1aa82b126fd..fc3a07a562f 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -594,6 +594,7 @@ const fr = { viewOff: "La modification dans la liste est désactivée pour cette vue.", objectReadOnly: "Ces enregistrements ne peuvent pas être modifiés ici.", noPermission: "Vous n'avez pas l'autorisation de modifier ces enregistrements.", + closedLocked: "Cet enregistrement est clôturé et ne peut plus être modifié.", approvalLocked: "Cet enregistrement est verrouillé pendant son approbation.", checking: "Vérification de la possibilité de modifier cet enregistrement…", noRecordPermission: "Vous n'avez pas l'autorisation de modifier cet enregistrement.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 1f1879a2262..61b4899cfe9 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -587,6 +587,7 @@ const ja = { viewOff: "このビューでは一覧での編集がオフになっています。", objectReadOnly: "これらのレコードはここでは編集できません。", noPermission: "これらのレコードを編集する権限がありません。", + closedLocked: "このレコードはクローズ済みのため変更できません。", approvalLocked: "このレコードは承認中のためロックされています。", checking: "このレコードを編集できるか確認しています…", noRecordPermission: "このレコードを編集する権限がありません。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 09afeebf1df..2c1c5a0a468 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -587,6 +587,7 @@ const ko = { viewOff: "이 보기에서는 목록 편집이 꺼져 있습니다.", objectReadOnly: "이 레코드는 여기에서 편집할 수 없습니다.", noPermission: "이 레코드를 편집할 권한이 없습니다.", + closedLocked: "이 레코드는 마감되어 변경할 수 없습니다.", approvalLocked: "이 레코드는 승인 중이라 잠겨 있습니다.", checking: "이 레코드를 편집할 수 있는지 확인하는 중…", noRecordPermission: "이 레코드를 편집할 권한이 없습니다.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 4932d7d36f1..e3701de9a95 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -594,6 +594,7 @@ const pt = { viewOff: "A edição na lista está desativada para esta visualização.", objectReadOnly: "Estes registros não podem ser editados aqui.", noPermission: "Você não tem permissão para editar estes registros.", + closedLocked: "Este registro está fechado e não pode mais ser alterado.", approvalLocked: "Este registro está bloqueado enquanto está em aprovação.", checking: "Verificando se este registro pode ser editado…", noRecordPermission: "Você não tem permissão para editar este registro.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 4d58e74579b..aed2cfb1f18 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -604,6 +604,7 @@ const ru = { viewOff: "Редактирование в списке отключено для этого представления.", objectReadOnly: "Эти записи нельзя изменить здесь.", noPermission: "У вас нет прав на изменение этих записей.", + closedLocked: "Эта запись закрыта, её нельзя изменить.", approvalLocked: "Эта запись заблокирована, пока находится на согласовании.", checking: "Проверяем, можно ли изменить эту запись…", noRecordPermission: "У вас нет прав на изменение этой записи.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index a824247db3a..41d21babc85 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -600,6 +600,7 @@ const zh = { viewOff: '此视图已关闭列表内编辑。', objectReadOnly: '这些记录不能在这里编辑。', noPermission: '您没有编辑这些记录的权限。', + closedLocked: '此记录已关闭,无法更改。', approvalLocked: '此记录正在审批中,已锁定。', checking: '正在确认这条记录能否编辑…', noRecordPermission: '您没有编辑此记录的权限。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 612b8bb838c..9a865b340e4 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -600,6 +600,7 @@ const zhHant = { viewOff: '此檢視已關閉列表內編輯。', objectReadOnly: '這些記錄不能在這裡編輯。', noPermission: '您沒有編輯這些記錄的權限。', + closedLocked: '此記錄已關閉,無法更改。', approvalLocked: '此記錄正在審批中,已鎖定。', checking: '正在確認這條記錄能否編輯…', noRecordPermission: '您沒有編輯此記錄的權限。', diff --git a/ui/packages/plugin-form/src/MasterDetailForm.closingHeaderLast-37773.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.closingHeaderLast-37773.test.tsx new file mode 100644 index 00000000000..9bbd6dc969f --- /dev/null +++ b/ui/packages/plugin-form/src/MasterDetailForm.closingHeaderLast-37773.test.tsx @@ -0,0 +1,160 @@ +/** + * 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#37773 (ADR-0162 D4) — one master-detail edit save that edits + * lines and sets the header's closing state lands whole: the header write is + * the batch's LAST operation, after every line write, so no line write meets a + * record the same save already closed. + * + * Drives the real `MasterDetailForm`: the header object's served definition + * declares `closedStates` (read off the header's own schema read), the user + * moves `status` to `paid` and edits a line, and the batch double records the + * order. A second save from the same mounted form diffs against what the first + * one wrote (the parent is found by its position, not at index 0), and a save + * that does not close keeps the header first. + */ +import { describe, it, expect, vi } from 'vitest'; +import { render, waitFor, fireEvent, screen, act } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import React from 'react'; + +import { registerAllFields } from '@object-ui/fields'; +import { MasterDetailForm } from './MasterDetailForm'; + +registerAllFields(); + +const INVOICE_SCHEMA = { + name: 'invoice', + fields: { + ref: { type: 'text', label: 'Ref' }, + status: { + type: 'select', + label: 'Status', + options: [{ label: 'Draft', value: 'draft' }, { label: 'Paid', value: 'paid' }], + }, + }, + closedStates: { status: ['paid'] }, +}; +const LINE_SCHEMA = { + name: 'invoice_line', + fields: { + qty: { type: 'number', label: 'Qty' }, + invoice: { type: 'master_detail', label: 'Invoice', reference: 'invoice' }, + }, +}; + +type Op = { object: string; action?: string; id?: string; data?: Record }; + +function echoBatch() { + let minted = 0; + return vi.fn(async (ops: Op[]) => ({ + results: ops.map((op) => { + if (op.action === 'create') return { id: `new${++minted}`, ...op.data }; + if (op.action === 'delete') return true; + return { id: op.id, ...op.data }; + }), + })); +} + +function renderForm(batchTransaction: ReturnType) { + const ds: any = { + getObjectSchema: vi.fn(async (o: string) => (o === 'invoice_line' ? LINE_SCHEMA : INVOICE_SCHEMA)), + findOne: vi.fn().mockResolvedValue({ id: 'inv1', ref: 'INV-1', status: 'draft' }), + find: vi.fn(async (o: string) => ({ data: o === 'invoice_line' ? [{ id: 'L1', qty: 1, invoice: 'inv1' }] : [] })), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + batchTransaction, + }; + return render( + , + ); +} + +const saveButton = () => screen.getByTestId('md-form-submit') as HTMLButtonElement; +const qtyInputs = () => screen.queryAllByLabelText('Qty') as HTMLInputElement[]; + +async function ready(container: HTMLElement) { + await waitFor(() => { + const ref = container.querySelector('input[name="ref"]') as HTMLInputElement | null; + if (!ref || ref.value !== 'INV-1') throw new Error('header not loaded'); + }); + await waitFor(() => expect(qtyInputs()).toHaveLength(1)); + await waitFor(() => expect(saveButton().disabled).toBe(false)); +} + +async function pickStatus(container: HTMLElement, label: string) { + const trigger = container.querySelector('[data-testid="select-trigger-status"]') as HTMLElement; + await userEvent.click(trigger); + await userEvent.click(await screen.findByRole('option', { name: label })); +} + +async function save(batch: ReturnType) { + const before = batch.mock.calls.length; + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(batch.mock.calls.length).toBeGreaterThan(before)); + await waitFor(() => expect(saveButton().disabled).toBe(false)); + return batch.mock.calls[batch.mock.calls.length - 1][0] as Op[]; +} + +describe('MasterDetailForm — a save that closes the header writes it last (objectstack#37773)', () => { + it('lines first, the closing header last; the next save diffs against what this one wrote', async () => { + const batch = echoBatch(); + const { container } = renderForm(batch); + await ready(container); + + await act(async () => { + fireEvent.change(qtyInputs()[0], { target: { value: '5' } }); + }); + await pickStatus(container, 'Paid'); + const ops = await save(batch); + expect(ops.map((op) => `${op.action} ${op.object}`)).toEqual(['update invoice_line', 'update invoice']); + expect(ops[0]).toEqual({ object: 'invoice_line', action: 'update', id: 'L1', data: { qty: 5 } }); + expect(ops[1]).toMatchObject({ object: 'invoice', action: 'update', id: 'inv1', data: { status: 'paid' } }); + + // The baseline advanced from the closing batch, the parent found at its + // own index: the same line, unchanged, is not written again. + await act(async () => { + fireEvent.change(qtyInputs()[0], { target: { value: '6' } }); + }); + const next = await save(batch); + expect(next.filter((op) => op.object === 'invoice_line')).toEqual([ + { object: 'invoice_line', action: 'update', id: 'L1', data: { qty: 6 } }, + ]); + }); + + it('control: a save that does not close keeps the header first', async () => { + const batch = echoBatch(); + const { container } = renderForm(batch); + await ready(container); + await act(async () => { + fireEvent.change(qtyInputs()[0], { target: { value: '5' } }); + }); + const ops = await save(batch); + expect(ops.map((op) => `${op.action} ${op.object}`)).toEqual(['update invoice', 'update invoice_line']); + }); +}); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 91e74bda150..6a2044f2bd4 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -56,6 +56,7 @@ import { FormSlotStore, type FormSlotHandoff, type FormSlotRequest } from './for import { buildMasterDetailBatch, buildMasterDetailEditBatch, + editBatchParentIndex, idOf, isBlankRow, sumRows, @@ -269,7 +270,8 @@ function isBuiltFrom( * the server's `/batch` and `emulateBatchTransaction` both do). The edit * builder puts the parent at index 0 and then, collection by collection in * the order it was handed them, one `create` per non-blank row without an - * id, in row order. Each such row is paired with the next create operation, + * id, in row order; a parent update that closes the record goes last + * instead (ADR-0162 D4), so the parent is skipped by its index, `parentIndex`. Each such row is paired with the next create operation, * and the pair is checked ({@link isBuiltFrom}) before it is trusted. A pair * that does not check out stops the pairing: the rows left unpaired stay * creates, which is the behaviour before this advance, never a row updating @@ -287,11 +289,12 @@ function childRowsAfterSave( ops: BatchTransactionOperation[], results: unknown, details: SavedDetailInput[], + parentIndex: number, ): SavedChildRows[] { const echoes = Array.isArray(results) ? results : []; const creates: Array<{ op: BatchTransactionOperation; echo: unknown }> = []; ops.forEach((op, k) => { - if (k > 0 && op.action === 'create') creates.push({ op, echo: echoes[k] }); + if (k !== parentIndex && op.action === 'create') creates.push({ op, echo: echoes[k] }); }); let nextCreate = 0; let pairingLost = false; @@ -317,9 +320,9 @@ function childRowsAfterSave( createdIds.set(row, id); written.set(id, pair.op.data ?? {}); } - for (let k = 1; k < ops.length; k++) { + for (let k = 0; k < ops.length; k++) { const op = ops[k]; - if (op.action === 'update' && op.object === childObject && op.id != null) { + if (k !== parentIndex && op.action === 'update' && op.object === childObject && op.id != null) { written.set(op.id, op.data ?? {}); } } @@ -687,13 +690,19 @@ interface HeaderRecordFeed { * when the object declares none. */ objectHandLock: unknown; + /** + * The header object's `closedStates`, landed with its field names: the edit + * save writes a header write that closes the record last (ADR-0162 D4). + * `undefined` until then or when the object declares none. + */ + objectClosedStates: unknown; /** Bumped per header record read started, so only the newest answer lands. */ seq: number; listeners: Set<(landed: 'record' | 'objectFields') => void>; } function createHeaderRecordFeed(opening: Record): HeaderRecordFeed { - return { record: opening, objectFields: null, objectHandLock: undefined, seq: 0, listeners: new Set() }; + return { record: opening, objectFields: null, objectHandLock: undefined, objectClosedStates: undefined, seq: 0, listeners: new Set() }; } /** @@ -749,10 +758,15 @@ function observeHeaderReads( const answer = call(args); if (args[0] === objectName) { observe(answer, (objectSchema) => { - const served = objectSchema as { fields?: Record; uiReadonlyWhen?: unknown } | null; + const served = objectSchema as { + fields?: Record; + uiReadonlyWhen?: unknown; + closedStates?: unknown; + } | null; const fields = served?.fields; feed.objectFields = fields ? Object.keys(fields) : []; feed.objectHandLock = served?.uiReadonlyWhen ?? undefined; + feed.objectClosedStates = served?.closedStates ?? undefined; feed.listeners.forEach((listener) => listener('objectFields')); }); } @@ -940,21 +954,28 @@ const preventSubmit = (event: React.FormEvent) => event.preventDefault(); * reads the same evidence): the operation the server names as the failed one, * else each field it names that only line operations write (a field the * parent's own operation carries is the header form's to mark). The parent is - * operation 0 in both batch builders. A refusal that names neither, a lock or - * a permission denial, is on no collection. + * operation `parentIndex`: 0 in both batch builders, or the last operation of + * an edit batch whose header write closes the record (ADR-0162 D4). A refusal + * that names neither, a lock or a permission denial, is on no collection. */ -function refusedChildObjects(err: unknown, ops: readonly BatchTransactionOperation[]): Set { +function refusedChildObjects( + err: unknown, + ops: readonly BatchTransactionOperation[], + parentIndex: number, +): Set { const out = new Set(); const failed = (err as { details?: { failedOperation?: { index?: unknown } } } | null)?.details?.failedOperation?.index; if (typeof failed === 'number') { - if (failed > 0 && ops[failed]?.object) out.add(ops[failed].object); + if (failed !== parentIndex && ops[failed]?.object) out.add(ops[failed].object); return out; } const carries = (op: BatchTransactionOperation | undefined, field: string) => !!op && op.action !== 'delete' && !!op.data && Object.prototype.hasOwnProperty.call(op.data, field); for (const { field } of extractFieldErrors(err) ?? []) { - if (carries(ops[0], field)) continue; - for (const op of ops.slice(1)) if (carries(op, field)) out.add(op.object); + if (carries(ops[parentIndex], field)) continue; + ops.forEach((op, k) => { + if (k !== parentIndex && carries(op, field)) out.add(op.object); + }); } return out; } @@ -2233,12 +2254,16 @@ export const MasterDetailForm: React.FC = ({ }, })) : null; + // [ADR-0162 D4] A header write that closes the record goes after the + // line writes, judged against the header object's `closedStates` as the + // header's own schema read served it. const ops = editDetails ? buildMasterDetailEditBatch( schema.objectName, String(schema.recordId), parentData, editDetails.map((d) => d.input), + { closedStates: headerReadRef.current?.feed.objectClosedStates }, ) : buildMasterDetailBatch( schema.objectName, @@ -2251,12 +2276,15 @@ export const MasterDetailForm: React.FC = ({ childSchema: childSchemasRef.current[e.config.childObject], })), ); + const parentIndex = editDetails + ? Math.max(0, editBatchParentIndex(ops, schema.objectName, String(schema.recordId))) + : 0; let res: Awaited>; try { res = await runBatchTransaction(dataSource, ops); } catch (err) { // A refusal on a placed collection marks the tab that holds it. - const refused = refusedChildObjects(err, ops); + const refused = refusedChildObjects(err, ops, parentIndex); slotStore.refuse(entries.filter((e) => refused.has(e.config.childObject)).map((e) => e.id)); throw err; } @@ -2269,7 +2297,7 @@ export const MasterDetailForm: React.FC = ({ // as a failed save with one baseline moved. Create mode has no baseline: // `handleSaved` empties the rows for the next entry. if (editDetails) { - const saved = childRowsAfterSave(ops, res?.results, editDetails); + const saved = childRowsAfterSave(ops, res?.results, editDetails, parentIndex); // objectui#10853 — these lines are now what the server holds, so a bus // re-read held behind them (this save's own echo included) is replayed // once the save has settled. diff --git a/ui/packages/plugin-form/src/masterDetailTx.closingHeaderLast-37773.test.ts b/ui/packages/plugin-form/src/masterDetailTx.closingHeaderLast-37773.test.ts new file mode 100644 index 00000000000..0842224b9f2 --- /dev/null +++ b/ui/packages/plugin-form/src/masterDetailTx.closingHeaderLast-37773.test.ts @@ -0,0 +1,101 @@ +/** + * 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#37773 (ADR-0162 D4) — a master-detail edit save that closes the + * header writes the header LAST. + * + * Inside one unit of work the closed-state lock is judged on the row as stored + * when each write reaches it: once the closing header write has landed, a line + * write after it meets a closed record and the whole save is refused. So the + * edit builder puts a header update that sets a closing value + * (`closedStates`, as the header object's served definition carries it) after + * every line write, and keeps it first otherwise. Create stays parent-first: + * its lines point at the parent through `{ $ref: 0 }`. + */ +import { describe, it, expect } from 'vitest'; +import { + buildMasterDetailBatch, + buildMasterDetailEditBatch, + closesRecord, + editBatchParentIndex, +} from './masterDetailTx'; + +const CLOSED_STATES = { status: ['paid', 'void'], approval_status: ['approved'] }; + +const LINES = { + childObject: 'invoice_line', + relationshipField: 'invoice', + original: [{ id: 'l1', qty: 1 }, { id: 'l2', qty: 2 }], + rows: [{ id: 'l1', qty: 5 }, { qty: 3 }], +}; + +const shape = (ops: ReturnType) => ops.map((op) => `${op.action} ${op.object}`); + +describe('buildMasterDetailEditBatch — a closing header write goes last (objectstack#37773)', () => { + it('a save that edits lines and sets a closing state writes every line first, the header last', () => { + const ops = buildMasterDetailEditBatch('invoice', 'inv1', { status: 'paid', note: 'settled' }, [LINES], { + closedStates: CLOSED_STATES, + }); + expect(shape(ops)).toEqual([ + 'create invoice_line', + 'update invoice_line', + 'delete invoice_line', + 'update invoice', + ]); + // The header write carries the closing value with the rest of its fields. + expect(ops[3]).toEqual({ object: 'invoice', action: 'update', id: 'inv1', data: { status: 'paid', note: 'settled' } }); + expect(editBatchParentIndex(ops, 'invoice', 'inv1')).toBe(3); + }); + + it('control: the same save without a closing value keeps the header first', () => { + const ops = buildMasterDetailEditBatch('invoice', 'inv1', { status: 'draft', note: 'settled' }, [LINES], { + closedStates: CLOSED_STATES, + }); + expect(shape(ops)[0]).toBe('update invoice'); + expect(editBatchParentIndex(ops, 'invoice', 'inv1')).toBe(0); + }); + + it('any listed field closes: an approval mirror value moves the header last too', () => { + const ops = buildMasterDetailEditBatch('invoice', 'inv1', { approval_status: 'approved' }, [LINES], { + closedStates: CLOSED_STATES, + }); + expect(shape(ops).at(-1)).toBe('update invoice'); + }); + + it('an object that declares no closed states, or a caller that passes none, keeps the header first', () => { + for (const options of [undefined, {}, { closedStates: undefined }, { closedStates: ['status'] }]) { + const ops = buildMasterDetailEditBatch('invoice', 'inv1', { status: 'paid' }, [LINES], options as any); + expect(shape(ops)[0]).toBe('update invoice'); + } + }); + + it('a header update with no line writes is the batch alone', () => { + const ops = buildMasterDetailEditBatch('invoice', 'inv1', { status: 'paid' }, [], { closedStates: CLOSED_STATES }); + expect(ops).toEqual([{ object: 'invoice', action: 'update', id: 'inv1', data: { status: 'paid' } }]); + }); + + it('create stays parent-first: its lines point at operation 0', () => { + const ops = buildMasterDetailBatch('invoice', { status: 'paid' }, [ + { childObject: 'invoice_line', relationshipField: 'invoice', rows: [{ qty: 1 }] }, + ]); + expect(shape(ops)).toEqual(['create invoice', 'create invoice_line']); + expect(ops[1].data).toEqual({ qty: 1, invoice: { $ref: 0 } }); + }); +}); + +describe('closesRecord', () => { + it('reads a carried listed field holding a listed value', () => { + expect(closesRecord({ status: 'paid' }, CLOSED_STATES)).toBe(true); + expect(closesRecord({ status: 'void' }, CLOSED_STATES)).toBe(true); + expect(closesRecord({ status: 'sent' }, CLOSED_STATES)).toBe(false); + expect(closesRecord({ note: 'paid' }, CLOSED_STATES)).toBe(false); + expect(closesRecord({ status: null }, CLOSED_STATES)).toBe(false); + expect(closesRecord({ status: 'paid' }, null)).toBe(false); + }); +}); diff --git a/ui/packages/plugin-form/src/masterDetailTx.ts b/ui/packages/plugin-form/src/masterDetailTx.ts index a02e66fec37..9e1cb0b944d 100644 --- a/ui/packages/plugin-form/src/masterDetailTx.ts +++ b/ui/packages/plugin-form/src/masterDetailTx.ts @@ -136,20 +136,56 @@ export function buildMasterDetailBatch( return ops; } +/** + * [ADR-0162 D4] Does this header payload put the record into one of its + * object's closed states? `closedStates` is the object's declaration as the + * served definition carries it (`{