Skip to content

Commit dc5cf70

Browse files
committed
fix(approvals, list): a list cell waits for the record's approval lock before it edits, and the lock of a page is read in one request (#35795)
- New route POST /api/v1/approvals/records/:object/locks ({ recordIds }, at most APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS), answering one entry per id exactly as the single-record lock read does (null where it answers 404). - IApprovalService.getRecordLocks (optional), implemented by the approvals plugin in two reads whatever the page size; client.approvals.getRecordLocks; route ledger row. - ObjectGrid asks the locks of the whole page on the first cell select, and an edit asked while the row's lock or update verdict is on its way waits for it (GridCellFacts.checking) instead of opening an editor the server would refuse. Claude-Session: https://claude.ai/code/session_01L6bhgXSK9qt8je9QbZvhKb Co-authored-by: Claude <noreply@anthropic.com>
1 parent 48c732c commit dc5cf70

31 files changed

Lines changed: 743 additions & 63 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 the record is locked while it is in approval. 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
@@ -154,6 +154,7 @@ import {
154154
type ReaderLabels,
155155
} from './reader-locale-labels.js';
156156
import type { SlotLabelSource } from './display-label-backfill.js';
157+
import { recordsHeldByLockingApproval } from './lifecycle-hooks.js';
157158
import {
158159
redactSnapshot,
159160
resolveReadableSnapshotFields,
@@ -10963,6 +10964,37 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1096310964
return fresh;
1096410965
}
1096510966

10967+
/**
10968+
* `IApprovalService.getRecordLocks` — {@link getRecordLock} for a page of
10969+
* rows, in two reads whatever the page size: the caller's read of the ids
10970+
* (the same #8652 anchor, one `$in` read AS THE CALLER, so an unreadable row
10971+
* and a missing one both answer `null` and stay indistinguishable) and one
10972+
* pending-request lookup judged by the record-lock hook's own judgement
10973+
* ({@link recordsHeldByLockingApproval}). Entry `i` answers `recordIds[i]`.
10974+
*
10975+
* The cap is the door's to refuse loudly; here a blank id answers `null`.
10976+
*/
10977+
async getRecordLocks(
10978+
object: string,
10979+
recordIds: readonly string[],
10980+
context: ExecutionContext,
10981+
): Promise<Array<{ locked: boolean } | null>> {
10982+
const objectName = String(object ?? '').trim();
10983+
const ids = recordIds.map((recordId) => String(recordId ?? '').trim());
10984+
const asked = Array.from(new Set(ids.filter((id) => id !== '')));
10985+
if (!objectName || asked.length === 0) return ids.map(() => null);
10986+
// The anchor. As the CALLER — see getRecordLock's doc block.
10987+
const readable = await this.engine.find(objectName, {
10988+
where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context,
10989+
});
10990+
const readableIds = new Set((Array.isArray(readable) ? readable : []).map((row: any) => String(row?.id)));
10991+
const readableAsked = asked.filter((id) => readableIds.has(id));
10992+
const held = readableAsked.length > 0
10993+
? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked)
10994+
: new Set<string>();
10995+
return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) } : null));
10996+
}
10997+
1096610998
async getRequest(requestId: string, context: ExecutionContext): Promise<ApprovalRequestRow | null> {
1096710999
return this.loadRequest(requestId, context, true);
1096811000
}

‎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)