Skip to content

Commit 67d87f3

Browse files
feat(console): the record page reads a closed record from its one payload request (ADR-0162 item 4) (#39011)
Fixes #37773 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在记录详情页上打开一张已关闭的单据(如已付款发票),「编辑」按钮变灰并提示「此记录已关闭,无法修改」,「删除」不再出现;打开记录页仍只发一个请求。 - 为什么做:属于「关闭态单据」(ADR-0162)这条线,网格那一半已合并,本次补上记录详情页,让读者不再把「已关闭」误认为「审批中」。 - 出错会怎样:最坏情况是按钮显示与服务端不一致,但服务端照样拒绝对已关闭记录的写入,数据不会被改坏;本改动只动界面,可直接撤回。 - 要你做什么:无。 ## What changes This is the record-page half of #37773. The grid, line grid and closing-header-last save landed in #38994; this half waited for the record page payload to carry the data lock, which #38999 added. - **The record page reads the data layer's lock from its one request.** The page's payload request (`POST /api/v1/data/{object}/{id}/page`) now asks `dataLock: true`. `seedRecordPageReaders` hands that part to `useRecordApprovals` through `seedRecordApprovals`, and the hook publishes it as `dataLock` in the same publish as the approvals answer. Opening a record page sends no lock read of its own. This is the one change against the backup branch, which sent a second `GET /data/:object/:id/lock`. - **Edit and Delete read `dataLock`, not the approvals-family lock.** - Closed record (`lockReason: 'closed_state'`, its own state or its master's): Edit is drawn greyed with "This record is closed, so it can't be changed.", a "Closed" chip shows where the header draws tags, Delete is hidden for either `lockSource`, and master-detail lines draw no New, Edit or Delete. - Closed and also held by an approval: reads as closed. - Held by an approval (`lockReason: 'approval'`): unchanged. The record's own approval keeps Delete; a line under a held master does not (`recordDeleteRefusedByLock`, which replaces `recordDeleteHeldByMaster`). - The approvals panel and the header's approval tag keep the approvals-family `recordLock`. - **Reads the hook sends itself still ask `GET /data/:object/:id/lock`.** That means `refresh()` after the record changes, and a consumer with no page payload behind it. A part refused `501` latches like the GET's `501`, so neither is asked again. - **The console's full-record edit dialog** (`AppContent`, not edited here; #38997 owns that file) reads `openApprovalOf(formApprovals)` as before, which now reads `dataLock`. Request counts, measured in the browser and pinned where noted: - Edit pressed on a record page: the dialog joins the page's answer and sends **0** lock or approvals reads. - Opened over a list (`?form=ID`): 3 reads, pinned in `AppContent.editDialogApprovalLock-27138`: approvals list, approvals lock, and the data lock read. On main it sends 2. - Deep-linked straight to a record page with `?form=ID`: the dialog's hook mounts before the page asks its payload, so the dialog sends its own 3 reads. The page still sends its one payload request. - `recordClosedByLock` and `DataRecordLock` stay exported for #38997's dialog wording. - `RecordPagePayload` (`@object-ui/types`) declares the payload's `dataLock` part as the spec's `RecordLock` or a part refusal. - New strings `detail.lockedClosed` and `detail.lockedClosedTooltip` in all 11 console locales. Read first, by risk: 1. `ui/packages/app-shell/src/hooks/useRecordApprovals.ts`: `startRead`'s `dataLockRead` choice (seeded vs own read) and `settleSeededDataLock`. 2. `ui/packages/app-shell/src/views/recordPagePayload.ts`: the `dataLock` seed passed beside the approvals seed. 3. `ui/packages/app-shell/src/views/RecordDetailView.tsx`: `recordClosed` in the Edit item (`editOff`, `editReason`) and the Delete affordance. Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/views/RecordDetailView.recordPagePayload-27627.test.tsx`. Expect 11 passed. Its last block opens a closed record and asserts one page request, no lock read and a greyed Edit. ## Tests All run at `fef530c6` (this branch's head) unless marked. - `RecordDetailView.recordPagePayload-27627`: the cold-open pin now also asserts `dataLock: true` in the one request body. A new block mounts the adapter the way the console's `AdapterProvider` does, which is what lets the hook send reads of its own: - a closed record opens with one page request, no lock read, Edit greyed, and the Closed chip carrying the sentence; - CONTROL: an unlocked record gets the same single request and a live Edit; - ablation: with no payload behind the page, the hook reads `GET /data/.../lock` itself, which shows the detector can see that read. - `useRecordApprovals.lockSource-37195`: - the seeded data lock is published with no lock GET; - no render sees `answered` without `dataLock`; - an approval-held record opens an approval; - CONTROL: the approvals-family lock alone opens none; - `refresh()` asks the data lock door once; - a `501` part latches, so no later GET goes out. - `RecordDetailView.harness` (`closedLock-37773`, `deleteFollowsLockSource-37195`) and `RecordDetailView.approvalLock-25934`: the hook's own-read path, carried over from the backup. They cover: - closed, line of a closed master, closed and held, approval-held CONTROL, unlocked CONTROL; - a reader whose object has no state field still gets the closed wording, with no field or value on the page. - `AppContent.editDialogApprovalLock-27138`: plus the request-set pin for the dialog over a list. <details><summary>Test and type-check readings</summary> - `pnpm --dir ui exec vitest run packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx packages/app-shell/src/views/RecordDetailView.recordPagePayload-27627.test.tsx`: 11 passed, 11 passed. - `pnpm --dir ui exec vitest run` on the harness, `approvalLock-25934`, `AppContent.editDialogApprovalLock-27138`, `recordOpenOneRequest-28470`, `feedLoadFailure-29188`, `recordReadFailure-11902` and `approvalRequestPage-28546`: Test Files 7 passed, Tests 139 passed. The 27138 file was re-run after its new pin: 6 passed. - Ablation, run once and restored. `startRead` was mutated so that seeded reads send the GET instead of taking the payload part. On-disk marker count 1, original anchor 0. Result: 13 failed across the two files, including every one-request pin in 27627 and the five payload tests in 37195. Restored with `git checkout HEAD`: `git diff HEAD` empty and the blob hash matches HEAD. - `pnpm --filter @object-ui/app-shell run type-check`, `@object-ui/types`, `@object-ui/i18n`: exit 0, after rebuilding types and i18n. - `eslint` on the 21 changed ts/tsx files under `ui/`: 0 errors. The 266 warnings are existing `no-explicit-any` warnings in the touched files. - Derived gates (`dispatch-gates.mjs --commands`, reconciled with `--ran`): 41 derived, 39 run (all exit 0, including `pnpm --dir ui exec vitest run scripts/`: 172 files passed, 2 skipped), 2 NOT MEASURED: `check:query-options-erasure` and `check:type-check-debt`, both killed by a 200 s timeout on the shared box and left to CI. - `node scripts/check-platform-checklist.mjs --changed-from origin/main`: 0 anchored files. Run because `recordDeleteHeldByMaster` was renamed. - `pnpm --dir ui run check:new-line-citations`: exit 0. </details> ## Acceptance notes - **The changeset is a new file**, `.changeset/37773-record-page-closed-lock.md`. The dispatch named `.changeset/37773-console-closed-lock.md`, but that file landed on main with #38994 and describes the grid half. Re-wording it would rewrite that half's pending note, so this half gets its own. - **The edit dialog over a list sends one more read than main** (3 instead of 2): the data lock read. The approvals lock read it still sends decides nothing in the dialog, which draws no approvals panel. Dropping it would change what the hook reads for its other consumers, which is out of scope. - **Pressing Edit on a record page re-asks the page payload** (the same body twice). Measured identical on main by restoring the four app-shell files to `77d15643` under the same dev server, so it does not come from this change. - **The Closed chip shows only where the page header draws tags.** It shows on the invoice line page but not on the showcase invoice's authored page; the greyed Edit and its sentence show on both. The state-lock chip on main is placed the same way. - **The approval-held case was not browser-verified.** The showcase's invoice sign-off flow does not lock the record: after submitting INV-1002, both lock doors answered `locked: false`. That case is pinned by the unit tests above. - **The record page re-reads the data lock after a change.** On a record-invalidation refresh, `refresh()` asks `GET /data/:object/:id/lock`, so a record closed by an edit on the page reads as closed without a reload. This is a read after a change, not an open. ## Verification Local showcase app on this branch: our own backend on a random port plus the console dev server proxied to it, 1440 x 900, signed in as admin. Every open sent one `POST .../page` carrying `dataLock: true` and no `.../lock` request. | | | |:--|:--| | Paid invoice INV-1003: Edit greyed, closed sentence on hover | Paid invoice: overflow has no Delete | | ![paid edit](https://github.com/objectstack-ai/objectstack/blob/ef703bcb351f00960c54b9cc8f26f64722c9c284/pr-assets/37773/1-paid-edit-hover.png?raw=true) | ![paid overflow](https://github.com/objectstack-ai/objectstack/blob/ef703bcb351f00960c54b9cc8f26f64722c9c284/pr-assets/37773/2-paid-overflow.png?raw=true) | | A line of the paid invoice (closed by its master, no authored predicate): Closed chip, Edit greyed with the sentence | The same line: overflow has no Delete | | ![line edit](https://github.com/objectstack-ai/objectstack/blob/ef703bcb351f00960c54b9cc8f26f64722c9c284/pr-assets/37773/3-line-edit-hover.png?raw=true) | ![line overflow](https://github.com/objectstack-ai/objectstack/blob/ef703bcb351f00960c54b9cc8f26f64722c9c284/pr-assets/37773/4-line-overflow.png?raw=true) | | CONTROL: draft invoice INV-1004: live Edit, Delete offered | CONTROL: a line of the draft invoice: Delete offered | | ![draft](https://github.com/objectstack-ai/objectstack/blob/ef703bcb351f00960c54b9cc8f26f64722c9c284/pr-assets/37773/5-draft-overflow.png?raw=true) | ![draft line](https://github.com/objectstack-ai/objectstack/blob/ef703bcb351f00960c54b9cc8f26f64722c9c284/pr-assets/37773/6-line-draft-overflow.png?raw=true) | The paid invoice also carries authored `edit.disabledWhen` and `delete.visibleWhen` predicates, so its greyed Edit and missing Delete are not by themselves evidence for this change. Its Edit reason now reads the closed sentence. The invoice line has no such predicates, so the line rows isolate this change, with the draft-invoice line as control. Claim on the card for this branch: #37773 comment 7330313783 (re-stating claim 7317217442 on `claude/issue-37773-record-page-lock`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzhKEbEnW8pwZRgK2gJ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 270d160 commit 67d87f3

22 files changed

Lines changed: 768 additions & 83 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/types': patch
4+
'@object-ui/i18n': patch
5+
---
6+
7+
fix(console): a closed record's page reads as closed, not as in approval, from the page's one request
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
- 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.
15+
- A record held by an approval behaves as before: its own approval keeps Delete, and a line of a held master does not.
16+
- 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.
17+
- 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.
18+
- `RecordPagePayload` (`@object-ui/types`) declares the payload's `dataLock` part.
19+
- New strings `detail.lockedClosed` and `detail.lockedClosedTooltip` in every console locale.

‎ui/packages/app-shell/src/console/__tests__/AppContent.editDialogApprovalLock-27138.test.tsx‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ import React from 'react';
3131
import { render, cleanup, waitFor } from '@testing-library/react';
3232
import { MemoryRouter, Routes, Route } from 'react-router-dom';
3333
import { registerAllFields } from '@object-ui/fields';
34+
// The console chain reaches `@objectstack/lint` behind a dynamic import; pay its first load at collection.
35+
import '@objectstack/lint';
3436

3537
registerAllFields();
3638

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

212+
// objectstack#37773 — over a list, no record page payload stands behind the
213+
// dialog, so its hook reads for itself: the approvals list, the approvals
214+
// lock (the panel's, asked when no pending request decides) and ONE data
215+
// lock read, which is what the dialog's lock is read from.
216+
it('over a list, the dialog sends one data lock read beside its approvals reads', async () => {
217+
const fetchSpy = serveApprovals({ requests: [], lock: false });
218+
openAt('/apps/crm/crm_contract?form=r1');
219+
await waitFor(() => expect(lastModal()?.schema?.mode).toBe('edit'));
220+
const lockishReads = () => fetchSpy.mock.calls
221+
.map(([u]) => new URL(String(u), 'http://x').pathname)
222+
.filter((u) => u.includes('/approvals/') || u.endsWith('/lock'));
223+
await waitFor(() => expect(lockishReads().some((u) => u.startsWith('/api/v1/data/'))).toBe(true));
224+
await new Promise((r) => setTimeout(r, 20));
225+
expect(lockishReads().sort()).toEqual([
226+
'/api/v1/approvals/records/crm_contract/r1/lock',
227+
'/api/v1/approvals/requests',
228+
'/api/v1/data/crm_contract/r1/lock',
229+
]);
230+
});
231+
206232
it('CONTROL — a create dialog asks nothing and is not locked', async () => {
207233
const fetchSpy = serveApprovals({ requests: [], lock: true });
208234
openAt('/apps/crm/crm_contract?form=new');

‎ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx‎

Lines changed: 110 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,27 @@
1313
* (`POST /data/:object/:id/page`) answers the lock beside the rows whether or
1414
* not a pending request decides it, so the kind is kept beside a pending
1515
* request too — a self-held line under a held master answers `'master'`.
16+
*
17+
* objectstack#37773 — the same payload carries the data layer's one lock read
18+
* (`dataLock`, ADR-0162 D9), which the seeded read publishes as `dataLock` in
19+
* the same publish and asks NO lock door for: the record page open stays one
20+
* request. The affordances read that one: `recordClosedByLock`,
21+
* `openApprovalOf`. A read the hook sends itself (`refresh()`) asks
22+
* `GET /data/:object/:id/lock`.
1623
*/
1724

18-
import { describe, it, expect, afterEach } from 'vitest';
25+
import * as React from 'react';
26+
import { describe, it, expect, afterEach, afterAll, vi } from 'vitest';
1927
import { renderHook, waitFor, act } from '@testing-library/react';
28+
import { AdapterCtx } from '@object-ui/react';
2029
import {
2130
__resetRecordApprovalsStore,
31+
openApprovalOf,
32+
recordClosedByLock,
2233
recordLockAnswerOf,
2334
seedRecordApprovals,
2435
useRecordApprovals,
36+
type DataRecordLock,
2537
type SeededRecordApprovals,
2638
} from './useRecordApprovals';
2739

@@ -36,17 +48,41 @@ const PENDING_ROW = {
3648
lock_record: true,
3749
};
3850

51+
/** What the data layer's lock door answers; set per test. */
52+
let dataLock: Record<string, unknown> = { locked: false };
53+
const dataLockGets: string[] = [];
54+
// Installed once for the whole file: it counts every ask of the data lock door
55+
// (a seeded read must send none), and no read may reach a socket after a test
56+
// returns.
57+
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
58+
const url = String(input);
59+
if (url.endsWith(`/data/${OBJECT}/${RECORD}/lock`)) {
60+
dataLockGets.push(url);
61+
return new Response(JSON.stringify({ success: true, data: dataLock }), { status: 200, headers: { 'content-type': 'application/json' } });
62+
}
63+
return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } });
64+
}));
65+
afterAll(() => vi.unstubAllGlobals());
66+
3967
afterEach(() => {
4068
__resetRecordApprovalsStore();
69+
dataLock = { locked: false };
70+
dataLockGets.length = 0;
4171
});
4272

43-
async function seeded(answer: SeededRecordApprovals) {
73+
async function seeded(answer: SeededRecordApprovals, dataLockPart?: Promise<DataRecordLock | null>) {
4474
let resolve!: (a: SeededRecordApprovals) => void;
45-
seedRecordApprovals(OBJECT, RECORD, new Promise((r) => { resolve = r; }));
46-
const hook = renderHook(() => useRecordApprovals(OBJECT, RECORD));
75+
seedRecordApprovals(OBJECT, RECORD, new Promise((r) => { resolve = r; }), dataLockPart);
76+
// Mounted as the console mounts it, under an adapter, so a read of the
77+
// hook's own WOULD ask the data lock door.
78+
const hook = renderHook(() => useRecordApprovals(OBJECT, RECORD), { wrapper: withAdapter });
4779
await act(async () => { resolve(answer); });
4880
await waitFor(() => expect(hook.result.current.answered).toBe(true));
49-
return hook.result.current;
81+
return Object.assign(hook.result.current, { hook });
82+
}
83+
84+
function withAdapter({ children }: { children: React.ReactNode }) {
85+
return <AdapterCtx.Provider value={{} as never}>{children}</AdapterCtx.Provider>;
5086
}
5187

5288
describe('useRecordApprovals — the composite lock\'s `lockSource` (objectstack#37195)', () => {
@@ -87,3 +123,72 @@ describe('recordLockAnswerOf — the two bits the lock doors serve, as the grid
87123
expect(recordLockAnswerOf(null)).toEqual({ locked: false });
88124
});
89125
});
126+
127+
describe('useRecordApprovals — the data lock off the record page payload (objectstack#37773)', () => {
128+
it('a closed record: `dataLock` names `closed_state`, so the record reads closed and no approval opens — and no lock door is asked', async () => {
129+
const out = await seeded(
130+
{ requests: [], lock: { locked: false } },
131+
Promise.resolve({ locked: true, lockSource: 'record', lockReason: 'closed_state' }),
132+
);
133+
const now = out.hook.result.current;
134+
expect(now.dataLock).toEqual({ locked: true, lockSource: 'record', lockReason: 'closed_state' });
135+
expect(recordClosedByLock(now)).toBe(true);
136+
expect(openApprovalOf(now)).toBeNull();
137+
// The approvals panel's lock is the payload's approvals part, untouched.
138+
expect(now.recordLock).toEqual({ locked: false });
139+
// The payload answered it: the open sent no lock read of its own.
140+
expect(dataLockGets).toEqual([]);
141+
});
142+
143+
it('the data lock lands in the same publish as the approvals answer: no render sees one without the other', async () => {
144+
let resolveAnswer!: (a: SeededRecordApprovals) => void;
145+
const answer = new Promise<SeededRecordApprovals>((r) => { resolveAnswer = r; });
146+
const closed: DataRecordLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' };
147+
seedRecordApprovals(OBJECT, RECORD, answer, answer.then(() => closed));
148+
const seen: Array<[boolean, boolean]> = [];
149+
const hook = renderHook(() => {
150+
const r = useRecordApprovals(OBJECT, RECORD);
151+
seen.push([r.answered, r.dataLock !== null]);
152+
return r;
153+
}, { wrapper: withAdapter });
154+
await act(async () => { resolveAnswer({ requests: [], lock: { locked: false } }); });
155+
await waitFor(() => expect(hook.result.current.answered).toBe(true));
156+
expect(seen.some(([answered]) => answered)).toBe(true);
157+
expect(seen.filter(([answered, locked]) => answered !== locked)).toEqual([]);
158+
expect(dataLockGets).toEqual([]);
159+
});
160+
161+
it('a record held by an approval the reader cannot see: the data lock opens it, whatever the approvals-family lock says', async () => {
162+
const out = await seeded(
163+
{ requests: [], lock: { locked: false } },
164+
Promise.resolve({ locked: true, lockSource: 'record', lockReason: 'approval' }),
165+
);
166+
expect(recordClosedByLock(out)).toBe(false);
167+
expect(openApprovalOf(out)).toEqual({ locked: true });
168+
});
169+
170+
it('CONTROL: the approvals-family lock alone opens no approval for the affordances', async () => {
171+
const out = await seeded({ requests: [], lock: { locked: true, lockSource: 'record' } }, Promise.resolve({ locked: false }));
172+
expect(out.recordLock).toEqual({ locked: true, lockSource: 'record' });
173+
expect(openApprovalOf(out)).toBeNull();
174+
});
175+
176+
it("a refresh after the open is the hook's own read: it asks the data lock door once, and takes its answer", async () => {
177+
const out = await seeded({ requests: [], lock: { locked: false } }, Promise.resolve({ locked: false }));
178+
expect(dataLockGets).toEqual([]);
179+
dataLock = { locked: true, lockSource: 'record', lockReason: 'closed_state' };
180+
await act(async () => { await out.hook.result.current.refresh(); });
181+
expect(dataLockGets).toHaveLength(1);
182+
expect(recordClosedByLock(out.hook.result.current)).toBe(true);
183+
});
184+
185+
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 () => {
186+
const refused = Promise.reject(Object.assign(new Error('Data lock refused'), { status: 501, code: 'NOT_IMPLEMENTED' }));
187+
refused.catch(() => undefined);
188+
const out = await seeded({ requests: [], lock: { locked: false } }, refused);
189+
expect(out.hook.result.current.dataLock).toBeNull();
190+
await act(async () => { await out.hook.result.current.refresh(); });
191+
expect(dataLockGets).toEqual([]);
192+
expect(out.hook.result.current.dataLock).toBeNull();
193+
});
194+
});

0 commit comments

Comments
 (0)