diff --git a/.changeset/39406-approval-snapshot-no-field-access.md b/.changeset/39406-approval-snapshot-no-field-access.md new file mode 100644 index 00000000000..6f2e8c2211a --- /dev/null +++ b/.changeset/39406-approval-snapshot-no-field-access.md @@ -0,0 +1,14 @@ +--- +'@object-ui/i18n': patch +--- + +fix(app-shell): an approver who may read none of the submitted record's fields is told so instead of seeing an empty pane + +Clause-②: no +Metadata-protocol: none + +Who sees it: an approver who opens an approval request on an object they may not read, or whose fields they may not read. + +- **The submitted-record card now says "You don't have access to this object's fields; ask an administrator."** where it used to draw nothing. The approver can tell an access gap from an empty submission. +- **Nothing more is shown than before.** The snapshot is still redacted for the reader, and the notice names no field and shows no value. +- New locale key `approvalsInbox.snapshotNoFieldAccess`. diff --git a/packages/qa/dogfood/test/approval-snapshot-no-object-read-39406.dogfood.test.ts b/packages/qa/dogfood/test/approval-snapshot-no-object-read-39406.dogfood.test.ts new file mode 100644 index 00000000000..9fddb89046d --- /dev/null +++ b/packages/qa/dogfood/test/approval-snapshot-no-object-read-39406.dogfood.test.ts @@ -0,0 +1,223 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#39406] An approver whose permission sets do not mention the object under +// approval is served the request's snapshot whole, keys and labels, on a real +// boot. +// +// ## Why this is pinned here +// +// The approval page draws the submitted record from the request's snapshot. +// `payload-redaction.ts` states the serve-time contract: redaction is by FIELD +// and "does not gate on OBJECT-level access", because an approver routinely has +// no read on the object they approve. The unit pins of that seam drive it with +// a stand-in field-visibility source, so nothing proved the real +// `SecurityPlugin` answers that way for a reader whose sets never name the +// object. This file does, end to end, and the page's rework (draw the served +// snapshot when the object's definition is withheld) stands on it. +// +// ## The composition +// +// `bootStack` with the real `SecurityPlugin`, `ObjectQL`, SQL driver, REST and +// auth layers, plus automation, the record-change trigger and the approvals +// plugin. One synthetic object with three plain fields; a flow routes each new +// record to a position the approver holds. +// +// - The approver's only set names `sys_approval_request` and nothing else: +// no entry for the object, no field entries. +// - The submitter holds a set that may create and read the object. +// +// ## What is asserted +// +// - The scene is real first: the stored snapshot carries every field, and the +// approver is refused the record on the data plane and the object's +// definition on the metadata plane (the reason the page has no definition). +// - The approver's inbox item and inbox list row carry every snapshot key with +// its stored value, and a label for every key (`payload_labels`). +// +// Fixtures are synthetic. `@objectstack/plugin-approvals` and +// `@objectstack/trigger-record-change` resolve to SOURCE here (this project's +// alias), so the verdict is about the checkout, not the last build. + +import { describe, it, expect } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { ApprovalsServicePlugin } from '@objectstack/plugin-approvals'; +import { RecordChangeTriggerPlugin } from '@objectstack/trigger-record-change'; +import { defineStack, defineFlow } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const OBJECT = 'noread_order'; +const POSITION = 'noread_reviewer'; +const SYS = { context: { isSystem: true } } as const; + +/** The record as submitted: synthetic values for every declared field. */ +const SUBMITTED = { name: 'Order one', device: 'Pump 3', fault: 'Seal leaks' }; +const LABELS = { name: 'Order No', device: 'Device', fault: 'Fault' }; + +const NoreadOrder = ObjectSchema.create({ + name: OBJECT, + label: 'No-read Order', + pluralLabel: 'No-read Orders', + fields: { + name: Field.text({ label: LABELS.name, required: true }), + device: Field.text({ label: LABELS.device }), + fault: Field.text({ label: LABELS.fault }), + }, +}); + +const NoreadFlow = defineFlow({ + name: 'noread_flow', + label: 'No-read Flow', + description: 'Routes each new order to the reviewer position.', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'On Create', config: { objectName: OBJECT, triggerType: 'record-after-create' } }, + { + id: 'gate', + type: 'approval', + label: 'Gate', + config: { approvers: [{ type: 'position', value: POSITION }], behavior: 'first_response' }, + }, + { id: 'approved', type: 'end', label: 'Approved' }, + { id: 'rejected', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'gate' }, + { id: 'e2', source: 'gate', target: 'approved', label: 'approve' }, + { id: 'e3', source: 'gate', target: 'rejected', label: 'reject' }, + ], +}); + +const noreadStack = defineStack({ + manifest: { + id: 'com.dogfood.snapshot-no-object-read', + namespace: 'noread', + version: '0.0.0', + type: 'app', + name: 'Snapshot No Object Read Fixture', + description: 'One object, one approval flow, an approver whose sets never name the object.', + }, + // ADR-0097: the flow's record-change start node needs both capabilities. + requires: ['automation', 'triggers'], + objects: [NoreadOrder], + flows: [NoreadFlow], +}); + +/** Every fresh member, the approver included: the request object only. The order object is not named. */ +const requestOnlySet = PermissionSetSchema.parse({ + name: 'noread_request_only', + label: 'No-read request only', + objects: { + sys_approval_request: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + }, +}); +/** The submitter: may create and read the order. */ +const submitterSet = PermissionSetSchema.parse({ + name: 'noread_submitter', + label: 'No-read submitter', + objects: { + [OBJECT]: { allowRead: true, allowCreate: true, allowEdit: false, allowDelete: false }, + sys_approval_request: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + }, +}); + +interface Reads { + item: Record; + itemLabels: Record; + list: Record; + listLabels: Record; +} + +/** The inbox item and the inbox list row, as one caller. */ +async function readInboxAs(stack: VerifyStack, token: string): Promise { + const listRes = await stack.apiAs(token, 'GET', '/approvals/requests?status=pending'); + expect(listRes.status).toBe(200); + const listBody = (await listRes.json()) as { data: Array> }; + const rows = listBody.data.filter((r) => r.object_name === OBJECT); + expect(rows).toHaveLength(1); + const itemRes = await stack.apiAs(token, 'GET', `/approvals/requests/${String(rows[0].id)}`); + expect(itemRes.status).toBe(200); + const item = (await itemRes.json()) as Record; + return { + item: (item.payload ?? {}) as Record, + itemLabels: (item.payload_labels ?? {}) as Record, + list: (rows[0].payload ?? {}) as Record, + listLabels: (rows[0].payload_labels ?? {}) as Record, + }; +} + +describe('[#39406] an approver whose sets do not mention the object is served the snapshot whole', () => { + it( + 'serves every submitted key, value and label to that approver, who is refused the record and the definition', + async () => { + const stack = await bootStack(noreadStack as unknown as Parameters[0], { + automation: true, + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, requestOnlySet, submitterSet], + fallbackPermissionSet: requestOnlySet.name, + }), + extraPlugins: [new RecordChangeTriggerPlugin(), new ApprovalsServicePlugin()], + }); + try { + const ql = (await stack.kernel.getServiceAsync('objectql')) as any; + const idOf = async (email: string) => + String((await ql.findOne('sys_user', { where: { email }, context: { isSystem: true } }))?.id ?? ''); + + const submitterToken = await stack.signUp('noread-submitter@verify.test'); + const approverToken = await stack.signUp('noread-approver@verify.test'); + const submitterId = await idOf('noread-submitter@verify.test'); + const approverId = await idOf('noread-approver@verify.test'); + expect(submitterId && approverId).toBeTruthy(); + + // Staff the position BEFORE the record exists: the slate resolves at + // request creation, and the assignment carries the holder's + // organization, as a write through a door does. + const membership = await ql.findOne('sys_member', { where: { user_id: approverId }, context: { isSystem: true } }); + await ql.insert( + 'sys_user_position', + { id: 'hold_noread_a', user_id: approverId, position: POSITION, organization_id: membership?.organization_id }, + SYS, + ); + const granted = await catalogPermissionSet(ql, submitterSet.name); + expect(granted, 'fixture permission set served by the security catalog').toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: submitterId, permission_set: granted.name }, SYS); + + const createRes = await stack.apiAs(submitterToken, 'POST', `/data/${OBJECT}`, SUBMITTED); + expect(createRes.status).toBe(201); + const created = (await createRes.json()) as { id?: string; record?: { id?: string } }; + const recordId = String(created.id ?? created.record?.id ?? ''); + expect(recordId).toBeTruthy(); + + // The scene, before any served read is believed. The snapshot at rest + // carries every submitted field, and the request names the approver. + const atRest = await ql.findOne('sys_approval_request', { where: { object_name: OBJECT }, context: { isSystem: true } }); + expect(atRest, 'the flow opened an approval request').toBeTruthy(); + expect(JSON.parse(String(atRest.payload_json))).toMatchObject(SUBMITTED); + + // The approver may not read the object: the record is refused on the + // data plane, and the definition is withheld on the metadata plane. + const dataRes = await stack.apiAs(approverToken, 'GET', `/data/${OBJECT}/${recordId}`); + expect(dataRes.status, 'the approver is refused the record').toBeGreaterThanOrEqual(400); + const metaRes = await stack.apiAs(approverToken, 'GET', `/meta/object/${OBJECT}`); + expect(metaRes.status, "the approver is refused the object's definition").toBe(404); + // Control: the submitter, who may read the object, is served both. + expect((await stack.apiAs(submitterToken, 'GET', `/data/${OBJECT}/${recordId}`)).status).toBe(200); + expect((await stack.apiAs(submitterToken, 'GET', `/meta/object/${OBJECT}`)).status).toBe(200); + + const approver = await readInboxAs(stack, approverToken); + for (const [key, value] of Object.entries(SUBMITTED)) { + expect(approver.item[key], `inbox item serves ${key}`).toBe(value); + expect(approver.list[key], `inbox list serves ${key}`).toBe(value); + expect(approver.itemLabels[key], `inbox item labels ${key}`).toBe(LABELS[key as keyof typeof LABELS]); + expect(approver.listLabels[key], `inbox list labels ${key}`).toBe(LABELS[key as keyof typeof LABELS]); + } + } finally { + await stack.stop(); + } + }, + 120_000, + ); +}); diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.noReadableFields-39406.test.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.noReadableFields-39406.test.tsx new file mode 100644 index 00000000000..a153d0dbd79 --- /dev/null +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.noReadableFields-39406.test.tsx @@ -0,0 +1,232 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The request page draws the submitted record an approver is served, even when + * that approver may not read the object (objectstack#39406, ruled option E). + * + * The service serves the snapshot redacted by field and does not gate it on + * object read; the object's definition, though, is withheld from a reader who + * may not read the object. The page used to drop the served snapshot in that + * case and draw nothing. Pinned here: + * + * 1. definition withheld, snapshot served whole: every served key is drawn + * under the label the service sent, a reference by the name the service + * resolved, headed with the object label the service sent; no notice; + * 2. definition withheld, snapshot served without a field the reader may not + * read: that field appears nowhere; + * 3. definition withheld, no field served: the notice, and no field; + * 4. definition served, no field served: the notice; + * 5. definition served, snapshot served whole, the reader's field + * permissions deny every field: no value is drawn, and no notice either, + * because the service did serve fields. + * + * Controls: a definition that is absent while the reader may read the object + * (a deleted object) draws nothing and claims no gap; a reader who may read + * one field gets the card with that field. + * + * The declared actions bar is doubled: what is under test is the page body. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; + +vi.mock('../DeclaredActionsBar.js', () => ({ + DeclaredActionsBar: () =>
, +})); + +/** What the reader may read, set per test. */ +const access = { + objectReadable: true, + readableFields: new Set(), +}; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + const perms = { + isLoaded: true, + can: (object: string) => object !== 'repair_order' || access.objectReadable, + check: (object: string) => ({ allowed: object !== 'repair_order' || access.objectReadable }), + checkField: (object: string, field: string) => + object !== 'repair_order' || access.readableFields.has(field), + getFieldPermissions: () => ({ readable: true, writable: false }), + }; + return { ...actual, usePermissions: () => perms }; +}); + +// Paid during collection, not inside a case's clocked window: the card's child +// tables load this package lazily. +import '@object-ui/plugin-detail'; +import { AdapterCtx, MetadataCtx, RecordContextProvider } from '@object-ui/react'; +import { ApprovalDecisionRenderer } from './ApprovalDecisionPanel'; +import { resetApproverDirectoryCache } from '../../hooks/useApproverDirectory'; + +const REPAIR_ORDER = { + name: 'repair_order', + label: 'Repair Order', + fields: { + name: { type: 'text', label: 'Order No' }, + device: { type: 'text', label: 'Device' }, + fault: { type: 'textarea', label: 'Fault' }, + estimate: { type: 'currency', label: 'Estimate' }, + }, +}; + +/** The record as submitted, whole. */ +const SUBMITTED = { id: 'ro_1', name: 'RO-7', device: 'Pump 3', fault: 'Seal leaks', estimate: 1200 }; + +const NOTICE = "You don't have access to this object's fields; ask an administrator."; + +function mount(opts: { + /** The object definition the metadata read answers; null = withheld. */ + definition: Record | null; + /** The snapshot as the service serves it to this reader. */ + payload: Record; + /** What the service serves beside the snapshot. */ + served?: { payload_labels?: Record; payload_display?: Record; object_label?: string }; +}) { + const adapter = { + getObjectSchema: vi.fn(async (name: string) => (name === 'repair_order' ? opts.definition : null)), + findOne: vi.fn(async () => { + throw Object.assign(new Error('forbidden'), { status: 403, code: 'PERMISSION_DENIED' }); + }), + find: vi.fn(async () => ({ data: [] })), + }; + const metadata = { + objects: opts.definition ? [opts.definition] : [], + getItem: async (type: string, name: string) => + type === 'object' && name === 'repair_order' ? opts.definition : null, + }; + const request = { + id: 'areq_1', + process_name: 'flow:repair_approval', + object_name: 'repair_order', + record_id: 'ro_1', + status: 'pending', + submitter_id: 'u9', + pending_approvers: ['u1'], + pending_approver_names: { u1: 'Zhang Manager' }, + viewer: { can_act: true, is_submitter: false, can_override: false }, + payload: opts.payload, + ...opts.served, + }; + render( + + + + + + + , + ); + return screen.getByTestId('approval-decision-panel'); +} + +function expectNoValueLeaks(panel: HTMLElement) { + for (const value of ['RO-7', 'Pump 3', 'Seal leaks', '1,200', 'Device', 'Fault']) { + expect(panel.textContent).not.toContain(value); + } +} + +beforeEach(() => { + resetApproverDirectoryCache(); + access.objectReadable = true; + access.readableFields = new Set(Object.keys(REPAIR_ORDER.fields)); +}); +afterEach(cleanup); + +const SERVED_LABELS = { name: 'Order No', device: 'Device', fault: 'Fault', estimate: 'Estimate', assignee: 'Assignee' }; + +const fieldKeys = (root: HTMLElement) => + [...root.querySelectorAll('[data-submitted-field]')].map((el) => el.getAttribute('data-submitted-field')); + +describe('the request page draws the snapshot an approver is served (objectstack#39406)', () => { + it('1: definition withheld, snapshot served whole: every key under its served label, a reference by its served name, no notice', async () => { + access.objectReadable = false; + access.readableFields = new Set(); + const panel = mount({ + definition: null, + payload: { ...SUBMITTED, assignee: 'u7' }, + served: { payload_labels: SERVED_LABELS, payload_display: { assignee: 'Ada Lovelace' }, object_label: 'Repair Order' }, + }); + const card = await within(panel).findByTestId('submitted-record'); + expect(fieldKeys(card)).toEqual(['name', 'device', 'fault', 'estimate', 'assignee']); + const labelOf = (key: string) => card.querySelector(`[data-submitted-field="${key}"] dt`)?.textContent; + expect(labelOf('device')).toBe('Device'); + expect(labelOf('assignee')).toBe('Assignee'); + expect(card.querySelector('[data-submitted-field="fault"] dd')?.textContent).toBe('Seal leaks'); + expect(card.querySelector('[data-submitted-field="estimate"] dd')?.textContent).toBe('1200'); + expect(card.querySelector('[data-submitted-field="assignee"] dd')?.textContent).toBe('Ada Lovelace'); + expect(card.querySelector('[data-submitted-heading]')?.textContent).toBe('As submitted'); + expect(card.textContent).toContain('Repair Order'); + expect(card.textContent).not.toContain('repair_order'); + expect(within(panel).queryByTestId('submitted-record-no-access')).toBeNull(); + }); + + it('2: definition withheld, a field the reader may not read is not served, and appears nowhere', async () => { + access.objectReadable = false; + access.readableFields = new Set(); + const panel = mount({ + definition: null, + payload: { name: 'RO-7', device: 'Pump 3' }, + served: { payload_labels: { name: 'Order No', device: 'Device' }, object_label: 'Repair Order' }, + }); + const card = await within(panel).findByTestId('submitted-record'); + expect(fieldKeys(card)).toEqual(['name', 'device']); + expect(panel.textContent).not.toContain('Fault'); + expect(panel.textContent).not.toContain('Seal leaks'); + }); + + it('3: definition withheld, no field served: the notice, and no field', async () => { + access.objectReadable = false; + access.readableFields = new Set(); + const panel = mount({ definition: null, payload: { id: 'ro_1' }, served: { object_label: 'Repair Order' } }); + const notice = await within(panel).findByTestId('submitted-record-no-access'); + expect(notice.textContent).toBe(NOTICE); + const card = within(panel).getByTestId('submitted-record'); + expect(card.contains(notice)).toBe(true); + expect(card.querySelectorAll('[data-submitted-field]')).toHaveLength(0); + expectNoValueLeaks(panel); + }); + + it('4: definition served, no field served: the notice', async () => { + access.readableFields = new Set(); + // The served definition loses every field the reader may not read (ADR-0106 D1). + const panel = mount({ definition: { ...REPAIR_ORDER, fields: {} }, payload: {} }); + const notice = await within(panel).findByTestId('submitted-record-no-access'); + expect(notice.textContent).toBe(NOTICE); + expectNoValueLeaks(panel); + }); + + it('5: definition served, fields served, the reader\'s field permissions deny every one: no value, and no notice', async () => { + access.readableFields = new Set(); + const panel = mount({ definition: REPAIR_ORDER, payload: SUBMITTED }); + await waitFor(() => expect(within(panel).getByTestId('declared-actions-probe')).toBeTruthy()); + await new Promise((resolve) => setTimeout(resolve, 20)); + expectNoValueLeaks(panel); + expect(within(panel).queryByTestId('submitted-record-no-access')).toBeNull(); + }); + + it('CONTROL: an absent definition the reader is allowed to read draws nothing and claims no gap', async () => { + const panel = mount({ definition: null, payload: SUBMITTED, served: { payload_labels: SERVED_LABELS } }); + // Let the definition read settle before asserting an absence. + await waitFor(() => expect(within(panel).getByTestId('declared-actions-probe')).toBeTruthy()); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(within(panel).queryByTestId('submitted-record')).toBeNull(); + expect(within(panel).queryByTestId('submitted-record-no-access')).toBeNull(); + }); + + it('CONTROL: one readable field draws the card with that field and no notice', async () => { + access.readableFields = new Set(['device']); + const panel = mount({ definition: REPAIR_ORDER, payload: { device: 'Pump 3' } }); + const card = await within(panel).findByTestId('submitted-record'); + expect(fieldKeys(card)).toEqual(['device']); + expect(within(panel).queryByTestId('submitted-record-no-access')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx b/ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx index 110fe69adb9..36df40e32d6 100644 --- a/ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx +++ b/ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx @@ -87,12 +87,41 @@ * Add, edit, delete or row action: the request page never edits the record. * They are drawn only once the record itself read. * + * ## A withheld definition: the snapshot as served + * + * The service serves the snapshot redacted by FIELD and does not gate it on + * the reader's read of the object (`payload-redaction.ts` in + * plugin-approvals): an approver routinely has no read on the object they + * approve, and the snapshot is how they see what they decide on. The object's + * DEFINITION is withheld from such a reader (the platform answers a schema + * read of an object the reader may not read as for a name that names no + * object). So when the definition is withheld while the reader's permissions + * deny reading the object, the card draws the snapshot as served + * (objectstack#39406): one untitled section, each served key under the label + * the service sent for it (`payload_labels`), each value as plain text or the + * name the service resolved for it (`payload_display`), headed with the + * object label the service sent (`object_label`). Nothing is narrowed again + * on the page: the reader's object permission would deny every field, and the + * service has already withheld the fields this reader may not read. A + * definition that is absent while the reader may read the object draws + * nothing, as before. + * + * ## The notice: the service served no field + * + * When the service served no field of the snapshot (framework bookkeeping + * aside), the card says so in place of the fields: "You don't have access to + * this object's fields; ask an administrator." It appears on that condition + * alone ({@link SubmittedRecordModel.noFieldAccess}), with or without the + * definition. A snapshot that holds only keys the object does not declare is + * a served snapshot: the card draws nothing for it and claims no gap. + * * Module-internal: nothing re-exports it from the package entry. */ import * as React from 'react'; import { Badge, EmptyValue, LazyIcon, cn, type FormSectionNavItem } from '@object-ui/components'; import { isDeadlineSettled, withoutDeniedFields } from '@object-ui/core'; +import { isSystemManagedField } from '@object-ui/types'; import { getCellRenderer, resolveCellRendererType } from '@object-ui/fields'; import { useSafeFieldLabel } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; @@ -141,6 +170,78 @@ export interface SubmittedRecordModel { display: Record | undefined; plan: SubmittedRecordPlan; current: CurrentRecordState; + /** + * The service served no field of the snapshot (see "The notice" above): the + * card draws the notice in place of the fields. + */ + noFieldAccess: boolean; + /** + * `declared`: drawn through the object's definition. `served`: the + * definition is withheld, so the snapshot is drawn as served (see "A + * withheld definition" above). + */ + face: 'declared' | 'served'; +} + +/** The snapshot keys that are fields the service served: not the row id, not framework bookkeeping. */ +function servedFieldKeys(payload: Record): string[] { + return Object.keys(payload).filter((key) => key !== 'id' && key !== '_id' && !isSystemManagedField(key)); +} + +/** + * A served value as text, for the face drawn without a definition: no field + * type is known there, so no typed cell can be chosen. + */ +function servedValueText(value: unknown): string { + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'boolean') return String(value); + if (Array.isArray(value)) return value.map(servedValueText).filter((v) => v !== '').join(', '); + if (value && typeof value === 'object') { + const named = value as Record; + for (const key of ['name', 'label', 'title']) { + if (typeof named[key] === 'string' && named[key] !== '') return named[key] as string; + } + return JSON.stringify(value); + } + return ''; +} + +/** + * The model of a snapshot drawn as served (see "A withheld definition" + * above): one untitled section of the served keys, labelled by the service. + */ +function servedModel( + target: string, + recordId: string | null, + payload: Record, + labels: Record | undefined, + objectLabel: string | undefined, + display: Record | undefined, + current: CurrentRecordState, +): SubmittedRecordModel { + const keys = servedFieldKeys(payload); + const fields: Record = {}; + for (const key of keys) { + const label = labels?.[key]; + fields[key] = { name: key, type: 'text', label: typeof label === 'string' && label !== '' ? label : key } as FieldDef; + } + return { + objectName: target, + recordId, + objectDef: { name: target, ...(objectLabel ? { label: objectLabel } : {}), fields }, + snapshot: payload, + display, + plan: { + sections: keys.length > 0 + ? [{ key: 'served', fields: keys.map((key) => ({ key, value: payload[key], changed: false, current: undefined })) }] + : [], + attachments: [], + changedCount: 0, + }, + current, + noFieldAccess: keys.length === 0, + face: 'served', + }; } /** An object's definition, when the one answered is `name`'s. */ @@ -204,20 +305,23 @@ function useCurrentRecord(objectName: string | null, recordId: string | null): C * and the current row narrowed for the reader, and the plan of what to draw. * Null until the definition answers, and when there is no snapshot or no * definition: without the declarations there is no label, face or `hidden` - * to honour. + * to honour. The one exception is a definition withheld from a reader who may + * not read the object: the snapshot is then drawn as served. */ export function useSubmittedRecord(request: { object_name?: string | null; record_id?: string | null; payload?: unknown; payload_display?: Record | null; + payload_labels?: Record | null; + object_label?: string | null; }): SubmittedRecordModel | null { const target = typeof request.object_name === 'string' && request.object_name !== '' ? request.object_name : null; const recordId = typeof request.record_id === 'string' && request.record_id !== '' ? request.record_id : null; const payload = request.payload; const hasSnapshot = !!payload && typeof payload === 'object' && !Array.isArray(payload); // No snapshot, nothing to draw: neither the definition nor the record is asked for. - const { item } = useMetadataItem('object', hasSnapshot ? target : null); + const { item, loading: definitionLoading } = useMetadataItem('object', hasSnapshot ? target : null); const current = useCurrentRecord(hasSnapshot ? target : null, hasSnapshot ? recordId : null); const perms = usePermissions(); const { t } = useObjectTranslation(); @@ -225,15 +329,27 @@ export function useSubmittedRecord(request: { const objectDef = target === null ? null : definitionOf(item, target); const display = request.payload_display ?? undefined; + const labels = request.payload_labels ?? undefined; + const objectLabel = typeof request.object_label === 'string' && request.object_label !== '' ? request.object_label : undefined; + + // The definition is withheld because the reader may not read the object, + // not because it is still loading or names no object. + const definitionWithheld = target !== null && hasSnapshot && objectDef === null && !definitionLoading + && perms?.isLoaded === true && !perms.can(target, 'read'); return React.useMemo(() => { - if (target === null || objectDef === null || !hasSnapshot) return null; + if (target === null || !hasSnapshot) return null; + if (objectDef === null) { + if (!definitionWithheld) return null; + return servedModel(target, recordId, payload as Record, labels, objectLabel, display, current); + } const snapshot = withoutDeniedFields(payload as Record, perms, target); const currentRow = current.status === 'readable' ? withoutDeniedFields(current.row, perms, target) : null; const sections = resolveSections(objectDef, sectionLabel, t); const plan = planSubmittedRecord(sections, objectDef.fields, snapshot, currentRow); - return { objectName: target, recordId, objectDef, snapshot, display, plan, current }; - }, [target, recordId, objectDef, hasSnapshot, payload, perms, current, sectionLabel, t, display]); + const noFieldAccess = servedFieldKeys(payload as Record).length === 0; + return { objectName: target, recordId, objectDef, snapshot, display, plan, current, noFieldAccess, face: 'declared' }; + }, [target, recordId, objectDef, definitionWithheld, hasSnapshot, payload, perms, current, sectionLabel, t, display, labels, objectLabel]); } /** @@ -335,8 +451,9 @@ function SubmittedValue({ model, field }: { model: SubmittedRecordModel; field: const def = { ...(model.objectDef.fields[field.key] as FieldDef), name: field.key }; const submitted = isBlank(field.value) ? - : model.display?.[field.key] ?? ( - + : model.display?.[field.key] ?? (model.face === 'served' + ? {servedValueText(field.value)} + : ); if (!field.changed) return <>{submitted}; const currentRow = model.current.status === 'readable' ? model.current.row : {}; @@ -453,10 +570,14 @@ export function SubmittedRecordCard({ model, className }: { model: SubmittedReco const recordLinks = useRelatedRecordActions(); const headingId = React.useId(); const { plan, current } = model; - if (plan.sections.length === 0) return null; + if (plan.sections.length === 0 && !model.noFieldAccess) return null; const anchorOf = (index: number) => `${headingId}-section-${index}`; - const objectName = servedObjectLabel(model.objectDef, language, objectLabel, model.objectName); + // A snapshot drawn as served is headed with the label the service sent, and + // never with the object's machine name in its place. + const objectName = model.face === 'served' && model.objectDef.label === undefined + ? null + : servedObjectLabel(model.objectDef, language, objectLabel, model.objectName); const href = current.status === 'readable' && model.recordId !== null && recordLinks?.recordHref ? recordLinks.recordHref(model.objectName, model.recordId) @@ -494,7 +615,14 @@ export function SubmittedRecordCard({ model, className }: { model: SubmittedReco )}
- {current.status === 'unreadable' && ( + {model.noFieldAccess && ( +

+ {String(t('approvalsInbox.snapshotNoFieldAccess', { + defaultValue: "You don't have access to this object's fields; ask an administrator.", + }))} +

+ )} + {current.status === 'unreadable' && !model.noFieldAccess && (

{String(t('approvalsInbox.snapshotCurrentUnreadable', { defaultValue: 'The current record cannot be read, so changes made after submission are not marked.', @@ -507,7 +635,7 @@ export function SubmittedRecordCard({ model, className }: { model: SubmittedReco section.label ? [{ key: section.key, label: section.label, anchorId: anchorOf(i) }] : [], )} /> -

+ {plan.sections.length > 0 &&
{plan.sections.map((section, i) => (
{section.label && } @@ -531,7 +659,7 @@ export function SubmittedRecordCard({ model, className }: { model: SubmittedReco
))} -
+
} ); } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index f1decd320f8..7bdd5c57702 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5448,6 +5448,7 @@ const ar = { snapshotOpenRecord: 'فتح السجل', snapshotCurrentUnreadable: 'تتعذر قراءة السجل الحالي، لذا لا تُعلَّم التغييرات التي تمت بعد الإرسال.', snapshotChildCurrent: 'الصفوف الحالية: لا يحفظ الإرسال الصفوف الفرعية.', + snapshotNoFieldAccess: "ليس لديك حق الوصول إلى حقول هذا الكائن؛ اطلب من المسؤول منحك الوصول.", progressTitle: 'تقدم الموافقة', attachmentsTitle: 'المرفقات', attachmentChip: 'مرفق', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 2d3313ffd7f..3a511736128 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5038,6 +5038,7 @@ const de = { snapshotOpenRecord: 'Datensatz öffnen', snapshotCurrentUnreadable: 'Der aktuelle Datensatz kann nicht gelesen werden, daher sind Änderungen nach der Einreichung nicht markiert.', snapshotChildCurrent: 'Aktuelle Zeilen: Die Einreichung speichert keine untergeordneten Zeilen.', + snapshotNoFieldAccess: "Sie haben keinen Zugriff auf die Felder dieses Objekts; bitten Sie Ihren Administrator um Zugriff.", progressTitle: 'Genehmigungsfortschritt', attachmentsTitle: 'Anhänge', attachmentChip: 'Anhang', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 87885c4cc07..174888139b2 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5985,6 +5985,7 @@ const en = { snapshotOpenRecord: 'Open record', snapshotCurrentUnreadable: 'The current record cannot be read, so changes made after submission are not marked.', snapshotChildCurrent: 'Current rows: the submission does not keep child rows.', + snapshotNoFieldAccess: "You don't have access to this object's fields; ask an administrator.", progressTitle: 'Approval progress', attachmentsTitle: 'Attachments', attachmentChip: 'Attachment', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 2f2e420189c..825647e0dcb 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5141,6 +5141,7 @@ const es = { snapshotOpenRecord: 'Abrir registro', snapshotCurrentUnreadable: 'No se puede leer el registro actual, así que los cambios posteriores al envío no se marcan.', snapshotChildCurrent: 'Filas actuales: el envío no guarda las filas secundarias.', + snapshotNoFieldAccess: "No tiene acceso a los campos de este objeto; pida acceso a su administrador.", progressTitle: 'Progreso de la aprobación', attachmentsTitle: 'Adjuntos', attachmentChip: 'Adjunto', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 92d095c6b36..6b059d425d2 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5137,6 +5137,7 @@ const fr = { snapshotOpenRecord: 'Ouvrir l’enregistrement', snapshotCurrentUnreadable: 'L’enregistrement actuel est illisible ; les modifications après la soumission ne sont donc pas signalées.', snapshotChildCurrent: 'Lignes actuelles : la soumission ne conserve pas les lignes enfants.', + snapshotNoFieldAccess: "Vous n'avez pas accès aux champs de cet objet ; demandez l'accès à votre administrateur.", progressTitle: 'Avancement de l’approbation', attachmentsTitle: 'Pièces jointes', attachmentChip: 'Pièce jointe', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 79103cf8363..b82505df12c 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5040,6 +5040,7 @@ const ja = { snapshotOpenRecord: 'レコードを開く', snapshotCurrentUnreadable: '現在のレコードを読み取れないため、申請後の変更は表示されません。', snapshotChildCurrent: '現在の値:申請時の明細行は保存されていません。', + snapshotNoFieldAccess: 'このオブジェクトのフィールドにアクセスする権限がありません。管理者にアクセス権を依頼してください。', progressTitle: '承認の進捗', attachmentsTitle: '添付ファイル', attachmentChip: '添付ファイル', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index bf63efdd035..16725341d19 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5037,6 +5037,7 @@ const ko = { snapshotOpenRecord: '레코드 열기', snapshotCurrentUnreadable: '현재 레코드를 읽을 수 없어 제출 후 변경 사항을 표시하지 않습니다.', snapshotChildCurrent: '현재 값: 제출 당시 하위 행은 저장되지 않습니다.', + snapshotNoFieldAccess: '이 개체의 필드에 접근할 권한이 없습니다. 관리자에게 접근 권한을 요청하세요.', progressTitle: '승인 진행 상황', attachmentsTitle: '첨부 파일', attachmentChip: '첨부 파일', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 43dbc10ca8a..7baa81a1a04 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5136,6 +5136,7 @@ const pt = { snapshotOpenRecord: 'Abrir registro', snapshotCurrentUnreadable: 'Não é possível ler o registro atual, então as alterações após o envio não são marcadas.', snapshotChildCurrent: 'Linhas atuais: o envio não guarda as linhas filhas.', + snapshotNoFieldAccess: "Você não tem acesso aos campos deste objeto; peça acesso ao seu administrador.", progressTitle: 'Progresso da aprovação', attachmentsTitle: 'Anexos', attachmentChip: 'Anexo', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index e90c106a8d6..ecdcdf19912 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5253,6 +5253,7 @@ const ru = { snapshotOpenRecord: 'Открыть запись', snapshotCurrentUnreadable: 'Не удаётся прочитать текущую запись, поэтому изменения после подачи не отмечены.', snapshotChildCurrent: 'Текущие строки: при подаче дочерние строки не сохраняются.', + snapshotNoFieldAccess: "У вас нет доступа к полям этого объекта; запросите доступ у администратора.", progressTitle: 'Ход согласования', attachmentsTitle: 'Вложения', attachmentChip: 'Вложение', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 58824e2183b..7751b9f3546 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5293,6 +5293,7 @@ const zh = { snapshotOpenRecord: '打开记录', snapshotCurrentUnreadable: '无法读取当前记录,提交后的改动无法标出。', snapshotChildCurrent: '当前值:提交时未保存子表数据。', + snapshotNoFieldAccess: '你没有查看此对象字段的权限,请联系管理员。', progressTitle: '审批进度', attachmentsTitle: '附件', attachmentChip: '附件', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 7378c1291ff..e4e58ace47d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5293,6 +5293,7 @@ const zhHant = { snapshotOpenRecord: '開啟記錄', snapshotCurrentUnreadable: '無法讀取當前記錄,提交後的改動無法標出。', snapshotChildCurrent: '當前值:提交時未儲存子表資料。', + snapshotNoFieldAccess: '你沒有檢視此物件欄位的權限,請聯絡管理員。', progressTitle: '審批進度', attachmentsTitle: '附件', attachmentChip: '附件',