Skip to content

Commit 40e22f1

Browse files
fix(approvals, list): a list cell waits for the record's approval lock before it edits, and a page's locks are read in one request (#35795) (#36295)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu3ktGWQBYiYJq1ThpuDKTbF)_ repo:objectstack#1 · os-sales · session_01L6bhgXSK9qt8je9QbZvhKb Fixes #35795 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 列表里直接改格子时:如果这条记录「是否被审批锁住」或「我能不能改这条」还没查回来,双击、回车、F2 或直接打字都不会立刻弹出编辑框,格子上先显示「正在确认这条记录能否编辑…」;答案一回来,没锁就自动打开编辑框(打的那个字也保留),锁了就显示「此记录正在审批中,已锁定。」。不会再出现「能进编辑、保存才被拒」。 - 查询中点了别的格子,就放弃这次等待,不会突然在别处弹出编辑框。查询中点开关、粘贴、清空:同样先提示正在确认,答案回来没锁才写入,锁了就不写并说明原因。 - 一页数据只发一个锁查询:第一次点格子时把整页的锁一起问;之后用方向键走动不再发请求。新增服务端批量接口 `POST /api/v1/approvals/records/:object/locks`(一次最多 200 条,读不到的记录和不存在的一样答 null),SDK 有对应方法。 - 风险:查询很慢时,用户第一次操作要等一下才出编辑框;没装审批服务的部署照旧(501 后不再问)。可直接撤回本 PR 回到原样。 - 需要你决定的:无。 ## What changes **Server (new route, contract, SDK).** - `IApprovalService.getRecordLocks?(object, recordIds, context)` (`packages/spec/src/contracts/approval-service.ts`, optional like `getRecordLock`): entry `i` answers `recordIds[i]` exactly as `getRecordLock` answers it (`{ locked }`, or `null` for an unreadable or missing record, never told apart). New export `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS = 200` (the explain batch's cap, so a page splits the same way for both reads). `api-surface/contracts.json` and `export-origins/contracts.json` regenerated. - `ApprovalService.getRecordLocks` (plugin-approvals): two engine reads whatever the page size: the caller's `id $in` read of the ids (the same anchor `getRecordLock` reads as the caller), then one pending-request lookup judged by the record-lock hook's own judgement through the new `recordsHeldByLockingApproval` (`lifecycle-hooks.ts`, the many-record form of `recordHeldByLockingApproval` over the same `lockingRequestsForRecords`). - `POST /api/v1/approvals/records/:object/locks` (`approvals-routes.ts`): body `{ "recordIds": [...] }` answers `{ success: true, data: { records: [{ recordId, locked }] } }` in order, `locked: null` where the single read answers 404. Closed query set EMPTY (`APPROVAL_RECORD_LOCKS_PARAMS`); the body is closed too (`readRecordLocksBody`): any other key, a non-list, a non-string or blank id, an empty list or more than the cap is refused whole with `400 VALIDATION_ERROR`, the service never asked. A service without `getRecordLocks` answers 501, never one `getRecordLock` per id. Route ledger row `sdk` → `client.approvals.getRecordLocks(object, recordIds)`. **List grid.** - `useRowApprovalLocks` asks the locks of the page in one request per `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS` ids when a cell is first selected (`ObjectGrid`'s `onCellSelect` passes the selected row plus the page's ids); rows already asked are not asked again, rows a later page brings are asked on the next select. It exposes `settling(recordId)`: the read the row waits on while it is on the wire. - `useRecordCrudVerdicts` exposes `settling()`: the explain questions on the wire as one promise (read from a ref, so it sees a question sent since the last render). - `ObjectGrid.describeCell`: when the cell has no read-only reason yet but the row's lock read, or its `update` verdict (when still unknown), is on the wire, the facts carry `checking: { text, settled }`. - `@object-ui/components` `GridCellFacts.checking` (optional, new): `data-table`'s `attemptEdit` shows `text` on the cell, remembers the edit (with its typed seed) and asks it again when `settled` settles, unless another cell was selected, a newer edit was asked or an editor is open by then. A toggle, paste or clear asked meanwhile shows `text` and writes nothing (an intrinsic refusal such as "required" is still said first). - i18n: `grid.readOnlyReason.checking` in all 11 locales plus the plugin's English fallback. Docs: `content/docs/automation/approvals.mdx` ("Reading the locks of a page of records"). Changeset `.changeset/35795-batched-record-lock-read.md` (patch on the seven packages the diff moves; `Metadata-protocol: none` ⇒ patch). ## Why PR #35747 read a row's lock with one `GET …/:recordId/lock` per selected row, sent on a double-click's first press and needed on its second. A slower answer let the editor open on a locked record and only the save was refused; the record verdict had the same window, and arrow keys sent one read per row (the L2 record 7034067196, S3 and N2). #35684 rules out 「能进编辑、保存被拒」. **Batch route over projection** (premise, accepted by the seat with the claim 7072869185): the lock is the approvals plugin's own judgement; projecting it into `GET /data/:object` would teach the data layer about approvals or add a virtual-field protocol and charge every list read, while a batch route is the same shape as the explain batch the list already sends, asked only when the reader first acts on a cell. ## Small calls made in this thread (Sales 22:19:27Z: listed here) - **Wait, then open** (the card's first arm) rather than "open nothing, say checking": the premise proposed the latter; building it showed that a real double-click on a fresh page (and every Playwright `dblclick`) would then always need a second double-click. The waiting edit is dropped by selecting another cell, so nothing opens elsewhere. - The lock and verdict of a page are asked on the first cell select (lazy, the #34208 posture), not on first paint. - The same cap as explain (200); a body with any other key is refused, like an unknown query name. - A row the caller cannot read (`locked: null`) and a failed read fall back to the `approval_status` column (fail open, as before; the server still refuses a locked write). - No principal key on the lock answers (unchanged from #35747): they are dropped on any data change of the object and on unmount. ## Verification Each new pin was run against the fix, then with the fix ablated. - `ObjectGrid.cellSelection-35684.test.tsx`, new top-level `describe` "an edit waits for the row's lock and verdict (objectstack#35795)", 7 cases with fake timers for the slow reads: a slow lock read on a locked row says checking for 1999 ms and then locked, never an editor; on an unlocked row the editor opens by itself when it answers; a key typed while checking is the editor's value; a slow verdict holds it the same way; selecting another cell drops the wait; a page sends one lock read and the arrow keys send none (lock or explain); a 501 deployment is asked once and edits. The existing lock case now reads the page in one request. Ablating the `checking` branch of `attemptEdit`: 5 of the 7 red, restored. - `rest-approvals-record-lock-route.test.ts`, new top-level `describe` for the route: preservation (service asked once with the ids in order and the caller; one entry per id; a full page at the cap), nine refusal shapes (400 + nested `VALIDATION_ERROR` + service never called), the empty closed query set, 501 when only `getRecordLock` exists (and it is not called), a read refusal relayed at its own status. - `record-lock-read.integration.test.ts` (real ObjectQL + better-sqlite3 + `ApprovalsServicePlugin.start()`), new top-level `describe`: for each of submitter, approver and a non-participant reader, the page answer equals `getRecordLock` per id (repeated ids, unreadable, missing); two engine reads for a page of three; an outsider is refused 403 as for one record; a blank id answers null; deciding unlocks the page as the hook does. - `client.test.ts`: one POST, object segment encoded, body `{ recordIds }`. - Local runs on the merged tree: see the next section. **Local runs** (merged tree, main `a5a5312f` + this branch, after `pnpm install --frozen-lockfile && pnpm build`): - `@objectstack/plugin-approvals` test: 126 files / 1,812 passed. `@objectstack/client`: 59 / 820 passed. `@objectstack/spec`: 869 files / 27,877 passed. `@objectstack/rest`: first run 2 red (the two write-route ledgers had no row for the new POST route); rows added (`no-record-echo` in the #8497 tripwire, a driven `approvals.getRecordLocks` row in the hook-refusal ledger), both files now 737 / 737. - Typecheck clean: rest, plugin-approvals, client, spec, ui plugin-grid, components, i18n. - UI (`packages/plugin-grid/ components/ plugin-list/ plugin-detail/ i18n/`): first run 18 red in 4 files: a paste / toggle / digit was dropped while checking (fixed: those writes now wait too, as the edit does), and `zh-Hant.ts` was not regenerated (fixed with `gen:zh-hant`). The six affected files then 102 / 102. A second full run of these packages is in progress; its result goes on this PR. - `spec check:generated`: `api-surface` and `export-origins` regenerated (one line each). `overlap-check.mjs`: clean against main and every open PR sharing a file (#36135, #36144, #36208). - Added after the seat's ask: `ObjectGrid.autosave-35685.test.tsx`, new top-level `describe` (2 cases, fake timers): a paste is not written for 1999 ms of a slow lock read and is written when it answers unlocked; on a locked answer it is never written and the cell says why. Ablating the wait in `writeCell`: both red, restored. ## Acceptance notes - **#36135** (draft) makes `getRecordLock` also answer `true` for a `master_detail` line of a locked record. This PR's batch answers the record half only. Whichever lands second carries the other half into `getRecordLocks` (the line half batched: one FK read of the page, one lookup per master object). `overlap-check.mjs` reads this branch clean against #36135 (it was moved off the lines #36135 edits). - The notice text stays on the cell until the answer arrives or the reader moves; it is not a toast. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (a contract interface member and a constant) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 block is the maintainer's summary, in the maintainer's language). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgXSK9qt8je9QbZvhKb)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgXSK9qt8je9QbZvhKb <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgXSK9qt8je9QbZvhKb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d8599c2 commit 40e22f1

34 files changed

Lines changed: 910 additions & 64 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/rest': patch
4+
'@objectstack/plugin-approvals': patch
5+
'@objectstack/client': patch
6+
'@object-ui/plugin-grid': patch
7+
'@object-ui/components': patch
8+
'@object-ui/i18n': patch
9+
---
10+
11+
fix(approvals, list): a list cell no longer opens an editor before it knows the record's approval lock, and the list reads the locks of a page in one request
12+
13+
Clause-②: yes (widening)
14+
Metadata-protocol: none
15+
16+
**What a list user sees.** On a list that edits in place, a double-click, Enter, F2 or a typed key on a cell whose record's approval lock or edit permission is still being read no longer opens an editor that the server would then refuse on save. The cell says "Checking whether this record can be edited…", and when the answer arrives the same edit goes ahead by itself (with the typed key), or the cell says why it does not: the record is locked while it is in approval, or the reader has no permission to edit it. Selecting another cell in the meantime drops the wait. Moving the selection with the arrow keys no longer sends a lock request per row: the first cell selected on a page asks the locks of every row on it at once.
17+
18+
**New route.** `POST /api/v1/approvals/records/:object/locks` with the body `{ "recordIds": ["<id>", ...] }` (at least one id, at most `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`, 200) answers `{ success: true, data: { records: [{ recordId, locked }] } }`, one entry per id in order. `locked` is what `GET /api/v1/approvals/records/:object/:recordId/lock` answers for that id, and `null` where that route answers 404: a record the caller cannot read and one that does not exist answer alike. Any other body (a key other than `recordIds`, an empty list, a non-string or blank id, more ids than the cap) and any query parameter are refused whole with `400 VALIDATION_ERROR`, never trimmed. A deployment whose approvals service does not implement the read answers `501`.
19+
20+
**Contract and SDK.** `IApprovalService` gains the optional member `getRecordLocks(object, recordIds, context)`, entry `i` answering `recordIds[i]` exactly as `getRecordLock` does; the approvals plugin implements it in two reads whatever the page size (the caller's read of the ids, then one pending-request lookup judged by the record-lock hook's own judgement). `@objectstack/spec/contracts` exports `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`. `@objectstack/client` gains `client.approvals.getRecordLocks(object, recordIds)`.
21+
22+
**Components.** `GridCellFacts` (the select-first table's per-cell facts) gains the optional `checking: { text, settled }`: while present, an edit asked on the cell shows `text` and is asked again when `settled` settles; a toggle, paste or clear shows `text` and writes nothing. A host that sets no `checking` sees no change.

‎content/docs/automation/approvals.mdx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,29 @@ SDK call is `client.approvals.getRecordLock(object, recordId)`, and the service
429429
member is `IApprovalService.getRecordLock`. An approvals service without that
430430
member answers `501`.
431431

432+
**Reading the locks of a page of records.** A list asks for every row on screen
433+
in one request rather than one per row:
434+
435+
```bash
436+
curl -b cookies.txt -X POST -H 'Content-Type: application/json' \
437+
-d '{"recordIds":["rec_123","rec_456","rec_789"]}' \
438+
"https://your-app.example.com/api/v1/approvals/records/expense/locks"
439+
# → { "success": true, "data": { "records": [
440+
# { "recordId": "rec_123", "locked": true },
441+
# { "recordId": "rec_456", "locked": false },
442+
# { "recordId": "rec_789", "locked": null } ] } }
443+
```
444+
445+
Each entry is what the single-record read answers for that id, in the order the
446+
ids were sent; `null` stands where that read answers `404`, so a record the
447+
caller cannot read and one that does not exist look the same. One request
448+
carries at most 200 ids (`APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`); a longer list,
449+
an empty one or any other body key is refused with `400 VALIDATION_ERROR`. The
450+
SDK call is `client.approvals.getRecordLocks(object, recordIds)`, the service
451+
member `IApprovalService.getRecordLocks`, and an approvals service without it
452+
answers `501`. A list that edits in place reads it when a cell is first
453+
selected, and holds an edit asked before the answer arrives until it does.
454+
432455
Only `approvers` is required on the node; everything else has a default
433456
(`behavior: 'first_response'`, `lockRecord: true`, `maxRevisions: 3`).
434457

‎packages/client/src/client.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,18 @@ describe('Approvals namespace (ADR-0019)', () => {
766766
expect(opts?.method ?? 'GET').toBe('GET');
767767
});
768768

769+
it('reads the approval locks of a page of records in one POST, object segment encoded', async () => {
770+
const records = [{ recordId: 'rec_1', locked: true }, { recordId: 'rec_2', locked: null }];
771+
const { client, fetchMock } = createMockClient({ success: true, data: { records } });
772+
const result = await client.approvals.getRecordLocks('sales order', ['rec_1', 'rec_2']);
773+
expect(result).toEqual({ records });
774+
expect(fetchMock).toHaveBeenCalledTimes(1);
775+
const [url, opts] = fetchMock.mock.calls[0];
776+
expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/sales%20order/locks');
777+
expect(opts.method).toBe('POST');
778+
expect(JSON.parse(opts.body)).toEqual({ recordIds: ['rec_1', 'rec_2'] });
779+
});
780+
769781
it('should record an approve decision', async () => {
770782
const { client, fetchMock } = createMockClient({
771783
request: { id: 'req-1', status: 'approved' }, finalized: true, decision: 'approve', resumed: true

‎packages/client/src/index.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7095,6 +7095,26 @@ export class ObjectStackClient {
70957095
return this.unwrapResponse<{ locked: boolean }>(res);
70967096
},
70977097

7098+
/**
7099+
* Whether each of a page of records of one object is held by a locking
7100+
* approval, in one request (`IApprovalService.getRecordLocks`): entry `i`
7101+
* answers `recordIds[i]` with what {@link getRecordLock} answers for that
7102+
* id, a record the caller cannot read (or that does not exist) as
7103+
* `locked: null`. At most `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS` ids per
7104+
* call, else 400; a deployment without the read answers 501.
7105+
*/
7106+
getRecordLocks: async (
7107+
object: string,
7108+
recordIds: readonly string[],
7109+
): Promise<{ records: Array<{ recordId: string; locked: boolean | null }> }> => {
7110+
const route = this.getRoute('approvals');
7111+
const res = await this.fetch(`${this.baseUrl}${route}/records/${encodeURIComponent(object)}/locks`, {
7112+
method: 'POST',
7113+
body: JSON.stringify({ recordIds: [...recordIds] }),
7114+
});
7115+
return this.unwrapResponse<{ records: Array<{ recordId: string; locked: boolean | null }> }>(res);
7116+
},
7117+
70987118
/**
70997119
* Record an approve decision on a request. Finalises the request when the
71007120
* node's behaviour is satisfied and resumes the owning flow run.

‎packages/plugins/plugin-approvals/src/approval-service.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ import {
156156
type ReaderLabels,
157157
} from './reader-locale-labels.js';
158158
import type { SlotLabelSource } from './display-label-backfill.js';
159+
import { recordsHeldByLockingApproval } from './lifecycle-hooks.js';
159160
import {
160161
redactSnapshot,
161162
resolveReadableSnapshotFields,
@@ -10992,6 +10993,37 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1099210993
return fresh;
1099310994
}
1099410995

10996+
/**
10997+
* `IApprovalService.getRecordLocks` — {@link getRecordLock} for a page of
10998+
* rows, in two reads whatever the page size: the caller's read of the ids
10999+
* (the same #8652 anchor, one `$in` read AS THE CALLER, so an unreadable row
11000+
* and a missing one both answer `null` and stay indistinguishable) and one
11001+
* pending-request lookup judged by the record-lock hook's own judgement
11002+
* ({@link recordsHeldByLockingApproval}). Entry `i` answers `recordIds[i]`.
11003+
*
11004+
* The cap is the door's to refuse loudly; here a blank id answers `null`.
11005+
*/
11006+
async getRecordLocks(
11007+
object: string,
11008+
recordIds: readonly string[],
11009+
context: ExecutionContext,
11010+
): Promise<Array<{ locked: boolean } | null>> {
11011+
const objectName = String(object ?? '').trim();
11012+
const ids = recordIds.map((recordId) => String(recordId ?? '').trim());
11013+
const asked = Array.from(new Set(ids.filter((id) => id !== '')));
11014+
if (!objectName || asked.length === 0) return ids.map(() => null);
11015+
// The anchor. As the CALLER — see getRecordLock's doc block.
11016+
const readable = await this.engine.find(objectName, {
11017+
where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context,
11018+
});
11019+
const readableIds = new Set((Array.isArray(readable) ? readable : []).map((row: any) => String(row?.id)));
11020+
const readableAsked = asked.filter((id) => readableIds.has(id));
11021+
const held = readableAsked.length > 0
11022+
? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked)
11023+
: new Set<string>();
11024+
return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) } : null));
11025+
}
11026+
1099511027
async getRequest(requestId: string, context: ExecutionContext): Promise<ApprovalRequestRow | null> {
1099611028
return this.loadRequest(requestId, context, true);
1099711029
}

‎packages/plugins/plugin-approvals/src/lifecycle-hooks.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,23 @@ async function lockingRequestsForRecords(
526526
return gating.filter((pending) => nodeConfigLocksRecord(parseJson<unknown>(pending?.node_config_json, {})));
527527
}
528528

529+
/**
530+
* {@link recordHeldByLockingApproval} for many records of one object at once:
531+
* the ids among `recordIds` held by a LOCKING pending approval. One
532+
* pending-request lookup for the whole list and the same judgement, so a page
533+
* asked at once and a record asked alone cannot disagree.
534+
*
535+
* ⚠️ Like the one-record form, it answers for the records, not for a caller.
536+
*/
537+
export async function recordsHeldByLockingApproval(
538+
engine: Pick<MinimalEngine, 'find'>,
539+
objectName: string,
540+
recordIds: ReadonlyArray<string>,
541+
): Promise<Set<string>> {
542+
const held = await lockingRequestsForRecords(engine, objectName, recordIds);
543+
return new Set(held.map((pending) => String(pending?.record_id ?? '')));
544+
}
545+
529546
/**
530547
* Narrow `candidates` (pending requests) to the ones whose record the caller's
531548
* predicate actually matches — asked of the engine as an intersection, so the

‎packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,56 @@ async function writeAs(rig: Rig, userId: string, object: string, recordId: strin
178178
}
179179
}
180180

181+
/**
182+
* `ApprovalService.getRecordLocks` — the same read for a page of rows: entry
183+
* `i` is what `getRecordLock` answers for `recordIds[i]`, so a list asking a
184+
* page at once and a record page asking one record cannot disagree.
185+
*/
186+
describe('ApprovalService.getRecordLocks — the lock read for a page of rows', () => {
187+
it('answers each id in order exactly as getRecordLock answers it, for every caller', async () => {
188+
const rig = await boot();
189+
const ids = [recordA(HELD), recordB(HELD), MISSING, recordA(HELD)];
190+
for (const caller of [SUBMITTER, APPROVER, READER]) {
191+
const page = await rig.svc.getRecordLocks(HELD, ids, asUser(caller));
192+
const oneByOne = [];
193+
for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(HELD, id, asUser(caller)));
194+
expect(page, caller).toEqual(oneByOne);
195+
}
196+
// The reader: `_a` locked; `_b` unreadable and `MISSING` absent read alike.
197+
expect(await rig.svc.getRecordLocks(HELD, ids, asUser(READER))).toEqual([{ locked: true }, null, null, { locked: true }]);
198+
expect(await rig.svc.getRecordLocks(OPEN, [recordA(OPEN), recordB(OPEN)], asUser(SUBMITTER)))
199+
.toEqual([{ locked: false }, { locked: false }]);
200+
});
201+
202+
it('reads the page in two engine reads whatever its size, never one per row', async () => {
203+
const rig = await boot();
204+
const find = rig.engine.find.bind(rig.engine);
205+
const reads: string[] = [];
206+
(rig.engine as any).find = (object: string, query: any) => {
207+
reads.push(object);
208+
return find(object, query);
209+
};
210+
await rig.svc.getRecordLocks(HELD, [recordA(HELD), recordB(HELD), MISSING], asUser(SUBMITTER));
211+
expect(reads).toEqual([HELD, 'sys_approval_request']);
212+
});
213+
214+
it('refuses a caller with no read on the object as getRecordLock does, and answers a blank id null', async () => {
215+
const rig = await boot();
216+
const refusal = await rig.svc.getRecordLocks(HELD, [recordA(HELD)], asUser(OUTSIDER)).then(
217+
() => 'answered', (err: any) => `${err?.code} ${err?.status}`,
218+
);
219+
expect(refusal).toBe('PERMISSION_DENIED 403');
220+
expect(await rig.svc.getRecordLocks(HELD, ['', recordA(HELD)], asUser(READER))).toEqual([null, { locked: true }]);
221+
});
222+
223+
it('unlocks the page once the request is decided, as the hook does', async () => {
224+
const rig = await boot();
225+
await rig.svc.decide(rig.requests.get(HELD)!, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER));
226+
expect(await rig.svc.getRecordLocks(HELD, [recordA(HELD)], asUser(READER))).toEqual([{ locked: false }]);
227+
expect(await writeAs(rig, READER, HELD, recordA(HELD))).toBe('written');
228+
});
229+
});
230+
181231
describe('[#26314] ApprovalService.getRecordLock', () => {
182232
it('tells a non-participant reader the record is locked, and nothing about the request', async () => {
183233
const rig = await boot();

‎packages/rest/src/approvals-routes.ts‎

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,11 @@ import { strandedDecisionDetails, sendError as sendEnvelopeError, sendOk } from
5252
// object's select options are built FROM this list (#3786), so it is the
5353
// object's own declaration, read where the object reads it, and not a second
5454
// list kept beside it.
55-
import { APPROVAL_STATUSES, type ApprovalStatus } from '@objectstack/spec/contracts';
55+
import {
56+
APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS,
57+
APPROVAL_STATUSES,
58+
type ApprovalStatus,
59+
} from '@objectstack/spec/contracts';
5660
import {
5761
classifiedRefusalAnswer,
5862
nestedRefusalEnvelope,
@@ -79,6 +83,52 @@ import {
7983
*/
8084
export const APPROVAL_RECORD_LOCK_PARAMS: readonly string[] = [];
8185

86+
/**
87+
* The closed query-parameter set of
88+
* `POST {basePath}/approvals/records/:object/locks`: EMPTY. **Measured**: the
89+
* handler reads the object from the path and the ids from the body, nothing
90+
* from the query string (the caller's context comes from the session and
91+
* headers). A name sent there is refused with the located 400, never dropped.
92+
*/
93+
export const APPROVAL_RECORD_LOCKS_PARAMS: readonly string[] = [];
94+
95+
/** The body keys `POST {basePath}/approvals/records/:object/locks` reads: `recordIds` alone. */
96+
const APPROVAL_RECORD_LOCKS_BODY_KEYS: readonly string[] = ['recordIds'];
97+
98+
/**
99+
* Read the body of `POST {basePath}/approvals/records/:object/locks`: the ids,
100+
* or the sentence that refuses the request. Every shape is refused whole,
101+
* never trimmed: a body key the door does not read, a `recordIds` that is not
102+
* a list of non-empty strings, an empty list and one over
103+
* {@link APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS}.
104+
*/
105+
export function readRecordLocksBody(body: unknown): { recordIds: string[] } | { refusal: string } {
106+
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
107+
return { refusal: 'The request body must be a JSON object of the form {"recordIds": ["<id>", ...]}.' };
108+
}
109+
const unknown = Object.keys(body).filter((key) => !APPROVAL_RECORD_LOCKS_BODY_KEYS.includes(key));
110+
if (unknown.length > 0) {
111+
return {
112+
refusal: `Unknown body field${unknown.length > 1 ? 's' : ''} ${unknown.map((key) => `"${key}"`).join(', ')}: `
113+
+ 'this request reads "recordIds" alone. Nothing was read.',
114+
};
115+
}
116+
const ids = (body as { recordIds?: unknown }).recordIds;
117+
if (!Array.isArray(ids) || ids.some((id) => typeof id !== 'string' || id.trim() === '')) {
118+
return { refusal: '"recordIds" must be a list of record ids, each a non-empty string.' };
119+
}
120+
if (ids.length === 0) {
121+
return { refusal: '"recordIds" names no record; send at least one id.' };
122+
}
123+
if (ids.length > APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS) {
124+
return {
125+
refusal: `"recordIds" carries ${ids.length} ids; one request carries at most `
126+
+ `${APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS}. Send the rest in another request. Nothing was read.`,
127+
};
128+
}
129+
return { recordIds: ids as string[] };
130+
}
131+
82132
/**
83133
* [#29880] Read `?status=` on `GET {basePath}/approvals/requests` against the
84134
* value set `sys_approval_request.status` declares.
@@ -466,6 +516,43 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s
466516
metadata: { summary: 'Whether a record is held by a locking approval', tags: ['approvals'] },
467517
});
468518

519+
// The lock of a PAGE of records, in one request: what a list asks before it
520+
// opens a cell editor, so moving through the rows sends no request per row.
521+
// Each entry is exactly the single-record door's answer for that id, the
522+
// 404 folded to `locked: null` (unreadable or missing, told apart by
523+
// nothing); a service without `getRecordLocks` answers 501, never one
524+
// `getRecordLock` per id.
525+
this.routeManager.register({
526+
method: 'POST',
527+
path: `${dataPath}/approvals/records/:object/locks`,
528+
handler: async (req: any, res: any) => {
529+
try {
530+
const environmentId = isScoped ? req.params?.environmentId : undefined;
531+
const context = await this.resolveExecCtx(environmentId, req);
532+
if (this.enforceAuth(req, res, context)) return;
533+
if (refuseUnknownQueryParams(req, res, APPROVAL_RECORD_LOCKS_PARAMS)) return;
534+
const read = readRecordLocksBody(req.body);
535+
if ('refusal' in read) {
536+
sendEnvelopeError(res, 400, 'VALIDATION_ERROR', read.refusal);
537+
return;
538+
}
539+
const svc = await resolveService(environmentId, req);
540+
if (!svc || typeof svc.getRecordLocks !== 'function') return respond501(res);
541+
const { object } = req.params;
542+
const answers = await svc.getRecordLocks(object, read.recordIds, context ?? {});
543+
sendOk(res, {
544+
records: read.recordIds.map((recordId, index) => ({
545+
recordId,
546+
locked: answers[index] ? answers[index]!.locked === true : null,
547+
})),
548+
});
549+
} catch (error: any) {
550+
handleRouteError(res, error);
551+
}
552+
},
553+
metadata: { summary: 'Whether each of a page of records is held by a locking approval', tags: ['approvals'] },
554+
});
555+
469556
// Record a decision on a node-driven request. Both branches funnel
470557
// through the contract's `decide()`, which finalizes the request and
471558
// resumes the owning flow run down the matching `approve` / `reject`

0 commit comments

Comments
 (0)