diff --git a/.changeset/35723-approval-activity-feed.md b/.changeset/35723-approval-activity-feed.md new file mode 100644 index 00000000000..df0dab4d7b7 --- /dev/null +++ b/.changeset/35723-approval-activity-feed.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-approvals': patch +'@object-ui/plugin-detail': patch +'@object-ui/app-shell': patch +--- + +feat(plugin-approvals): a record's activity shows its approval steps, to the users who can read its approvals + +Clause-②: no +Metadata-protocol: none + +A record under approval used to show no approval in its activity: nothing wrote an activity entry for an approval step, so the activity stream's one-line approval entry was reachable only from items a host supplied by hand. + +- **One activity entry per approval step.** plugin-approvals now appends one `sys_activity` entry for each step it records in its decision log, about the record the request governs: submitted, approved (`Approved · Manager review`, the step's label after the dot), rejected (`Rejected · Manager review`), sent back for revision (`Sent back for revision · Manager review`), resubmitted, recalled, and cancelled (the record was deleted). Other actions (a reminder, a reassignment, a thread comment, …) write none, and an object that sets `enable.activities: false` gets none, as the CRUD mirror writes none for it. The entry carries no decision comment. It follows ADR-0052 §5, so no published vocabulary changes: `type` is the built-in `system`, the domain kind is `metadata.kind: 'approval'` (with the step's action, its label and the flow and step names beside it), and `source_object` / `source_id` name the request. A deployment without plugin-audit has no `sys_activity` and gets no entries. +- **Each entry reads in the reader's language.** The stored `summary` is the English line from plugin-approvals' own catalog (`approvalActivity*` messages, shipped in all eleven of its locales). A read that carries a locale is served the line re-composed in that locale, and the step's label is read from the app's language pack (`flows..approvals..label`) the way the approvals tab reads it, else the stored label: a zh-CN reader sees `已批准 · 经理审批`. A system read, or a read with no locale, gets the stored English line. A failed append never fails the approval step; it is logged once at `error`. +- **Only the users who can read the record's approvals read those entries.** A read of `sys_activity` keeps an approval entry only when the approvals service would serve the caller its request: a participant (submitter, current or past approver), the override actor, or a reader of the record where the object opts into `enable.approvalsVisibleToReaders`. Every other entry is served as before, and plugin-audit's rule that the record must be readable still applies. The record page's activity count and its rows agree. +- **The stream draws each entry as the approval line, and 「看审批」 opens the approvals.** The console reads an activity row with `type: 'system'`, `metadata.kind: 'approval'` and a `sys_approval_request` source as the `approval` feed kind (`APPROVAL_ACTIVITY_FEED_TYPE`, exported from `@object-ui/plugin-detail`), so `approval` now counts as produced. The record page supplies the new `RecordViewApprovalsContext`, and the approval line's 「看审批」 opens the record's 审批 tab, the same place the approval tag in the header opens; with no approvals the reader is served, the line has no link. The entry keeps `sys_activity`'s own lifecycle (reaped after 14 days); the 审批 tab keeps the full history. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index 603b69e00bb..ffcad6496e4 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -510,7 +510,7 @@ edited (`is_edited` on the row). ### Feed kinds with no producer -`FeedItemType` publishes thirteen kinds. ObjectUI produces **five** of them: +`FeedItemType` publishes thirteen kinds. ObjectUI produces **six** of them: | kind | produced by | |---|---| @@ -519,22 +519,23 @@ edited (`is_edited` on the row). | `event` | `sys_activity` type `scheduled` | | `system` | `sys_activity` type `system`, **and** any author-extended type the map has never seen (it renders through the generic presentation rather than vanishing), **and** a `completed` row a milestone fired (`metadata.kind: 'milestone'`) | | `comment` | `sys_comment` rows, merged in by the console's record page and handed to the block through the discussion context | +| `approval` | `sys_activity` type `system` with `metadata.kind: 'approval'` and `source_object: 'sys_approval_request'`, which plugin-approvals writes once per approval step (submitted, approved, rejected, recalled); served only to the users who can read the record's approvals | -The other eight — `email`, `call`, `note`, `file`, `record_create`, -`record_delete`, `approval`, `sharing` — have no producer on any ObjectUI +The other seven — `email`, `call`, `note`, `file`, `record_create`, +`record_delete`, `sharing` — have no producer on any ObjectUI surface. A `types` list of only such kinds renders a **permanently empty** timeline. Since objectui#5877 it also emits one `console.warn` per distinct kind, so the emptiness is diagnosable instead of looking like "a working feature with no data yet". Beside the default composer such a list is refused before it ever renders. -`types: ['approval']` leaves out `'comment'` while `showCommentInput` defaults +`types: ['call']` leaves out `'comment'` while `showCommentInput` defaults to `true`, so `os lint`, `os validate`, `os build`, the page save door and the console's schema mirror report it at error as `component-props-invalid` at `properties.showCommentInput` (`properties.feed.showCommentInput` on `record:chatter` / `record:discussion`). Add `'comment'` to `types` when the block should take comments, or set `showCommentInput: false` when it should -stay comment-free; `types: ['approval']` with `showCommentInput: false` parses +stay comment-free; `types: ['call']` with `showCommentInput: false` parses and renders the empty timeline above. A page already stored with the shape still loads; its next save is refused. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 9c96a92a58f..383e9144494 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -120,7 +120,7 @@ bugs — it is the protection or the side effect that silently does not happen. | 13 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `isPerfDisclosurePrincipal` | | 15 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `enforceApiExposure` | | 16 | **Read-audit rows are not written** | plugin-audit | Lose: the "a person opened this record" trail. `sudo()` keeps the caller's `userId`, so this flag is the only thing separating a human read from a platform one | `installReadAuditWriter` | -| 17 | Approval snapshot payload redaction skipped, and so is the snapshot query guard and the reader-locale label overlay | plugin-approvals | Get: the whole snapshot on `find` / `findOne` — the audit/replay channel — and a filter, sort or grouping by it on any read; and a request's `process_label` / `current_step_label` as stored, never in a locale the context carries, so nothing the platform reads back and writes again holds a reader's language. Lose: field-visibility redaction over approval payloads, the refusal of a query over the snapshot for a reader withheld a field of the objects it can reach, and the flow and step labels in the reader's language | `bindSnapshotRedactionMiddleware`, `bindSnapshotPredicateGuard`, `bindReaderLocaleLabelsMiddleware` | +| 17 | Approval snapshot payload redaction skipped, and so is the snapshot query guard and the reader-locale label overlay | plugin-approvals | Get: the whole snapshot on `find` / `findOne` — the audit/replay channel — and a filter, sort or grouping by it on any read; a request's `process_label` / `current_step_label` as stored, and an approval entry's `sys_activity.summary` as stored (its English line), never in a locale the context carries, so nothing the platform reads back and writes again holds a reader's language. Lose: field-visibility redaction over approval payloads, the refusal of a query over the snapshot for a reader withheld a field of the objects it can reach, and the flow and step labels and the approval entry's line in the reader's language | `bindSnapshotRedactionMiddleware`, `bindSnapshotPredicateGuard`, `bindReaderLocaleLabelsMiddleware`, `bindApprovalActivityLocale` | | 18 | REST anonymous-deny seam satisfied | rest | Get: `enforceAuth` passes with no `userId`. Not reachable from the wire — `isSystem` is never set on an inbound request | `enforceAuth` | | 18b | Settings namespace read scope not applied | service-settings | Get: a read of `sys_setting`, `sys_setting_audit` or `sys_platform_setting` across every namespace, whatever each namespace's `readPermission` names — the settings service's own reads of its stores take this path. Lose: the per-namespace read gate the generic data API applies to every other caller, the same rule the settings routes enforce | `settingsReadDoorMiddleware` | | 18c | **Credential-column filter / sort refusal not applied** — a `where`, `orderBy`, per-aggregation `filter` or `expand` entry naming a `password` / `secret` column is evaluated | objectql | Get: the server's own match on a stored credential value, a lookup that never returns it. Every other caller, administrators included, is refused `400 INVALID_FIELD` for anything but a has-a-value check (ADR-0100). Lose: nothing a wire caller reaches — `isSystem` is never set on an inbound request | `rejectCredentialEvaluation` | @@ -572,6 +572,7 @@ and CI refuses one that differs from what the tree produces. | `packages/objectql/src/stored-metadata-type-read-gate.ts#storedMetadataTypeReadFilter` | 1 | 18d | | `packages/observability/src/perf-timing.ts#isPerfDisclosurePrincipal` | 1 | 13 | | `packages/plugins/organizations/src/organizations-plugin.ts#start` | 1 | 62 | +| `packages/plugins/plugin-approvals/src/approval-activity-feed.ts#bindApprovalActivityLocale` | 1 | 17 | | `packages/plugins/plugin-approvals/src/approval-service.ts#assertAttachmentsUploadedByCaller` | 1 | 43 | | `packages/plugins/plugin-approvals/src/approval-service.ts#comment` | 1 | 43 | | `packages/plugins/plugin-approvals/src/approval-service.ts#isOverrideActor` | 1 | 43 | diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index 0cdc477f910..9944d4a929d 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 41 | -| Object name statically decidable | 39 | +| Write call sites | 42 | +| Object name statically decidable | 40 | | Object name chosen at run time | 2 | | Object name spelled inline | 38 | -| Object name spelled through a `const` | 1 | +| Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 39 | +| Against a tenancy-enabled object | 40 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 41 | +| Threading a tenant context | 42 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 39 | +| Threading a decidably elevated (`isSystem`) context | 40 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 41 | +| Receiver carried a readable engine type | 42 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -48,6 +48,7 @@ a row or a number here — fix the code, or the census, and regenerate. | file | verb | object | tenancy | tenant context | n | |---|---|---|---|---|---:| | `packages/plugins/plugin-approvals/src/action-slot-backfill.ts` | `update` | `sys_approval_action` | enabled | elevated | 2 | +| `packages/plugins/plugin-approvals/src/approval-activity-feed.ts` | `insert` | `sys_activity` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `object` | undecidable | context, elevation undecidable | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 17 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | diff --git a/packages/plugins/plugin-approvals/src/approval-activity-feed-35723.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-activity-feed-35723.integration.test.ts new file mode 100644 index 00000000000..4fea6edc38b --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-activity-feed-35723.integration.test.ts @@ -0,0 +1,361 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35723] Approval steps reach the record's activity stream, and only the + * users who can read the record's approvals read them. + * + * - one `sys_activity` entry per approval step (submitted, approved, + * rejected, recalled, sent back, resubmitted, cancelled) about the record the request + * governs, in the shape the + * console reads as the `approval` feed kind: `type: 'system'`, + * `metadata.kind: 'approval'`, `source_object: 'sys_approval_request'`; + * - no entry for a step the stream does not show (a thread comment), and none + * on an object that sets `enable.activities: false`; + * - a reader with a locale is served each entry's line in that locale, the + * step's label read from the app's flows pack (a zh-CN reader below); a + * reader without one, and the system, are served the stored English line; + * - on the generic data door, as the record page reads its stream (the record + * named by `object_name` + `record_id`): a participant reads the entries, a + * reader of the record who participates in nothing reads none — while every + * other entry about the record stays served to both, and the stream's count + * agrees with its rows — and an object that opts into the record-reader tier + * serves the same reader its entries. + * + * ## The rig + * + * The sibling read-gate suites' (`record-reader-opt-in.integration.test.ts`): a + * real ObjectQL engine over better-sqlite3, the real + * `ApprovalsServicePlugin.start()`, so the producer and the gate are bound as in + * a deployment, and the real data-door normalizer. Two stand-ins: RECORD + * READABILITY (one middleware per business object scopes a caller to its own + * records), and `sys_activity`'s definition, which is plugin-audit's — this + * package does not depend on it, so the suite declares the columns the stream + * reads. plugin-audit's own parent-record gate is not mounted: what is under + * test is the narrowing this package adds on top of it. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import type { ApprovalService } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; +import { createMemoryI18n } from '@objectstack/core'; +import { ApprovalsTranslations } from './translations/index.js'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; + +const PKG = 'approvals-activity-feed-35723-test'; +const READ_OPS = new Set(['find', 'findOne', 'count', 'aggregate']); +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const asUser = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const SUBMITTER = 'u_submitter'; +const APPROVER = 'u_approver'; +/** Reads every record and participates in nothing. */ +const READER = 'u_reader'; + +/** Declares nothing: the record-reader tier stays off. */ +const SHEET = 'memo_sheet'; +/** Opts into the record-reader tier in its own `enable` block. */ +const OPEN_SHEET = 'exam_sheet'; +/** Opts out of its timeline (`enable.activities: false`). */ +const MUTED_SHEET = 'quiet_sheet'; +/** The step's authored label, and its label in the app's zh-CN pack. */ +const STEP = 'Manager review'; +const STEP_ZH = '经理审批'; + +const text = (name: string) => ({ name, label: name, type: 'text' as const }); + +function sheet(name: string, enable?: Record) { + return { + name, + label: name, + fields: { id: { ...text('id'), primaryKey: true }, title: text('title') }, + ...(enable ? { enable } : {}), + }; +} + +/** `sys_user`: the columns the entry's actor snapshot reads. */ +const sysUser = { + name: 'sys_user', + label: 'User', + nameField: 'name', + fields: { id: { ...text('id'), primaryKey: true }, name: text('name'), image: text('image'), email: text('email') }, +}; + +/** `sys_activity`, the stand-in (see the header): the columns the stream reads. */ +const sysActivity = { + name: 'sys_activity', + label: 'Activity Feed', + fields: { + id: { ...text('id'), primaryKey: true }, + timestamp: { name: 'timestamp', label: 'Timestamp', type: 'datetime' as const }, + type: text('type'), + summary: text('summary'), + actor_id: text('actor_id'), + actor_name: text('actor_name'), + actor_avatar_url: text('actor_avatar_url'), + object_name: text('object_name'), + record_id: text('record_id'), + source_object: text('source_object'), + source_id: text('source_id'), + metadata: { name: 'metadata', label: 'Metadata', type: 'textarea' as const }, + }, +}; + +const nodeConfig = { approvers: [{ type: 'user' as const, value: APPROVER }], behavior: 'first_response' as const }; + +interface Rig { + engine: ObjectQL; + svc: ApprovalService; + protocol: any; +} + +let current: ObjectQL | undefined; + +afterEach(async () => { + try { await current?.destroy(); } catch { /* noop */ } + current = undefined; +}); + +function guardReads(engine: ObjectQL, object: string): void { + engine.registerMiddleware(async (op: any, next: () => Promise) => { + const ctx = op.context; + if (READ_OPS.has(op.operation) && ctx && !ctx.isSystem && op.ast) { + const scope = { id: { $like: `${object}_%` } }; + op.ast.where = op.ast.where ? { $and: [op.ast.where, scope] } : scope; + } + return next(); + }, { object }); +} + +async function boot(opts: { i18n?: unknown } = {}): Promise { + const engine = new ObjectQL(); + current = engine; + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, + }), true); + await engine.init(); + for (const def of [ + sheet(SHEET), sheet(OPEN_SHEET, { approvalsVisibleToReaders: true }), sheet(MUTED_SHEET, { activities: false }), + sysUser, sysActivity, + SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, + ]) { + engine.registry.registerObject(def as any, PKG, PKG); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const object of [SHEET, OPEN_SHEET]) guardReads(engine, object); + for (const [id, name] of [[SUBMITTER, 'Sam Submitter'], [APPROVER, 'Ada Approver'], [READER, 'Rae Reader']]) { + await engine.insert('sys_user', { id, name, image: `https://img.example/${id}.png` }, { context: SYSTEM } as any); + } + + const services: Record = { objectql: engine, ...(opts.i18n ? { i18n: opts.i18n } : {}) }; + const ctx: any = { + getService: (name: string) => { + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); + return services[name]; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: () => {}, + logger: { info: () => {}, debug: () => {}, warn: () => {}, error: () => {} }, + }; + await new ApprovalsServicePlugin().start(ctx); + const svc = services.approvals as ApprovalService; + svc.attachAutomation({ + resume: async () => ({ status: 'completed' }), + cancelRun: async () => undefined, + getRun: async (runId: string) => ({ id: runId, status: 'paused' }), + getFlow: async () => ({ + name: 'memo_review', + nodes: [{ id: 'review', type: 'approval' }, { id: 'rework', type: APPROVAL_REVISE_NODE_TYPE }], + edges: [{ id: 'e_revise', source: 'review', target: 'rework', label: 'revise' }], + }), + } as any); + return { engine, svc, protocol: new ObjectStackProtocolImplementation(engine as any) }; +} + +async function open(rig: Rig, object: string, recordId: string): Promise { + await rig.engine.insert(object, { id: recordId, title: recordId }, { context: SYSTEM } as any); + const row: any = await rig.svc.openNodeRequest({ + object, recordId, runId: `run_${recordId}`, nodeId: 'review', nodeLabel: STEP, flowName: 'memo_review', + config: nodeConfig as any, submitterId: SUBMITTER, record: { id: recordId, title: recordId }, + }, asUser(SUBMITTER)); + return String(row.id); +} + +/** Every `sys_activity` row about `recordId`, as the system reads them, oldest first. */ +async function entriesOf(rig: Rig, recordId: string): Promise { + const rows = (await rig.engine.find('sys_activity', { + where: { record_id: recordId }, context: SYSTEM, + })) as any[]; + return rows.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp)) || 0); +} + +/** The record page's stream read on the data door: its rows' summaries and its count. */ +async function streamOf(rig: Rig, caller: any, object: string, recordId: string, query: Record = {}) { + const res = await rig.protocol.findData({ + object: 'sys_activity', + query: { object_name: object, record_id: recordId, $count: true, ...query }, + context: caller, + }); + const records = (res.records as any[]); + return { + approval: records.filter((r) => r.source_object === 'sys_approval_request').map((r) => r.summary).sort(), + other: records.filter((r) => r.source_object !== 'sys_approval_request').map((r) => r.summary).sort(), + total: res.total, + }; +} + +const kindOf = (row: any) => JSON.parse(row.metadata); + +describe('approval steps on the record activity stream (#35723)', () => { + it('writes one approval entry per step — submitted, approved, rejected, recalled — about the governed record', async () => { + const rig = await boot(); + const approved = await open(rig, SHEET, `${SHEET}_approved`); + await rig.svc.comment(approved, { actorId: APPROVER, comment: 'looking' }, asUser(APPROVER)); + await rig.svc.decideNode(approved, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); + const rejected = await open(rig, SHEET, `${SHEET}_rejected`); + await rig.svc.decideNode(rejected, { decision: 'reject', actorId: APPROVER, comment: 'no budget' }, asUser(APPROVER)); + const recalled = await open(rig, SHEET, `${SHEET}_recalled`); + await rig.svc.recall(recalled, { actorId: SUBMITTER } as any, asUser(SUBMITTER)); + + const cases: Array<[string, string, Array<[string, string]>]> = [ + [`${SHEET}_approved`, approved, [['submit', SUBMITTER], ['approve', APPROVER]]], + [`${SHEET}_rejected`, rejected, [['submit', SUBMITTER], ['reject', APPROVER]]], + [`${SHEET}_recalled`, recalled, [['submit', SUBMITTER], ['recall', SUBMITTER]]], + ]; + for (const [recordId, requestId, steps] of cases) { + const entries = await entriesOf(rig, recordId); + // One per step; the thread comment on the first request wrote none. + expect(entries.map((e) => [kindOf(e).action, e.actor_id]), recordId).toEqual(steps); + for (const entry of entries) { + expect(entry).toMatchObject({ + type: 'system', + object_name: SHEET, + record_id: recordId, + source_object: 'sys_approval_request', + source_id: requestId, + }); + expect(kindOf(entry).kind).toBe('approval'); + // No decision comment rides on the one line. + expect(entry.metadata).not.toContain('no budget'); + expect(entry.summary).not.toContain('no budget'); + } + } + const [submitted, approvedEntry] = await entriesOf(rig, `${SHEET}_approved`); + expect(submitted).toMatchObject({ + summary: 'Submitted for approval', + actor_name: 'Sam Submitter', + actor_avatar_url: `https://img.example/${SUBMITTER}.png`, + }); + // The step half of the line, and the machine names its label is translated by. + expect(approvedEntry.summary).toBe(`Approved · ${STEP}`); + expect(kindOf(approvedEntry)).toEqual({ + kind: 'approval', action: 'approve', step_label: STEP, flow_name: 'memo_review', step_name: 'review', + }); + expect((await entriesOf(rig, `${SHEET}_rejected`))[1].summary).toBe(`Rejected · ${STEP}`); + expect((await entriesOf(rig, `${SHEET}_recalled`))[1].summary).toBe('Recalled the approval request'); + expect(approvedEntry.actor_name).toBe('Ada Approver'); + }); + + it('writes an entry when a request is sent back for revision and when it is resubmitted', async () => { + const rig = await boot(); + const recordId = `${SHEET}_revised`; + const requestId = await open(rig, SHEET, recordId); + await rig.svc.sendBack(requestId, { actorId: APPROVER }, asUser(APPROVER)); + await rig.svc.resubmit(requestId, { actorId: SUBMITTER }, asUser(SUBMITTER)); + const entries = await entriesOf(rig, recordId); + expect(entries.map((e) => [kindOf(e).action, e.summary])).toEqual([ + ['submit', 'Submitted for approval'], + ['revise', `Sent back for revision · ${STEP}`], + ['resubmit', 'Resubmitted for approval'], + ]); + }); + + it('writes a cancelled entry, attributed to no one, when the governed record is deleted', async () => { + const rig = await boot(); + const recordId = `${SHEET}_deleted`; + await open(rig, SHEET, recordId); + await rig.engine.delete(SHEET, { where: { id: recordId }, context: SYSTEM } as any); + const entries = await entriesOf(rig, recordId); + expect(entries.map((e) => [kindOf(e).action, e.summary, e.actor_id ?? null])).toEqual([ + ['submit', 'Submitted for approval', SUBMITTER], + ['cancel', 'Approval request cancelled', null], + ]); + }); + + it('writes no entry on an object that sets enable.activities: false', async () => { + const rig = await boot(); + const recordId = `${MUTED_SHEET}_a`; + const requestId = await open(rig, MUTED_SHEET, recordId); + await rig.svc.decideNode(requestId, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); + // The decision log has the steps; the muted timeline has none of them. + const actions = (await rig.engine.find('sys_approval_action', { + where: { request_id: requestId }, context: SYSTEM, + })) as any[]; + expect(actions.map((a) => a.action).sort()).toEqual(['approve', 'submit']); + expect(await entriesOf(rig, recordId)).toEqual([]); + }); + + it('serves a zh-CN reader each line in zh-CN, its step label from the flows pack; others read the stored line', async () => { + const i18n = createMemoryI18n(); + for (const [locale, data] of Object.entries(ApprovalsTranslations)) i18n.loadTranslations(locale, data as any); + i18n.loadTranslations('zh-CN', { flows: { memo_review: { approvals: { review: { label: STEP_ZH } } } } }); + const rig = await boot({ i18n }); + const recordId = `${SHEET}_zh`; + const requestId = await open(rig, SHEET, recordId); + await rig.svc.decideNode(requestId, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); + const zh = { ...asUser(SUBMITTER), locale: 'zh-CN' }; + + expect((await streamOf(rig, zh, SHEET, recordId)).approval).toEqual([`已批准 · ${STEP_ZH}`, '已提交审批']); + // A list that projects only the line still recognises the entry, and is served only what it asked for. + const projected = await rig.protocol.findData({ + object: 'sys_activity', query: { object_name: SHEET, record_id: recordId, $select: 'summary' }, context: zh, + }); + expect((projected.records as any[]).map((r) => r.summary).sort()).toEqual([`已批准 · ${STEP_ZH}`, '已提交审批']); + for (const row of projected.records as any[]) expect(Object.keys(row).filter((k) => k !== 'id')).toEqual(['summary']); + // A reader with no locale, and the system with one, read the stored English. + expect((await streamOf(rig, asUser(SUBMITTER), SHEET, recordId)).approval) + .toEqual([`Approved · ${STEP}`, 'Submitted for approval']); + const stored = (await rig.engine.find('sys_activity', { + where: { record_id: recordId }, context: { ...SYSTEM, locale: 'zh-CN' }, + })) as any[]; + expect(stored.map((r) => r.summary).sort()).toEqual([`Approved · ${STEP}`, 'Submitted for approval']); + }); + + it('serves the entries to a participant, none to a reader without approval access, and keeps every other entry', async () => { + const rig = await boot(); + const recordId = `${SHEET}_a`; + await open(rig, SHEET, recordId); + await rig.engine.insert('sys_activity', { + id: 'act_created', type: 'created', summary: 'Created memo', timestamp: '2026-01-01T00:00:00.000Z', + object_name: SHEET, record_id: recordId, + }, { context: SYSTEM } as any); + + const participant = await streamOf(rig, asUser(SUBMITTER), SHEET, recordId); + expect(participant).toEqual({ approval: ['Submitted for approval'], other: ['Created memo'], total: 2 }); + + // The same record, read by a user who can open it but is served none of its approvals. + expect(await rig.svc.listRequests({ object: SHEET, recordId }, asUser(READER))).toEqual([]); + const reader = await streamOf(rig, asUser(READER), SHEET, recordId); + expect(reader).toEqual({ approval: [], other: ['Created memo'], total: 1 }); + + // The system's own reads are never narrowed. + expect((await entriesOf(rig, recordId)).length).toBe(2); + }); + + it('serves a reader the entries of a record whose object opts into the record-reader tier', async () => { + const rig = await boot(); + const recordId = `${OPEN_SHEET}_a`; + await open(rig, OPEN_SHEET, recordId); + expect((await rig.svc.listRequests({ object: OPEN_SHEET, recordId }, asUser(READER))).length).toBe(1); + const reader = await streamOf(rig, asUser(READER), OPEN_SHEET, recordId); + expect(reader).toEqual({ approval: ['Submitted for approval'], other: [], total: 1 }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-activity-feed.ts b/packages/plugins/plugin-approvals/src/approval-activity-feed.ts new file mode 100644 index 00000000000..800c61a4ce9 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-activity-feed.ts @@ -0,0 +1,474 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35723] Approval steps on the record's activity stream. + * + * The record page's 动态 stream draws `sys_activity` rows. Until this module + * nothing wrote one for an approval, so a record under approval showed no + * approval in its activity: the stream's one-line approval entry (the + * `approval` feed kind, with 「看审批」 opening the record's approvals) was + * reachable only from items a host supplied by hand. + * + * ## The producer + * + * {@link bindApprovalActivityFeed}: an `afterInsert` hook on the decision log, + * `sys_approval_action`. Every approval step already lands there, one row per + * step, written by `ApprovalService` with the record it governs copied onto + * the row (`object_name` + `record_id`, the request's pointer pair). For each + * row of a kind in {@link APPROVAL_ACTIVITY_STEPS} — `submit`, `approve`, + * `reject`, `recall`, `revise` (sent back for revision), `resubmit` and + * `cancel` — the hook appends one `sys_activity` row about that record. Reading the decision log rather than calling in from each decision + * method keeps `approval-service.ts` untouched, and a step the service learns + * to record in a new place reaches the stream with no second call site. + * + * The row is shaped as ADR-0052 §5 says a domain event rides the ActivityPointer + * model, so no published vocabulary moves: + * + * - `type` stays domain-NEUTRAL: `system`, a built-in value only the platform + * may write (`SYS_ACTIVITY_PLATFORM_TYPES`; the app activity door refuses + * it), so an app cannot write a row that reads as an approval step; + * - the domain kind rides in `metadata.kind` ({@link APPROVAL_ACTIVITY_KIND}), + * with the step's action kind, its stored label, and the two machine names + * the label is translated by (`flow_name`, `step_name`) beside it; + * - `source_object` / `source_id` point at the request + * (`sys_approval_request`), the entity the entry drills to. + * + * The console reads exactly that triple as the `approval` feed kind + * (`recordActivityFeed.ts` in `@object-ui/plugin-detail`, which restates the + * three values because it cannot depend on this server plugin). + * + * The row carries no decision comment and no snapshot value: it is the one + * line the stream draws, and the request's detail stays on the approvals tab. + * + * [#35723 L1 N2] An object with `enable.activities: false` gets no entry, as + * the CRUD mirror writes none for it (`audit-writers.ts`): that flag stops + * mirroring into the object's timeline and hides the timeline, so an entry + * there would be written for no reader. + * + * ## In the reader's language + * + * `summary` is the line composed in English from this plugin's catalog + * (`approvalActivity*` in `translations/messages.ts`, {@link APPROVAL_ACTIVITY_STEPS}), + * the text every reader of the column without a locale is served — the shape + * #26167 gave the CRUD mirror (`activity-summary-message.ts` in plugin-audit): + * the sentence is stored with its CODE beside it (here the step's `action` and + * the step's machine names in `metadata`), and a read re-composes it per + * reader. {@link bindApprovalActivityLocale}, an engine middleware on + * `sys_activity`, does that for a non-system read that carries a locale, with + * the approvals door's own lookup (`readerLabelsFor`, `reader-locale-labels.ts`): + * the sentence is `messages.approvalActivity*` in the reader's locale, and the + * step label is `flows..approvals..label` read the way the + * approvals door reads it, else the stored label. ⛔ Nothing here is a second + * negotiation or a second label rule. Nothing is re-composed for a system read, + * a read with no locale or no `i18n` service, a key the locale's pack misses, + * or a row whose `summary` the read was not served — the stored line stands. + * + * ## Who reads it + * + * The card's rule: an approval entry is read by the same users who can read + * the record's approvals. `sys_activity`'s own gate (plugin-audit's + * parent-record gate) keeps a row whenever its record is readable, which here + * would switch the record-reader tier on for every object, against its default + * OFF (`request-read-gate.ts` says why that gate is not this one). + * + * {@link bindApprovalActivityReadGate} therefore narrows `sys_activity` reads + * once more, for the approval rows alone: a row whose `source_object` is + * `sys_approval_request` is kept only when its `source_id` is a request the + * approvals door would serve the caller. ⛔ Nothing here decides who may see a + * request: the answer is the approvals service's own + * ({@link RequestVisibilitySource}, the same source the generic door's gates on + * the request tables read), and a read that names the record (`object_name` + + * `record_id` both pinned, as the record page reads its stream) is asked with + * that record, so an object that opted into the record-reader tier serves its + * readers there too. Every other row passes untouched; plugin-audit's gate + * still applies on top, so a reader must also be able to read the record. + * + * Added as a conjunct of `ast.where` on `find`, `findOne`, `count` and + * `aggregate`, so the record page's `timeline` count and its rows agree. Fails + * CLOSED for the approval rows only: when the source cannot answer, the read + * keeps every other row and no approval row. + * + * ## What stays as it was + * + * A deployment without plugin-audit has no `sys_activity`; the hook then writes + * nothing. A failed append never fails the approval step: the decision log row + * is the record of the step, and the activity row a projection of it. The + * failure is logged at `error` once, with what is lost and the fix. + * `sys_activity` keeps its own lifecycle (entries are reaped after 14 days); + * the approvals tab keeps the full history. + */ + +import { createFieldPresenceProbe } from '@objectstack/metadata-core'; +import type { ApprovalActionKind } from '@objectstack/spec/contracts'; +import { pinnedEquality } from './payload-predicate-guard.js'; +import { APPROVAL_REQUEST_OBJECT, type MiddlewareEngine } from './payload-redaction-middleware.js'; +import { REQUEST_READ_OPS, type RequestVisibilitySource } from './request-read-gate.js'; +import { approvalMessageKey, interpolate } from './approval-notification-text.js'; +import { flowNameOfProcess, readerLabelsFor, type ReaderLabelI18n, type ReaderLabels } from './reader-locale-labels.js'; +import { enMessages, type ApprovalMessageId } from './translations/messages.js'; + +/** The activity stream's table (plugin-audit's). */ +export const ACTIVITY_OBJECT = 'sys_activity'; + +/** The decision log the producer reads. */ +export const APPROVAL_ACTION_OBJECT = 'sys_approval_action'; + +/** `sys_activity.type` of an approval entry: domain-neutral and platform-only (ADR-0052 §5). */ +export const APPROVAL_ACTIVITY_TYPE = 'system'; + +/** `metadata.kind` of an approval entry: the domain kind (ADR-0052 §5). */ +export const APPROVAL_ACTIVITY_KIND = 'approval'; + +/** `sys_activity.source_object` of an approval entry: the request it drills to. */ +export const APPROVAL_ACTIVITY_SOURCE_OBJECT = APPROVAL_REQUEST_OBJECT; + +/** The hook package the producer binds under, so a second `start()` replaces it. */ +export const APPROVAL_ACTIVITY_HOOK_PACKAGE = 'plugin-approvals:activity'; + +/** The catalog sentences of one step kind: its line, and for a decision at a step the twin naming the step. */ +export interface ApprovalActivityStep { + line: ApprovalMessageId; + stepped?: ApprovalMessageId; +} + +/** + * The approval steps the stream shows, each with the catalog sentence its + * entry is written with (`translations/messages.ts`). A kind not listed (a + * reminder, a reassignment, a thread comment, …) writes no entry. + */ +export const APPROVAL_ACTIVITY_STEPS: Readonly>> = Object.freeze({ + submit: { line: 'approvalActivitySubmitted' }, + approve: { line: 'approvalActivityApproved', stepped: 'approvalActivityApprovedStep' }, + reject: { line: 'approvalActivityRejected', stepped: 'approvalActivityRejectedStep' }, + recall: { line: 'approvalActivityRecalled' }, + revise: { line: 'approvalActivitySentBack', stepped: 'approvalActivitySentBackStep' }, + resubmit: { line: 'approvalActivityResubmitted' }, + cancel: { line: 'approvalActivityCancelled' }, +}); + +/** `sys_activity.summary` holds at most this many characters. */ +const SUMMARY_MAX = 500; + +/** The kernel logger's slice used here (`Logger` in `@objectstack/spec/contracts`). */ +type Logger = { + warn: (message: string, meta?: Record) => void; + error?: (message: string, error?: Error, meta?: Record) => void; +}; + +/** The engine slice the producer needs. */ +export interface ApprovalActivityEngine { + registerHook(event: string, handler: (ctx: any) => unknown, options?: Record): void; + unregisterHooksByPackage?(packageId: string): number; + insert(object: string, data: Record, options?: Record): Promise; + find(object: string, options?: Record): Promise; + getSchema?(object: string): unknown; +} + +const text = (value: unknown): string | null => + typeof value === 'string' && value.trim() ? value.trim() : null; + +/** + * The catalog sentence of a step and its params: the step's twin naming the + * step's label where the kind has one and a label is known + * (`Approved · Manager review`), else its line. `null` for a kind the stream + * does not show. + */ +export function approvalActivityMessage( + kind: string, + stepLabel: unknown, +): { id: ApprovalMessageId; params: Record } | null { + const step = Object.prototype.hasOwnProperty.call(APPROVAL_ACTIVITY_STEPS, kind) + ? APPROVAL_ACTIVITY_STEPS[kind as ApprovalActionKind] + : undefined; + if (!step) return null; + const label = step.stepped ? text(stepLabel) : null; + return label && step.stepped ? { id: step.stepped, params: { step: label } } : { id: step.line, params: {} }; +} + +/** The summary an approval entry is written with: its catalog sentence in English ({@link approvalActivityMessage}). */ +export function approvalActivitySummary(kind: string, stepLabel: unknown): string | null { + const message = approvalActivityMessage(kind, stepLabel); + return message ? interpolate(enMessages[message.id], message.params).slice(0, SUMMARY_MAX) : null; +} + +/** What the entry names of the person who took the step. */ +export interface ApprovalActivityActor { + name: string | null; + avatarUrl: string | null; +} + +/** + * The `sys_activity` row for one decision-log row, or `null` when the row is + * not a step the stream shows or names no record. + */ +export function approvalActivityRow( + action: Record, + actor: ApprovalActivityActor, + flowName?: string | null, +): Record | null { + const kind = text(action.action); + const object = text(action.object_name); + const recordId = action.record_id == null ? null : String(action.record_id); + const requestId = action.request_id == null ? null : String(action.request_id); + if (!kind || !object || !recordId || !requestId) return null; + const summary = approvalActivitySummary(kind, action.step_label); + if (!summary) return null; + const actorId = text(action.actor_id); + const stepLabel = text(action.step_label); + const stepName = text(action.step_name); + const flow = text(flowName); + return { + type: APPROVAL_ACTIVITY_TYPE, + timestamp: text(action.created_at) ?? new Date().toISOString(), + summary, + actor_id: actorId, + ...(actorId && actor.name ? { actor_name: actor.name } : {}), + ...(actorId && actor.avatarUrl ? { actor_avatar_url: actor.avatarUrl } : {}), + object_name: object, + record_id: recordId, + source_object: APPROVAL_ACTIVITY_SOURCE_OBJECT, + source_id: requestId, + metadata: JSON.stringify({ + kind: APPROVAL_ACTIVITY_KIND, + action: kind, + ...(stepLabel ? { step_label: stepLabel } : {}), + ...(flow && stepName ? { flow_name: flow, step_name: stepName } : {}), + }), + }; +} + +/** + * Bind the producer: one `sys_activity` row per approval step written to + * `sys_approval_action` (see the header). + */ +export function bindApprovalActivityFeed(engine: ApprovalActivityEngine, logger?: Logger): void { + engine.unregisterHooksByPackage?.(APPROVAL_ACTIVITY_HOOK_PACKAGE); + const has = createFieldPresenceProbe(engine); + let reported = false; + + const actorOf = async (userId: string): Promise => { + const none = { name: null, avatarUrl: null }; + try { + const schema: any = engine.getSchema?.('sys_user'); + const titleField = typeof schema?.nameField === 'string' && has('sys_user', schema.nameField) + ? schema.nameField + : has('sys_user', 'name') ? 'name' : null; + const avatarField = has('sys_user', 'image') ? 'image' : null; + if (!titleField && !avatarField) return none; + const rows = await engine.find('sys_user', { + where: { id: userId }, + fields: ['id', ...(titleField ? [titleField] : []), ...(avatarField ? [avatarField] : [])], + limit: 1, + context: { isSystem: true }, + }); + const row: any = Array.isArray(rows) ? rows[0] : undefined; + if (!row) return none; + return { + name: titleField ? text(row[titleField]) : null, + avatarUrl: avatarField ? text(row[avatarField]) : null, + }; + } catch { + return none; + } + }; + + /** The flow a request runs (`process_name` without `flow:`), the key its step label is translated by. */ + const flowOf = async (requestId: unknown, transaction: unknown): Promise => { + if (requestId == null) return null; + try { + const rows = await engine.find(APPROVAL_ACTIVITY_SOURCE_OBJECT, { + where: { id: String(requestId) }, + fields: ['id', 'process_name'], + limit: 1, + context: { isSystem: true, ...(transaction != null ? { transaction } : {}) }, + }); + const row: any = Array.isArray(rows) ? rows[0] : undefined; + return flowNameOfProcess(row?.process_name) ?? null; + } catch { + // The entry is still written, in its stored label only. + return null; + } + }; + + engine.registerHook('afterInsert', async (ctx: any) => { + const action = ctx?.result as Record | undefined; + if (!action || typeof action !== 'object') return; + // No activity stream on this deployment (no plugin-audit): nothing to write. + if (!has(ACTIVITY_OBJECT, 'type')) return; + if (!approvalActivityMessage(text(action.action) ?? '', null)) return; + // [L1 N2] An object that opts out of its timeline gets no entry, as the CRUD mirror writes none. + const governed = text(action.object_name); + if (!governed || objectMutesActivities(engine, governed)) return; + const actorId = text(action.actor_id); + const row = approvalActivityRow( + action, + actorId ? await actorOf(actorId) : { name: null, avatarUrl: null }, + await flowOf(action.request_id, ctx?.transaction), + ); + if (!row) return; + const organizationId = text(action.organization_id); + if (organizationId && has(ACTIVITY_OBJECT, 'organization_id')) row.organization_id = organizationId; + try { + await engine.insert(ACTIVITY_OBJECT, row, { + context: { + isSystem: true, + ...(organizationId ? { tenantId: organizationId } : {}), + ...(ctx?.transaction != null ? { transaction: ctx.transaction } : {}), + }, + }); + } catch (err: any) { + if (reported) return; + reported = true; + logger?.error?.( + '[approvals] an approval step was recorded but its entry on the record\'s activity stream was not written — ' + + 'the approval itself stands and the approvals tab shows it, but the record\'s activity will keep looking ' + + 'complete without it; later failures are not logged again. Check that sys_activity (plugin-audit) is ' + + 'provisioned and writable on this datasource.', + err instanceof Error ? err : undefined, + { action: action.action, request: action.request_id, error: err?.message ?? String(err) }, + ); + } + }, { object: APPROVAL_ACTION_OBJECT, packageId: APPROVAL_ACTIVITY_HOOK_PACKAGE, priority: 100 }); +} + +/** Whether `object` declares `enable.activities: false` (the spec default is on). */ +function objectMutesActivities(engine: ApprovalActivityEngine, object: string): boolean { + try { + const def: any = engine.getSchema?.(object); + return def?.enable?.activities === false; + } catch { + return false; + } +} + +/** + * The conjunct that keeps every non-approval row and, of the approval rows, + * those whose request is in `visible`; `null` (every request in scope) adds + * none. + */ +export function approvalActivityVisibilityFilter( + visible: ReadonlySet | null, +): Readonly> | null { + if (visible === null) return null; + const notApproval = [ + { source_object: null }, + { source_object: { $ne: APPROVAL_ACTIVITY_SOURCE_OBJECT } }, + ]; + if (visible.size === 0) return { $or: notApproval }; + const ids = [...visible]; + return { $or: [...notApproval, { source_id: ids.length === 1 ? ids[0] : { $in: ids } }] }; +} + +/** + * Bind the read gate on `sys_activity` that serves an approval entry only to a + * caller the approvals door serves its request (see the header). + */ +export function bindApprovalActivityReadGate( + engine: MiddlewareEngine, + source: RequestVisibilitySource, + logger?: Logger, +): void { + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + const ast = opCtx?.ast as { where?: unknown } | undefined; + const context = opCtx?.context; + if (!REQUEST_READ_OPS.has(opCtx?.operation) || !ast || !context) return next(); + let filter: Readonly> | null; + try { + const object = pinnedEquality(ast.where, 'object_name'); + const recordId = pinnedEquality(ast.where, 'record_id'); + const target = object !== null && recordId !== null ? { object, recordId } : undefined; + filter = approvalActivityVisibilityFilter(await source.visibleRequestIdsFor(context, target)); + } catch (err: any) { + logger?.warn?.( + '[approvals] activity read gate could not resolve which approval requests the caller may see — ' + + 'the read is served without its approval entries (fail closed)', + { operation: opCtx.operation, error: err?.message ?? String(err) }, + ); + filter = approvalActivityVisibilityFilter(new Set()); + } + if (filter) ast.where = ast.where ? { $and: [ast.where, filter] } : filter; + return next(); + }, { object: ACTIVITY_OBJECT }); +} + +/** The columns {@link localizeApprovalActivityRow} recognises an approval entry by. */ +const RECOGNITION_COLUMNS = ['type', 'source_object', 'metadata'] as const; + +/** A stored `metadata` value: a JSON object, or `null` for anything else. */ +function metadataOf(raw: unknown): Record | null { + if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw as Record; + if (typeof raw !== 'string' || !raw.trim()) return null; + try { + const value = JSON.parse(raw); + return value && typeof value === 'object' && !Array.isArray(value) ? value : null; + } catch { + return null; + } +} + +/** + * Overlay an approval entry's served `summary` with its line in the reader's + * language, in place: the step's catalog sentence through `labels`, its + * `{{step}}` the step's label as the approvals door reads it, else the stored + * label. Any other row, a row served without a `summary`, and a sentence the + * reader's pack does not hold keep what they carry. + */ +export function localizeApprovalActivityRow(row: Record, labels: ReaderLabels): void { + if (typeof row.summary !== 'string' || !row.summary) return; + if (row.type !== APPROVAL_ACTIVITY_TYPE || row.source_object !== APPROVAL_ACTIVITY_SOURCE_OBJECT) return; + const metadata = metadataOf(row.metadata); + if (!metadata || metadata.kind !== APPROVAL_ACTIVITY_KIND) return; + const flow = text(metadata.flow_name); + const node = text(metadata.step_name); + const step = (flow && node ? labels.stepLabel(flow, node) : undefined) ?? text(metadata.step_label); + const message = approvalActivityMessage(text(metadata.action) ?? '', step); + if (!message) return; + const line = labels.sentence(approvalMessageKey(message.id), message.params); + if (line) row.summary = line.slice(0, SUMMARY_MAX); +} + +/** + * Bind the middleware that serves an approval entry's line in the reader's + * language (see the header). `getI18n` is resolved on each read: the `i18n` + * service is another plugin's and may start after this one. A read that + * projects `summary` without the columns an entry is recognised by borrows + * them for the read and takes them off every row before the rows go back. + */ +export function bindApprovalActivityLocale( + engine: MiddlewareEngine, + getI18n: () => ReaderLabelI18n | undefined, + logger?: Logger, +): void { + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx?.operation !== 'find' && opCtx?.operation !== 'findOne') return next(); + const context = opCtx?.context; + if (!context || context.isSystem) return next(); + let labels: ReaderLabels | undefined; + try { + labels = readerLabelsFor(getI18n(), context.locale); + } catch { + // The i18n service is optional and late-bound: the stored line stands. + labels = undefined; + } + if (!labels) return next(); + const fields: unknown = opCtx.ast?.fields; + const borrowed = Array.isArray(fields) && fields.length > 0 && fields.includes('summary') + ? RECOGNITION_COLUMNS.filter((column) => !fields.includes(column)) + : []; + if (borrowed.length > 0) opCtx.ast.fields = [...(fields as unknown[]), ...borrowed]; + await next(); + const result = opCtx.result; + const rows: unknown[] = Array.isArray(result) ? result : result ? [result] : []; + for (const row of rows) { + if (!row || typeof row !== 'object') continue; + try { + localizeApprovalActivityRow(row as Record, labels); + } catch (err: any) { + logger?.warn('[approvals] activity entry locale middleware failed — the stored line is served', { + error: err?.message ?? String(err), + }); + } + for (const column of borrowed) delete (row as Record)[column]; + } + }, { object: ACTIVITY_OBJECT }); +} diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index cfb6b7a9716..5bd9df80e01 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -39,6 +39,11 @@ import { bindSnapshotRedactionMiddleware } from './payload-redaction-middleware. import { bindSnapshotPredicateGuard } from './payload-predicate-guard.js'; import { bindRequestChildReadGates, bindRequestReadGate } from './request-read-gate.js'; import { bindReaderLocaleLabelsMiddleware } from './reader-locale-labels-middleware.js'; +import { + bindApprovalActivityFeed, + bindApprovalActivityLocale, + bindApprovalActivityReadGate, +} from './approval-activity-feed.js'; import type { FieldVisibilitySource } from './payload-redaction.js'; import { registerApprovalNode, type ApprovalAutomationSurface } from './approval-node.js'; import { backfillActionSlots } from './action-slot-backfill.js'; @@ -452,6 +457,15 @@ export class ApprovalsServicePlugin implements Plugin { // Bound beside the gate, not behind `disableAutoHooks`, for the gate's // reason: the approvals door localizes whenever the service runs. bindReaderLocaleLabelsMiddleware(engine as any, i18nService, ctx.logger); + // [#35723] …and the approval entries on a record's activity stream: one + // `sys_activity` row per approval step, served only to a caller this + // service would serve the request (`approval-activity-feed.ts`). The + // gate and the producer bind together: an entry is never written where + // its reads could not be narrowed. + bindApprovalActivityReadGate(engine as any, visibility, ctx.logger); + bindApprovalActivityFeed(engine as any, ctx.logger); + // …each entry's line in the reader's language, by the same lookup. + bindApprovalActivityLocale(engine as any, i18nService, ctx.logger); } else { ctx.logger.warn( 'ApprovalsServicePlugin: the ObjectQL engine has no middleware seam — reads of sys_approval_request, ' diff --git a/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts b/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts index b96e181032d..67f772015bb 100644 --- a/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts +++ b/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts @@ -192,6 +192,16 @@ const PERSON_SITES: Readonly { expect(editCommand()).toBeUndefined(); }); }); + +// ── RecordDetailView.approvalActivityLine-35723 ───────────────────────────── + +/** + * objectstack#35723 — plugin-approvals writes one `sys_activity` entry per + * approval step about the record it governs (`type: 'system'`, + * `metadata.kind: 'approval'`, the request as its source). The record page's + * stream draws it as the one-line approval entry, and the page wires its + * 「看审批」 to the record's approvals: the 审批 tab the header's approval tag + * opens (objectstack#35595). With no approvals served to the reader the line + * keeps no link. + */ +describe('RecordDetailView.approvalActivityLine-35723', () => { + restoreAfterBlock(); + + const OBJECT = 'os_35723_memo'; + const RECORD = 'm1'; + const REQUEST = 'req_35723'; + + const MEMO_DEF = { + name: OBJECT, + label: 'Memo', + fields: { id: { label: 'Id', type: 'text' }, name: { label: 'Name', type: 'text' } }, + }; + + const ENTRY = { + id: 'act_submit', + type: 'system', + summary: 'Submitted for approval', + timestamp: '2026-11-20T09:00:00.000Z', + actor_id: 'u_submitter', + actor_name: 'Sam Submitter', + object_name: OBJECT, + record_id: RECORD, + source_object: 'sys_approval_request', + source_id: REQUEST, + metadata: JSON.stringify({ kind: 'approval', action: 'submit' }), + }; + + const REQUEST_ROW = { + id: REQUEST, + process_name: 'flow:memo_review', + object_name: OBJECT, + record_id: RECORD, + status: 'pending', + submitter_id: 'u_submitter', + current_step: 'review', + pending_approvers: ['user:u_approver'], + viewer: { can_act: false, is_submitter: false, can_override: false }, + }; + + /** The approvals door: the record's requests, as this reader is served them. */ + function stubApprovals(requests: Record[]) { + vi.stubGlobal('fetch', vi.fn(async (url: string) => { + const u = String(url); + const body = u.includes('/approvals/requests?object=') + ? { data: requests } + : u.endsWith(`/approvals/requests/${REQUEST}`) ? (requests[0] ?? {}) : { data: [] }; + return { ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }; + }) as never); + } + + function renderMemo() { + const pages: any[] = []; + const metadata = { + objects: [MEMO_DEF], pages, loading: false, error: null, + refresh: async () => {}, invalidate: () => {}, + ensureType: async () => pages, getItem: async () => null, getItemsByType: () => pages, + } as any; + const ds = { + find: vi.fn(async (object: string) => (object === 'sys_activity' + ? { data: [ENTRY], total: 1 } + : { data: [], total: 0 })), + findOne: vi.fn(async () => ({ id: RECORD, name: 'Budget memo' })), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: async () => MEMO_DEF, + } as Record; + return render( + + + {}} + objectNameOverride={OBJECT} + recordIdOverride={RECORD} + /> + + , + ); + } + + /** The stream is the page's 动态 tab: open it. */ + async function openStream(container: HTMLElement) { + const tab = await waitFor(() => { + const found = container.querySelector('[role="tab"][data-record-tab="timeline"]'); + expect(found).not.toBeNull(); + return found as HTMLButtonElement; + }, { timeout: 5000 }); + await act(async () => { fireEvent.click(tab); }); + } + + beforeAll(() => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + }); + + it('draws the entry as the approval line, and 「看审批」 opens the 审批 tab', async () => { + stubApprovals([REQUEST_ROW]); + const { container } = renderMemo(); + // The page draws its 审批 tab once the reader is served the request. + await waitFor(() => expect(container.querySelector('[role="tab"][data-record-tab="approvals"]')).not.toBeNull(), { timeout: 5000 }); + await openStream(container); + const link = await waitFor(() => { + const found = container.querySelector('[data-stream-approval-row] [data-stream-view-approval]'); + expect(found).not.toBeNull(); + return found as HTMLButtonElement; + }, { timeout: 5000 }); + expect(container.querySelector('[data-related-enlarged="approvals"]')).toBeNull(); + await act(async () => { fireEvent.click(link); }); + await waitFor(() => expect(container.querySelector('[data-related-enlarged="approvals"]')).not.toBeNull()); + }); + + it('CONTROL — no approvals served to the reader: the line, with no link', async () => { + stubApprovals([]); + const { container } = renderMemo(); + await openStream(container); + await waitFor(() => expect(container.querySelector('[data-stream-approval-row]')).not.toBeNull(), { timeout: 5000 }); + await act(async () => {}); + expect(container.querySelector('[data-stream-view-approval]')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index c57a6b3bfde..39af152e45f 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -10,7 +10,7 @@ import { useState, useEffect, useLayoutEffect, useCallback, useContext, useMemo, useRef, type ReactElement } from 'react'; import { useParams, useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom'; -import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; +import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, RecordViewApprovalsContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; import { isRefusedFeedRead } from '@object-ui/plugin-detail/core'; // objectstack#36075 — the comment panel's unresolved count and the moderator's verdict. import { unresolvedThreadCount, useRecordVerdict } from '@object-ui/plugin-detail'; @@ -6022,20 +6022,28 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri : approvals.latestRequest?.status === 'rejected' && !approvals.pendingRequest && !lockedForReader ? 'border-destructive/30 bg-destructive/10 text-destructive' : 'border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-300'; + // Open the record's approvals: the panel where the page draws it, else its + // 审批 tab (objectstack#35595). The approval tag below and the activity + // stream's 「看审批」 on an approval entry (objectstack#35723) both open it. + // A plain function, not a hook: this runs below the page's early returns. + const openRecordApprovals = () => { + const panel = pageRootEl?.querySelector('[data-testid="record-approvals-panel"]'); + if (panel) { + panel.scrollIntoView({ block: 'start', behavior: 'smooth' }); + return; + } + // objectstack#35595 — the approvals panel is the page's 审批 tab, not + // drawn on 概览: open that tab. + if (pageColumns) openEnlargedRelated('approvals'); + else if (!hasApprovalsNode) handleTabChange('approvals'); + }; + // objectstack#35723 — 「看审批」 only where there are approvals this reader is + // served, the same condition the page's 审批 tab is drawn on. + const viewApprovals = approvals.available && approvals.requests.length > 0 ? openRecordApprovals : null; const approvalTag = approvalTagText ? (