From 8749c1895d8163df71ad85235e1ed07e2298e565 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:27:37 +0000 Subject: [PATCH 1/5] wip(approvals): hold a closing field's decision until the approval is over, and judge it at each door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../plugin-approvals/src/approval-service.ts | 753 ++++++++++++++++-- .../src/sys-approval-request.object.ts | 17 + .../src/translations/messages.ts | 22 + 3 files changed, 734 insertions(+), 58 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 6b0c526b581..5622e1649d7 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -365,8 +365,19 @@ export interface ApprovalResumeSurface { * therefore acts only on an explicit terminal-failure status and treats * `null` — unknown run, evicted log, no durable store, no automation engine — * as "still alive". + * + * [ADR-0162 Execution item 8] Its step log is read too + * (`ExecutionLogEntry.steps`, which the engine already answers): the door + * that judges an approval places where the run stopped, and a failure the + * flow routed, against the set the approval's requests carry. A step inside + * a region names its container (`parentNodeId`). */ - getRun?(runId: string): Promise<{ status?: string; flowName?: string; startedAt?: string } | null>; + getRun?(runId: string): Promise<{ + status?: string; + flowName?: string; + startedAt?: string; + steps?: ReadonlyArray<{ nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string }>; + } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps * a decision from being recorded against a run that can never advance @@ -1839,6 +1850,81 @@ interface MirrorRefusal { */ const REFUSED_MIRROR_TOPIC = 'approval.status_mirror_refused'; +/** + * [ADR-0162 D5, Execution item 8] The topic of the notice the submitter gets + * when the approval of their record ended between two of its steps and the + * plugin put the record back. + */ +const ABANDONED_APPROVAL_TOPIC = 'approval.abandoned'; + +/** + * [ADR-0162 Execution item 8] The keys of a request's config snapshot that the + * judgement of an approval leaves: the approval was abandoned (`__abandoned`), + * and a later step of it could not open (`__laterStepNotOpened`). Internal + * stamps, like `__round`: the snapshot is not authored config. + */ +const ABANDONED_KEY = '__abandoned'; +const LATER_STEP_NOT_OPENED_KEY = '__laterStepNotOpened'; + +/** The run statuses a run reports while it is being advanced, or is about to be. */ +const ADVANCING_RUN_STATUSES: ReadonlySet = new Set(['pending', 'running', 'retrying']); + +/** + * [ADR-0162 Execution item 8] What the door answered for an approval after it + * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). + * `unstamped`: the approval was not stamped, and nothing is judged. `judged`: + * no request of it carries the mark, or a writer that recalled its latest + * request already wrote what it leaves. `ended`: it ended between two steps + * and held nothing back, so only the mark was cleared. + */ +type ApprovalJudgement = 'unstamped' | 'judged' | 'in_progress' | 'undetermined' | 'finished' | 'abandoned' | 'ended'; + +/** One node of the between-two-steps set a request carries (`between_steps_json`). */ +interface StampedNode { + readonly flow: string; + readonly node: string; +} + +/** + * [ADR-0162 Execution item 8] The between-two-steps set `row` carries, or + * `undefined` where its approval was not stamped: no step of it can act on an + * object that declares `closedStates`, or the plugin could not place it. An + * empty set (`[]`) is a stamp: such an approval is judged like any other. + */ +function stampOf(row: any): StampedNode[] | undefined { + const raw = row?.between_steps_json; + if (typeof raw !== 'string' || raw === '') return undefined; + const parsed = parseJson(raw, undefined); + if (!Array.isArray(parsed)) return undefined; + return parsed + .filter((n): n is { flow?: unknown; node?: unknown } => !!n && typeof n === 'object') + .map((n) => ({ flow: String(n.flow ?? ''), node: String(n.node ?? '') })) + .filter((n) => n.node !== ''); +} + +/** + * [ADR-0162 Execution item 8] Whether the node `nodeId` of the flow `flow` + * stands in `stamp`. The set names each flow by the key the engine files it + * under; where the run's own flow key is unknown, or names no flow of the set, + * the node is matched by its id alone, which can only read more stops as + * between two steps (a resubmission), never fewer (a closed document on an + * unfinished approval). + */ +function standsBetweenSteps(stamp: readonly StampedNode[], flow: string | undefined, nodeId: string): boolean { + if (flow && stamp.some((n) => n.flow === flow)) return stamp.some((n) => n.flow === flow && n.node === nodeId); + return stamp.some((n) => n.node === nodeId); +} + +/** [ADR-0162 Execution item 8] Whether `row` carries the mark: it was decided, and what follows is not judged yet. */ +function isMarked(row: any): boolean { + return row?.unjudged_since != null && row.unjudged_since !== ''; +} + +/** The timeline line an approval that ended between two steps leaves on its latest request. */ +function abandonedNoteText(why: string, left: string): string { + return `The approval did not go on: ${why} ${left}`; +} + /** The timeline line a refused write of the status mirror leaves on its request. */ function refusedMirrorNoteText(status: string, reason: string): string { return `The approval status '${status}' could not be written to the record: ${reason}`; @@ -5148,6 +5234,476 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return Array.isArray(closed) && (closed.includes('approved') || closed.includes('rejected')); } + /** + * [ADR-0162 D5, Execution item 8] Whether a decision on `row`'s step is held + * back: `row` is a request of an approval the check stamped when it opened, + * and its object closes on `field` at `approved` or `rejected`. Both + * decisions are held back, whichever of the two the object closes on, and + * the field keeps `pending` until the approval is over + * ({@link judgeApprovalAfterDoor}). Every other status is written as before. + */ + private holdsBackDecision(row: any, field: string): boolean { + return stampOf(row) !== undefined && this.closesOnApprovalOutcome(String(row?.object_name ?? ''), field); + } + + /** + * [ADR-0162 D5, Execution item 8] The door's judgement of an approval, after + * a door resumed or cancelled one of its runs: a decision (by a person or + * the platform's clock), a send-back, a resubmission, a recall and the + * continuation of a restored run. It never takes the resume's own answer + * for it, which is about the request's own run. + * + * The approval is the request's root run, on the request's record. The door + * asks its own table for the approval's requests on the record and reads + * the run that carries the record (`record_run_id`), and answers one of: + * + * - **in progress**: a request of the approval is pending or returned on + * the record, or the run is parked at a pause a step can follow (a node + * of the set the request carries). Nothing is written, and the mark + * stays. + * - **finished**: the run completed, stopped on a node outside the set, or + * is parked at a pause outside it, and no failure it routed, nor a later + * step that could not open, ended it between two steps. The mirror writes + * the decision of the approval's latest request on the record, where that + * request was decided and its decision was held back, in the name of + * whoever decided it ({@link attributedMirrorContext}). + * - **abandoned**: the run ended between two steps + * ({@link abandonApproval}). + * - **cannot tell**: another process is advancing the run, or the run or + * the table cannot be read. Nothing is written, and the mark stays for + * the reconciler. + * + * In an approval that holds nothing back, finished and abandoned both end + * the hold: the mark is cleared and nothing is written. Where the approval's + * latest request was recalled, the writer that recalled it already wrote + * what an abandoned approval leaves: the mark is cleared and nothing more is + * written. Where no request of the approval carries the mark, it was judged + * already, and nothing is done. The marks are cleared once the outcome or + * the put-back lands; a write a rule or a hook of the app refused leaves + * them, so that the reconciler tries it again. + * + * Best-effort and never throws: the door's own action is durable before + * this runs. + */ + private async judgeApprovalAfterDoor( + request: { id?: unknown } | null | undefined, + door: string, + decided?: { requestId: string; actorId: string | null }, + ): Promise { + const requestId = request?.id != null ? String(request.id) : ''; + if (!requestId) return 'unstamped'; + try { + const own = await this.engine.find('sys_approval_request', { + where: { id: requestId }, limit: 1, context: SYSTEM_CTX, + }); + const row: any = Array.isArray(own) ? own[0] : undefined; + const stamp = stampOf(row); + if (!row || stamp === undefined || !row.root_run_id) return 'unstamped'; + + const approval: any[] = (await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + orderBy: [{ field: 'created_at', order: 'asc' }], + limit: 500, context: SYSTEM_CTX, + })) ?? []; + if (approval.some((r) => r.status === 'pending' || r.status === 'returned')) return 'in_progress'; + const marked = approval.filter(isMarked); + if (marked.length === 0) return 'judged'; + const latest = approval[approval.length - 1] ?? row; + if (latest.status !== 'approved' && latest.status !== 'rejected') { + await this.clearMarks(marked); + return 'judged'; + } + + const reading = await this.readCarryingRun(latest, stamp, approval); + if (reading.answer === 'undetermined') { + this.logger?.info?.( + `[approvals] after ${door}, the approval of ${row.object_name}/${row.record_id} could not be judged yet: ${reading.why} ` + + 'Nothing was written; the request keeps its mark, and the reconciler judges it.', + { request: requestId, latest: latest.id, run: reading.runId ?? null }, + ); + return 'undetermined'; + } + if (reading.answer === 'in_progress') return 'in_progress'; + + const config = parseJson(latest.node_config_json, { approvers: [] } as any); + const field = typeof config.approvalStatusField === 'string' && config.approvalStatusField + ? config.approvalStatusField : undefined; + const holds = !!field && this.holdsBackDecision(latest, field); + if (reading.answer === 'finished') { + if (!holds) { + await this.clearMarks(marked); + return 'finished'; + } + const actor = decided && decided.requestId === String(latest.id) + ? decided.actorId + : await this.deciderOf(latest); + const refusal = await this.mirrorStatusField( + latest.object_name, latest.record_id, field!, String(latest.status), actor, + latest.organization_id ?? null, undefined, { request: latest, step: latest.flow_node_id ?? latest.current_step ?? null }, + ); + if (!refusal) await this.clearMarks(marked); + return 'finished'; + } + if (!holds) { + await this.clearMarks(marked); + return 'ended'; + } + await this.abandonApproval(latest, marked, field!, reading.why); + return 'abandoned'; + } catch (err: any) { + this.logger?.warn?.( + `[approvals] after ${door}, the approval of request '${requestId}' could not be judged: ${err?.message ?? err}. ` + + 'Nothing was written; its marks stand, and the reconciler judges it.', + { request: requestId, error: err?.message ?? String(err) }, + ); + return 'undetermined'; + } + } + + /** + * [ADR-0162 D5, Execution item 8] Read the run that carries `latest`'s + * record, once no request of the approval is pending or returned on it, and + * place where it stopped against `stamp`. + * + * - A run another process is advancing, or one that cannot be read: + * `undetermined`. + * - Parked: at a node of the set, `in_progress`; elsewhere it is over. + * - Ended (completed, failed, cancelled, timed out, refused): over. + * + * Over, it ended between two steps where a later step of the approval was + * reached and could not open (the note on `latest`, {@link noteLaterStepNotOpened}), + * whatever the flow did with that failure; where a node of the set failed at + * the top level of the run and the flow routed the failure, and no request + * of the approval opened after it (N46 c′: a failure handled in a + * `try_catch` region is the author's statement that it needs no later step); + * and where the run stopped on a node of the set. Otherwise it finished: an + * end after the last step is the approval's end, also where a node after + * the last step failed. + */ + private async readCarryingRun( + latest: any, + stamp: readonly StampedNode[], + approval: readonly any[], + ): Promise< + | { answer: 'undetermined'; why: string; runId?: string } + | { answer: 'in_progress' } + | { answer: 'finished' } + | { answer: 'abandoned'; why: string } + > { + const runId = String(latest.record_run_id ?? latest.root_run_id ?? ''); + const automation = this.automation; + if (!runId) return { answer: 'undetermined', why: 'the request records no run that carries its record.' }; + if (typeof automation?.getRun !== 'function') { + return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId }; + } + let run: { status?: string; flowName?: string; steps?: unknown } | null; + try { + run = await automation.getRun(runId); + } catch (err: any) { + return { answer: 'undetermined', why: `the run '${runId}' could not be read (${err?.message ?? err}).`, runId }; + } + const status = typeof run?.status === 'string' ? run.status : ''; + if (!run || !status) return { answer: 'undetermined', why: `the run '${runId}' reports no status.`, runId }; + if (ADVANCING_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' is ${status}, so another process may be advancing it.`, runId }; + } + const flow = typeof run.flowName === 'string' ? run.flowName : undefined; + const steps = (Array.isArray(run.steps) ? run.steps : []) as Array<{ + nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; + }>; + + let stoppedAt: string | undefined; + if (status === 'paused') { + let parked: { nodeId?: string; flowName?: string } | undefined; + try { + parked = await automation.suspensionOf?.(runId); + } catch (err: any) { + return { answer: 'undetermined', why: `where the run '${runId}' is parked could not be read (${err?.message ?? err}).`, runId }; + } + if (!parked?.nodeId) return { answer: 'undetermined', why: `the run '${runId}' reports paused, and no pause of it can be found.`, runId }; + if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) return { answer: 'in_progress' }; + } else if (!TERMINAL_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.`, runId }; + } else if (status !== 'completed') { + const failed = [...steps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId); + const last = failed ?? steps[steps.length - 1]; + stoppedAt = last && typeof last.nodeId === 'string' ? last.nodeId : undefined; + } + + const config = parseJson>(latest.node_config_json, {}); + const notOpened = config[LATER_STEP_NOT_OPENED_KEY] as { node?: unknown; reason?: unknown } | undefined; + if (notOpened && typeof notOpened === 'object') { + return { + answer: 'abandoned', + why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, + }; + } + // A failure the flow routed, at the top level of the run, on a node of the + // set, after which no request of the approval opened. + const instant = (v: unknown): number => (v == null || v === '' ? NaN : new Date(v as string).getTime()); + const lastOpened = approval.reduce((acc, r) => { + const at = instant(r?.created_at); + return Number.isFinite(at) && at > acc ? at : acc; + }, -Infinity); + const routed = steps.find((s) => s?.status === 'failure' + && !s.parentNodeId + && typeof s.nodeId === 'string' + && s.nodeId !== stoppedAt + && standsBetweenSteps(stamp, flow, s.nodeId) + && !(instant(s.startedAt) < lastOpened)); + if (routed) { + return { answer: 'abandoned', why: `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.` }; + } + if (status !== 'paused' && status !== 'completed') { + if (!stoppedAt) return { answer: 'abandoned', why: `its run ended ${status}, at a node the plugin cannot place.` }; + if (standsBetweenSteps(stamp, flow, stoppedAt)) { + return { answer: 'abandoned', why: `its run ended ${status} at node '${stoppedAt}', between two steps.` }; + } + } + return { answer: 'finished' }; + } + + /** + * [ADR-0162 D5, Execution item 8] Abandon an approval whose run ended + * between two steps, for its record, once no request of it is open. The + * decisions already made stay on their requests, with who decided and when. + * + * 1. The approval is marked abandoned on its latest request (`__abandoned` + * on its snapshot), first, so that the door that continues a restored + * run refuses it however far the rest gets ({@link continueRestoredRun}). + * 2. The mirror writes what an abandoned approval leaves, by item 7's + * order ({@link abandonedValueOnClosingField}): `recalled` where the + * field declares it and the object does not close on it, otherwise the + * value at submit, the default or empty, never a closed value. Where a + * request of another approval is pending or returned on the record and + * mirrors onto the same field, it writes nothing: the field is that + * approval's now. + * 3. A line with no actor on the latest request's timeline says that the + * approval did not go on, why, and what the record was put back to. + * 4. The submitter is told, and submits again. + * + * The marks are cleared where the put-back landed or nothing was to be + * written; a put-back a rule or a hook of the app refused is reported by the + * mirror and leaves them, for the reconciler to try again. + */ + private async abandonApproval(latest: any, marked: readonly any[], field: string, why: string): Promise { + const now = this.clock.now().toISOString(); + const object = String(latest.object_name); + const recordId = String(latest.record_id); + const org = latest.organization_id ?? null; + const step = latest.flow_node_id ?? latest.current_step ?? null; + + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [ABANDONED_KEY]: { at: now, reason: why } }), + }, { context: SYSTEM_CTX }); + + let other: any; + try { + const open = await this.engine.find('sys_approval_request', { + where: { object_name: object, record_id: recordId, status: { $in: ['pending', 'returned'] } }, + limit: 50, context: SYSTEM_CTX, + }); + other = (Array.isArray(open) ? open : []).find((r: any) => + String(r?.root_run_id ?? '') !== String(latest.root_run_id ?? '') + && parseJson(r?.node_config_json, { approvers: [] } as any).approvalStatusField === field); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether another approval is open on the record of an abandoned one; the put-back goes ahead', { + request: latest.id, object, record: recordId, error: err?.message ?? String(err), + }); + } + + let refusal: MirrorRefusal | undefined; + let left: string; + if (other) { + left = `The record's ${field} was left as it is: the request '${String(other.id)}' of another approval is open on it.`; + } else { + refusal = await this.mirrorStatusField( + object, recordId, field, 'recalled', null, org, + { payloadJson: latest.payload_json }, { request: latest, step }, + ); + if (refusal) { + left = `The record's ${field} could not be put back: ${refusal.message}`; + } else { + let value: unknown; + try { + const rows = await this.engine.find(object, { where: { id: recordId }, fields: ['id', field], limit: 1, context: SYSTEM_CTX }); + value = Array.isArray(rows) ? rows[0]?.[field] : undefined; + } catch { value = undefined; } + left = value == null || value === '' + ? `The record's ${field} was put back to empty.` + : `The record's ${field} was put back to '${String(value)}'.`; + } + } + + try { + await this.engine.insert('sys_approval_action', await this.actionRow(latest, { + id: uid('aact'), request_id: latest.id, organization_id: org, + step_name: step, step_index: 0, action: 'comment', + actor_id: null, + comment: abandonedNoteText(why, left), + created_at: now, + }), { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note an abandoned approval on its request timeline', { + request: latest.id, error: err?.message ?? String(err), + }); + } + this.logger?.warn?.( + `[approvals] the approval of ${object}/${recordId} ended between two steps and was abandoned: ${why} ${left} ` + + 'The decisions already made stay on their requests; the submitter was told, and submits again.', + { request: latest.id, object, record: recordId, field }, + ); + + if (latest.submitter_id) { + try { + await this.notify({ + topic: ABANDONED_APPROVAL_TOPIC, + organizationId: org, + audience: [String(latest.submitter_id)], + source: { object: 'sys_approval_request', id: String(latest.id) }, + dedupKey: `approval-abandoned-${String(latest.id)}`, + about: { object, recordId }, + text: (subject) => approvalNotificationText({ + title: 'approvalAbandonedTitle', body: 'approvalAbandonedBody', params: subject, + }), + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the submitter of an abandoned approval', { + request: latest.id, error: err?.message ?? String(err), + }); + } + } + + if (!refusal) await this.clearMarks(marked); + } + + /** + * [ADR-0162 Execution item 8] Clear the mark on `rows`, one keyed update + * each: the approval they belong to has been judged, or their requests' + * approval has moved on, or a writer abandoned it. Best-effort: a mark that + * stays is judged again by the reconciler, which writes nothing twice. + */ + private async clearMarks(rows: readonly any[]): Promise { + for (const r of rows) { + if (!isMarked(r)) continue; + try { + await this.engine.update('sys_approval_request', { id: r.id, unjudged_since: null }, { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not clear the mark on a judged request; the reconciler judges it again', { + request: r.id, error: err?.message ?? String(err), + }); + } + } + } + + /** + * [ADR-0162 Execution item 8] Clear the marks on the requests of `row`'s + * approval on its record other than `row` itself. A recall, an override and + * the dead-run sweep abandon the approval at its open request, and the + * marks its earlier decisions left would otherwise hold the record. A new + * request of the approval, as it opens, ends the passage its earlier + * decisions began. No-op for a request of an approval that was not stamped. + */ + private async clearEarlierMarks(row: any): Promise { + if (stampOf(row) === undefined || !row?.root_run_id) return; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + fields: ['id', 'unjudged_since'], limit: 500, context: SYSTEM_CTX, + }); + await this.clearMarks((Array.isArray(rows) ? rows : []).filter((r: any) => String(r.id) !== String(row.id))); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the marks of an approval\'s earlier requests; the reconciler judges them', { + request: row?.id, error: err?.message ?? String(err), + }); + } + } + + /** + * [ADR-0162 D5, Execution item 8] An abandoned approval does not go on. + * Refuse {@link continueRestoredRun} for a request of an approval the door + * or the reconciler marked abandoned on its record: an operator who put a + * failed run's pause back would otherwise open the next step on a document + * that has since been put back, and perhaps submitted again. The operator + * cancels the restored run instead. A read that fails refuses as well: the + * continuation is a repair, and it waits for a store that answers. + */ + private async refuseAbandonedContinuation(raw: any, requestId: string): Promise { + if (stampOf(raw) === undefined || !raw?.root_run_id) return; + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: raw.root_run_id, object_name: raw.object_name, record_id: raw.record_id }, + fields: ['id', 'node_config_json'], limit: 500, context: SYSTEM_CTX, + }); + const abandoned = (Array.isArray(rows) ? rows : []).find((r: any) => + parseJson>(r?.node_config_json, {})[ABANDONED_KEY] !== undefined); + if (!abandoned) return; + const runId = String(raw.flow_run_id ?? ''); + throw new Error( + `INVALID_STATE: the approval of ${String(raw.object_name)}/${String(raw.record_id)} that request ${requestId} ` + + `belongs to was abandoned when its run ended between two steps (request '${String(abandoned.id)}'), and its ` + + `record was put back, so it does not go on. Cancel the restored run '${runId}' with the automation engine's ` + + `cancelRun('${runId}'); the submitter submits the record again.`, + ); + } + + /** + * [ADR-0162 Execution item 8] Who decided `request`: the actor of its last + * `approve` or `reject` row, or `null` (a write with no actor) where none + * names one, as for the SLA sweep's auto-decision. + */ + private async deciderOf(request: any): Promise { + try { + const rows = await this.engine.find('sys_approval_action', { + where: { request_id: request.id, action: { $in: ['approve', 'reject'] } }, + orderBy: [{ field: 'created_at', order: 'desc' }], + fields: ['id', 'actor_id'], limit: 1, context: SYSTEM_CTX, + }); + const actor = Array.isArray(rows) ? rows[0]?.actor_id : undefined; + return actor != null && String(actor) !== '' ? String(actor) : null; + } catch { + return null; + } + } + + /** + * [ADR-0162 Execution item 8] Keep a durable note on the approval's latest + * request on the record where a later step of it was reached and could not + * open (an empty slate under `onEmptyApprovers: 'fail'`, another request + * pending on the record, or any other failure of its opening), so that the + * judgement of the approval does not depend on how the flow routed that + * failure ({@link readCarryingRun}). A failure of the approval's first + * request leaves no note: no request of it exists. Best-effort. + */ + private async noteLaterStepNotOpened( + input: { object: string; recordId: string; nodeId: string; rootRun?: ApprovalRootRun | null }, + failure: unknown, + ): Promise { + const rootRunId = input.rootRun?.runId; + if (!rootRunId) return; + try { + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: rootRunId, object_name: input.object, record_id: input.recordId }, + orderBy: [{ field: 'created_at', order: 'desc' }], + limit: 1, context: SYSTEM_CTX, + }); + const latest: any = Array.isArray(rows) ? rows[0] : undefined; + if (!latest || stampOf(latest) === undefined) return; + const now = this.clock.now().toISOString(); + const reason = String((failure as { message?: unknown } | undefined)?.message ?? failure).slice(0, 500); + const snapshot = parseJson>(latest.node_config_json, {}); + await this.engine.update('sys_approval_request', { + id: latest.id, updated_at: now, + node_config_json: JSON.stringify({ ...snapshot, [LATER_STEP_NOT_OPENED_KEY]: { node: input.nodeId, at: now, reason } }), + }, { context: SYSTEM_CTX }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not note on the approval that a later step could not open; the run\'s own stop decides its judgement', { + object: input.object, record: input.recordId, node: input.nodeId, error: err?.message ?? String(err), + }); + } + } + /** * [ADR-0162 D5, Execution item 7 "The check"] Judge an approval at its first * request, and answer the between-two-steps set the request carries @@ -5857,6 +6413,21 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega locale?: string; }, context: ExecutionContext, + ): Promise { + try { + return await this.openNodeRequestBody(input, context); + } catch (err) { + // [ADR-0162 Execution item 8] A later step of an approval that could not + // open leaves a note on the approval's latest request. + await this.noteLaterStepNotOpened(input, err); + throw err; + } + } + + /** {@link openNodeRequest}'s body: its docblock is this method's contract. */ + private async openNodeRequestBody( + input: Parameters[0], + context: ExecutionContext, ): Promise { if (!input.object) throw new Error('VALIDATION_FAILED: object is required'); if (!input.recordId) throw new Error('VALIDATION_FAILED: recordId is required'); @@ -6281,6 +6852,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; await this.engine.insert('sys_approval_request', row, { context: SYSTEM_CTX }); await this.syncApproverIndex(id, approvers, requestOrg, now, platformSlotOpened); + // [ADR-0162 Execution item 8] A new request of the approval ends the + // passage its earlier decisions began: their marks are cleared. + await this.clearEarlierMarks(row); await this.engine.insert('sys_approval_action', await this.actionRow(row, { id: uid('aact'), request_id: id, organization_id: requestOrg, step_name: input.nodeId, step_index: 0, action: 'submit', @@ -6959,14 +7533,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega acceptedOutputs || (config as any).__decisionOutputs ? { ...((config as any).__decisionOutputs ?? {}), ...(acceptedOutputs ?? {}) } : undefined; + // [ADR-0162 Execution item 8] The decision leaves the mark on a request of + // an approval the check stamped, in the update that records it. await this.engine.update('sys_approval_request', { id: requestId, status: finalStatus, pending_approvers: null, pending_approver_labels: null, completed_at: now, updated_at: now, + ...(stampOf(raw) !== undefined ? { unjudged_since: now } : {}), ...(mergedOutputs ? { node_config_json: JSON.stringify({ ...config, __decisionOutputs: mergedOutputs }), } : {}), }, { context: SYSTEM_CTX }); await this.syncApproverIndex(requestId, [], org, now); - if (config.approvalStatusField) { + if (config.approvalStatusField && !this.holdsBackDecision(raw, config.approvalStatusField)) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, finalStatus, actingUserId(context), org, undefined, { request: raw, step: nodeId }, @@ -7487,6 +8064,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega submitterToldBy: 'outcome' | 'escalation', ): Promise { const result = await this.decideNode(requestId, input, context); + // [ADR-0162 Execution item 8] After the resume, the door judges the + // approval: the outcome is written only once it is over. + const judge = () => this.judgeApprovalAfterDoor( + result.request, `the ${result.decision} decision`, { requestId: String(requestId), actorId: actingUserId(context) }, + ); let resumed = false; let resumeError: string | undefined; @@ -7510,21 +8092,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // session), never off the input: the decider's segment names them, as // the decision's own audit row does. Only beside a decider. const impersonatedBy = decider ? impersonatorOf(context) : undefined; - const outcome = await this.resumeRecordedOutcome( - result.runId, requestId, `the ${result.decision} decision`, - { - branchLabel, - // #3447 P2: accepted decision outputs ride the resume envelope and - // land as `.` flow variables — a later approval node's - // `expression` approver reads them as `vars..`. - // Reserved keys are spread LAST so no output can shadow them (the - // whitelist already rejects them; this is defense in depth). - output: { ...(result.outputs ?? {}), decision: result.decision, requestId }, - ...(decider ? { resumedBy: decider } : {}), - ...(impersonatedBy ? { impersonatedBy } : {}), - }, - result.decision, - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + result.runId, requestId, `the ${result.decision} decision`, + { + branchLabel, + // #3447 P2: accepted decision outputs ride the resume envelope and + // land as `.` flow variables — a later approval node's + // `expression` approver reads them as `vars..`. + // Reserved keys are spread LAST so no output can shadow them (the + // whitelist already rejects them; this is defense in depth). + output: { ...(result.outputs ?? {}), decision: result.decision, requestId }, + ...(decider ? { resumedBy: decider } : {}), + ...(impersonatedBy ? { impersonatedBy } : {}), + }, + result.decision, + ); + } catch (err) { + // [ADR-0162 Execution item 8] A run that failed after the decision + // ended where it stopped: the door judges it before it reports the strand. + await judge(); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; resumeFailure = outcome.resumeFailure; @@ -7534,7 +8124,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // whether this decision ended the process or moved it to a further // approval step. A resume that strands has thrown above, so — as on the // send-back — a stranded decision tells no one. - if (result.finalized && submitterToldBy === 'outcome') { + // An approval the door abandoned told its submitter so itself. + const judgement = result.finalized ? await judge() : undefined; + if (result.finalized && submitterToldBy === 'outcome' && judgement !== 'abandoned') { await this.notifyDecisionOutcome(result.request, result.decision, input.comment, context); } @@ -7770,6 +8362,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega actingUserId(context), org, { payloadJson: raw.payload_json }, { request: raw, step: nodeId }, ); } + // [ADR-0162 Execution item 8] The recall abandons the approval at its open + // request: the marks its earlier decisions left are cleared. + await this.clearEarlierMarks(raw); // A recall ABANDONS the request, so a run that cannot be resumed must not // fail the call — the withdrawal and the record-lock release are the point, @@ -7879,6 +8474,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } } + // [ADR-0162 Execution item 8] After the resume or the cancel the recall + // made, the door judges the approval. + await this.judgeApprovalAfterDoor(raw, 'the recall'); + const fresh = await this.readBackRequest(requestId, context); return { request: fresh, @@ -8378,9 +8977,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }), { context: SYSTEM_CTX }); await this.engine.update('sys_approval_request', { id: requestId, status: 'rejected', pending_approvers: null, pending_approver_labels: null, completed_at: now, updated_at: now, + // [ADR-0162 Execution item 8] A decision, so it leaves the mark. + ...(stampOf(raw) !== undefined ? { unjudged_since: now } : {}), }, { context: SYSTEM_CTX }); await this.syncApproverIndex(requestId, [], org, now); - if (config.approvalStatusField) { + if (config.approvalStatusField && !this.holdsBackDecision(raw, config.approvalStatusField)) { await this.mirrorStatusField( raw.object_name, raw.record_id, config.approvalStatusField, 'rejected', actingUserId(context), org, undefined, { request: raw, step: nodeId }, @@ -8389,17 +8990,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the auto-rejection', - { - branchLabel: APPROVAL_BRANCH_LABELS.reject, - output: { decision: 'reject', autoRejected: true, requestId }, - }, - 'reject', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the auto-rejection', + { + branchLabel: APPROVAL_BRANCH_LABELS.reject, + output: { decision: 'reject', autoRejected: true, requestId }, + }, + 'reject', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The auto-rejection is a decision: the door judges the approval. + await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); if (raw.submitter_id) { await this.notify({ topic: 'approval.returned', @@ -8432,17 +9041,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the send-back', - { - branchLabel: APPROVAL_BRANCH_LABELS.revise, - output: { decision: 'revise', requestId }, - }, - 'revise', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the send-back', + { + branchLabel: APPROVAL_BRANCH_LABELS.revise, + output: { decision: 'revise', requestId }, + }, + 'revise', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the send-back'); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The door judges the approval after the send-back. + await this.judgeApprovalAfterDoor(raw, 'the send-back'); if (raw.submitter_id) { // [#24978] The approver's own words, when they wrote some, are the body @@ -8531,17 +9148,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let resumed = false; let resumeError: string | undefined; if (runId) { - const outcome = await this.resumeRecordedOutcome( - runId, requestId, 'the resubmit', - { - branchLabel: APPROVAL_BRANCH_LABELS.resubmit, - output: { resubmitted: true, requestId }, - }, - 'resubmit', - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, 'the resubmit', + { + branchLabel: APPROVAL_BRANCH_LABELS.resubmit, + output: { resubmitted: true, requestId }, + }, + 'resubmit', + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the resubmission'); + throw err; + } resumed = outcome.resumed; resumeError = outcome.resumeError; } + // [ADR-0162 Execution item 8] The door judges the approval after the resubmission. + await this.judgeApprovalAfterDoor(raw, 'the resubmission'); const fresh = await this.readBackRequest(requestId, context); return { request: fresh, runId, resumed, ...(resumeError ? { resumeError } : {}) }; @@ -10274,6 +10899,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // next round. Same guard `recall`-in-revise-window and `resubmit` already // use, for the same reason. await this.assertLatestForRun(raw); + await this.refuseAbandonedContinuation(raw, requestId); // The signal, before the store is asked anything — a request this verb // cannot serve is refused without a suspension read. @@ -10352,21 +10978,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // `RESUME_IN_PROGRESS` tolerance, the same stranded envelope with the // engine's own `repairable` discriminator, and the same re-journalling — // so a continuation that strands AGAIN is repairable exactly like the first. - const outcome = await this.resumeRecordedOutcome( - runId, requestId, signal.what, - { - branchLabel: signal.branchLabel, output: signal.output, - // The journalled decider (ruling A): the replayed nodes after the - // decision run as the person who decided, not as the run's trigger. - ...(typeof signal.resumedBy === 'string' && signal.resumedBy ? { resumedBy: signal.resumedBy } : {}), - // The journalled impersonator beside that decider: the replayed - // segment is stamped exactly as the decision's own resume would have. - ...(typeof signal.resumedBy === 'string' && signal.resumedBy - && typeof signal.impersonatedBy === 'string' && signal.impersonatedBy.trim() - ? { impersonatedBy: signal.impersonatedBy.trim() } : {}), - }, - signal.decision, - ); + let outcome: Awaited>; + try { + outcome = await this.resumeRecordedOutcome( + runId, requestId, signal.what, + { + branchLabel: signal.branchLabel, output: signal.output, + // The journalled decider (ruling A): the replayed nodes after the + // decision run as the person who decided, not as the run's trigger. + ...(typeof signal.resumedBy === 'string' && signal.resumedBy ? { resumedBy: signal.resumedBy } : {}), + // The journalled impersonator beside that decider: the replayed + // segment is stamped exactly as the decision's own resume would have. + ...(typeof signal.resumedBy === 'string' && signal.resumedBy + && typeof signal.impersonatedBy === 'string' && signal.impersonatedBy.trim() + ? { impersonatedBy: signal.impersonatedBy.trim() } : {}), + }, + signal.decision, + ); + } catch (err) { + await this.judgeApprovalAfterDoor(raw, 'the continuation of a restored run'); + throw err; + } + // [ADR-0162 Execution item 8] The door judges the approval after the continuation. + await this.judgeApprovalAfterDoor(raw, 'the continuation of a restored run'); return { resumed: outcome.resumed, @@ -10470,6 +11104,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega { payloadJson: raw.payload_json }, { request: raw, step: raw.current_step ?? null }, ); } + // [ADR-0162 Execution item 8] The sweep abandons the approval at its open + // request: the marks its earlier decisions left are cleared. + await this.clearEarlierMarks(raw); this.logger?.warn?.('[approvals] released a record held by a dead approval run', { request: raw.id, run: runId, runStatus, object: raw.object_name, record: raw.record_id, diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index 7b71d3b95cf..a12b49ea3bb 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -571,6 +571,21 @@ export const SysApprovalRequest = ObjectSchema.create({ group: 'State', }), + // [ADR-0162 D5, Execution item 8] The mark: when the request was decided, + // while what follows that decision has not been judged yet. Set in the + // update that records an approve or a reject on a request of an approval + // the check stamped (`between_steps_json`), and cleared when the plugin + // has judged the approval: finished, abandoned, or moved on to its next + // request on the record. The store filters on it, oldest first, so that + // whatever no door judged can be found; null on every other request. + unjudged_since: Field.datetime({ + label: 'Unjudged Since', + required: false, + readonly: true, + description: 'When this request was decided, while what follows the decision has not been judged yet.', + group: 'State', + }), + node_config_json: Field.textarea({ label: 'Node Config', required: false, @@ -639,6 +654,8 @@ export const SysApprovalRequest = ObjectSchema.create({ { fields: ['root_run_id', 'object_name', 'record_id'] }, // Every request on the record one run carries. { fields: ['record_run_id'] }, + // [ADR-0162 Execution item 8] The decided requests whose approval is not judged yet, oldest first. + { fields: ['unjudged_since'] }, ], // Server-declared decision actions (objectui#2678 P2-4). The console's diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index ee99b8e5e41..2523492c39f 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -152,6 +152,8 @@ const enSentences = { approvalReassignedBody: 'You are now an approver on {{object}} {{record}}.', approvalAutoRejectedTitle: 'Approval auto-rejected', approvalAutoRejectedBody: 'Your {{object}} {{record}} exceeded the revision limit ({{limit}}) and was rejected.', + approvalAbandonedTitle: 'Approval did not finish', + approvalAbandonedBody: 'The approval of your {{object}} {{record}} stopped between two of its steps, so it did not finish and the record was put back to an open status. Submit it again when it is ready.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', approvalRequestInfoTitle: 'More information requested', @@ -299,6 +301,8 @@ export const zhCNMessages: ApprovalMessages = { approvalReassignedBody: '您现在是 {{object}} {{record}} 的审批人。', approvalAutoRejectedTitle: '审批已自动驳回', approvalAutoRejectedBody: '您的{{object}} {{record}} 已超过退回修改次数上限({{limit}}),已被驳回。', + approvalAbandonedTitle: '审批未能完成', + approvalAbandonedBody: '您的{{object}} {{record}} 的审批在两个步骤之间停止,未能完成,记录已恢复为未关闭的状态。准备好后请重新提交。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '您的{{object}} {{record}} 需要修改后才能获批。', approvalRequestInfoTitle: '需要补充信息', @@ -383,6 +387,8 @@ export const jaJPMessages: ApprovalMessages = { approvalReassignedBody: 'あなたは {{object}} {{record}} の承認者になりました。', approvalAutoRejectedTitle: '承認が自動的に却下されました', approvalAutoRejectedBody: 'あなたの{{object}} {{record}} は差し戻し回数の上限({{limit}})を超えたため却下されました。', + approvalAbandonedTitle: '承認が完了しませんでした', + approvalAbandonedBody: 'あなたの{{object}} {{record}} の承認は 2 つのステップの間で停止したため完了せず、レコードは閉じていないステータスに戻されました。準備ができたら再度申請してください。', approvalReturnedTitle: '修正のため差し戻されました', approvalReturnedBody: 'あなたの{{object}} {{record}} は、承認を受ける前に修正が必要です。', approvalRequestInfoTitle: '追加情報が求められています', @@ -467,6 +473,8 @@ export const esESMessages: ApprovalMessages = { approvalReassignedBody: 'Ahora es aprobador de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Aprobación rechazada automáticamente', approvalAutoRejectedBody: 'Su {{object}} {{record}} superó el límite de revisiones ({{limit}}) y se ha rechazado.', + approvalAbandonedTitle: 'La aprobación no terminó', + approvalAbandonedBody: 'La aprobación de su {{object}} {{record}} se detuvo entre dos de sus pasos, así que no terminó y el registro volvió a un estado abierto. Envíelo de nuevo cuando esté listo.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', approvalRequestInfoTitle: 'Se solicita más información', @@ -551,6 +559,8 @@ export const zhHantMessages: ApprovalMessages = { approvalReassignedBody: '你現在是 {{object}} {{record}} 的核准人。', approvalAutoRejectedTitle: '核准已自動駁回', approvalAutoRejectedBody: '你的{{object}} {{record}} 已超過退回修改次數上限({{limit}}),因此被駁回。', + approvalAbandonedTitle: '核准未能完成', + approvalAbandonedBody: '你的{{object}} {{record}} 的核准在兩個步驟之間停止,未能完成,記錄已恢復為未關閉的狀態。準備好後請重新送出。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '你的{{object}} {{record}} 需要修改後才能獲得核准。', approvalRequestInfoTitle: '需要補充資訊', @@ -635,6 +645,8 @@ export const arMessages: ApprovalMessages = { approvalReassignedBody: 'أصبحت الآن موافِقًا على {{object}} {{record}}.', approvalAutoRejectedTitle: 'رُفضت الموافقة تلقائيًا', approvalAutoRejectedBody: 'تجاوز طلبك بشأن {{object}} {{record}} حد المراجعات ({{limit}}) فرُفض.', + approvalAbandonedTitle: 'لم تكتمل الموافقة', + approvalAbandonedBody: 'توقفت الموافقة على {{object}} {{record}} بين خطوتين من خطواتها، فلم تكتمل وأُعيد السجل إلى حالة مفتوحة. أعد إرساله عندما يكون جاهزًا.', approvalReturnedTitle: 'أُعيد للمراجعة', approvalReturnedBody: 'يحتاج طلبك بشأن {{object}} {{record}} إلى تعديل قبل أن تمكن الموافقة عليه.', approvalRequestInfoTitle: 'مطلوب مزيد من المعلومات', @@ -719,6 +731,8 @@ export const frMessages: ApprovalMessages = { approvalReassignedBody: 'Vous êtes désormais approbateur de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Approbation rejetée automatiquement', approvalAutoRejectedBody: 'Votre demande sur {{object}} {{record}} a dépassé la limite de révisions ({{limit}}) et a été rejetée.', + approvalAbandonedTitle: 'L’approbation n’a pas abouti', + approvalAbandonedBody: 'L’approbation de votre {{object}} {{record}} s’est arrêtée entre deux de ses étapes : elle n’a pas abouti et l’enregistrement est revenu à un statut ouvert. Soumettez-le à nouveau lorsqu’il est prêt.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', approvalRequestInfoTitle: 'Informations complémentaires demandées', @@ -803,6 +817,8 @@ export const ptBRMessages: ApprovalMessages = { approvalReassignedBody: 'Agora você é aprovador de {{object}} {{record}}.', approvalAutoRejectedTitle: 'Aprovação rejeitada automaticamente', approvalAutoRejectedBody: 'Sua solicitação sobre {{object}} {{record}} excedeu o limite de revisões ({{limit}}) e foi rejeitada.', + approvalAbandonedTitle: 'A aprovação não foi concluída', + approvalAbandonedBody: 'A aprovação de {{object}} {{record}} parou entre duas de suas etapas, por isso não foi concluída e o registro voltou a um status aberto. Envie-o novamente quando estiver pronto.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', approvalRequestInfoTitle: 'Mais informações solicitadas', @@ -887,6 +903,8 @@ export const ruMessages: ApprovalMessages = { approvalReassignedBody: 'Теперь вы согласующий по {{object}} {{record}}.', approvalAutoRejectedTitle: 'Согласование отклонено автоматически', approvalAutoRejectedBody: 'Ваш запрос по {{object}} {{record}} превысил лимит доработок ({{limit}}) и был отклонён.', + approvalAbandonedTitle: 'Согласование не завершено', + approvalAbandonedBody: 'Согласование {{object}} {{record}} остановилось между двумя шагами, поэтому не завершилось, и запись возвращена в открытый статус. Отправьте её снова, когда она будет готова.', approvalReturnedTitle: 'Возвращено на доработку', approvalReturnedBody: 'Ваш запрос по {{object}} {{record}} нужно доработать, прежде чем его можно будет одобрить.', approvalRequestInfoTitle: 'Запрошены дополнительные сведения', @@ -971,6 +989,8 @@ export const deMessages: ApprovalMessages = { approvalReassignedBody: 'Sie sind jetzt Genehmiger für {{object}} {{record}}.', approvalAutoRejectedTitle: 'Genehmigung automatisch abgelehnt', approvalAutoRejectedBody: 'Ihre Anfrage zu {{object}} {{record}} hat das Überarbeitungslimit ({{limit}}) überschritten und wurde abgelehnt.', + approvalAbandonedTitle: 'Genehmigung nicht abgeschlossen', + approvalAbandonedBody: 'Die Genehmigung zu {{object}} {{record}} hat zwischen zwei ihrer Schritte angehalten. Sie wurde nicht abgeschlossen, und der Datensatz wurde auf einen offenen Status zurückgesetzt. Reichen Sie ihn erneut ein, wenn er bereit ist.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', approvalRequestInfoTitle: 'Weitere Informationen angefordert', @@ -1055,6 +1075,8 @@ export const koMessages: ApprovalMessages = { approvalReassignedBody: '이제 {{object}} {{record}}의 승인자입니다.', approvalAutoRejectedTitle: '승인이 자동 반려되었습니다', approvalAutoRejectedBody: '{{object}} {{record}}이(가) 수정 횟수 한도({{limit}})를 넘어 반려되었습니다.', + approvalAbandonedTitle: '승인이 완료되지 않았습니다', + approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', approvalRequestInfoTitle: '추가 정보 요청', From 9cd8adcaaac8e4130eb974374f458e5c8c8fd545 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:34:46 +0000 Subject: [PATCH 2/5] test(approvals): the outcome when the approval is over, case by case; the mark's translations and changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../37767-outcome-when-approval-over.md | 20 + ...utcome-when-over-37767.integration.test.ts | 515 ++++++++++++++++++ .../plugin-approvals/src/approval-service.ts | 27 +- .../src/approver-address-readers.test.ts | 8 +- ...-closing-field-refusal.integration.test.ts | 9 +- .../stored-process-package-backfill.test.ts | 2 + .../src/translations/ar.objects.generated.ts | 4 + .../src/translations/de.objects.generated.ts | 4 + .../src/translations/en.objects.generated.ts | 4 + .../translations/es-ES.objects.generated.ts | 4 + .../src/translations/fr.objects.generated.ts | 4 + .../translations/ja-JP.objects.generated.ts | 4 + .../src/translations/ko.objects.generated.ts | 4 + .../translations/pt-BR.objects.generated.ts | 4 + .../src/translations/ru.objects.generated.ts | 4 + .../translations/zh-CN.objects.generated.ts | 4 + .../translations/zh-Hant.objects.generated.ts | 4 + 17 files changed, 615 insertions(+), 10 deletions(-) create mode 100644 .changeset/37767-outcome-when-approval-over.md create mode 100644 packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts diff --git a/.changeset/37767-outcome-when-approval-over.md b/.changeset/37767-outcome-when-approval-over.md new file mode 100644 index 00000000000..131a7031538 --- /dev/null +++ b/.changeset/37767-outcome-when-approval-over.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): on a field its object closes on, an approval's decision is written when the approval is over (ADR-0162 Execution item 8, the outcome) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only datetime column `unjudged_since` (the mark) and an index on it; the `getRun` member of the automation surface the plugin declares (`ApprovalResumeSurface`) now also types the step log the engine already returns; the plugin's message catalog gains `approvalAbandonedTitle` and `approvalAbandonedBody` in all 11 locale packs, sent on the topic `approval.abandoned`. + +What changes, only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The decision is held back.** Where the object closes on the step's mirror field at `approved` or `rejected`, neither decision is written onto the record when it is made. The request records it as before, and the field keeps `pending`. Every other status (`pending` as a request opens, `returned` at a send-back, what a recall leaves) is written as before. +- **The mark.** Every decision on a request of such an approval sets `unjudged_since` in the update that records it, also where nothing is held back. It is cleared when the approval is judged, and when the approval's next request opens on the record. A recall, an administrator's override and the dead-run sweep clear it on the approval's earlier requests. +- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the run completed, stopped after the last step, or is parked at a pause no step can follow): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. +- **An abandoned approval.** The latest request is marked abandoned, the field is put back by item 7's order (never a closed value, and nothing where another approval's request is open on the record on the same field), a timeline line with no actor says why and what the record was put back to, and the submitter is told on `approval.abandoned` instead of `approval.approved` or `approval.rejected`. The decisions already made stay on their requests. +- **A restored run is refused.** `continueRestoredRun` refuses a request of an abandoned approval with `INVALID_STATE` and tells the operator to cancel the restored run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key, or whose requests could not be placed. An approval on an object that declares the key on another field than the approval's holds nothing back: its decisions are written at once, as before, and the door only clears the mark. diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts new file mode 100644 index 00000000000..fdbdc7e45de --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -0,0 +1,515 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8 "The outcome when the approval is over", + * #37767 slice 3] On a field the object closes on at `approved` or + * `rejected`, every step's decision is held back and the field keeps + * `pending` until the approval is over for the record. After each door that + * resumes or cancels a run of the approval, the plugin reads the run that + * carries the record and asks its own table for a request of the approval on + * the record: finished, it writes the decision of the approval's latest + * request; in progress, nothing; ended between two steps, it abandons the + * approval and puts the field back; cannot tell, nothing, and the mark stays. + * + * Each case records the value the field keeps. Real kernel, real ObjectQL + * engine, real automation engine, real approval node, driver-sql on + * better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { strandedDecisionDetails } from '@objectstack/types'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.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 { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes on `approved` alone: a rejected order moves on. */ +const order = { name: 'crm_order', label: 'Order', fields, closedStates: { approval_status: ['approved'] } }; +/** Closes on `rejected` alone: an approved claim moves on. */ +const claim = { name: 'crm_claim', label: 'Claim', fields, closedStates: { approval_status: ['rejected'] } }; +/** Declares closed states, on another field than the approval's: its approval holds nothing back. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, which behaves as before. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +const mark = (id: string) => ({ id, type: 'mark', label: id }); +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[], extra: Record = {}) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges, ...extra }); +/** `a` then `b`, each step's reject edge to the end. */ +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +const FLOWS = [ + // Two steps: the second opens in the segment the first decision resumes. + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // Two steps and a node after the last that reads the record. + flow('two_step_then_read', [step('first', 'approver'), step('second', 'approver2'), mark('read')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'read', 'approve'), edge('second', 'read', 'reject'), edge('read', 'end')]), + // A timer after the last step. + flow('wait_after', [step('first', 'approver'), step('second', 'approver2'), + { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'hold', 'approve'), edge('second', 'end', 'reject'), edge('hold', 'end')]), + // A node that fails after the last step. + flow('fail_after', [step('first', 'approver'), step('second', 'approver2'), mark('boom')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'boom', 'approve'), edge('second', 'end', 'reject'), edge('boom', 'end')]), + // The second step resolves to no one under `fail`: unrouted, with a fault edge to the end, and with one to a third step. + flow('second_empty', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' })], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + flow('second_empty_fault_end', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' })], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'end', undefined, 'fault')]), + flow('second_empty_fault_third', [step('first', 'approver'), step('second', 'nobody', { onEmptyApprovers: 'fail' }), step('third', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'third', undefined, 'fault'), ...decided('third', 'end')]), + // Another node between two steps fails: with a fault edge to the end, and unrouted. + flow('boom_between_fault_end', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), + flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + // That node's failure handled in a try_catch region, after which a gateway ends the flow. + flow('boom_handled', [step('first', 'approver'), + { id: 'guard', type: 'try_catch', label: 'Guard', config: { try: { nodes: [mark('boom')], edges: [] }, catch: { nodes: [mark('handled')], edges: [] } } }, + { id: 'gate', type: 'decision', label: 'Gate' }, + step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'guard', 'approve'), edge('first', 'end', 'reject'), edge('guard', 'gate'), + { id: 'gate_end', source: 'gate', target: 'end', condition: 'true' }, + { id: 'gate_second', source: 'gate', target: 'second', condition: 'false' }, + ...decided('second', 'end')]), + // The second step can send back into a revise window. + flow('second_revise', [step('first', 'approver'), step('second', 'approver2'), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), + { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // The same, with no send-back left: a send-back auto-rejects. + flow('second_revise_spent', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), + { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // A batch whose items are records, each approved in its own run of `item_step`. + flow('item_step', [step('only', 'approver'), mark('after')], [edge('start', 'only'), edge('only', 'after', 'approve'), edge('only', 'end', 'reject'), edge('after', 'end')]), + { name: 'batch', label: 'batch', type: 'autolaunched', variables: [{ name: 'items', type: 'list', isInput: true }], + nodes: [START, { id: 'each', type: 'map', label: 'Each', config: { collection: { dialect: 'cel', source: 'items' }, flowName: 'item_step', itemObject: 'crm_invoice' } }, END], + edges: [edge('start', 'each'), edge('each', 'end')] }, +]; + +describe('[ADR-0162 item 8] the outcome is written when the approval is over', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** Nodes of type `mark` that throw, by id. */ + let throwOn: Set; + /** What each `read` node saw on the record's field. */ + let seen: unknown[]; + let notices: Array<{ topic: string; audience: string[] }>; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + throwOn = new Set(); + seen = []; + notices = []; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, order, claim, ticket, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any, _variables: any, context: any) { + if (throwOn.has(node.id)) throw new Error(`${node.id} failed`); + if (node.id === 'read') { + const id = context?.record?.id; + seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); + } + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const steps = async (id: string) => (await requestsOn(id)).map((r) => [r.flow_node_id, r.status]); + const marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const pendingOn = async (id: string) => (await requestsOn(id)).find((r) => r.status === 'pending' || r.status === 'returned'); + const timeline = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS }) as any[]) + .map((a) => [a.action, a.actor_id ?? null, a.comment ?? null]); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T }), (e: any) => ({ error: e as Error })); + + describe('the decision is held back, and written when the approval is over', () => { + it('two steps approved: the field reads pending after the first and approved once the run ends; marks are set and cleared', async () => { + expect((await start('two_step', 'crm_invoice', 'i_two')).status).toBe('paused'); + await decide('i_two', 'approve', 'approver'); + expect(await steps('i_two')).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(await field('crm_invoice', 'i_two'), 'the first decision is held back').toBe('pending'); + expect(await marks('i_two'), 'the next request opened, so the first decision\'s passage ended').toEqual([false, false]); + + await decide('i_two', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_two')).toBe('approved'); + expect(await marks('i_two'), 'judged: no mark stands').toEqual([false, false]); + }); + + it('a node after the last decision reads pending; the outcome lands as the run ends', async () => { + await start('two_step_then_read', 'crm_invoice', 'i_read'); + await decide('i_read', 'approve', 'approver'); + await decide('i_read', 'approve', 'approver2'); + expect(seen).toEqual(['pending']); + expect(await field('crm_invoice', 'i_read')).toBe('approved'); + }); + + it('a second step that rejects on an object that closes on approved alone: pending until the approval is over, then rejected', async () => { + await start('two_step_then_read', 'crm_order', 'o_rej'); + await decide('o_rej', 'approve', 'approver'); + expect(await field('crm_order', 'o_rej'), 'the first decision is held back').toBe('pending'); + await decide('o_rej', 'reject', 'approver2'); + expect(seen, 'held back although the object does not close on rejected').toEqual(['pending']); + expect(await field('crm_order', 'o_rej')).toBe('rejected'); + }); + + it('a first step that approves on an object that closes on rejected alone: pending until the approval is over', async () => { + await start('two_step_then_read', 'crm_claim', 'c_app'); + await decide('c_app', 'approve', 'approver'); + expect(await field('crm_claim', 'c_app'), 'the object does not close on approved, and it is held back all the same').toBe('pending'); + await decide('c_app', 'approve', 'approver2'); + expect(seen).toEqual(['pending']); + expect(await field('crm_claim', 'c_app')).toBe('approved'); + }); + + it('a wait after the last step: the outcome is written as the run parks', async () => { + await start('wait_after', 'crm_invoice', 'i_wait'); + await decide('i_wait', 'approve', 'approver'); + await decide('i_wait', 'approve', 'approver2'); + expect((await automation.getRun(String((await requestsOn('i_wait'))[0].record_run_id)))?.status).toBe('paused'); + expect(await field('crm_invoice', 'i_wait')).toBe('approved'); + }); + + it('a node that fails after the last step: the outcome stands', async () => { + await start('fail_after', 'crm_invoice', 'i_fail_after'); + await decide('i_fail_after', 'approve', 'approver'); + throwOn.add('boom'); + const out = await settle(decide('i_fail_after', 'approve', 'approver2')); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + expect(await field('crm_invoice', 'i_fail_after')).toBe('approved'); + expect(await marks('i_fail_after')).toEqual([false, false]); + }); + + it('the outcome is written in the name of the person who decided the last step', async () => { + await start('two_step', 'crm_invoice', 'i_who'); + await decide('i_who', 'approve', 'approver'); + const writes: unknown[] = []; + const original = ql.update.bind(ql); + (ql as any).update = async (object: string, data: any, options?: any) => { + if (object === 'crm_invoice') writes.push([data.approval_status, options?.context?.userId, options?.context?.isSystem]); + return original(object, data, options); + }; + await decide('i_who', 'approve', 'approver2'); + expect(writes).toEqual([['approved', 'approver2', true]]); + }); + }); + + describe('a map item that is a record', () => { + it('its outcome does not wait for the later items, and a later item\'s failure does not undo it', async () => { + await seed('crm_invoice', 'i_m1'); + await seed('crm_invoice', 'i_m2'); + const items = [await read('crm_invoice', 'i_m1'), await read('crm_invoice', 'i_m2')]; + const batch: any = await automation.execute('batch', { params: { items }, userId: 'owner' } as any); + expect(batch.status).toBe('paused'); + + await decide('i_m1', 'approve', 'approver'); + expect(await pendingOn('i_m2'), 'the next item is in approval').toBeTruthy(); + expect(await field('crm_invoice', 'i_m1'), 'the first item\'s approval is over for its record').toBe('approved'); + + throwOn.add('after'); + await settle(decide('i_m2', 'approve', 'approver')); + expect(await field('crm_invoice', 'i_m1')).toBe('approved'); + // A node after the last step of a `map` body stands before that step's + // next opening (ADR-0162 D5): the second item's run stopped between two + // steps, and only its own record is put back. + expect(await field('crm_invoice', 'i_m2')).toBe('recalled'); + }); + }); + + describe('an abandoned latest request: nothing is written', () => { + it('a first step approved, a second recalled, and a run that then completes: no approved', async () => { + await start('two_step', 'crm_invoice', 'i_recall'); + await decide('i_recall', 'approve', 'approver'); + const second = await pendingOn('i_recall'); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + const run = await automation.getRun(String(second.record_run_id)); + expect(run?.status).toBe('completed'); + expect(await steps('i_recall')).toEqual([['first', 'approved'], ['second', 'recalled']]); + expect(await field('crm_invoice', 'i_recall')).toBe('recalled'); + expect(await marks('i_recall')).toEqual([false, false]); + }); + + it('the same for a returned request recalled in its revise window', async () => { + await start('second_revise', 'crm_invoice', 'i_revise'); + await decide('i_revise', 'approve', 'approver'); + const second = await pendingOn('i_revise'); + await svc.sendBack(String(second.id), { actorId: 'approver2', comment: 'fix it' } as any, asPerson('approver2')); + expect(await field('crm_invoice', 'i_revise')).toBe('returned'); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await steps('i_revise')).toEqual([['first', 'approved'], ['second', 'recalled']]); + expect(await field('crm_invoice', 'i_revise')).toBe('recalled'); + expect(await marks('i_revise')).toEqual([false, false]); + }); + }); + + describe('the other doors', () => { + it('a send-back, a resubmission and the decision of the new round: the field reads returned, then pending, then approved', async () => { + await start('second_revise', 'crm_invoice', 'i_round'); + await decide('i_round', 'approve', 'approver'); + const second = await pendingOn('i_round'); + await svc.sendBack(String(second.id), { actorId: 'approver2', comment: 'fix it' } as any, asPerson('approver2')); + expect(await field('crm_invoice', 'i_round')).toBe('returned'); + await svc.resubmit(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await field('crm_invoice', 'i_round')).toBe('pending'); + await decide('i_round', 'approve', 'approver2'); + expect(await steps('i_round')).toEqual([['first', 'approved'], ['second', 'returned'], ['second', 'approved']]); + expect(await field('crm_invoice', 'i_round')).toBe('approved'); + expect(await marks('i_round')).toEqual([false, false, false]); + }); + + it('a send-back past the revision limit auto-rejects: held back, then written when the approval is over', async () => { + await start('second_revise_spent', 'crm_invoice', 'i_spent'); + await decide('i_spent', 'approve', 'approver'); + const second = await pendingOn('i_spent'); + const out: any = await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect(out.autoRejected).toBe(true); + expect(await steps('i_spent')).toEqual([['first', 'approved'], ['second', 'rejected']]); + expect(await field('crm_invoice', 'i_spent')).toBe('rejected'); + expect(await marks('i_spent')).toEqual([false, false]); + }); + + it('a recall clears a mark an earlier decision of the approval left', async () => { + await start('two_step', 'crm_invoice', 'i_clear'); + await decide('i_clear', 'approve', 'approver'); + const [first, second] = await requestsOn('i_clear'); + // The shape a process that died before the next request cleared it leaves. + await ql.update('sys_approval_request', { id: first.id, unjudged_since: new Date().toISOString() }, { context: SYS }); + expect(await marks('i_clear')).toEqual([true, false]); + await svc.recall(String(second.id), { actorId: 'owner' } as any, asPerson('owner')); + expect(await marks('i_clear')).toEqual([false, false]); + expect(await field('crm_invoice', 'i_clear')).toBe('recalled'); + }); + }); + + describe('a later step that cannot open', () => { + it('on an empty slate, unrouted: the approval is abandoned and the field is put back', async () => { + await start('second_empty', 'crm_invoice', 'i_empty'); + const out = await settle(decide('i_empty', 'approve', 'approver')); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + const [first] = await requestsOn('i_empty'); + expect(first.status, 'the decision stays on its request').toBe('approved'); + expect(await field('crm_invoice', 'i_empty')).toBe('recalled'); + expect(JSON.parse(first.node_config_json).__abandoned).toBeTruthy(); + expect(JSON.parse(first.node_config_json).__laterStepNotOpened.node).toBe('second'); + const line = (await timeline(String(first.id))).at(-1)!; + expect(line.slice(0, 2), 'a line with no actor').toEqual(['comment', null]); + expect(line[2]).toMatch(/^The approval did not go on: its step 'second' could not open \(.*NO_APPROVERS.*\)\. The record's approval_status was put back to 'recalled'\.$/); + expect(notices.filter((n) => n.topic === 'approval.abandoned').map((n) => n.audience)).toEqual([['owner']]); + expect(notices.some((n) => n.topic === 'approval.approved'), 'no approved notice for an approval that did not finish').toBe(false); + expect(await marks('i_empty')).toEqual([false]); + }); + + it('with a fault edge to the end: abandoned', async () => { + await start('second_empty_fault_end', 'crm_invoice', 'i_empty_end'); + await decide('i_empty_end', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_empty_end'))[0].record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_empty_end')).toBe('recalled'); + }); + + it('with a fault edge to another step, which opens: in progress, then finished', async () => { + await start('second_empty_fault_third', 'crm_invoice', 'i_empty_third'); + await decide('i_empty_third', 'approve', 'approver'); + expect(await steps('i_empty_third')).toEqual([['first', 'approved'], ['third', 'pending']]); + expect(await field('crm_invoice', 'i_empty_third')).toBe('pending'); + await decide('i_empty_third', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_empty_third')).toBe('approved'); + }); + + it('on a request of another approval already pending on the record: the field keeps that approval\'s pending', async () => { + await start('two_step', 'crm_invoice', 'i_dup'); + const [first] = await requestsOn('i_dup'); + // Another approval's request on the record, on the same field: the + // shape a second approval leaves when it opens between two steps. + await ql.insert('sys_approval_request', { + id: 'areq_other', process_name: 'flow:other', object_name: 'crm_invoice', record_id: 'i_dup', status: 'pending', + root_run_id: 'run_other', record_run_id: 'run_other', flow_run_id: 'run_other', flow_node_id: 'x', + node_config_json: JSON.stringify({ approvers: [], approvalStatusField: 'approval_status' }), + organization_id: ORG, created_at: new Date().toISOString(), + }, { context: SYS }); + const out = await settle(svc.decide(String(first.id), { decision: 'approve', actorId: 'approver' } as any, asPerson('approver'))); + expect('error' in out && out.error.message).toMatch(/^RESUME_FAILED/); + const mine = (await requestsOn('i_dup')).filter((r) => r.root_run_id !== 'run_other'); + expect(mine.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved']]); + expect(JSON.parse(mine[0].node_config_json).__abandoned).toBeTruthy(); + expect(await field('crm_invoice', 'i_dup')).toBe('pending'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/left as it is: the request 'areq_other' of another approval is open on it\.$/); + }); + }); + + describe('another node between two steps fails', () => { + it('with a fault edge to the end: abandoned', async () => { + await start('boom_between_fault_end', 'crm_invoice', 'i_boom_end'); + throwOn.add('boom'); + await decide('i_boom_end', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_boom_end'))[0].record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_boom_end')).toBe('recalled'); + const [first] = await requestsOn('i_boom_end'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + }); + + it('handled in a try_catch region, after which a gateway ends the flow: finished', async () => { + await start('boom_handled', 'crm_invoice', 'i_handled'); + throwOn.add('boom'); + await decide('i_handled', 'approve', 'approver'); + expect((await automation.getRun(String((await requestsOn('i_handled'))[0].record_run_id)))?.status).toBe('completed'); + expect(await steps('i_handled')).toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_handled')).toBe('approved'); + }); + + it('unrouted: the run fails between two steps, the approval is abandoned, and a restored run is refused', async () => { + await start('boom_between', 'crm_invoice', 'i_boom'); + throwOn.add('boom'); + const out = await settle(decide('i_boom', 'approve', 'approver')); + expect('error' in out && strandedDecisionDetails(out.error)?.repairable).toBe(true); + expect(await field('crm_invoice', 'i_boom')).toBe('recalled'); + const [first] = await requestsOn('i_boom'); + + throwOn.clear(); + const restored = await (automation as any).restoreConsumedSuspension(String(first.flow_run_id), { requestedBy: 'ops', reason: 'test' }); + expect(restored.restored).toBe(true); + const refused = await settle(svc.continueRestoredRun(String(first.id))); + expect('error' in refused && refused.error.message).toMatch(/^INVALID_STATE: .*was abandoned when its run ended between two steps.*Cancel the restored run/); + expect(await steps('i_boom'), 'no next step opened').toEqual([['first', 'approved']]); + }); + }); + + describe('an approval that holds nothing back, and the control', () => { + it('an object whose closed states are on another field: the decision is written at once, the mark is set and cleared', async () => { + await start('two_step_then_read', 'crm_ticket', 't_two'); + const [first] = await requestsOn('t_two'); + expect(first.between_steps_json, 'stamped: the object declares the key').toBeTruthy(); + await decide('t_two', 'approve', 'approver'); + await decide('t_two', 'approve', 'approver2'); + expect(seen, 'as on main: a node after the decision reads it').toEqual(['approved']); + expect(await field('crm_ticket', 't_two')).toBe('approved'); + expect(await marks('t_two')).toEqual([false, false]); + }); + + it('the same object, whose run ends between two steps: nothing is written and the mark is cleared', async () => { + await start('boom_between_fault_end', 'crm_ticket', 't_boom'); + throwOn.add('boom'); + await decide('t_boom', 'approve', 'approver'); + const [first] = await requestsOn('t_boom'); + expect(await field('crm_ticket', 't_boom')).toBe('approved'); + expect(JSON.parse(first.node_config_json).__abandoned ?? null).toBeNull(); + expect(await marks('t_boom')).toEqual([false]); + }); + + it('an object that declares no closed state: unstamped, no mark, written as before', async () => { + await start('two_step_then_read', 'crm_memo', 'm_two'); + await decide('m_two', 'approve', 'approver'); + await decide('m_two', 'approve', 'approver2'); + const rows = await requestsOn('m_two'); + expect(rows.map((r) => r.between_steps_json ?? null)).toEqual([null, null]); + expect(rows.map((r) => r.unjudged_since ?? null)).toEqual([null, null]); + expect(seen).toEqual(['approved']); + expect(await field('crm_memo', 'm_two')).toBe('approved'); + }); + }); + + describe('cannot tell', () => { + it('a run another process is advancing: nothing is written, and the mark stays', async () => { + await start('two_step', 'crm_invoice', 'i_busy'); + await decide('i_busy', 'approve', 'approver'); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string) => ({ ...(await original(id)), status: 'running' }); + await decide('i_busy', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_busy')).toBe('pending'); + expect(await marks('i_busy')).toEqual([false, true]); + }); + + it('a run that cannot be read: nothing is written, and the mark stays', async () => { + await start('two_step', 'crm_invoice', 'i_unread'); + await decide('i_unread', 'approve', 'approver'); + (automation as any).getRun = async () => { throw new Error('store down'); }; + await decide('i_unread', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_unread')).toBe('pending'); + expect(await marks('i_unread')).toEqual([false, true]); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 5622e1649d7..97ef2cf320c 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -5305,10 +5305,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega orderBy: [{ field: 'created_at', order: 'asc' }], limit: 500, context: SYSTEM_CTX, })) ?? []; - if (approval.some((r) => r.status === 'pending' || r.status === 'returned')) return 'in_progress'; + // Open: a pending request, or a returned one in its revise window, which + // is the approval's latest (a resubmitted round stays `returned`). + const latest = approval[approval.length - 1] ?? row; + if (approval.some((r) => r.status === 'pending') || latest.status === 'returned') return 'in_progress'; const marked = approval.filter(isMarked); if (marked.length === 0) return 'judged'; - const latest = approval[approval.length - 1] ?? row; if (latest.status !== 'approved' && latest.status !== 'rejected') { await this.clearMarks(marked); return 'judged'; @@ -5505,9 +5507,24 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega where: { object_name: object, record_id: recordId, status: { $in: ['pending', 'returned'] } }, limit: 50, context: SYSTEM_CTX, }); - other = (Array.isArray(open) ? open : []).find((r: any) => - String(r?.root_run_id ?? '') !== String(latest.root_run_id ?? '') - && parseJson(r?.node_config_json, { approvers: [] } as any).approvalStatusField === field); + for (const r of Array.isArray(open) ? open : []) { + if (String(r?.root_run_id ?? '') === String(latest.root_run_id ?? '')) continue; + if (parseJson(r?.node_config_json, { approvers: [] } as any).approvalStatusField !== field) continue; + // A returned request is open only in its revise window: no later + // request of its approval on the record (a resubmitted round stays + // `returned`). + if (r.status === 'returned') { + const later = await this.engine.find('sys_approval_request', { + where: r.root_run_id + ? { root_run_id: r.root_run_id, object_name: object, record_id: recordId, created_at: { $gt: r.created_at } } + : { flow_run_id: r.flow_run_id, object_name: object, record_id: recordId, created_at: { $gt: r.created_at } }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + if (Array.isArray(later) && later.length > 0) continue; + } + other = r; + break; + } } catch (err: any) { this.logger?.warn?.('[approvals] could not read whether another approval is open on the record of an abandoned one; the put-back goes ahead', { request: latest.id, object, record: recordId, error: err?.message ?? String(err), 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 75501d513b6..2aa9c3663b9 100644 --- a/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts +++ b/packages/plugins/plugin-approvals/src/approver-address-readers.test.ts @@ -168,7 +168,7 @@ const SLOT_COLUMNS = new Set(['approver', 'acted_as', 'pending_approvers']); /** The person column of `sys_approval_action` (#21411). */ const PERSON_COLUMN = 'actor_id'; -type PersonRole = 'caller-user-id' | 'display' | 'migration'; +type PersonRole = 'caller-user-id' | 'display' | 'migration' | 'attribution'; /** * Every read of `actor_id` in this package, keyed ` · { + it("a later request's `pending` refused: the request stays open, the refusal is reported, and the field keeps `pending`", async () => { await seed('crm_invoice', 'i_later'); const first = await open('two_step', 'crm_invoice', 'i_later'); hookRefuses.add('pending'); @@ -286,9 +286,10 @@ describe('[ADR-0162 item 8] a refused write of the status mirror on a field the { id: first, step: 'first', status: 'approved' }, { id: second.id, step: 'second', status: 'pending' }, ]); - // The outcome is still written at each decision on this branch; holding it - // back until the approval is over is the next piece of the item. - expect(await field('crm_invoice', 'i_later'), 'the value the field keeps').toBe('approved'); + // [ADR-0162 item 8, slice 3] The first step's decision is held back until + // the approval is over, so the field still holds the `pending` the first + // request wrote. + expect(await field('crm_invoice', 'i_later'), 'the value the field keeps').toBe('pending'); await expectReported('crm_invoice', 'i_later', second.id, 'pending', HOOK_REFUSAL); }); diff --git a/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts b/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts index ffba6519a24..ced440da7e7 100644 --- a/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts +++ b/packages/plugins/plugin-approvals/src/stored-process-package-backfill.test.ts @@ -172,6 +172,8 @@ describe('R7 — an open approval request gains the package that holds its flow' // ADR-0162 item 7 (the root run) adds these two, after this card. { fields: ['root_run_id', 'object_name', 'record_id'], unique: false }, { fields: ['record_run_id'], unique: false }, + // ADR-0162 item 8 (the mark) adds this one. + { fields: ['unjudged_since'], unique: false }, ])); expect((SysApprovalRequest.fields as Record).process_package).toMatchObject({ type: 'text', required: false, readonly: true, diff --git a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts index 2088ab9929f..ae1412ca4c4 100644 --- a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts @@ -121,6 +121,10 @@ export const arObjects: NonNullable = { label: "بين الخطوات", help: "عُقد التدفق التي تقع بين خطوتين من الموافقة التي ينتمي إليها هذا الطلب." }, + unjudged_since: { + label: "غير محسوم منذ", + help: "وقت البتّ في هذا الطلب، ما دام ما يلي القرار لم يُحسم بعد." + }, node_config_json: { label: "إعداد العقدة", help: "لقطة من إعداد عقدة الموافقة (الموافِقون/السلوك) للطلبات التي تقودها العُقد." diff --git a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts index 8bffeec4815..eb6407dc6ac 100644 --- a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts @@ -121,6 +121,10 @@ export const deObjects: NonNullable = { label: "Zwischen Schritten", help: "Flussknoten, die zwischen zwei Schritten der Genehmigung stehen, zu der diese Anfrage gehört." }, + unjudged_since: { + label: "Nicht beurteilt seit", + help: "Wann diese Anfrage entschieden wurde, solange noch nicht beurteilt ist, was auf die Entscheidung folgt." + }, node_config_json: { label: "Knotenkonfiguration", help: "Momentaufnahme der Konfiguration des Genehmigungsknotens (Genehmiger/Verhalten) bei knotengesteuerten Anfragen." diff --git a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts index b13662521df..8b691d648b8 100644 --- a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts @@ -121,6 +121,10 @@ export const enObjects: NonNullable = { label: "Between Steps", help: "Flow nodes that stand between two steps of the approval this request belongs to." }, + unjudged_since: { + label: "Unjudged Since", + help: "When this request was decided, while what follows the decision has not been judged yet." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts index fc110876cf8..f9fb91e1361 100644 --- a/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/es-ES.objects.generated.ts @@ -121,6 +121,10 @@ export const esESObjects: NonNullable = { label: "Entre pasos", help: "Nodos del flujo que están entre dos pasos de la aprobación a la que pertenece esta solicitud." }, + unjudged_since: { + label: "Sin evaluar desde", + help: "Cuándo se decidió esta solicitud, mientras aún no se ha evaluado lo que sigue a la decisión." + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts index 7f5d81ac7f9..3f00197197e 100644 --- a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts @@ -121,6 +121,10 @@ export const frObjects: NonNullable = { label: "Entre les étapes", help: "Nœuds du flux situés entre deux étapes de l'approbation à laquelle appartient cette demande." }, + unjudged_since: { + label: "Non évaluée depuis", + help: "Date à laquelle cette demande a été décidée, tant que la suite de la décision n'a pas encore été évaluée." + }, node_config_json: { label: "Configuration du nœud", help: "Instantané de la configuration du nœud d’approbation (approbateurs/comportement) pour les demandes pilotées par un nœud." diff --git a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts index 59912ac12c6..df8aca292a8 100644 --- a/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ja-JP.objects.generated.ts @@ -121,6 +121,10 @@ export const jaJPObjects: NonNullable = { label: "ステップ間", help: "この申請が属する承認で、二つのステップの間にあるフローノード。" }, + unjudged_since: { + label: "未判定の開始日時", + help: "この申請が決定された日時。その決定に続く処理がまだ判定されていない間だけ記録されます。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts index e8e20789290..a36e7e8df6f 100644 --- a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts @@ -121,6 +121,10 @@ export const koObjects: NonNullable = { label: "단계 사이", help: "이 요청이 속한 승인에서 두 단계 사이에 있는 플로 노드입니다." }, + unjudged_since: { + label: "미판정 시작 시각", + help: "이 요청이 결정된 시각으로, 그 결정 이후의 진행이 아직 판정되지 않은 동안 기록됩니다." + }, node_config_json: { label: "노드 구성", help: "노드 기반 요청의 승인 노드 구성(승인자/동작) 스냅숏입니다." diff --git a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts index 085246ac1d1..48536977db7 100644 --- a/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/pt-BR.objects.generated.ts @@ -121,6 +121,10 @@ export const ptBRObjects: NonNullable = { label: "Entre etapas", help: "Nós do fluxo que ficam entre duas etapas da aprovação à qual esta solicitação pertence." }, + unjudged_since: { + label: "Não avaliada desde", + help: "Quando esta solicitação foi decidida, enquanto o que segue a decisão ainda não foi avaliado." + }, node_config_json: { label: "Configuração do nó", help: "Instantâneo da configuração do nó de aprovação (aprovadores/comportamento) para solicitações conduzidas por nó." diff --git a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts index d8bcf649534..37e4895ac26 100644 --- a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts @@ -121,6 +121,10 @@ export const ruObjects: NonNullable = { label: "Между шагами", help: "Узлы потока, стоящие между двумя шагами согласования, к которому относится этот запрос." }, + unjudged_since: { + label: "Не оценено с", + help: "Когда по этому запросу было принято решение, пока то, что следует за решением, ещё не оценено." + }, node_config_json: { label: "Конфигурация узла", help: "Снимок конфигурации узла согласования (согласующие/поведение) для запросов, запускаемых узлом." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts index ea9abebff29..34a3c318b97 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-CN.objects.generated.ts @@ -121,6 +121,10 @@ export const zhCNObjects: NonNullable = { label: "步骤之间", help: "审批中位于两个步骤之间的流程节点。" }, + unjudged_since: { + label: "待判定起始时间", + help: "此请求被决定的时间;在此决定之后的流程尚未判定时记录。" + }, node_config_json: { label: "Node Config", help: "Snapshot of the Approval node config (approvers/behavior) for node-driven requests." diff --git a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts index ef80bead5ac..2b4c6bb8517 100644 --- a/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/zh-Hant.objects.generated.ts @@ -121,6 +121,10 @@ export const zhHantObjects: NonNullable = { label: "步驟之間", help: "審批中位於兩個步驟之間的流程節點。" }, + unjudged_since: { + label: "待判定起始時間", + help: "此請求被決定的時間;在此決定之後的流程尚未判定時記錄。" + }, node_config_json: { label: "節點設定", help: "由節點驅動之請求的核准節點設定(核准人/行為)快照。" From 47f42865a1517f27f02e579115248a0e00b081aa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:43:02 +0000 Subject: [PATCH 3/5] fix(approvals): the door also reads the latest request's own run, for a subflow body's routed failure; census regenerated Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../plugins/plugin-approvals.md | 18 +++---- ...utcome-when-over-37767.integration.test.ts | 13 +++++ .../plugin-approvals/src/approval-service.ts | 50 +++++++++++++------ 3 files changed, 58 insertions(+), 23 deletions(-) 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 b3808a404c1..607d59f8519 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 | 45 | -| Object name statically decidable | 43 | +| Write call sites | 49 | +| Object name statically decidable | 47 | | Object name chosen at run time | 2 | -| Object name spelled inline | 41 | +| Object name spelled inline | 45 | | 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 | 43 | +| Against a tenancy-enabled object | 47 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 45 | +| Threading a tenant context | 49 | | 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 | 43 | +| Threading a decidably elevated (`isSystem`) context | 47 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 45 | +| Receiver carried a readable engine type | 49 | | 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 | @@ -50,11 +50,11 @@ a row or a number here — fix the code, or the census, and regenerate. | `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 | 19 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 20 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 11 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 14 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts index fdbdc7e45de..ebcd807abe4 100644 --- a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -100,6 +100,9 @@ const FLOWS = [ [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + // The same two steps in a `subflow` child, whose steps the parent's run does not log. + flow('parent_of_boom', [{ id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'boom_between_fault_end' } }], + [edge('start', 'sub'), edge('sub', 'end')]), // That node's failure handled in a try_catch region, after which a gateway ends the flow. flow('boom_handled', [step('first', 'approver'), { id: 'guard', type: 'try_catch', label: 'Guard', config: { try: { nodes: [mark('boom')], edges: [] }, catch: { nodes: [mark('handled')], edges: [] } } }, @@ -432,6 +435,16 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); }); + it('in a subflow child, with a fault edge to the child\'s end: abandoned, read off the child\'s own run', async () => { + await start('parent_of_boom', 'crm_invoice', 'i_child'); + throwOn.add('boom'); + await decide('i_child', 'approve', 'approver'); + const [first] = await requestsOn('i_child'); + expect(first.flow_run_id, 'the request is the child run\'s').not.toBe(first.record_run_id); + expect((await automation.getRun(String(first.record_run_id)))?.status).toBe('completed'); + expect(await field('crm_invoice', 'i_child')).toBe('recalled'); + }); + it('handled in a try_catch region, after which a gateway ends the flow: finished', async () => { await start('boom_handled', 'crm_invoice', 'i_handled'); throwOn.add('boom'); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 97ef2cf320c..cde5a60e96e 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -5441,25 +5441,47 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; } // A failure the flow routed, at the top level of the run, on a node of the - // set, after which no request of the approval opened. + // set, after which no request of the approval opened; or a stop on a node + // of the set. Read on the run that carries the record, and on the latest + // request's own run where that is another (a `subflow` body runs in a + // child run of its own, whose steps the carrying run does not log). const instant = (v: unknown): number => (v == null || v === '' ? NaN : new Date(v as string).getTime()); const lastOpened = approval.reduce((acc, r) => { const at = instant(r?.created_at); return Number.isFinite(at) && at > acc ? at : acc; }, -Infinity); - const routed = steps.find((s) => s?.status === 'failure' - && !s.parentNodeId - && typeof s.nodeId === 'string' - && s.nodeId !== stoppedAt - && standsBetweenSteps(stamp, flow, s.nodeId) - && !(instant(s.startedAt) < lastOpened)); - if (routed) { - return { answer: 'abandoned', why: `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.` }; - } - if (status !== 'paused' && status !== 'completed') { - if (!stoppedAt) return { answer: 'abandoned', why: `its run ended ${status}, at a node the plugin cannot place.` }; - if (standsBetweenSteps(stamp, flow, stoppedAt)) { - return { answer: 'abandoned', why: `its run ended ${status} at node '${stoppedAt}', between two steps.` }; + const endedBetween = ( + log: ReadonlyArray<{ nodeId?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown }>, + logFlow: string | undefined, + logStatus: string, + stop: string | undefined, + ): string | undefined => { + const routed = log.find((s) => s?.status === 'failure' + && !s.parentNodeId + && typeof s.nodeId === 'string' + && s.nodeId !== stop + && standsBetweenSteps(stamp, logFlow, s.nodeId) + && !(instant(s.startedAt) < lastOpened)); + if (routed) return `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.`; + if (logStatus === 'paused' || logStatus === 'completed') return undefined; + if (!stop) return `its run ended ${logStatus}, at a node the plugin cannot place.`; + if (standsBetweenSteps(stamp, logFlow, stop)) return `its run ended ${logStatus} at node '${stop}', between two steps.`; + return undefined; + }; + const carried = endedBetween(steps, flow, status, stoppedAt); + if (carried) return { answer: 'abandoned', why: carried }; + const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; + if (ownRunId && ownRunId !== runId) { + let own: { status?: string; flowName?: string; steps?: unknown } | null = null; + try { own = await automation.getRun(ownRunId); } catch { own = null; } + const ownStatus = typeof own?.status === 'string' ? own.status : ''; + if (own && TERMINAL_RUN_STATUSES.has(ownStatus)) { + const ownSteps = (Array.isArray(own.steps) ? own.steps : []) as typeof steps; + const failed = ownStatus === 'completed' ? undefined + : ([...ownSteps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId) ?? ownSteps[ownSteps.length - 1]); + const ownStop = failed && typeof failed.nodeId === 'string' ? failed.nodeId : undefined; + const inChild = endedBetween(ownSteps, typeof own.flowName === 'string' ? own.flowName : undefined, ownStatus, ownStop); + if (inChild) return { answer: 'abandoned', why: inChild }; } } return { answer: 'finished' }; From a5d0d155f8089a548d38a1a50c35b407d21d5c41 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:00:16 +0000 Subject: [PATCH 4/5] test(approvals): the held-back decision and the advancing run each have an observation an ablation turns red The two-step case now records every value written to the field: the second step's opening writes `pending` straight after the first decision, so the field read alone could not tell a held-back decision from a written one. The two cannot-tell cases assert the reason the door logs, since a run that is advancing and a status the plugin does not place answer alike. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- ...utcome-when-over-37767.integration.test.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts index ebcd807abe4..f1d621e56a1 100644 --- a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -137,6 +137,7 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( /** What each `read` node saw on the record's field. */ let seen: unknown[]; let notices: Array<{ topic: string; audience: string[] }>; + let infos: string[]; afterEach(async () => { try { await kernel?.shutdown(); } catch { /* noop */ } @@ -171,7 +172,9 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); } const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; - svc = new ApprovalService({ engine: ql, logger: quiet as any }); + infos = []; + const heard = { ...quiet, info: (m: unknown) => { infos.push(String(m)); } }; + svc = new ApprovalService({ engine: ql, logger: heard as any }); svc.noteSweepClockScheduled(); svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); svc.attachAutomation(automation as any); @@ -213,6 +216,15 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( describe('the decision is held back, and written when the approval is over', () => { it('two steps approved: the field reads pending after the first and approved once the run ends; marks are set and cleared', async () => { + // Every value written to the field, in order: the second step's opening + // writes `pending` straight after the first decision, so the field read + // alone cannot tell a held-back decision from a written one. + const written: unknown[] = []; + const update = ql.update.bind(ql); + (ql as any).update = async (object: string, data: any, opts?: any) => { + if (object === 'crm_invoice' && data?.id === 'i_two' && 'approval_status' in data) written.push(data.approval_status); + return update(object, data, opts); + }; expect((await start('two_step', 'crm_invoice', 'i_two')).status).toBe('paused'); await decide('i_two', 'approve', 'approver'); expect(await steps('i_two')).toEqual([['first', 'approved'], ['second', 'pending']]); @@ -221,6 +233,7 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await decide('i_two', 'approve', 'approver2'); expect(await field('crm_invoice', 'i_two')).toBe('approved'); + expect(written, 'the first decision was never written onto the record').toEqual(['pending', 'pending', 'approved']); expect(await marks('i_two'), 'judged: no mark stands').toEqual([false, false]); }); @@ -514,6 +527,9 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await decide('i_busy', 'approve', 'approver2'); expect(await field('crm_invoice', 'i_busy')).toBe('pending'); expect(await marks('i_busy')).toEqual([false, true]); + // The reason names the advancing run, not only an unplaced status: the + // two answer alike, and only the reason tells them apart. + expect(infos.some((m) => m.includes('i_busy') && m.includes("is running, so another process may be advancing it"))).toBe(true); }); it('a run that cannot be read: nothing is written, and the mark stays', async () => { @@ -523,6 +539,7 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( await decide('i_unread', 'approve', 'approver2'); expect(await field('crm_invoice', 'i_unread')).toBe('pending'); expect(await marks('i_unread')).toEqual([false, true]); + expect(infos.some((m) => m.includes('i_unread') && m.includes('could not be read (store down)'))).toBe(true); }); }); }); From a3b666ce0f924639fb77cdc71f371608f79d4982 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:14:32 +0000 Subject: [PATCH 5/5] fix(approvals): where a run stopped is its last top-level step, and a refusing end is an end A run that ends on an `end` declaring `outcome: 'refused'` reached an end of the flow, as a completed run did; it logs no step for the `end`, so its last step is the approval just decided and was read as a stop between two steps, abandoning a rejection. A cancelled run, or one failed by a child or settled as unresumable, logs nothing after the node it stood on, so the stop is its last top-level step; an earlier failure the flow routed on is no longer taken for it. The approval's requests are read newest first, so the latest is in the window however many there are, and an auto-rejection the door abandoned no longer also sends the auto-rejected notice. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- ...utcome-when-over-37767.integration.test.ts | 34 +++++++++++++ .../plugin-approvals/src/approval-service.ts | 49 ++++++++++++++----- 2 files changed, 72 insertions(+), 11 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts index f1d621e56a1..08297d72bc1 100644 --- a/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-outcome-when-over-37767.integration.test.ts @@ -120,6 +120,14 @@ const FLOWS = [ flow('second_revise_spent', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }], [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end'), edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }]), + // The first step's reject edge to an `end` that refuses: the run ends `refused`, an `end` logging no step. + flow('refuse_on_reject', [step('first', 'approver'), step('second', 'approver2'), + { id: 'refuse', type: 'end', label: 'Refuse', config: { outcome: 'refused', message: 'Refused' } }], + [edge('start', 'first'), edge('first', 'second', 'approve'), edge('first', 'refuse', 'reject'), ...decided('second', 'end')]), + // A node before the first step fails and is routed on; the first step is in a `subflow` child, the second after it. + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + flow('early_fault_then_sub', [mark('early'), { id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'child_one_step' } }, step('second', 'approver2')], + [edge('start', 'early'), edge('early', 'sub'), edge('early', 'sub', undefined, 'fault'), edge('sub', 'second'), ...decided('second', 'end')]), // A batch whose items are records, each approved in its own run of `item_step`. flow('item_step', [step('only', 'approver'), mark('after')], [edge('start', 'only'), edge('only', 'after', 'approve'), edge('only', 'end', 'reject'), edge('after', 'end')]), { name: 'batch', label: 'batch', type: 'autolaunched', variables: [{ name: 'items', type: 'list', isInput: true }], @@ -518,6 +526,32 @@ describe('[ADR-0162 item 8] the outcome is written when the approval is over', ( }); }); + describe('where a run stopped', () => { + it('a run that ends on a refusing end is finished: the rejection is written, not abandoned', async () => { + await start('refuse_on_reject', 'crm_invoice', 'i_refused'); + await decide('i_refused', 'reject', 'approver'); + const [only] = await requestsOn('i_refused'); + expect((await automation.getRun(String(only.record_run_id)))?.status).toBe('refused'); + expect(await field('crm_invoice', 'i_refused')).toBe('rejected'); + expect(await marks('i_refused')).toEqual([false]); + expect(notices.some((n) => n.topic === 'approval.abandoned')).toBe(false); + expect(notices.filter((n) => n.topic === 'approval.rejected').map((n) => n.audience)).toEqual([['owner']]); + }); + + it('a cancelled run stopped where it stood, not at an earlier failure the flow routed on: abandoned', async () => { + throwOn.add('early'); + await start('early_fault_then_sub', 'crm_invoice', 'i_cancel'); + const [child] = await requestsOn('i_cancel'); + expect(child.flow_run_id, 'the request is the child run\'s').not.toBe(child.record_run_id); + await automation.cancelRun(String(child.record_run_id)); + await settle(decide('i_cancel', 'approve', 'approver')); + expect((await automation.getRun(String(child.record_run_id)))?.status).toBe('cancelled'); + expect(await steps('i_cancel'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_cancel'), 'stopped at the subflow, between two steps').toBe('recalled'); + expect(await marks('i_cancel')).toEqual([false]); + }); + }); + describe('cannot tell', () => { it('a run another process is advancing: nothing is written, and the mark stays', async () => { await start('two_step', 'crm_invoice', 'i_busy'); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index cde5a60e96e..65fcbcc58df 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1869,6 +1869,33 @@ const LATER_STEP_NOT_OPENED_KEY = '__laterStepNotOpened'; /** The run statuses a run reports while it is being advanced, or is about to be. */ const ADVANCING_RUN_STATUSES: ReadonlySet = new Set(['pending', 'running', 'retrying']); +/** + * [ADR-0162 Execution item 8] The terminal statuses of a run that reached an + * `end` the flow declares: `completed`, and `refused` (an `end` with + * `outcome: 'refused'`, a successful evaluation that said no). Such a run + * stopped nowhere between two steps, so the door reads it as finished, a + * failure it routed on the way apart. An `end` logs no step of its own, so + * the last step of a refused run is the node before it, often the approval + * that was just decided, and must not be read as where the run stopped. + */ +const REACHED_AN_END: ReadonlySet = new Set(['completed', 'refused']); + +/** + * [ADR-0162 Execution item 8] Where a terminal run stopped, read off its step + * log: the last step at the top level of the run (one that ran in no + * `loop`, `parallel` or `try_catch` region), else the last step. An + * unrouted failure is the last step a run logs, and a run that was cancelled, + * failed by a child's failure or settled as unresumable logs nothing after + * the node it stood on, so the last step names the node in every case; an + * earlier failure that the flow routed on is not where the run stopped. + * `undefined` for a run that reached an `end` ({@link REACHED_AN_END}). + */ +function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }>, status: string): string | undefined { + if (REACHED_AN_END.has(status)) return undefined; + const last = [...log].reverse().find((s) => !s?.parentNodeId) ?? log[log.length - 1]; + return last && typeof last.nodeId === 'string' ? last.nodeId : undefined; +} + /** * [ADR-0162 Execution item 8] What the door answered for an approval after it * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). @@ -5302,9 +5329,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const approval: any[] = (await this.engine.find('sys_approval_request', { where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, - orderBy: [{ field: 'created_at', order: 'asc' }], + orderBy: [{ field: 'created_at', order: 'desc' }], limit: 500, context: SYSTEM_CTX, })) ?? []; + // Newest first, so the latest is in the window however many requests + // the approval has; read oldest first below. + approval.reverse(); // Open: a pending request, or a returned one in its revise window, which // is the approval's latest (a resubmitted round stays `returned`). const latest = approval[approval.length - 1] ?? row; @@ -5426,10 +5456,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) return { answer: 'in_progress' }; } else if (!TERMINAL_RUN_STATUSES.has(status)) { return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.`, runId }; - } else if (status !== 'completed') { - const failed = [...steps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId); - const last = failed ?? steps[steps.length - 1]; - stoppedAt = last && typeof last.nodeId === 'string' ? last.nodeId : undefined; + } else { + stoppedAt = stopOf(steps, status); } const config = parseJson>(latest.node_config_json, {}); @@ -5463,7 +5491,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega && standsBetweenSteps(stamp, logFlow, s.nodeId) && !(instant(s.startedAt) < lastOpened)); if (routed) return `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.`; - if (logStatus === 'paused' || logStatus === 'completed') return undefined; + if (logStatus === 'paused' || REACHED_AN_END.has(logStatus)) return undefined; if (!stop) return `its run ended ${logStatus}, at a node the plugin cannot place.`; if (standsBetweenSteps(stamp, logFlow, stop)) return `its run ended ${logStatus} at node '${stop}', between two steps.`; return undefined; @@ -5477,9 +5505,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const ownStatus = typeof own?.status === 'string' ? own.status : ''; if (own && TERMINAL_RUN_STATUSES.has(ownStatus)) { const ownSteps = (Array.isArray(own.steps) ? own.steps : []) as typeof steps; - const failed = ownStatus === 'completed' ? undefined - : ([...ownSteps].reverse().find((s) => s?.status === 'failure' && !s.parentNodeId) ?? ownSteps[ownSteps.length - 1]); - const ownStop = failed && typeof failed.nodeId === 'string' ? failed.nodeId : undefined; + const ownStop = stopOf(ownSteps, ownStatus); const inChild = endedBetween(ownSteps, typeof own.flowName === 'string' ? own.flowName : undefined, ownStatus, ownStop); if (inChild) return { answer: 'abandoned', why: inChild }; } @@ -9047,8 +9073,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega resumeError = outcome.resumeError; } // [ADR-0162 Execution item 8] The auto-rejection is a decision: the door judges the approval. - await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); - if (raw.submitter_id) { + // An abandoned approval has told its submitter already, on its own topic. + const judged = await this.judgeApprovalAfterDoor(raw, 'the auto-rejection', { requestId: String(requestId), actorId: actingUserId(context) }); + if (raw.submitter_id && judged !== 'abandoned') { await this.notify({ topic: 'approval.returned', organizationId: raw.organization_id,