Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/38997-edit-dialog-closed-lock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@object-ui/permissions': patch
'@object-ui/plugin-form': patch
'@object-ui/app-shell': patch
---

fix(console): the record edit dialog opens locked with the closed sentence on a closed record

Clause-②: yes (widening)
Metadata-protocol: none

The widening: the exported `lockedBy` prop of `RecordFieldAccessScopeProps` (`@object-ui/permissions`) and of `ModalFormProps` (`@object-ui/plugin-form`) accepts `'closed'` beside `'approval'`.

The console's full-record edit dialog now opens read-only on a closed record (one of its object's `closedStates` holds, its own or its master's, ADR-0162). It says "This record is closed, so it can't be changed." (the record page's sentence, `detail.lockedClosedTooltip`) and offers no Save. Before, it opened editable and the server's refusal of the save was the user's first notice.

- The dialog reads the closed state from the data lock the record page reads (`recordClosedByLock` on `useRecordApprovals`). It sends no request of its own: on a record page it uses the page's answer.
- A record that is closed and also held by an approval reads as closed, as on the record page. A record held only by an approval reads as before.
- `RecordFieldAccessScope`, `ModalForm` and `RecordFieldAccessForForm` accept `lockedBy: 'closed'` beside `'approval'`. The scope refuses the row's update with the new reason `record-closed`, and `closedFormAffordance` answers it as the new `'closed'` affordance, which `closedForRecord` treats like `'approval'` (no Save).
13 changes: 11 additions & 2 deletions ui/packages/app-shell/src/console/AppContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { ConsoleFormOwnerLine } from '../views/consoleFormOwnerLine.js';
import { Empty, EmptyTitle, EmptyDescription, Button, DataErrorState, cn } from '@object-ui/components';
import { toast } from 'sonner';
import { useActionRunner, useGlobalUndo, useMutationInvalidationBridge, notifyDataChanged, FilterScopeProvider, resolveApprovalLock, claimAnswerWarnings, toastRecordSave, type AnswerWarningClaim, type AnsweredLoadFailure, type RecordSaveFeedback } from '@object-ui/react';
import { useRecordApprovals, openApprovalOf } from '../hooks/useRecordApprovals.js';
import { useRecordApprovals, openApprovalOf, recordClosedByLock } from '../hooks/useRecordApprovals.js';
import { useObjectTranslation, useObjectLabel, recordSaveMessage as buildRecordSaveMessage } from '@object-ui/i18n';
import type { AppAccessVerdict, ConnectionState } from '@object-ui/data-objectstack';
import { useAuth, useWorkspaceAdminStatus } from '@object-ui/auth';
Expand Down Expand Up @@ -1079,6 +1079,15 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
openApproval: openApprovalOf(formApprovals),
recordStatus: undefined,
}).locked;
// objectstack#38997 (ADR-0162) — a CLOSED record (a closed state of its
// object holds, its own or its master's), from the same hook's data lock
// read (`recordClosedByLock`, the record page's rule), so the dialog asks
// nothing of its own: on a record page it joins the page's payload answer.
// It opens read-only with the record page's closed sentence; a record both
// closed and held reads as closed, as on the record page.
const formLockedBy: 'closed' | 'approval' | undefined = recordClosedByLock(formApprovals)
? 'closed'
: formApprovalLocked ? 'approval' : undefined;

// objectstack-ai/objectstack#26172 — a record save names the record it wrote
// (`ux-conventions.write-feedback`): `Task "Quarterly review" created`. The
Expand Down Expand Up @@ -1774,7 +1783,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
<ConsoleFormOwnerLine>
<LazyModalForm
key={`${formObjectDef.name}:${editingRecord?.id || 'new'}`}
lockedBy={formApprovalLocked ? 'approval' : undefined}
lockedBy={formLockedBy}
schema={{
type: 'object-form',
formType: 'modal',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
* → `'approval'`; it declares `lockRecord: false` → no lock;
* - CONTROL no approval running → no lock;
* - CONTROL a create dialog asks nothing and is not locked.
*
* objectstack#38997 (ADR-0162) — the same hook's data lock answering
* `lockReason: 'closed_state'` → `lockedBy: 'closed'`, also when an approval
* holds the record as well (closed wins, as on the record page); no read of
* its own beyond the hook's.
*/

import '@testing-library/jest-dom/vitest';
Expand Down Expand Up @@ -131,7 +136,7 @@ vi.mock('@object-ui/react', async (importOriginal) => ({
import { AppContent } from '../AppContent';
import { __resetRecordApprovalsStore } from '../../hooks/useRecordApprovals';

type Approvals = { requests: any[]; lock: boolean };
type Approvals = { requests: any[]; lock: boolean; closed?: boolean };

/** What the approvals routes answer; set per test. */
let served: Approvals = { requests: [], lock: false };
Expand All @@ -143,7 +148,12 @@ const fetchSpy = vi.fn(async (input: RequestInfo | URL) => {
// objectstack#37773 — the dialog's lock is the data layer's one lock read
// (`/data/:object/:id/lock`), answering `lockReason: 'approval'` here.
const body = /\/data\/[^/]+\/[^/]+\/lock$/.test(url)
? { success: true, data: served.lock ? { locked: true, lockSource: 'record', lockReason: 'approval' } : { locked: false } }
? {
success: true,
data: served.closed
? { locked: true, lockSource: 'record', lockReason: 'closed_state' }
: served.lock ? { locked: true, lockSource: 'record', lockReason: 'approval' } : { locked: false },
}
: url.includes('/approvals/records/')
? { success: true, data: { locked: served.lock } }
: url.includes('/approvals/requests?')
Expand Down Expand Up @@ -238,3 +248,30 @@ describe('[#27138] the console edit dialog reads the approvals record lock', ()
expect(approvalReads(fetchSpy)).toEqual([]);
});
});

describe('[#38997] the console edit dialog reads the closed lock (ADR-0162)', () => {
it.each([
['a closed record', { requests: [], lock: false, closed: true }],
['a closed record an approval also holds (closed wins)', { requests: [PENDING], lock: true, closed: true }],
])('%s: the dialog is handed the closed lock', async (_label, approvals) => {
serveApprovals(approvals);
openAt('/apps/crm/crm_contract?form=r1');
await waitFor(() => expect(lastModal()?.schema?.mode).toBe('edit'));
await waitFor(() => expect(lastModal().lockedBy).toBe('closed'));
});

it('a closed record adds no read: the same three lock-ish reads as an open one', async () => {
const fetchSpy = serveApprovals({ requests: [], lock: false, closed: true });
openAt('/apps/crm/crm_contract?form=r1');
await waitFor(() => expect(lastModal()?.lockedBy).toBe('closed'));
await new Promise((r) => setTimeout(r, 20));
const lockishReads = fetchSpy.mock.calls
.map(([u]) => new URL(String(u), 'http://x').pathname)
.filter((u) => u.includes('/approvals/') || u.endsWith('/lock'));
expect(lockishReads.sort()).toEqual([
'/api/v1/approvals/records/crm_contract/r1/lock',
'/api/v1/approvals/requests',
'/api/v1/data/crm_contract/r1/lock',
]);
});
});
24 changes: 16 additions & 8 deletions ui/packages/permissions/src/RecordFieldAccessScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,12 @@ export interface RecordFieldAccessAnswer {
*
* - `record-not-writable` — the projection answered `writable: false`;
* - `record-locked-by-approval` — the host reported a pending approval that
* locks the record (`lockedBy: 'approval'`).
* locks the record (`lockedBy: 'approval'`);
* - `record-closed` — the host reported the record closed: one of its
* object's closed states holds, its own or its master's (`lockedBy:
* 'closed'`, ADR-0162).
*/
type RecordWriteRefusal = 'record-not-writable' | 'record-locked-by-approval';
type RecordWriteRefusal = 'record-not-writable' | 'record-locked-by-approval' | 'record-closed';

export interface RecordFieldAccessScopeProps {
/** The object the record belongs to. Matched case-insensitively, as `MePermissionsProvider` matches object names. */
Expand All @@ -62,11 +65,14 @@ export interface RecordFieldAccessScopeProps {
* A lock on the record that the projection does not judge and the host
* reads from its own door: `'approval'` while a pending approval locks the
* record (the approvals service's record lock, answered to every reader).
* The row then answers as not writable, exactly as `writable: false` does,
* without waiting for the projection. The host passes the verdict it already
* draws its own lock from; the scope never re-derives it.
* `'closed'` while the record is closed (ADR-0162: a closed state of its
* object holds, its own or its master's, as the data layer's lock read
* answers it). The row then answers as not writable, exactly as
* `writable: false` does, without waiting for the projection. The host
* passes the verdict it already draws its own lock from, and decides which
* one when both hold; the scope never re-derives it.
*/
lockedBy?: 'approval';
lockedBy?: 'approval' | 'closed';
children: ReactNode;
}

Expand Down Expand Up @@ -168,7 +174,8 @@ function scoped(
const refusal: RecordWriteRefusal | undefined =
answer?.writable === false ? 'record-not-writable'
: lockedBy === 'approval' ? 'record-locked-by-approval'
: undefined;
: lockedBy === 'closed' ? 'record-closed'
: undefined;
const result = refusal ? refusedRow(value, objKey, recordId, refusal) : value;
SCOPE_OF.set(result, key);
byAnswer.set(answerKey, result);
Expand Down Expand Up @@ -238,7 +245,8 @@ function refusedRow(
* why. `lockedBy: 'approval'` answers the same way with the reason
* `record-locked-by-approval`: the approvals record lock is judged on the
* values a save sends, so the projection leaves it out, and the host passes
* the lock it already reads. `writable: true` or an absent `writable` changes
* the lock it already reads. `lockedBy: 'closed'` does too, with the reason
* `record-closed` (ADR-0162's closed-state lock, also outside the projection). `writable: true` or an absent `writable` changes
* nothing. Until the answer arrives the row-blind answer stands for the row,
* as it does for the fields.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const PROJECTION = { editable: ['title', 'summary'] };
function mount(
load: (o: string, id: string) => Promise<any>,
{ lockedBy, principal = ANSWER, nestedLock = false }: {
lockedBy?: 'approval';
lockedBy?: 'approval' | 'closed';
principal?: MePermissionsResponse;
nestedLock?: boolean;
} = {},
Expand Down Expand Up @@ -137,6 +137,20 @@ describe('[#27138] RecordFieldAccessScope — the row verdict', () => {
expect(writable.last().check('rfa_contract', 'update').reason).toBe('record-locked-by-approval');
});

// objectstack#38997 — ADR-0162: the host's closed lock answers the same way, with its own reason.
it("a host's closed lock refuses the row with record-closed, before any answer and over a writable one", async () => {
let resolve: ((v: any) => void) | undefined;
const pending = mount(() => new Promise((r) => { resolve = r; }), { lockedBy: 'closed' });
await waitFor(() => expect(resolve).toBeTypeOf('function'));
expect(pending.last().check('rfa_contract', 'update')).toEqual({ allowed: false, reason: 'record-closed' });
expect(pending.last().checkField('rfa_contract', 'title', 'write')).toBe(false);
expect(pending.last().checkField('rfa_contract', 'title', 'read')).toBe(true);

const writable = mount(async () => ({ ...PROJECTION, writable: true }), { lockedBy: 'closed' });
await new Promise((r) => setTimeout(r, 0));
expect(writable.last().check('rfa_contract', 'update').reason).toBe('record-closed');
});

it('an object grant the enclosing provider refuses keeps its own reason', async () => {
const { last } = mount(async () => ({ ...PROJECTION, writable: false }), { principal: READ_ONLY_GRANT });
await new Promise((r) => setTimeout(r, 0));
Expand Down
7 changes: 4 additions & 3 deletions ui/packages/plugin-form/src/ModalForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ import {
type LoadedRecordSnapshot,
} from './sanitize';
import { closedForRecord, closedFormAffordance, fieldWriteGate, gateFormFields } from './fieldWriteGate';
import { RecordFieldAccessForForm } from './recordFieldAccess';
import { RecordFieldAccessForForm, type RecordFieldAccessForFormProps } from './recordFieldAccess';
import { ClosedAffordanceNotice } from './closedAffordanceNotice';
import { seedCreateValues } from './schemaDefaults';
import { createWritePayload } from './writePayload';
Expand Down Expand Up @@ -317,11 +317,12 @@ export interface ModalFormProps {
/**
* A lock on the edited record that the host reads and the record's field
* projection leaves out: `'approval'` while a pending approval locks it
* (objectstack#27138). The dialog then draws the record read-only, says
* (objectstack#27138), `'closed'` while the record is closed (ADR-0162,
* objectstack#38997). The dialog then draws the record read-only, says
* why, and offers no Save, as it does for a row the server answers
* `writable: false`. Read on an `edit` form with a `recordId` only.
*/
lockedBy?: 'approval';
lockedBy?: RecordFieldAccessForFormProps['lockedBy'];
}

/**
Expand Down
13 changes: 9 additions & 4 deletions ui/packages/plugin-form/src/closedAffordanceNotice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ import type { ClosedFormAffordance } from './fieldWriteGate';
* sentence names the record, not the object: the caller may edit other
* records of it. `record` is the server's row verdict (sharing, ownership,
* row-level security); `approval` a pending approval that locks the record,
* said with the record page's own lock sentence.
* said with the record page's own lock sentence; `closed` a record in one of
* its object's closed states (ADR-0162), said with the record page's own
* closed sentence.
*
* `role="status"`, the package's pattern for a form state (`UploadInFlightNotice`):
* nothing has failed, and an assertive live region would interrupt a
Expand All @@ -54,6 +56,7 @@ const useClosedAffordanceTranslation = createSafeTranslation(
'form.noPermissionToEdit': "You don't have permission to edit {{object}} records. The fields are read-only.",
'form.noPermissionToEditRecord': "You don't have permission to edit this record. The fields are read-only.",
'detail.lockedTooltip': 'This record has a pending approval request; editing is locked',
'detail.lockedClosedTooltip': "This record is closed, so it can't be changed.",
},
'form.noPermissionToCreate',
);
Expand Down Expand Up @@ -87,9 +90,11 @@ export function ClosedAffordanceNotice({
? t('form.noPermissionToEditRecord')
: affordance === 'approval'
? t('detail.lockedTooltip')
: affordance === 'edit'
? t('form.noPermissionToEdit', { object })
: t('form.noPermissionToCreate', { object });
: affordance === 'closed'
? t('detail.lockedClosedTooltip')
: affordance === 'edit'
? t('form.noPermissionToEdit', { object })
: t('form.noPermissionToCreate', { object });

return (
<p
Expand Down
10 changes: 6 additions & 4 deletions ui/packages/plugin-form/src/fieldWriteGate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,10 @@ function managedModeLocked(
* THIS record refusing the update while the object allows it (objectstack#27138)
* — `record` when the server's record projection answered `writable: false`
* (sharing, ownership, row-level security), `approval` when the host reported
* a pending approval that locks the record.
* a pending approval that locks the record, `closed` when the host reported
* the record closed (ADR-0162: a closed state of its object holds).
*/
export type ClosedFormAffordance = 'create' | 'edit' | 'record' | 'approval';
export type ClosedFormAffordance = 'create' | 'edit' | 'record' | 'approval' | 'closed';

/**
* The row reasons `RecordFieldAccessScope` (`@object-ui/permissions`) answers
Expand All @@ -294,6 +295,7 @@ export type ClosedFormAffordance = 'create' | 'edit' | 'record' | 'approval';
const ROW_REFUSALS: ReadonlyMap<string, ClosedFormAffordance> = new Map<string, ClosedFormAffordance>([
['record-not-writable', 'record'],
['record-locked-by-approval', 'approval'],
['record-closed', 'closed'],
]);

/**
Expand All @@ -302,7 +304,7 @@ const ROW_REFUSALS: ReadonlyMap<string, ClosedFormAffordance> = new Map<string,
* nothing on the form the server would accept (objectstack#27138).
*/
export function closedForRecord(affordance: ClosedFormAffordance | undefined): boolean {
return affordance === 'record' || affordance === 'approval';
return affordance === 'record' || affordance === 'approval' || affordance === 'closed';
}

/**
Expand All @@ -313,7 +315,7 @@ export function closedForRecord(affordance: ClosedFormAffordance | undefined): b
*
* It is {@link managedModeLocked}, the very predicate {@link gateFormFields}
* disables every drawn field on, read for its reason: `create` for a create
* form, `edit` for an edit form, and `record` / `approval` for an edit form
* form, `edit` for an edit form, and `record` / `approval` / `closed` for an edit form
* whose own row refuses the update (the reason the scoped `check` gave). The
* locked form's notice
* (`ClosedAffordanceNotice`) and the wizard's navigation gate read THIS, not a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
* `AppContent` passes for a record a pending approval locks) → read-only, the
* record page's lock sentence, no Save — on a data source without the record
* projection too.
* And under the host's closed lock (`lockedBy: 'closed'`, what `AppContent`
* passes for a record in one of its object's closed states, ADR-0162) →
* read-only, the record page's closed sentence, no Save (objectstack#38997).
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, waitFor, cleanup } from '@testing-library/react';
Expand Down Expand Up @@ -163,3 +166,22 @@ describe("[#27138] the console's edit dialog under the host's approval lock", ()
expect(saveButtons()).toBe(0);
});
});

describe("[#38997] the console's edit dialog under the host's closed lock (ADR-0162)", () => {
it.each([
['a writable row', { ...PROJECTION, writable: true }],
['a data source without the record projection', null],
])('on %s, a closed record is drawn read-only with the closed sentence and no Save', async (_label, access) => {
const ds = makeDS(access);
render(
<MePermissionsProvider initialPermissions={principal(true)}>
<ModalForm schema={schema('modal')} dataSource={ds as any} lockedBy="closed" />
</MePermissionsProvider>,
);
await drawn();
await waitFor(() => expect(locked()).toEqual({ title: true, summary: true }));
expect(notice()?.getAttribute('data-affordance')).toBe('closed');
expect(notice()?.textContent).toBe("This record is closed, so it can't be changed.");
expect(saveButtons()).toBe(0);
});
});
7 changes: 4 additions & 3 deletions ui/packages/plugin-form/src/recordFieldAccess.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,23 @@
* `writable: false` the scope refuses every field of the record and the
* record's update, so the form draws read-only, says why and offers no Save.
* A host that reads a lock the projection leaves out — a pending approval
* that locks the record — passes it as `lockedBy`, and it reaches the same
* that locks the record, or the record being closed (ADR-0162) — passes it as
* `lockedBy`, and it reaches the same
* gates the same way. A form edits a stored record under that lock even on a
* data source without the projection: the scope then has no answer to ask
* for, and only the host's lock narrows the row.
*/

import React, { useEffect, useState } from 'react';
import { RecordFieldAccessScope } from '@object-ui/permissions';
import { RecordFieldAccessScope, type RecordFieldAccessScopeProps } from '@object-ui/permissions';
import { useDataInvalidation } from '@object-ui/react';
import type { DataSource } from '@object-ui/types';

export interface RecordFieldAccessForFormProps {
schema: { objectName?: string; mode?: string; recordId?: string | number | null };
dataSource?: DataSource | null;
/** A lock the host reads on the record and the projection leaves out (`RecordFieldAccessScope`'s `lockedBy`). */
lockedBy?: 'approval';
lockedBy?: RecordFieldAccessScopeProps['lockedBy'];
children: React.ReactNode;
}

Expand Down
Loading