Skip to content

Commit 1de73c0

Browse files
feat(rest): the record page composite lock carries lockSource, and the record page hides Delete on a master-held line (#38829)
repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2 Fixes #37195 Clause-②: yes (widening: the record page composite's published `lock` gains `lockSource`, and the published `@object-ui/types` `RecordPagePayload.approvals.lock` gains the same optional `lockSource`) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:审批锁住主单时,明细行的记录页不再显示「删除」;明细行被自己的审批锁住、或没有被锁时,「删除」照旧显示。 - 为什么做:把「被谁锁」这一条已定的裁决(表格已经按它隐藏删除)带到记录页,让记录页不再提供服务器必然拒绝的删除。 - 出错会怎样:最坏情况是明细行在主单被锁时仍显示「删除」,点了之后服务器照样拒绝,数据不受影响;改动可以直接撤回。 - 要你做什么:无。 ## What changes - **Spec** (`packages/spec/src/api/record-page.zod.ts`): the `approvals` part's `lock` gains the optional member `lockSource: 'record' | 'master'` beside `locked`. Before, the object was non-strict, so a parse silently stripped the kind. Regenerated `packages/spec/docs/references/api/record-page.md` with `gen:docs`. - **REST** (`packages/rest/src/record-page-routes.ts`): the composite now builds its lock through `recordLockPayload`, the projection both lock doors already serve (now exported from `approvals-routes.ts`; the package index does not re-export it). So the fifth door answers `lockSource` by construction, drops any other field a service returns, and serves `{ locked: true }` alone when the service names no kind. `null` still means unreadable, missing, or no lock service. - **Console** (`ui/packages/app-shell`): `useRecordApprovals` keeps the kind (`recordLock` passes it through; a new `lockSource` result field keeps it beside a visible pending request too, since the composite answers the lock either way). `recordLockAnswerOf` reads the lock door's untyped answer the way the grid's `useRowApprovalLocks` does; the composite answer is read through its type. A new helper `views/recordDeleteHeldByMaster.ts` holds the rule, and `RecordDetailView` only calls it: Delete goes on `lockSource: 'master'`, as the grid's row menu does. - **Types** (`ui/packages/types/src/data.ts`): the published `@object-ui/types` `RecordPagePayload.approvals.lock` gains the same optional `lockSource?: 'record' | 'master'`, so the client type matches the wire; the hook's composite path reads the kind through that type, and only the untyped lock-door fetch keeps a runtime narrowing (`recordLockAnswerOf`), as the grid does. Read first, by risk: 1. `ui/packages/app-shell/src/hooks/useRecordApprovals.ts`, the seeded branch of `startRead`: the kind is kept beside a pending row, while `recordLock` stays `null` there as before. 2. `packages/rest/src/record-page-routes.ts`, the `answerApprovals` lock lines. 3. `packages/spec/src/api/record-page.zod.ts`, the widened `lock` object. ## Tests - `packages/rest/src/record-page-routes.test.ts`: parity pin. The same mocked service answers both the composite and `GET /approvals/records/:object/:recordId/lock` on one server. The composite's `approvals.lock` equals the single door's `data` in the four card cases (own approval; line of a held master; self-held line under a held master; unheld) plus a locked answer naming no kind. A `null` answer stays a `null` lock. - `packages/spec/src/api/record-page.test.ts`: the parse keeps `lockSource` and refuses an unknown kind at `['lock', 'lockSource']`. - `ui/packages/app-shell/src/hooks/useRecordApprovals.lockSource-37195.test.tsx`: the seeded (composite) path in the same four cases, including the kind beside a visible pending row. - `ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx`, block `deleteFollowsLockSource-37195`: the real page's overflow menu has no Delete on `master`, and keeps Delete on `record`, unheld, and on a locked answer naming no kind. Ablations, each restored with `git checkout HEAD`. Reverting the route to the old `{ locked }` projection turns 3 parity cases red (the 3 locked-with-kind cases; unheld and no-kind stay green, as expected). Dropping the view's `recordDeleteHeldByMaster` call turns the `master` case red. ## Acceptance notes - PM hypothesis falsified: `MetadataLockSourceSchema` (`packages/spec/src/kernel/metadata-protection.zod.ts`) is the metadata-protection enum (`artifact | package | env-forced`), not the approval kind. The approval kind has no Zod schema anywhere in spec; it is a TypeScript literal union on `IApprovalService.getRecordLock`. The kind is therefore declared inline, in the one schema that needs it, with no new export: `check:api-surface` is unchanged. - `ui/packages/app-shell/src/views/recordPagePayload.ts` needed no change: it hands `answer.lock` through, now typed with `lockSource`. - The fallback read (an adapter without `getRecordPage`, or `refresh()` after a decision) does not ask the lock door when the viewer can see a pending request, as before. On that path a self-held line under a held master keeps Delete until the next page read. This fails open: the server still refuses with `RECORD_LOCKED`. The composite path, which is the record page's normal read, answers the kind in that case. - Out of scope, as the claim says: the two loose-id rows on the card (7152712740, 7153086539) stay open there. This build does not touch the doors' anchoring. ## Verification Two-minute check: `pnpm --filter @objectstack/rest exec vitest run src/record-page-routes.test.ts`. Expected: the five `lockSource` parity cases and the null case pass. <details><summary>Local gates (head 6fae497)</summary> - Local gates (head 6fae497): `dispatch-gates --ran`: 97 derived families, 96 run with exit 0 (including `pnpm --dir ui exec vitest run scripts/`: 172 files, 5159 tests passed), 1 NOT MEASURED: `check:dual-build-cjs-loads` PREREQUISITE NOT MET because there is no repo-wide dist (exit 3), owed to CI. `@object-ui/types` build (cache miss; `dist/data.d.ts` carries `lockSource`) and type-check exit 0; `@object-ui/app-shell` type-check exit 0; `@objectstack/spec check:generated` exit 0. - UI consumers of `useRecordApprovals` / `seedRecordApprovals` / `recordPagePayload`: 37 files, 331 tests passed (round 0). </details> L2: a published schema widens, so a contract-tier review is owed. --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d7d4605 commit 1de73c0

13 files changed

Lines changed: 411 additions & 21 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/rest': patch
4+
'@object-ui/types': patch
5+
---
6+
7+
feat(rest): the record page composite's approval lock says which approval holds the record (`lockSource`), as the lock doors do
8+
9+
Clause-②: yes (widening: the record page composite's published `lock` gains `lockSource`)
10+
Metadata-protocol: none
11+
12+
Widened: `RecordPageApprovalsSchema`'s `lock` (the `approvals` part of `POST /data/:object/:id/page`) gains the optional member `lockSource: 'record' | 'master'`, present on a locked record only; `@object-ui/types`'s `RecordPagePayload.approvals.lock` gains the same optional `lockSource`.
13+
14+
The record page's one read now answers its approval lock through the same projection as `GET /approvals/records/:object/:recordId/lock` and `POST /approvals/records/:object/locks`: `locked`, and on a locked record which approval holds it, `record` (its own) or `master` (the master of a master-detail line; it wins when both hold). A locked answer from a service that names no kind is still served `{ locked: true }` alone, and `null` still means the deployment answers no lock or the record is unreadable or missing. Before this, the composite served `{ locked }` only, so a record page could not tell a line held by its own approval, which may be deleted, from a line of a held master, whose delete the server refuses with `RECORD_LOCKED`. The Console's record page now hides Delete on `lockSource: 'master'`, as the grid's row menu does.

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,11 @@ export function readRecordLocksBody(body: unknown): { recordIds: string[] } | {
136136
* implementation hands back (a request id, a `pending` flag) is never served:
137137
* the answer stays one lock bit plus one kind bit (#8652 ruling 5299823744).
138138
* A locked answer from an implementation that names no kind is served
139-
* `{ locked: true }` alone, never a guessed kind.
139+
* `{ locked: true }` alone, never a guessed kind. The record page composite
140+
* (`record-page-routes.ts`) serves its `approvals.lock` through this too, so
141+
* the fifth door cannot answer a different lock than these two.
140142
*/
141-
function recordLockPayload(
143+
export function recordLockPayload(
142144
lock: { locked: boolean; lockSource?: unknown },
143145
): { locked: boolean; lockSource?: 'record' | 'master' } {
144146
if (lock.locked !== true) return { locked: false };

‎packages/rest/src/record-page-routes.test.ts‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ function boot(opts: BootOpts = {}) {
153153
await route.handler({ method: 'POST', params, query, headers: {}, body } as any, res);
154154
return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] };
155155
};
156-
return { getData, findData, call, apiGate };
156+
return { getData, findData, call, apiGate, rest };
157157
}
158158

159159
const recordNotFound = () => Object.assign(new Error('Record a1 not found in account'), {
@@ -830,3 +830,47 @@ describe('[#30343] one action is one entry in the timeline count, as the 动态
830830
expect(data.timeline).toEqual({ total: 3 });
831831
});
832832
});
833+
834+
describe('the approval part\'s lock answers `lockSource` exactly as the single lock door does', () => {
835+
// What `IApprovalService.getRecordLock` answers in each case the contract
836+
// names; the extra `requestId` is a field neither door may serve.
837+
const CASES: Array<[string, unknown]> = [
838+
['a record held by its own approval', { locked: true, lockSource: 'record', requestId: 'ar1' }],
839+
['a line of a held master', { locked: true, lockSource: 'master', requestId: 'ar9' }],
840+
['a self-held line under a held master (the master wins)', { locked: true, lockSource: 'master', requestId: 'ar9' }],
841+
['an unheld record', { locked: false }],
842+
['a locked answer that names no kind', { locked: true }],
843+
];
844+
845+
for (const [name, served] of CASES) {
846+
it(name, async () => {
847+
const approvals = {
848+
listRequests: vi.fn().mockResolvedValue([]),
849+
getRecordLock: vi.fn().mockResolvedValue(served),
850+
};
851+
const { call, rest } = boot({ approvals });
852+
const page = await call({ approvals: true });
853+
expect(page.status).toBe(200);
854+
const composite = RecordPageResponseSchema.parse(page.body.data).approvals;
855+
856+
const door = (rest as any).getRoutes().find(
857+
(r: any) => r.method === 'GET' && r.path === '/api/v1/approvals/records/:object/:recordId/lock',
858+
);
859+
const res = mockRes();
860+
await door.handler({ method: 'GET', params: { object: 'account', recordId: 'a1' }, query: {}, headers: {}, body: {} } as any, res);
861+
expect(res.statusCode).toBe(200);
862+
const single = res.json.mock.calls.at(-1)?.[0]?.data;
863+
864+
expect(composite).toEqual({ requests: [], lock: single });
865+
expect(single).not.toHaveProperty('requestId');
866+
expect(approvals.getRecordLock.mock.calls).toEqual([['account', 'a1', CTX], ['account', 'a1', CTX]]);
867+
});
868+
}
869+
870+
it('an unreadable or missing record is still a null lock, where the door answers 404', async () => {
871+
const approvals = { listRequests: vi.fn().mockResolvedValue([]), getRecordLock: vi.fn().mockResolvedValue(null) };
872+
const { call } = boot({ approvals });
873+
const page = await call({ approvals: true });
874+
expect(RecordPageResponseSchema.parse(page.body.data).approvals).toEqual({ requests: [], lock: null });
875+
});
876+
});

‎packages/rest/src/record-page-routes.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import { measureServerTiming } from '@objectstack/observability';
4848
import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY, sendError, sendOk } from '@objectstack/types';
4949
import { recordNotFoundError } from '@objectstack/core';
5050
import { refuseUnknownQueryParams } from './query-allowlist.js';
51+
import { recordLockPayload } from './approvals-routes.js';
5152
import { logUnexpectedRouteError, mapDataError, nestedRefusalEnvelope } from './error-response.js';
5253
import type { ServerScopedDataRequest } from './data-action-routes.js';
5354
import { apiAccessDenialFromEnable, type RestServer } from './rest-server.js';
@@ -482,10 +483,14 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath:
482483
if (full && full.id === pending.id) enriched = { ...pending, ...full };
483484
}
484485
const requests = enriched ? rows.map((r) => (r === pending ? enriched : r)) : rows;
485-
let lock: { locked: boolean } | null = null;
486+
// The lock door's own projection (`recordLockPayload`):
487+
// `locked`, and `lockSource` on a locked record, so the
488+
// page tells a line held by its own approval from one
489+
// held by its master's, as the grid does.
490+
let lock: ReturnType<typeof recordLockPayload> | null = null;
486491
if (typeof svc.getRecordLock === 'function') {
487492
const answer = await svc.getRecordLock(object, id, context ?? {});
488-
lock = answer ? { locked: answer.locked === true } : null;
493+
lock = answer ? recordLockPayload(answer) : null;
489494
}
490495
return { requests, lock };
491496
} catch (error) {

‎packages/spec/docs/references/api/record-page.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,14 @@ const result = RecordPageActivityRequestSchema.parse(data);
8989
| Property | Type | Required | Description |
9090
| :--- | :--- | :--- | :--- |
9191
| **requests** | `Record<string, any>[]` | ✅ | The record's approval requests the caller may see, as `GET /approvals/requests` lists them for the record; empty when the deployment runs no approval service. |
92-
| **lock** | `{ locked: boolean } \| null` | ✅ | Whether a locking approval holds the record; null when the deployment answers no lock. |
92+
| **lock** | `{ locked: boolean; lockSource?: Enum<'record' \| 'master'> } \| null` | ✅ | Whether a locking approval holds the record, and which one; null when the deployment answers no lock. |
93+
94+
### Nested Shape: `RecordPageApprovals.lock`
95+
96+
| Property | Type | Required | Description |
97+
| :--- | :--- | :--- | :--- |
98+
| **locked** | `boolean` | ✅ | Whether a locking approval holds the record. |
99+
| **lockSource** | `Enum<'record' \| 'master'>` | optional | On a locked record only, which approval holds it, as `GET /approvals/records/{object}/{id}/lock` answers it: `record` (its own approval) or `master` (the master of a master-detail line; it wins when both hold). Absent on an unlocked record, and on a locked one whose service names no kind. |
93100

94101

95102
---
@@ -498,7 +505,7 @@ This schema accepts one of the following structures:
498505
| Property | Type | Required | Description |
499506
| :--- | :--- | :--- | :--- |
500507
| **requests** | `Record<string, any>[]` | ✅ | The record's approval requests the caller may see, as `GET /approvals/requests` lists them for the record; empty when the deployment runs no approval service. |
501-
| **lock** | `{ locked: boolean } \| null` | ✅ | Whether a locking approval holds the record; null when the deployment answers no lock. |
508+
| **lock** | `{ locked: boolean; lockSource?: Enum<'record' \| 'master'> } \| null` | ✅ | Whether a locking approval holds the record, and which one; null when the deployment answers no lock. |
502509

503510
### Nested Shape: `RecordPageResponse.approvals[option 2]`
504511

‎packages/spec/src/api/record-page.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES,
99
RECORD_TIMELINE_UPDATE_ACTIVITY_TYPE,
1010
RECORD_PAGE_MAX_ATTACHMENT_ROWS,
11+
RecordPageApprovalsSchema,
1112
RecordPageDiscussionSchema,
1213
RecordPageExplainOperationSchema,
1314
RecordPageRelatedAnswerSchema,
@@ -156,3 +157,23 @@ describe('[#28737] the timeline part names its sources strictly and answers the
156157
}
157158
});
158159
});
160+
161+
describe('the approval part\'s lock carries which approval holds the record, as the lock door answers it', () => {
162+
it('keeps `lockSource` beside `locked`, and still takes an answer without it and a null lock', () => {
163+
for (const lock of [
164+
{ locked: true, lockSource: 'record' },
165+
{ locked: true, lockSource: 'master' },
166+
{ locked: true },
167+
{ locked: false },
168+
null,
169+
]) {
170+
expect(RecordPageApprovalsSchema.parse({ requests: [], lock }).lock, JSON.stringify(lock)).toEqual(lock);
171+
}
172+
});
173+
174+
it('refuses a kind the lock door never answers', () => {
175+
const answer = RecordPageApprovalsSchema.safeParse({ requests: [], lock: { locked: true, lockSource: 'package' } });
176+
expect(answer.success).toBe(false);
177+
expect(answer.error?.issues[0]?.path).toEqual(['lock', 'lockSource']);
178+
});
179+
});

‎packages/spec/src/api/record-page.zod.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,8 +318,15 @@ export const RecordPageApprovalsSchema = lazySchema(() => z.object({
318318
'The record\'s approval requests the caller may see, as `GET /approvals/requests` lists them for the record; '
319319
+ 'empty when the deployment runs no approval service.',
320320
),
321-
lock: z.object({ locked: z.boolean() }).nullable().describe(
322-
'Whether a locking approval holds the record; null when the deployment answers no lock.',
321+
lock: z.object({
322+
locked: z.boolean().describe('Whether a locking approval holds the record.'),
323+
lockSource: z.enum(['record', 'master']).optional().describe(
324+
'On a locked record only, which approval holds it, as `GET /approvals/records/{object}/{id}/lock` '
325+
+ 'answers it: `record` (its own approval) or `master` (the master of a master-detail line; it wins '
326+
+ 'when both hold). Absent on an unlocked record, and on a locked one whose service names no kind.',
327+
),
328+
}).nullable().describe(
329+
'Whether a locking approval holds the record, and which one; null when the deployment answers no lock.',
323330
),
324331
}));
325332
export type RecordPageApprovals = z.input<typeof RecordPageApprovalsSchema>;
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#37195 — the record page's approvals read keeps the lock's
11+
* `lockSource`, which approval holds the record: its own (`'record'`) or, for
12+
* a master-detail line, its master's (`'master'`). The composite payload
13+
* (`POST /data/:object/:id/page`) answers the lock beside the rows whether or
14+
* not a pending request decides it, so the kind is kept beside a pending
15+
* request too — a self-held line under a held master answers `'master'`.
16+
*/
17+
18+
import { describe, it, expect, afterEach } from 'vitest';
19+
import { renderHook, waitFor, act } from '@testing-library/react';
20+
import {
21+
__resetRecordApprovalsStore,
22+
recordLockAnswerOf,
23+
seedRecordApprovals,
24+
useRecordApprovals,
25+
type SeededRecordApprovals,
26+
} from './useRecordApprovals';
27+
28+
const OBJECT = 'order_line';
29+
const RECORD = 'line_1';
30+
const PENDING_ROW = {
31+
id: 'req_line',
32+
process_name: 'flow:line_review',
33+
object_name: OBJECT,
34+
record_id: RECORD,
35+
status: 'pending',
36+
lock_record: true,
37+
};
38+
39+
afterEach(() => {
40+
__resetRecordApprovalsStore();
41+
});
42+
43+
async function seeded(answer: SeededRecordApprovals) {
44+
let resolve!: (a: SeededRecordApprovals) => void;
45+
seedRecordApprovals(OBJECT, RECORD, new Promise((r) => { resolve = r; }));
46+
const hook = renderHook(() => useRecordApprovals(OBJECT, RECORD));
47+
await act(async () => { resolve(answer); });
48+
await waitFor(() => expect(hook.result.current.answered).toBe(true));
49+
return hook.result.current;
50+
}
51+
52+
describe('useRecordApprovals — the composite lock\'s `lockSource` (objectstack#37195)', () => {
53+
it('a record held by its own approval: locked, `record`', async () => {
54+
const out = await seeded({ requests: [], lock: { locked: true, lockSource: 'record' } });
55+
expect(out.recordLock).toEqual({ locked: true, lockSource: 'record' });
56+
expect(out.lockSource).toBe('record');
57+
});
58+
59+
it('a line of a held master: locked, `master`', async () => {
60+
const out = await seeded({ requests: [], lock: { locked: true, lockSource: 'master' } });
61+
expect(out.recordLock).toEqual({ locked: true, lockSource: 'master' });
62+
expect(out.lockSource).toBe('master');
63+
});
64+
65+
it('a self-held line under a held master: the pending row decides the lock, and the kind is still `master`', async () => {
66+
const out = await seeded({ requests: [PENDING_ROW], lock: { locked: true, lockSource: 'master' } });
67+
expect(out.pendingRequest?.id).toBe('req_line');
68+
expect(out.recordLock).toBeNull();
69+
expect(out.lockSource).toBe('master');
70+
});
71+
72+
it('an unheld record, and a deployment that answers no lock: no kind', async () => {
73+
expect((await seeded({ requests: [], lock: { locked: false } })).lockSource).toBeNull();
74+
__resetRecordApprovalsStore();
75+
const none = await seeded({ requests: [], lock: null });
76+
expect(none.recordLock).toBeNull();
77+
expect(none.lockSource).toBeNull();
78+
});
79+
});
80+
81+
describe('recordLockAnswerOf — the two bits the lock doors serve, as the grid reads them', () => {
82+
it('keeps a named kind on a locked answer only', () => {
83+
expect(recordLockAnswerOf({ locked: true, lockSource: 'master', requestId: 'r' } as any)).toEqual({ locked: true, lockSource: 'master' });
84+
expect(recordLockAnswerOf({ locked: true, lockSource: 'record' })).toEqual({ locked: true, lockSource: 'record' });
85+
expect(recordLockAnswerOf({ locked: true, lockSource: 'package' })).toEqual({ locked: true });
86+
expect(recordLockAnswerOf({ locked: false, lockSource: 'master' })).toEqual({ locked: false });
87+
expect(recordLockAnswerOf(null)).toEqual({ locked: false });
88+
});
89+
});

0 commit comments

Comments
 (0)