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
20 changes: 20 additions & 0 deletions .changeset/37773-console-closed-lock.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 4 additions & 3 deletions content/docs/data-modeling/closed-states.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,7 @@ const ar = {
viewOff: "التحرير في القائمة متوقف لهذا العرض.",
objectReadOnly: "لا يمكن تحرير هذه السجلات هنا.",
noPermission: "ليس لديك إذن بتحرير هذه السجلات.",
closedLocked: "هذا السجل مغلق ولا يمكن تغييره.",
approvalLocked: "هذا السجل مقفل أثناء الموافقة عليه.",
checking: "جارٍ التحقق مما إذا كان يمكن تعديل هذا السجل…",
noRecordPermission: "ليس لديك إذن بتحرير هذا السجل.",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,7 @@ const ja = {
viewOff: "このビューでは一覧での編集がオフになっています。",
objectReadOnly: "これらのレコードはここでは編集できません。",
noPermission: "これらのレコードを編集する権限がありません。",
closedLocked: "このレコードはクローズ済みのため変更できません。",
approvalLocked: "このレコードは承認中のためロックされています。",
checking: "このレコードを編集できるか確認しています…",
noRecordPermission: "このレコードを編集する権限がありません。",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,7 @@ const ko = {
viewOff: "이 보기에서는 목록 편집이 꺼져 있습니다.",
objectReadOnly: "이 레코드는 여기에서 편집할 수 없습니다.",
noPermission: "이 레코드를 편집할 권한이 없습니다.",
closedLocked: "이 레코드는 마감되어 변경할 수 없습니다.",
approvalLocked: "이 레코드는 승인 중이라 잠겨 있습니다.",
checking: "이 레코드를 편집할 수 있는지 확인하는 중…",
noRecordPermission: "이 레코드를 편집할 권한이 없습니다.",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,7 @@ const ru = {
viewOff: "Редактирование в списке отключено для этого представления.",
objectReadOnly: "Эти записи нельзя изменить здесь.",
noPermission: "У вас нет прав на изменение этих записей.",
closedLocked: "Эта запись закрыта, её нельзя изменить.",
approvalLocked: "Эта запись заблокирована, пока находится на согласовании.",
checking: "Проверяем, можно ли изменить эту запись…",
noRecordPermission: "У вас нет прав на изменение этой записи.",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/zh-Hans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ const zh = {
viewOff: '此视图已关闭列表内编辑。',
objectReadOnly: '这些记录不能在这里编辑。',
noPermission: '您没有编辑这些记录的权限。',
closedLocked: '此记录已关闭,无法更改。',
approvalLocked: '此记录正在审批中,已锁定。',
checking: '正在确认这条记录能否编辑…',
noRecordPermission: '您没有编辑此记录的权限。',
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/zh-Hant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ const zhHant = {
viewOff: '此檢視已關閉列表內編輯。',
objectReadOnly: '這些記錄不能在這裡編輯。',
noPermission: '您沒有編輯這些記錄的權限。',
closedLocked: '此記錄已關閉,無法更改。',
approvalLocked: '此記錄正在審批中,已鎖定。',
checking: '正在確認這條記錄能否編輯…',
noRecordPermission: '您沒有編輯此記錄的權限。',
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, any> };

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<typeof echoBatch>) {
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(
<MasterDetailForm
schema={{
objectName: 'invoice',
mode: 'edit',
recordId: 'inv1',
fields: ['ref', 'status'],
onSuccess: vi.fn(),
details: [
{
childObject: 'invoice_line',
relationshipField: 'invoice',
columns: [{ name: 'qty', label: 'Qty', type: 'number' } as any],
},
],
} as any}
dataSource={ds}
/>,
);
}

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<typeof echoBatch>) {
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']);
});
});
Loading
Loading