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
19 changes: 19 additions & 0 deletions .changeset/37773-record-page-closed-lock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@object-ui/app-shell': patch
'@object-ui/types': patch
'@object-ui/i18n': patch
---

fix(console): a closed record's page reads as closed, not as in approval, from the page's one request

Clause-②: no
Metadata-protocol: none

The record page now reads the data layer's lock for its Edit and Delete, and words the reason from its `lockReason`. It asks for that lock in the request it already sends when it opens (`POST /api/v1/data/{object}/{id}/page` with `dataLock: true`), so opening a record page is still one request. It no longer asks the approvals lock read for these affordances; the approvals panel and the header's approval tag keep reading it.

- A closed record (`lockReason: 'closed_state'`, its own state or its master's) shows Edit greyed with "This record is closed, so it can't be changed.", a "Closed" chip, and no Delete, for either `lockSource`. Its master-detail lines offer no New, Edit or Delete. A record that is closed and also held by an approval reads as closed.
- A record 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, and the page shows neither the field nor its value.
- When nothing on screen is a record page, the edit dialog opened over a list reads the record's lock through `GET /api/v1/data/{object}/{id}/lock` next to its approvals reads. The record page does the same when it re-reads after the record changes. Over its record page, the dialog reuses the page's answer and sends nothing.
- `RecordPagePayload` (`@object-ui/types`) declares the payload's `dataLock` part.
- New strings `detail.lockedClosed` and `detail.lockedClosedTooltip` in every console locale.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import React from 'react';
import { render, cleanup, waitFor } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { registerAllFields } from '@object-ui/fields';
// The console chain reaches `@objectstack/lint` behind a dynamic import; pay its first load at collection.
import '@objectstack/lint';

registerAllFields();

Expand Down Expand Up @@ -138,7 +140,11 @@ let served: Approvals = { requests: [], lock: false };
// test body returns can reach a socket; handed back in `afterAll`.
const fetchSpy = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
const body = url.includes('/approvals/records/')
// objectstack#37773 — the dialog's lock is the data layer's one lock read
// (`/data/:object/:id/lock`), answering `lockReason: 'approval'` here.
const body = /\/data\/[^/]+\/[^/]+\/lock$/.test(url)
? { success: true, data: served.lock ? { locked: true, lockSource: 'record', lockReason: 'approval' } : { locked: false } }
: url.includes('/approvals/records/')
? { success: true, data: { locked: served.lock } }
: url.includes('/approvals/requests?')
? { data: served.requests }
Expand Down Expand Up @@ -203,6 +209,26 @@ describe('[#27138] the console edit dialog reads the approvals record lock', ()
expect(lastModal().lockedBy).toBeUndefined();
});

// objectstack#37773 — over a list, no record page payload stands behind the
// dialog, so its hook reads for itself: the approvals list, the approvals
// lock (the panel's, asked when no pending request decides) and ONE data
// lock read, which is what the dialog's lock is read from.
it('over a list, the dialog sends one data lock read beside its approvals reads', async () => {
const fetchSpy = serveApprovals({ requests: [], lock: false });
openAt('/apps/crm/crm_contract?form=r1');
await waitFor(() => expect(lastModal()?.schema?.mode).toBe('edit'));
const lockishReads = () => fetchSpy.mock.calls
.map(([u]) => new URL(String(u), 'http://x').pathname)
.filter((u) => u.includes('/approvals/') || u.endsWith('/lock'));
await waitFor(() => expect(lockishReads().some((u) => u.startsWith('/api/v1/data/'))).toBe(true));
await new Promise((r) => setTimeout(r, 20));
expect(lockishReads().sort()).toEqual([
'/api/v1/approvals/records/crm_contract/r1/lock',
'/api/v1/approvals/requests',
'/api/v1/data/crm_contract/r1/lock',
]);
});

it('CONTROL — a create dialog asks nothing and is not locked', async () => {
const fetchSpy = serveApprovals({ requests: [], lock: true });
openAt('/apps/crm/crm_contract?form=new');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,27 @@
* (`POST /data/:object/:id/page`) answers the lock beside the rows whether or
* not a pending request decides it, so the kind is kept beside a pending
* request too — a self-held line under a held master answers `'master'`.
*
* objectstack#37773 — the same payload carries the data layer's one lock read
* (`dataLock`, ADR-0162 D9), which the seeded read publishes as `dataLock` in
* the same publish and asks NO lock door for: the record page open stays one
* request. The affordances read that one: `recordClosedByLock`,
* `openApprovalOf`. A read the hook sends itself (`refresh()`) asks
* `GET /data/:object/:id/lock`.
*/

import { describe, it, expect, afterEach } from 'vitest';
import * as React from 'react';
import { describe, it, expect, afterEach, afterAll, vi } from 'vitest';
import { renderHook, waitFor, act } from '@testing-library/react';
import { AdapterCtx } from '@object-ui/react';
import {
__resetRecordApprovalsStore,
openApprovalOf,
recordClosedByLock,
recordLockAnswerOf,
seedRecordApprovals,
useRecordApprovals,
type DataRecordLock,
type SeededRecordApprovals,
} from './useRecordApprovals';

Expand All @@ -36,17 +48,41 @@ const PENDING_ROW = {
lock_record: true,
};

/** What the data layer's lock door answers; set per test. */
let dataLock: Record<string, unknown> = { locked: false };
const dataLockGets: string[] = [];
// Installed once for the whole file: it counts every ask of the data lock door
// (a seeded read must send none), and no read may reach a socket after a test
// returns.
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith(`/data/${OBJECT}/${RECORD}/lock`)) {
dataLockGets.push(url);
return new Response(JSON.stringify({ success: true, data: dataLock }), { status: 200, headers: { 'content-type': 'application/json' } });
}
return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } });
}));
afterAll(() => vi.unstubAllGlobals());

afterEach(() => {
__resetRecordApprovalsStore();
dataLock = { locked: false };
dataLockGets.length = 0;
});

async function seeded(answer: SeededRecordApprovals) {
async function seeded(answer: SeededRecordApprovals, dataLockPart?: Promise<DataRecordLock | null>) {
let resolve!: (a: SeededRecordApprovals) => void;
seedRecordApprovals(OBJECT, RECORD, new Promise((r) => { resolve = r; }));
const hook = renderHook(() => useRecordApprovals(OBJECT, RECORD));
seedRecordApprovals(OBJECT, RECORD, new Promise((r) => { resolve = r; }), dataLockPart);
// Mounted as the console mounts it, under an adapter, so a read of the
// hook's own WOULD ask the data lock door.
const hook = renderHook(() => useRecordApprovals(OBJECT, RECORD), { wrapper: withAdapter });
await act(async () => { resolve(answer); });
await waitFor(() => expect(hook.result.current.answered).toBe(true));
return hook.result.current;
return Object.assign(hook.result.current, { hook });
}

function withAdapter({ children }: { children: React.ReactNode }) {
return <AdapterCtx.Provider value={{} as never}>{children}</AdapterCtx.Provider>;
}

describe('useRecordApprovals — the composite lock\'s `lockSource` (objectstack#37195)', () => {
Expand Down Expand Up @@ -87,3 +123,72 @@ describe('recordLockAnswerOf — the two bits the lock doors serve, as the grid
expect(recordLockAnswerOf(null)).toEqual({ locked: false });
});
});

describe('useRecordApprovals — the data lock off the record page payload (objectstack#37773)', () => {
it('a closed record: `dataLock` names `closed_state`, so the record reads closed and no approval opens — and no lock door is asked', async () => {
const out = await seeded(
{ requests: [], lock: { locked: false } },
Promise.resolve({ locked: true, lockSource: 'record', lockReason: 'closed_state' }),
);
const now = out.hook.result.current;
expect(now.dataLock).toEqual({ locked: true, lockSource: 'record', lockReason: 'closed_state' });
expect(recordClosedByLock(now)).toBe(true);
expect(openApprovalOf(now)).toBeNull();
// The approvals panel's lock is the payload's approvals part, untouched.
expect(now.recordLock).toEqual({ locked: false });
// The payload answered it: the open sent no lock read of its own.
expect(dataLockGets).toEqual([]);
});

it('the data lock lands in the same publish as the approvals answer: no render sees one without the other', async () => {
let resolveAnswer!: (a: SeededRecordApprovals) => void;
const answer = new Promise<SeededRecordApprovals>((r) => { resolveAnswer = r; });
const closed: DataRecordLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' };
seedRecordApprovals(OBJECT, RECORD, answer, answer.then(() => closed));
const seen: Array<[boolean, boolean]> = [];
const hook = renderHook(() => {
const r = useRecordApprovals(OBJECT, RECORD);
seen.push([r.answered, r.dataLock !== null]);
return r;
}, { wrapper: withAdapter });
await act(async () => { resolveAnswer({ requests: [], lock: { locked: false } }); });
await waitFor(() => expect(hook.result.current.answered).toBe(true));
expect(seen.some(([answered]) => answered)).toBe(true);
expect(seen.filter(([answered, locked]) => answered !== locked)).toEqual([]);
expect(dataLockGets).toEqual([]);
});

it('a record held by an approval the reader cannot see: the data lock opens it, whatever the approvals-family lock says', async () => {
const out = await seeded(
{ requests: [], lock: { locked: false } },
Promise.resolve({ locked: true, lockSource: 'record', lockReason: 'approval' }),
);
expect(recordClosedByLock(out)).toBe(false);
expect(openApprovalOf(out)).toEqual({ locked: true });
});

it('CONTROL: the approvals-family lock alone opens no approval for the affordances', async () => {
const out = await seeded({ requests: [], lock: { locked: true, lockSource: 'record' } }, Promise.resolve({ locked: false }));
expect(out.recordLock).toEqual({ locked: true, lockSource: 'record' });
expect(openApprovalOf(out)).toBeNull();
});

it("a refresh after the open is the hook's own read: it asks the data lock door once, and takes its answer", async () => {
const out = await seeded({ requests: [], lock: { locked: false } }, Promise.resolve({ locked: false }));
expect(dataLockGets).toEqual([]);
dataLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' };
await act(async () => { await out.hook.result.current.refresh(); });
expect(dataLockGets).toHaveLength(1);
expect(recordClosedByLock(out.hook.result.current)).toBe(true);
});

it('a payload whose engine has no lock read (part refused 501): no answer, and a later refresh does not ask the door either', async () => {
const refused = Promise.reject(Object.assign(new Error('Data lock refused'), { status: 501, code: 'NOT_IMPLEMENTED' }));
refused.catch(() => undefined);
const out = await seeded({ requests: [], lock: { locked: false } }, refused);
expect(out.hook.result.current.dataLock).toBeNull();
await act(async () => { await out.hook.result.current.refresh(); });
expect(dataLockGets).toEqual([]);
expect(out.hook.result.current.dataLock).toBeNull();
});
});
Loading
Loading