diff --git a/.changeset/37766-opening-check.md b/.changeset/37766-opening-check.md new file mode 100644 index 00000000000..ce7e3b7040f --- /dev/null +++ b/.changeset/37766-opening-check.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): an approval that cannot show itself in progress on a field its object closes on does not open (ADR-0162 Execution item 7, the check) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `sys_approval_request` gains the engine-written, read-only column `between_steps_json`; `ApprovalService` gains `noteSweepClockScheduled()`, and the input of `ApprovalService.openNodeRequest` gains the optional member `locale` (the run's locale, for the refusal's wording); the plugin's message catalog gains twelve `approvalOpening*` sentences in all 11 locale packs. + +At an approval's first request the plugin now reads the approval whole: the flow its root run was started on and every flow a `subflow` or a `map` in it names, to any depth. Where a step can act on an object that declares `closedStates`: + +- **The between-two-steps set is stamped** on the request, and every later request of the same approval carries the same set. It lists the nodes after which a step of the approval can still follow, so that a run that stops there can later be told from one that stopped after the last step. +- **The approval does not open** where a step mirrors onto a field the object closes on at `pending`, `returned`, `approved` or `rejected`, and one of these is missing: the field declares `pending` and the object closes on neither `pending` nor `returned`; a `state_machine` rule on the field that declares the moves out of a closed `approved` or `rejected` includes `pending` among them; the field has no `readonlyWhen` and no request-status option has a `visibleWhen`; every step that can act on the object mirrors onto the same field; no node that can pause the run (a `wait`, a `screen`, a node type with no descriptor) stands between two steps, and no `map` runs an approval step for items it does not show are not records. An approval one of whose flows cannot be read does not open either, and neither does one on a host that runs no `job` service. + +A refused approval fails its run at the step with `VALIDATION_FAILED` and one sentence per gap naming the flow, the step, the object, the field and what is missing, in the run's locale. No request row is written. + +Not judged, and unchanged: an application in which no object declares `closedStates`; an approval whose objects declare none, once it has been read whole (in an application where some object declares the key, an approval one of whose flows cannot be read is refused, whatever objects the parts that were read act on, since its objects cannot be known); a request whose run hands no root run; a later request of an approval already open (also one opened before the object declared the key); a request that cannot be placed because an earlier request on the record since its root run started records no root run. A writing node between two steps of a flow that runs as the user is not refused. diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index bc93e658922..4a0ea9a5f43 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -243,6 +243,8 @@ export function registerApprovalNode( runRoot: !hasParentRun(context), rootRun, recordRun, + // [ADR-0162 Execution item 7] A refused opening is worded in the run's locale. + locale: typeof context?.locale === 'string' ? context.locale : undefined, }, { ...SYSTEM_CTX, userId: context?.userId, diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts new file mode 100644 index 00000000000..33fe0a448a9 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check-37766.integration.test.ts @@ -0,0 +1,232 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7 "The check", #37766 slice B] The check when an + * approval opens, as the service runs it at a request's opening: placed by + * the request's root run, judged once at the approval's first request, its + * between-two-steps set stamped on every request of an approval that touches + * an object declaring `closedStates`, and a refusal that names what is + * missing, in the run's locale. The read of the definition itself, arm by + * arm, is pinned over fixtures in `approval-opening-check.test.ts`. + * + * Real kernel, real ObjectQL engine, real automation engine (which hands the + * root run, slice A), real approval node, driver-sql on better-sqlite3 + * `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +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, other_status: { ...statusField, name: 'other_status' } }; +/** Closes on its approval's outcome, and meets every condition of D5. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** The same object, declaring no closed state. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, field = 'approval_status') => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: field }, +}); +const endEdges = (from: string, to: string, n: number) => [ + { id: `e${n}a`, source: from, target: to, label: 'approve' }, + { id: `e${n}r`, source: from, target: 'end', label: 'reject' }, +]; + +/** Two steps on the same field: opens. */ +const twoStep = { + name: 'two_step', label: 'Two steps', type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), step('second', 'approver2'), { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'second', 2), ...endEdges('second', 'end', 3)], +}; +/** A timer between the two steps: D5 condition 5. */ +const waitBetween = { + name: 'wait_between', label: 'Wait between', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), + { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }, + step('second', 'approver2'), { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'hold', 2), { id: 'e3', source: 'hold', target: 'second' }, ...endEdges('second', 'end', 4)], +}; +/** The second step mirrors onto another field: D5 condition 4. */ +const otherField = { + name: 'other_field', label: 'Other field', type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, step('first', 'approver'), step('second', 'approver2', 'other_status'), { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'first' }, ...endEdges('first', 'second', 2), ...endEdges('second', 'end', 3)], +}; + +describe('[ADR-0162 item 7] the check when an approval opens', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + async function boot(opts: { sweeps?: boolean; invoiceDef?: Record } = {}) { + 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 [opts.invoiceDef ?? invoice, 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 }); + if (opts.sweeps !== false) svc.noteSweepClockScheduled(); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + for (const flow of [twoStep, waitBetween, otherField]) automation.registerFlow(flow.name, flow as any); + } + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + 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 seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (flow: string, object: string, id: string, extra: Record = {}) => + automation.execute(flow, { object, record: await read(object, id), userId: 'owner', ...extra } as any) as Promise; + const approve = async (requestId: string, who: string) => + svc.decide(requestId, { decision: 'approve', actorId: who } as any, asPerson(who)); + + describe('an approval that meets every condition', () => { + beforeEach(() => boot()); + + it('opens, and each of its requests carries the set its first request was stamped with', async () => { + await seed('crm_invoice', 'i_ok'); + expect((await start('two_step', 'crm_invoice', 'i_ok')).status).toBe('paused'); + const [first] = await requestsOn('i_ok'); + expect(first.status).toBe('pending'); + const stamp = JSON.parse(first.between_steps_json); + expect(stamp).toEqual([{ flow: 'two_step', node: 'first' }]); + + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_ok'); + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json, 'a later request copies the first request\'s set').toBe(first.between_steps_json); + }); + + it('stamps nothing on an approval whose object declares no closed state', async () => { + await seed('crm_memo', 'm_ok'); + expect((await start('wait_between', 'crm_memo', 'm_ok')).status).toBe('paused'); + const [row] = await requestsOn('m_ok'); + expect(row.status).toBe('pending'); + expect(row.between_steps_json ?? null).toBeNull(); + }); + }); + + describe('an approval that misses a condition', () => { + beforeEach(() => boot()); + + it('does not open: the run fails with a sentence naming the flow, the step, the object and what is missing', async () => { + await seed('crm_invoice', 'i_wait'); + const out = await start('wait_between', 'crm_invoice', 'i_wait'); + expect(out.status).toBe('failed'); + const said = JSON.stringify(out); + expect(said).toContain('VALIDATION_FAILED'); + expect(said).toContain('Node hold (wait) of flow wait_between can pause the run between two approval steps of crm_invoice'); + expect(await requestsOn('i_wait'), 'no request opened').toEqual([]); + }); + + it('words the refusal in the run\'s locale', async () => { + await seed('crm_invoice', 'i_zh'); + const out = await start('other_field', 'crm_invoice', 'i_zh', { locale: 'zh-CN' }); + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain('流程 other_field 的步骤 second 可以作用于 crm_invoice,却把状态写到字段 other_status'); + }); + + }); + + it('does not judge a later request whose approval\'s earlier requests record no root run', async () => { + const { closedStates: _declared, ...undeclared } = invoice; + await boot({ invoiceDef: undeclared }); + await seed('crm_invoice', 'i_unplaced'); + expect((await start('other_field', 'crm_invoice', 'i_unplaced')).status).toBe('paused'); + const [first] = await requestsOn('i_unplaced'); + // The shape of a request opened before requests recorded their root run. + await ql.update('sys_approval_request', { id: first.id, root_run_id: null, root_run_started_at: null, record_run_id: null }, { context: SYS }); + expect((await requestsOn('i_unplaced'))[0].root_run_id ?? null).toBeNull(); + + ql.registry.registerObject(invoice as any, 'approvals-test', 'approvals-test'); + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_unplaced'); + // Judged, the second step's other field would refuse it; it cannot be placed, so it opens. + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json ?? null).toBeNull(); + }); + + it('does not judge again a later request of an approval opened before the object declared closedStates', async () => { + const { closedStates: _declared, ...undeclared } = invoice; + await boot({ invoiceDef: undeclared }); + await seed('crm_invoice', 'i_before'); + expect((await start('other_field', 'crm_invoice', 'i_before')).status).toBe('paused'); + const [first] = await requestsOn('i_before'); + expect(first.between_steps_json ?? null).toBeNull(); + + // The object now declares the key, as after an upgrade. + ql.registry.registerObject(invoice as any, 'approvals-test', 'approvals-test'); + await approve(String(first.id), 'approver'); + const rows = await requestsOn('i_before'); + expect(rows.map((r) => [r.flow_node_id, r.status])).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(rows[1].between_steps_json ?? null).toBeNull(); + }); + + it('refuses the first request on a host that runs no job service', async () => { + await boot({ sweeps: false }); + await seed('crm_invoice', 'i_host'); + const out = await start('two_step', 'crm_invoice', 'i_host'); + expect(out.status).toBe('failed'); + expect(JSON.stringify(out)).toContain('crm_invoice declares closedStates, and this host runs no job service'); + expect(await requestsOn('i_host')).toEqual([]); + + // An approval whose objects declare no closed state opens on that host. + await seed('crm_memo', 'm_host'); + expect((await start('two_step', 'crm_memo', 'm_host')).status).toBe('paused'); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts new file mode 100644 index 00000000000..0a5a830b5e0 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.test.ts @@ -0,0 +1,337 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 7 "The check", #37766 slice B] The read of an + * approval's whole definition at its first request, over fixtures: each D5 + * condition as revised on 2026-11-27, the between-two-steps set it stamps, the + * unread parts, and the host's `job` service. The service's wiring (root run, + * later requests, the refusal and its locale) is pinned in + * `approval-opening-check-37766.integration.test.ts`. + */ + +import { describe, expect, it } from 'vitest'; +import { + judgeApprovalOpening, + type OpeningCheckSource, + type OpeningFlowBody, + type OpeningFlowNode, + type OpeningGap, +} from './approval-opening-check.js'; + +const STATUSES = ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled']; + +function statusField(extra: Record = {}, options: unknown[] = STATUSES.map((v) => ({ value: v, label: v }))) { + return { type: 'select', options, ...extra }; +} + +/** An object that closes on `approved` and `rejected` of `status`, and meets every condition. */ +function invoice(over: Record = {}) { + return { name: 'invoice', closedStates: { status: ['approved', 'rejected'] }, fields: { status: statusField() }, ...over }; +} + +const memo = { name: 'memo', fields: { status: statusField() } }; + +const DESCRIPTORS: Record = { + wait: { supportsPause: true }, + screen: { supportsPause: true }, + approval: { supportsPause: true }, + decision: {}, + assignment: {}, + update_record: {}, + create_record: {}, + loop: {}, + parallel: {}, + try_catch: {}, +}; + +function source(spec: { + objects?: Record; + flows?: Record; + descriptors?: Record; + host?: boolean; +}): OpeningCheckSource & { read: string[] } { + const objects = spec.objects ?? { invoice: invoice(), memo }; + const descriptors = { ...DESCRIPTORS, ...spec.descriptors }; + const read: string[] = []; + return { + read, + objectSchema: (name) => { read.push(name); return objects[name]; }, + calleeFlow: async (name) => (spec.flows?.[name] ? { key: name, body: spec.flows[name]! } : null), + nodeDescriptor: (type) => descriptors[type], + hostRunsReconciler: spec.host ?? true, + }; +} + +const step = (id: string, field: string | null = 'status'): OpeningFlowNode => + ({ id, type: 'approval', config: field ? { approvalStatusField: field } : {} }); +const n = (id: string, type: string, config: Record = {}): OpeningFlowNode => ({ id, type, config }); + +/** A body whose nodes run one after another, wrapped in `start` and `end`. */ +function chain(...nodes: OpeningFlowNode[]): OpeningFlowBody { + const all = [n('start', 'start'), ...nodes, n('end', 'end')]; + return { nodes: all, edges: all.slice(1).map((b, i) => ({ source: all[i]!.id, target: b.id })) }; +} + +async function judge(root: OpeningFlowBody, opts: Parameters[0] & { rootObject?: string | null } = {}) { + const src = source(opts); + const rootObject = opts.rootObject === undefined ? 'invoice' : opts.rootObject; + const out = await judgeApprovalOpening({ rootFlow: { key: 'F', body: root }, rootFlowName: 'F', rootObject }, src); + return { ...out, read: src.read }; +} + +const kinds = (gaps: OpeningGap[]) => gaps.map((g) => g.kind); + +describe('the opening check: an approval that meets every condition', () => { + it('opens a two-step approval on a closing field, and stamps what stands between the steps', async () => { + const out = await judge(chain(step('a1'), n('d1', 'decision'), step('a2'))); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + // a1 (a step can follow it) and d1 (after a1, before a2); not a2, after which no step follows. + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'd1' }]); + }); + + it('does not refuse a writing node in a run-as-user flow (the withdrawn writing-node condition)', async () => { + const root = { ...chain(step('a1'), n('w', 'update_record', { objectName: 'invoice', fields: { note: 'x' } }), step('a2')), runAs: 'user' }; + const out = await judge(root); + expect(out.gaps).toEqual([]); + expect(out.between).toContainEqual({ flow: 'F', node: 'w' }); + }); +}); + +describe('the opening check: D5 conditions 1 to 3, on the field', () => { + it('refuses a field that does not declare pending', async () => { + const objects = { invoice: invoice({ fields: { status: statusField({}, ['draft', 'approved', 'rejected']) } }) }; + const out = await judge(chain(step('a1')), { objects }); + expect(out.gaps).toEqual([{ kind: 'no_pending_option', flow: 'F', step: 'a1', object: 'invoice', field: 'status' }]); + }); + + it.each(['pending', 'returned'])('refuses an object that closes on %s', async (value) => { + const objects = { invoice: invoice({ closedStates: { status: ['approved', value] } }) }; + const out = await judge(chain(step('a1')), { objects }); + expect(out.gaps).toEqual([{ kind: 'closes_in_flight', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value }]); + }); + + it('refuses a state_machine rule whose moves out of a closed approved leave out pending', async () => { + const validations = [{ name: 'flow_of_status', type: 'state_machine', field: 'status', transitions: { approved: ['draft'], rejected: ['pending', 'draft'] } }]; + const out = await judge(chain(step('a1')), { objects: { invoice: invoice({ validations }) } }); + expect(out.gaps).toEqual([{ kind: 'state_machine_no_pending', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value: 'approved', rule: 'flow_of_status' }]); + }); + + it('reads a state_machine rule that keeps a closed value final as missing pending, and one that declares no move out of it as nothing', async () => { + const final = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { rejected: [] } }]; + expect(kinds((await judge(chain(step('a1')), { objects: { invoice: invoice({ validations: final }) } })).gaps)).toEqual(['state_machine_no_pending']); + const silent = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { draft: ['pending'] } }]; + expect((await judge(chain(step('a1')), { objects: { invoice: invoice({ validations: silent }) } })).gaps).toEqual([]); + }); + + it('refuses a field that carries a readonlyWhen', async () => { + const objects = { invoice: invoice({ fields: { status: statusField({ readonlyWhen: 'record.locked' }) } }) }; + expect((await judge(chain(step('a1')), { objects })).gaps) + .toEqual([{ kind: 'readonly_when', flow: 'F', step: 'a1', object: 'invoice', field: 'status' }]); + }); + + it.each(['pending', 'returned', 'approved', 'rejected', 'recalled'])('refuses a visibleWhen on the %s option', async (value) => { + const options = STATUSES.map((v) => (v === value ? { value: v, label: v, visibleWhen: 'false' } : { value: v, label: v })); + const objects = { invoice: invoice({ fields: { status: statusField({}, options) } }) }; + expect((await judge(chain(step('a1')), { objects })).gaps) + .toEqual([{ kind: 'option_visible_when', flow: 'F', step: 'a1', object: 'invoice', field: 'status', value }]); + }); + + it('does not refuse a visibleWhen on an option that is no request status', async () => { + const options = STATUSES.map((v) => (v === 'draft' ? { value: v, label: v, visibleWhen: 'false' } : { value: v, label: v })); + expect((await judge(chain(step('a1')), { objects: { invoice: invoice({ fields: { status: statusField({}, options) } }) } })).gaps).toEqual([]); + }); + + it('reads nothing of an object that closes only on values of its own, also with a state_machine that keeps one final', async () => { + const validations = [{ name: 'r', type: 'state_machine', field: 'status', transitions: { archived: [] } }]; + const objects = { invoice: invoice({ closedStates: { status: ['archived'] }, validations, fields: { status: statusField({ readonlyWhen: 'x' }) } }) }; + const out = await judge(chain(step('a1'), n('w', 'wait'), step('a2')), { objects }); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + expect(out.between.length).toBeGreaterThan(0); + }); +}); + +describe('the opening check: D5 condition 4, every step mirrors onto the field', () => { + it.each([ + ['after', [step('a1'), step('a2', 'other_status')]], + ['ahead of', [step('a2', 'other_status'), step('a1')]], + ] as const)('refuses a step %s a concerned step that mirrors onto another field', async (_where, nodes) => { + const out = await judge(chain(...nodes)); + expect(out.gaps).toEqual([{ kind: 'other_field', flow: 'F', step: 'a2', object: 'invoice', field: 'status', other: 'other_status' }]); + }); + + it('refuses a step that names no field beside a concerned one', async () => { + const out = await judge(chain(step('a1'), step('a2', null))); + expect(out.gaps).toEqual([{ kind: 'no_field', flow: 'F', step: 'a2', object: 'invoice', field: 'status' }]); + }); + + it('does not refuse, but stamps, an approval none of whose steps names a closing field', async () => { + const out = await judge(chain(step('a1', null), n('w', 'wait'), step('a2', 'other_status'))); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'w' }]); + }); + + it('refuses a step two levels down that mirrors onto another field', async () => { + const flows = { + S1: chain(n('s2', 'subflow', { flowName: 'S2' })), + S2: chain(step('deep', 'other_status')), + }; + const out = await judge(chain(step('a1'), n('s1', 'subflow', { flowName: 'S1' })), { flows }); + expect(out.gaps).toEqual([{ kind: 'other_field', flow: 'S2', step: 'deep', object: 'invoice', field: 'status', other: 'other_status' }]); + }); +}); + +describe('the opening check: D5 condition 5, no pause between two steps', () => { + it.each(['wait', 'screen'])('refuses a %s between two steps', async (type) => { + const out = await judge(chain(step('a1'), n('p', type), step('a2'))); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'F', node: 'p', type, object: 'invoice' }]); + }); + + it.each(['wait', 'screen'])('refuses a %s between two steps in a screen flow too (a run with no record trigger)', async (type) => { + const root = { ...chain(step('a1'), n('p', type), step('a2')), type: 'screen' }; + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); + + it('does not refuse a pause before the first step or after the last', async () => { + expect((await judge(chain(n('p0', 'wait'), step('a1'), step('a2'), n('p1', 'screen')))).gaps).toEqual([]); + }); + + it('refuses a node type that publishes no descriptor, and one the engine cannot be asked about', async () => { + expect(kinds((await judge(chain(step('a1'), n('x', 'custom_thing'), step('a2')))).gaps)).toEqual(['pause_between_steps']); + const unread = await judge(chain(step('a1'), n('x', 'decision'), step('a2')), { descriptors: { decision: 'unread' } }); + expect(kinds(unread.gaps)).toEqual(['pause_between_steps']); + }); + + it('follows aliasOf to the canonical descriptor', async () => { + const descriptors = { hold: { aliasOf: 'wait' }, branch: { aliasOf: 'decision' } }; + expect(kinds((await judge(chain(step('a1'), n('x', 'hold'), step('a2')), { descriptors })).gaps)).toEqual(['pause_between_steps']); + expect((await judge(chain(step('a1'), n('x', 'branch'), step('a2')), { descriptors })).gaps).toEqual([]); + }); + + it('does not refuse the revise window of a returned request', async () => { + expect((await judge(chain(step('a1'), n('rev', 'approval_revise'), step('a2')))).gaps).toEqual([]); + }); + + it('refuses a pause after the only step of a loop body, where the step opens again', async () => { + const root = chain(n('l', 'loop', { collection: '{{items}}', body: chain(step('a1'), n('p', 'wait')) })); + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); + + it('refuses a pause in one of two child runs side by side, where the other branch\'s step can follow it', async () => { + const flows = { C1: chain(step('c1'), n('p', 'wait')), C2: chain(step('c2')) }; + const root = chain(n('par', 'parallel', { + branches: [ + { name: 'one', ...chain(n('s1', 'subflow', { flowName: 'C1' })) }, + { name: 'two', ...chain(n('s2', 'subflow', { flowName: 'C2' })) }, + ], + })); + const out = await judge(root, { flows }); + expect(out.gaps).toEqual([{ kind: 'pause_between_steps', flow: 'C1', node: 'p', type: 'wait', object: 'invoice' }]); + }); + + it('refuses a pause in a catch region, where a step that failed is followed by another', async () => { + const root = chain(n('t', 'try_catch', { try: chain(step('a1')), catch: chain(n('p', 'wait')) }), step('a2')); + expect(kinds((await judge(root)).gaps)).toEqual(['pause_between_steps']); + }); +}); + +describe('the opening check: D5 condition 5, a map with an approval body', () => { + const body = { B: chain(step('b1')) }; + const map = (collection: unknown, extra: Record = {}) => n('m', 'map', { flowName: 'B', collection, ...extra }); + + it.each([ + ['ahead of', [map('{{record.lines}}'), step('a1')]], + ['between', [step('a1'), map('{{record.lines}}'), step('a2')]], + ['after', [step('a1'), map('{{record.lines}}')]], + ] as const)('refuses a map whose items are read from an expression, %s the parent\'s steps', async (_where, nodes) => { + const out = await judge(chain(...nodes), { flows: body }); + expect(out.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('refuses it also where the node names an object for its items', async () => { + const objects = { invoice: invoice(), invoice_line: { name: 'invoice_line', fields: {} } }; + const out = await judge(chain(step('a1'), map('{{record.lines}}', { itemObject: 'invoice_line' })), { flows: body, objects }); + expect(out.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('reads items written out with none a record as steps of the parent, and refuses one that is a record', async () => { + const plain = await judge(chain(step('a1'), map([{ amount: 1 }, { amount: 2 }])), { flows: body }); + expect(plain.gaps).toEqual([]); + // As steps of the parent, the body's step is held to condition 4 on the parent's object. + const otherField = await judge(chain(step('a1'), map([{ amount: 1 }])), { flows: { B: chain(step('b1', 'other_status')) } }); + expect(otherField.gaps).toEqual([{ kind: 'other_field', flow: 'B', step: 'b1', object: 'invoice', field: 'status', other: 'other_status' }]); + const oneRecord = await judge(chain(step('a1'), map([{ amount: 1 }, { id: 'inv-2' }])), { flows: body }); + expect(oneRecord.gaps).toContainEqual({ kind: 'map_with_approval', flow: 'F', node: 'm', object: 'invoice' }); + }); + + it('does not refuse a map whose parent\'s object the conditions do not concern', async () => { + const out = await judge(chain(step('a1'), map('{{record.lines}}', { itemObject: 'invoice' })), { flows: body, rootObject: 'memo' }); + expect(kinds(out.gaps)).not.toContain('map_with_approval'); + expect(out.gaps).toEqual([]); + }); + + it('does not refuse the batch of a run with no record', async () => { + const out = await judge(chain(map('{{input.ids}}', { itemObject: 'invoice' })), { flows: body, rootObject: null }); + expect(out.gaps).toEqual([]); + expect(out.touchesClosedStates).toBe(true); + }); + + it('stamps a map body including its only step', async () => { + const flows = { B: chain(n('p', 'assignment'), step('b1'), n('q', 'assignment')) }; + const out = await judge(chain(map('{{input.ids}}', { itemObject: 'invoice' })), { flows, rootObject: 'memo' }); + expect(out.gaps).toEqual([]); + expect(out.between).toEqual([ + { flow: 'B', node: 'b1' }, { flow: 'B', node: 'end' }, { flow: 'B', node: 'p' }, { flow: 'B', node: 'q' }, { flow: 'B', node: 'start' }, + { flow: 'F', node: 'm' }, + ]); + }); +}); + +describe('the opening check: the stamp', () => { + it('leaves out a branch that passes over the remaining steps', async () => { + const root: OpeningFlowBody = { + nodes: [n('start', 'start'), step('a1'), n('d', 'decision'), step('a2'), n('end', 'end'), n('skip', 'assignment'), n('end2', 'end')], + edges: [ + { source: 'start', target: 'a1' }, { source: 'a1', target: 'd' }, { source: 'd', target: 'a2' }, + { source: 'a2', target: 'end' }, { source: 'd', target: 'skip' }, { source: 'skip', target: 'end2' }, + ], + }; + const out = await judge(root); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'd' }]); + }); + + it('follows a subflow into its body', async () => { + const flows = { S: chain(n('x', 'assignment'), step('a2')) }; + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'S' })), { flows }); + expect(out.gaps).toEqual([]); + expect(out.between).toEqual([{ flow: 'F', node: 'a1' }, { flow: 'F', node: 'sub' }, { flow: 'S', node: 'start' }, { flow: 'S', node: 'x' }]); + }); + + it('does not count a subflow after the last step as between', async () => { + const flows = { S: chain(n('x', 'assignment')) }; + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'S' })), { flows }); + expect(out.between).toEqual([]); + }); +}); + +describe('the opening check: what it does not read, and what it cannot', () => { + it('reads nothing more of an approval whose objects declare no closedStates', async () => { + const out = await judge(chain(step('a1'), n('w', 'wait'), step('a2', null)), { rootObject: 'memo', host: false }); + expect(out).toMatchObject({ touchesClosedStates: false, between: [], gaps: [] }); + expect(new Set(out.read)).toEqual(new Set(['memo'])); + }); + + it('refuses an approval one of whose flows cannot be read', async () => { + const out = await judge(chain(step('a1'), n('sub', 'subflow', { flowName: 'missing' }))); + expect(out.gaps).toContainEqual({ kind: 'unreadable_flow', flow: 'missing' }); + const noRoot = await judgeApprovalOpening({ rootFlow: null, rootFlowName: 'gone', rootObject: 'invoice' }, source({})); + expect(noRoot.gaps).toEqual([{ kind: 'unreadable_flow', flow: 'gone' }]); + }); + + it('refuses on a host that runs no job service, for an approval touching a closing object', async () => { + const out = await judge(chain(step('a1', null)), { host: false }); + expect(out.gaps).toEqual([{ kind: 'no_job_service', object: 'invoice' }]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-opening-check.ts b/packages/plugins/plugin-approvals/src/approval-opening-check.ts new file mode 100644 index 00000000000..7bf8bd0ec74 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-check.ts @@ -0,0 +1,644 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 7 "The check"] The check when an approval + * opens, read off the approval's definition at its first request. + * + * An approval is one passage of a record through its approval flow, taken as + * a whole: the flow its root run was started on, and every flow a `subflow` + * or a `map` in it names, to any depth. This module reads that whole once and + * answers three things: + * + * 1. **Whether the approval touches an object that declares `closedStates`**: + * a step of it can act on such an object. Only then is anything stamped or + * refused. + * 2. **The set of nodes that stand between two steps** ({@link OpeningJudgement.between}), + * which each request of the approval carries from its opening, so that the + * plugin can later place a stop or a pause against it (ADR-0162 item 8, + * design note 7210179412 question 3, T2). It is stamped for every approval + * that touches such an object, also one the conditions do not concern. + * 3. **What is missing**, for every step whose mirror field the object closes + * on at a status the mirror writes for a request that is not abandoned + * (`pending`, `returned`, `approved`, `rejected`): the five conditions of + * ADR-0162 D5 as revised on 2026-11-27, the approval's unread parts, and + * the host's `job` service. + * + * Between two steps means after a step is decided, whichever way, and before + * the next step opens; the next step can be the same step opened again (a + * `map` body or a `loop` body that holds one). The read is a reachability + * over one graph of the whole approval: every node of every flow, a `subflow` + * or a `map` joined to the body it calls, every region (`loop`, `parallel`, + * `try_catch`) joined to its container. It is context-insensitive and errs one + * way only: a node that could stand between two steps on some path counts as + * standing there. A stop wrongly read as "between" costs a resubmission; the + * other error would close a document on an unfinished approval (ADR-0162 D5). + * + * Pure over a {@link OpeningCheckSource}: the service hands it the readers it + * has (the engine's object registry, the automation engine's flow lookup and + * node descriptors, whether the host runs a `job` service), and the tests hand + * it fixtures. + */ + +import { FLOW_REGION_SLOTS_BY_TYPE } from '@objectstack/spec/automation'; + +/** The statuses the mirror writes for a request that is not abandoned. */ +const IN_APPROVAL_STATUSES = ['pending', 'returned', 'approved', 'rejected'] as const; +/** The statuses of a request whose option may carry no `visibleWhen` (D5 condition 3). */ +const REQUEST_STATUSES = ['pending', 'returned', 'approved', 'rejected', 'recalled'] as const; +/** The node types that have no executor and cannot pause (N43). */ +const STRUCTURAL_TYPES: ReadonlySet = new Set(['start', 'end']); +/** The type of an approval step. */ +const APPROVAL_TYPE = 'approval'; +/** The revise window of a returned request: not a pause between two steps (D5, ADR-0044). */ +const REVISE_WINDOW_TYPE = 'approval_revise'; +/** The two node types that call another flow; they are read by their bodies. */ +const CALL_TYPES: ReadonlySet = new Set(['subflow', 'map']); +/** How many flows one approval may name before it is read as not readable whole. */ +const MAX_FLOWS = 64; +/** How many region levels the read descends. */ +const MAX_REGION_DEPTH = 16; +/** How many `aliasOf` hops a node type's descriptor is followed. */ +const MAX_ALIAS_HOPS = 8; + +/** A flow body as the engine holds it: the parts this check reads. */ +export interface OpeningFlowBody { + nodes?: ReadonlyArray; + edges?: ReadonlyArray; +} +export interface OpeningFlowNode { + id: string; + type?: string; + label?: string; + config?: Record | null; +} +export interface OpeningFlowEdge { + source: string; + target: string; +} + +/** A flow the check read, by the key the engine files it under. */ +export interface OpeningFlow { + key: string; + body: OpeningFlowBody; +} + +/** The readers the check needs. Every one answers, never throws: the service wraps its reads. */ +export interface OpeningCheckSource { + /** The object definition registered under `name`, or `undefined`. */ + objectSchema(name: string): unknown; + /** The flow a `subflow` or a `map` of the flow filed under `callerKey` names as `name`; `null` when it cannot be read. */ + calleeFlow(name: string, callerKey: string): Promise; + /** + * The published descriptor of a node type: `undefined` where the type + * publishes none, `'unread'` where the engine cannot be asked. + */ + nodeDescriptor(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined | 'unread'; + /** Whether the host runs the plugin's sweeps, the reconciler of ADR-0162 item 8 (a `job` service). */ + hostRunsReconciler: boolean; +} + +/** One thing that keeps the approval from opening. */ +export type OpeningGap = + | { kind: 'no_pending_option'; flow: string; step: string; object: string; field: string } + | { kind: 'closes_in_flight'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'state_machine_no_pending'; flow: string; step: string; object: string; field: string; value: string; rule: string } + | { kind: 'readonly_when'; flow: string; step: string; object: string; field: string } + | { kind: 'option_visible_when'; flow: string; step: string; object: string; field: string; value: string } + | { kind: 'other_field'; flow: string; step: string; object: string; field: string; other: string } + | { kind: 'no_field'; flow: string; step: string; object: string; field: string } + | { kind: 'pause_between_steps'; flow: string; node: string; type: string; object: string } + | { kind: 'map_with_approval'; flow: string; node: string; object: string } + | { kind: 'unreadable_flow'; flow: string } + | { kind: 'no_job_service'; object: string }; + +/** One node of the between-two-steps set: the flow it is in, by the key the engine files it under, and its id. */ +export interface BetweenNode { + flow: string; + node: string; +} + +/** What the check answers for an approval's first request. */ +export interface OpeningJudgement { + /** Whether a step of the approval can act on an object that declares `closedStates`. */ + touchesClosedStates: boolean; + /** The nodes that stand between two steps, sorted; stamped only where {@link touchesClosedStates}. */ + between: BetweenNode[]; + /** What keeps the approval from opening; empty when it opens. */ + gaps: OpeningGap[]; +} + +/** What the check is handed about the run that opens the request. */ +export interface OpeningCheckInput { + /** The flow the approval's root run was started on, read by the caller; `null` when it could not be read. */ + rootFlow: OpeningFlow | null; + /** The flow name of the root run, for a refusal that names an unread root flow. */ + rootFlowName: string; + /** The object of the root run's record; `null` for a root run that carries none (a batch). */ + rootObject: string | null; +} + +/** An object's declared closed values, field → values, or `undefined` when it declares none. */ +export function closedValuesOf(schema: unknown): ReadonlyMap> | undefined { + const declared = (schema as { closedStates?: unknown } | null | undefined)?.closedStates; + if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return undefined; + const out = new Map>(); + for (const [field, values] of Object.entries(declared as Record)) { + if (!Array.isArray(values)) continue; + const set = new Set(values.filter((v): v is string => typeof v === 'string')); + if (set.size > 0) out.set(field, set); + } + return out.size > 0 ? out : undefined; +} + +/** A vertex of the approval's graph. A node is one vertex; a container or a call is two (its entry and its exit). */ +type Vertex = string; + +interface StepInfo { + flow: string; + node: OpeningFlowNode; + field: string | undefined; +} + +interface MapInfo { + flow: string; + node: OpeningFlowNode; + callee: string | null; + /** Whether the node shows that none of its items is a record (items written out, none of them one). */ + noRecordItems: boolean; +} + +/** + * Read the approval whole and judge it. Never throws: a part that cannot be + * read is a gap ({@link OpeningGap} `unreadable_flow`), and an approval with + * one cannot be judged, so it does not open. + */ +export async function judgeApprovalOpening(input: OpeningCheckInput, source: OpeningCheckSource): Promise { + const gaps: OpeningGap[] = []; + if (!input.rootFlow) { + return { touchesClosedStates: true, between: [], gaps: [{ kind: 'unreadable_flow', flow: input.rootFlowName }] }; + } + + // ── 1. Read every flow of the approval, to any depth ────────────────────── + const flows = new Map(); + /** For each flow: the flows it calls, by call node, with how the call hands objects down. */ + const calls = new Map>(); + const queue: OpeningFlow[] = [input.rootFlow]; + flows.set(input.rootFlow.key, input.rootFlow.body); + while (queue.length > 0) { + const { key, body } = queue.shift()!; + const out: Array<{ node: OpeningFlowNode; callee: string | null; kind: 'subflow' | 'map' }> = []; + for (const node of allNodes(body)) { + if (!node.type || !CALL_TYPES.has(node.type)) continue; + const name = typeof node.config?.flowName === 'string' ? node.config.flowName : ''; + if (!name) { + gaps.push({ kind: 'unreadable_flow', flow: `${key} › ${node.id}` }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + const callee = await source.calleeFlow(name, key); + if (!callee) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + out.push({ node, callee: null, kind: node.type as 'subflow' | 'map' }); + continue; + } + out.push({ node, callee: callee.key, kind: node.type as 'subflow' | 'map' }); + if (!flows.has(callee.key)) { + if (flows.size >= MAX_FLOWS) { + gaps.push({ kind: 'unreadable_flow', flow: name }); + continue; + } + flows.set(callee.key, callee.body); + queue.push(callee); + } + } + calls.set(key, out); + } + + // ── 2. The objects each flow's steps can act on ─────────────────────────── + // The root flow acts on the root run's record. A `subflow` body acts on its + // caller's record. A `map` body acts on an item where the item is a record, + // on the object the node names for its items (else its caller's), and on its + // caller's record where the item is not one; the check cannot read ahead + // whether an item is a record unless the items are written out in the node. + const objects = new Map>(); + for (const key of flows.keys()) objects.set(key, new Set()); + if (input.rootObject) objects.get(input.rootFlow.key)!.add(input.rootObject); + const maps: MapInfo[] = []; + for (const [key, list] of calls) { + for (const call of list) { + if (call.kind === 'map') maps.push({ flow: key, node: call.node, callee: call.callee, noRecordItems: itemsShowNoRecord(call.node) }); + } + } + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + const mine = objects.get(key)!; + for (const call of list) { + if (!call.callee) continue; + const theirs = objects.get(call.callee)!; + const before = theirs.size; + if (call.kind === 'subflow') { + for (const o of mine) theirs.add(o); + } else { + const items = mapItems(call.node); + const anyRecord = items === undefined || items.some(isRecordItem); + const anyOther = items === undefined || items.some((i) => !isRecordItem(i)); + if (anyOther) for (const o of mine) theirs.add(o); + if (anyRecord) { + const itemObject = typeof call.node.config?.itemObject === 'string' && call.node.config.itemObject + ? call.node.config.itemObject : undefined; + if (itemObject) theirs.add(itemObject); + else for (const o of mine) theirs.add(o); + } + } + if (theirs.size !== before) changed = true; + } + } + } + + // ── 3. The steps, and whether the approval touches a closing object ─────── + const steps: StepInfo[] = []; + for (const [key, body] of flows) { + for (const node of allNodes(body)) { + if (node.type !== APPROVAL_TYPE) continue; + const field = typeof node.config?.approvalStatusField === 'string' && node.config.approvalStatusField + ? node.config.approvalStatusField : undefined; + steps.push({ flow: key, node, field }); + } + } + const declaring = (object: string) => closedValuesOf(source.objectSchema(object)) !== undefined; + const touchesClosedStates = gaps.length > 0 + || steps.some((s) => [...objects.get(s.flow)!].some(declaring)); + if (!touchesClosedStates) return { touchesClosedStates: false, between: [], gaps: [] }; + + // ── 4. The nodes between two steps ──────────────────────────────────────── + const graph = buildGraph(flows, calls); + const stepVertices = steps.map((s) => vertexOf(s.flow, s.node.id)); + const after = reach(graph.succ, stepVertices); + const before = reach(graph.pred, stepVertices); + const betweenKeys = new Set(); + const pausing: Array<{ flow: string; node: OpeningFlowNode }> = []; + // A node other than a step is between two steps where a step can come + // before it and a step can follow it. A step is in the set where a step can + // follow it: a run that stops on a step decided with no later step logged + // (design note question 3, T2) stopped between two steps exactly then. + for (const [vertex, owner] of graph.owner) { + if (!before.has(vertex)) continue; + const isStep = owner.node.type === APPROVAL_TYPE; + if (!isStep && !after.has(vertex)) continue; + const k = `${owner.flow}\u0000${owner.node.id}`; + if (betweenKeys.has(k)) continue; + betweenKeys.add(k); + if (!isStep && canPause(owner.node, source)) pausing.push(owner); + } + // A `map` or a `loop` whose body holds a step stands between two steps + // where it is entered before a step and left after one: between one item's + // (one pass's) step and the next, the run is parked at the node or back on + // it. A `subflow` is not: its body runs once. + for (const { flow, node } of graph.owner.values()) { + if (node.type !== 'map' && node.type !== 'loop') continue; + if (before.has(vertexOf(flow, node.id, 'in')) && after.has(vertexOf(flow, node.id, 'out'))) { + betweenKeys.add(`${flow}\u0000${node.id}`); + } + } + const between = [...betweenKeys] + .map((k) => { const [flow, node] = k.split('\u0000'); return { flow, node }; }) + .sort((a, b) => (a.flow === b.flow ? cmp(a.node, b.node) : cmp(a.flow, b.flow))); + + // ── 5. The conditions, for every step they concern ──────────────────────── + const concernedObjects = new Set(); + for (const step of steps) { + for (const object of objects.get(step.flow)!) { + const schema = source.objectSchema(object); + const closed = closedValuesOf(schema); + if (!closed || !step.field) continue; + const values = closed.get(step.field); + if (!values || !IN_APPROVAL_STATUSES.some((s) => values.has(s))) continue; + concernedObjects.add(object); + judgeField(step, object, step.field, schema, values, gaps); + // Condition 4: every step that can act on a record of the object names that field. + for (const other of steps) { + if (other === step || !objects.get(other.flow)!.has(object)) continue; + if (other.field === step.field) continue; + if (other.field) gaps.push({ kind: 'other_field', flow: other.flow, step: other.node.id, object, field: step.field, other: other.field }); + else gaps.push({ kind: 'no_field', flow: other.flow, step: other.node.id, object, field: step.field }); + } + } + } + if (concernedObjects.size > 0) { + const object = [...concernedObjects].sort(cmp)[0]; + // Condition 5: no node that can pause the run of itself stands between two steps. + for (const p of pausing) { + gaps.push({ kind: 'pause_between_steps', flow: p.flow, node: p.node.id, type: String(p.node.type ?? ''), object }); + } + // Condition 5, its second half: no `map` with an approval step in its body, + // at any depth, where the parent's object is one the conditions concern, + // unless the node shows that none of its items is a record. + const holdsStep = flowsHoldingSteps(flows, calls, steps); + for (const m of maps) { + if (!m.callee || !holdsStep.has(m.callee) || m.noRecordItems) continue; + const parentObjects = [...objects.get(m.flow)!].filter((o) => concernedObjects.has(o)).sort(cmp); + if (parentObjects.length > 0) gaps.push({ kind: 'map_with_approval', flow: m.flow, node: m.node.id, object: parentObjects[0] }); + } + } + + // ── 6. The host ─────────────────────────────────────────────────────────── + if (!source.hostRunsReconciler) { + const object = steps.flatMap((s) => [...objects.get(s.flow)!]).filter(declaring).sort(cmp)[0]; + if (object) gaps.push({ kind: 'no_job_service', object }); + } + + return { touchesClosedStates, between, gaps: dedupe(gaps) }; +} + +/** D5 conditions 1 to 3, on the field `field` of `object`, for `step`. */ +function judgeField( + step: StepInfo, object: string, field: string, schema: unknown, + closed: ReadonlySet, gaps: OpeningGap[], +): void { + const flow = step.flow; + const stepId = step.node.id; + const def = (schema as { fields?: Record } | undefined)?.fields?.[field] as + { options?: unknown; readonlyWhen?: unknown } | undefined; + const options = Array.isArray(def?.options) ? def!.options as unknown[] : []; + const optionOf = (value: string): Record | undefined => { + for (const o of options) { + if (o && typeof o === 'object' && String((o as { value?: unknown }).value) === value) return o as Record; + } + return undefined; + }; + const declares = (value: string) => options.some((o) => (o && typeof o === 'object' ? String((o as { value?: unknown }).value) : String(o)) === value); + + // 1. The field declares `pending`, and the object closes on neither `pending` nor `returned`. + if (!declares('pending')) gaps.push({ kind: 'no_pending_option', flow, step: stepId, object, field }); + for (const value of ['pending', 'returned']) { + if (closed.has(value)) gaps.push({ kind: 'closes_in_flight', flow, step: stepId, object, field, value }); + } + + // 2. A `state_machine` rule on the field that declares the moves out of a + // closed `approved` or `rejected` has `pending` among them. + const rules = (schema as { validations?: unknown } | undefined)?.validations; + if (Array.isArray(rules)) { + for (const rule of rules) { + const r = rule as { type?: unknown; field?: unknown; active?: unknown; transitions?: unknown; name?: unknown } | null; + if (!r || r.type !== 'state_machine' || r.field !== field || r.active === false) continue; + const transitions = r.transitions && typeof r.transitions === 'object' ? r.transitions as Record : {}; + for (const value of ['approved', 'rejected']) { + if (!closed.has(value) || !Object.prototype.hasOwnProperty.call(transitions, value)) continue; + const moves = transitions[value]; + if (!Array.isArray(moves) || !moves.includes('pending')) { + gaps.push({ kind: 'state_machine_no_pending', flow, step: stepId, object, field, value, rule: String(r.name ?? '') }); + } + } + } + } + + // 3. The field carries no `readonlyWhen`, and none of its options for a request's status carries a `visibleWhen`. + if (def?.readonlyWhen != null) gaps.push({ kind: 'readonly_when', flow, step: stepId, object, field }); + for (const value of REQUEST_STATUSES) { + const option = optionOf(value); + if (option && option.visibleWhen != null) gaps.push({ kind: 'option_visible_when', flow, step: stepId, object, field, value }); + } +} + +/** Whether a node can pause the run of itself, by what its type declares (D5 condition 5, N43). */ +function canPause(node: OpeningFlowNode, source: OpeningCheckSource): boolean { + const type = node.type; + if (!type) return true; // a node it cannot place counts as one that can + if (STRUCTURAL_TYPES.has(type) || type === APPROVAL_TYPE || type === REVISE_WINDOW_TYPE || CALL_TYPES.has(type)) return false; + let descriptor = source.nodeDescriptor(type); + for (let hop = 0; descriptor && descriptor !== 'unread' && typeof descriptor.aliasOf === 'string' && hop < MAX_ALIAS_HOPS; hop++) { + const canonical = source.nodeDescriptor(descriptor.aliasOf as string); + if (!canonical || canonical === 'unread' || canonical === descriptor) break; + descriptor = canonical; + } + if (descriptor === 'unread' || descriptor === undefined) return true; + return descriptor.supportsPause === true; +} + +/** Every node of a body, its regions' nodes included, to {@link MAX_REGION_DEPTH}. */ +function allNodes(body: OpeningFlowBody): OpeningFlowNode[] { + const out: OpeningFlowNode[] = []; + const visit = (nodes: ReadonlyArray | undefined, depth: number) => { + for (const node of nodes ?? []) { + if (!node || typeof node !== 'object' || typeof node.id !== 'string') continue; + out.push(node); + if (depth >= MAX_REGION_DEPTH) continue; + for (const region of regionsOf(node)) visit(region.nodes, depth + 1); + } + }; + visit(body.nodes, 0); + return out; +} + +/** The regions a container node holds, in slot order. */ +function regionsOf(node: OpeningFlowNode): Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> { + const slots = node.type ? FLOW_REGION_SLOTS_BY_TYPE.get(node.type) : undefined; + if (!slots) return []; + const out: Array<{ slot: string; region: OpeningFlowBody } & OpeningFlowBody> = []; + for (const slot of slots) { + const value = node.config?.[slot.key]; + const list = slot.arity === 'many' ? (Array.isArray(value) ? value : []) : (value ? [value] : []); + list.forEach((raw, i) => { + // A `parallel` branch carries its region beside its name; read either shape. + const region = raw && typeof raw === 'object' && 'region' in (raw as object) + ? (raw as { region?: OpeningFlowBody }).region : raw as OpeningFlowBody; + if (region && typeof region === 'object') { + out.push({ slot: `${slot.key}[${i}]`, region, nodes: region.nodes, edges: region.edges }); + } + }); + } + return out; +} + +/** The items a `map` node writes out in itself, or `undefined` where they are read from an expression. */ +function mapItems(node: OpeningFlowNode): unknown[] | undefined { + const collection = node.config?.collection; + return Array.isArray(collection) ? collection : undefined; +} + +/** Whether an item is a record, read as the `map` node reads it (an object with a string `id`). */ +function isRecordItem(item: unknown): boolean { + return item != null && typeof item === 'object' && typeof (item as { id?: unknown }).id === 'string'; +} + +/** Whether a `map` node shows that none of its items is a record: its items are written out, and none is one. */ +function itemsShowNoRecord(node: OpeningFlowNode): boolean { + const items = mapItems(node); + return items !== undefined && !items.some(isRecordItem); +} + +/** The flows whose body holds an approval step at any depth, through the flows it calls. */ +function flowsHoldingSteps( + flows: Map, + calls: Map>, + steps: StepInfo[], +): Set { + const holds = new Set(steps.map((s) => s.flow)); + for (let changed = true, rounds = 0; changed && rounds <= flows.size + 1; rounds++) { + changed = false; + for (const [key, list] of calls) { + if (holds.has(key)) continue; + if (list.some((c) => c.callee && holds.has(c.callee))) { holds.add(key); changed = true; } + } + } + return holds; +} + +function vertexOf(flow: string, node: string, part = ''): Vertex { + return `${flow}\u0000${node}\u0000${part}`; +} + +interface Graph { + succ: Map>; + pred: Map>; + /** Each vertex that stands for a node, with the node and its flow. Synthetic vertices are absent. */ + owner: Map; +} + +/** + * One graph of the whole approval. A plain node is one vertex. A container + * (`loop`, `parallel`, `try_catch`) and a call (`subflow`, `map`) are two, its + * entry and its exit, joined through the regions or the body it runs: + * - a region or a called body is entered from the entry and left to the exit; + * - a `loop` body and a `map` body may run again (exit → entry) or not at all + * (entry → exit); + * - the branches of a `parallel` may interleave, so each branch's exit leads + * into every other branch; + * - every node of a `try` region may fail into its `catch` region and to the + * container's exit; + * - an edge of the flow, a `fault` edge included, leads from its source's exit + * to its target's entry. + * A step is one vertex: its decision leaves it. + */ +function buildGraph( + flows: Map, + calls: Map>, +): Graph { + const succ = new Map>(); + const pred = new Map>(); + const owner = new Map(); + const link = (a: Vertex, b: Vertex) => { + if (!succ.has(a)) succ.set(a, new Set()); + if (!pred.has(b)) pred.set(b, new Set()); + succ.get(a)!.add(b); + pred.get(b)!.add(a); + }; + const entryOfFlow = (key: string) => vertexOf(key, '', 'flow-entry'); + const exitOfFlow = (key: string) => vertexOf(key, '', 'flow-exit'); + const calleeOf = new Map(); + for (const [key, list] of calls) for (const c of list) calleeOf.set(`${key}\u0000${c.node.id}`, c); + + const isCompound = (node: OpeningFlowNode) => !!node.type && (CALL_TYPES.has(node.type) || FLOW_REGION_SLOTS_BY_TYPE.has(node.type)); + const inOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'in' : ''); + const outOf = (flow: string, node: OpeningFlowNode) => vertexOf(flow, node.id, isCompound(node) ? 'out' : ''); + + /** Wire one graph (a flow's top level or a region); answers its entry and exit vertices. */ + const wire = (flow: string, nodes: ReadonlyArray | undefined, edges: ReadonlyArray | undefined, depth: number): + { entries: Vertex[]; exits: Vertex[]; inner: Vertex[] } => { + const list = (nodes ?? []).filter((n) => n && typeof n === 'object' && typeof n.id === 'string'); + const byId = new Map(list.map((n) => [n.id, n])); + const inner: Vertex[] = []; + const hasIn = new Set(); + const hasOut = new Set(); + for (const e of edges ?? []) { + const a = byId.get(e?.source); + const b = byId.get(e?.target); + if (!a || !b) continue; + link(outOf(flow, a), inOf(flow, b)); + hasOut.add(a.id); + hasIn.add(b.id); + } + for (const node of list) { + const vin = inOf(flow, node); + const vout = outOf(flow, node); + owner.set(vin, { flow, node }); + owner.set(vout, { flow, node }); + inner.push(vin); + if (vout !== vin) inner.push(vout); + const call = calleeOf.get(`${flow}\u0000${node.id}`); + if (call) { + if (call.callee) { + link(vin, entryOfFlow(call.callee)); + link(exitOfFlow(call.callee), vout); + if (call.kind === 'map') link(exitOfFlow(call.callee), entryOfFlow(call.callee)); + } else { + link(vin, vout); + } + if (call.kind === 'map') link(vin, vout); + continue; + } + const regions = depth < MAX_REGION_DEPTH ? regionsOf(node) : []; + if (node.type && FLOW_REGION_SLOTS_BY_TYPE.has(node.type)) { + const wired = regions.map((r) => ({ slot: r.slot, ...wire(flow, r.nodes, r.edges, depth + 1) })); + if (wired.length === 0) link(vin, vout); + if (node.type === 'try_catch') { + const tryR = wired.filter((w) => w.slot.startsWith('try')); + const catchR = wired.filter((w) => w.slot.startsWith('catch')); + for (const t of tryR) { + for (const e of t.entries) link(vin, e); + for (const x of t.exits) link(x, vout); + for (const v of t.inner) { + link(v, vout); + for (const c of catchR) for (const e of c.entries) link(v, e); + } + } + for (const c of catchR) for (const x of c.exits) link(x, vout); + } else { + for (const w of wired) { + for (const e of w.entries) link(vin, e); + for (const x of w.exits) link(x, vout); + } + if (node.type === 'loop') { + link(vin, vout); + for (const w of wired) for (const x of w.exits) for (const e of w.entries) link(x, e); + } + if (node.type === 'parallel') { + for (const a of wired) for (const b of wired) { + if (a === b) continue; + for (const x of a.exits) for (const e of b.entries) link(x, e); + } + } + } + } + } + const entries = list.filter((n) => (depth === 0 ? n.type === 'start' || !hasIn.has(n.id) : !hasIn.has(n.id))).map((n) => inOf(flow, n)); + const exits = list.filter((n) => !hasOut.has(n.id)).map((n) => outOf(flow, n)); + return { entries, exits, inner }; + }; + + for (const [key, body] of flows) { + const { entries, exits } = wire(key, body.nodes, body.edges, 0); + for (const e of entries) link(entryOfFlow(key), e); + for (const x of exits) link(x, exitOfFlow(key)); + } + return { succ, pred, owner }; +} + +/** The vertices reachable from `starts` by one edge or more. */ +function reach(edges: Map>, starts: Vertex[]): Set { + const seen = new Set(); + const stack: Vertex[] = []; + for (const s of starts) for (const n of edges.get(s) ?? []) stack.push(n); + while (stack.length > 0) { + const v = stack.pop()!; + if (seen.has(v)) continue; + seen.add(v); + for (const n of edges.get(v) ?? []) if (!seen.has(n)) stack.push(n); + } + return seen; +} + +function cmp(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function dedupe(gaps: OpeningGap[]): OpeningGap[] { + const seen = new Set(); + return gaps.filter((g) => { + const k = JSON.stringify(g); + if (seen.has(k)) return false; + seen.add(k); + return true; + }); +} diff --git a/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts new file mode 100644 index 00000000000..3018bdec513 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-opening-refusal.ts @@ -0,0 +1,60 @@ +/** + * The sentence an approval's first request is refused with when the opening + * check (ADR-0162 Execution item 7, #37766 slice B) finds a gap: one lead + * naming the record, then one sentence per gap naming the flow, step, object, + * field and what is missing — in the run's locale, from the plugin's own + * catalog (`translations/messages.ts`), falling back to `en`. + */ + +import { interpolate } from './approval-notification-text.js'; +import type { OpeningGap } from './approval-opening-check.js'; +import { approvalMessages, type ApprovalMessageId } from './translations/messages.js'; + +type Pack = (typeof approvalMessages)[keyof typeof approvalMessages]; + +const GAP_SENTENCE: Readonly> = { + no_pending_option: 'approvalOpeningNoPendingOption', + closes_in_flight: 'approvalOpeningClosesInFlight', + state_machine_no_pending: 'approvalOpeningStateMachine', + readonly_when: 'approvalOpeningReadonlyWhen', + option_visible_when: 'approvalOpeningOptionVisibleWhen', + other_field: 'approvalOpeningOtherField', + no_field: 'approvalOpeningNoField', + pause_between_steps: 'approvalOpeningPause', + map_with_approval: 'approvalOpeningMapApproval', + unreadable_flow: 'approvalOpeningUnreadableFlow', + no_job_service: 'approvalOpeningNoJobService', +}; + +/** + * The catalog pack for `locale`: the exact tag; else `zh-Hant` for a + * Traditional Chinese tag (`zh-TW`, `zh-HK`, `zh-MO`); else the first pack of + * the same language; else `en`. + */ +export function openingRefusalPack(locale: string | undefined): Pack { + const packs = approvalMessages as Readonly>; + if (!locale) return approvalMessages.en; + const wanted = locale.replace(/_/g, '-').toLowerCase(); + const tags = Object.keys(packs); + const exact = tags.find((t) => t.toLowerCase() === wanted); + if (exact) return packs[exact]!; + if (/^zh-(hant|tw|hk|mo)\b/.test(wanted) && packs['zh-Hant']) return packs['zh-Hant']!; + const language = wanted.split('-')[0]; + const same = tags.find((t) => t.toLowerCase().split('-')[0] === language); + return same ? packs[same]! : approvalMessages.en; +} + +/** The refusal text for `gaps`, on the record `subject`, in `locale`. */ +export function openingRefusalText( + gaps: readonly OpeningGap[], + subject: { object: string; record: string }, + locale?: string, +): string { + const pack = openingRefusalPack(locale); + const lead = interpolate(pack.approvalOpeningRefusedLead, { object: subject.object, record: subject.record }); + const sentences = gaps.map((gap) => { + const { kind, ...params } = gap; + return interpolate(pack[GAP_SENTENCE[kind]], params as Record); + }); + return [lead, ...sentences].join(' '); +} diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 5aaa0294034..6b0c526b581 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -179,6 +179,8 @@ import { APPROVALS_INBOX_PATH, renderConfirmPage, renderResultPage } from './act import { consolePageLink, type ConsolePageComposer } from './public-base-url.js'; import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; +import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; +import { openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, approvalNotificationText, @@ -223,7 +225,18 @@ export interface ApprovalEngine { * registering door wrote for a package, with its `source`. Optional so a * double without it answers "origin unknown", and the gate refuses. */ - registry?: { getPackage?(id: string): { source?: unknown } | undefined }; + registry?: { + getPackage?(id: string): { source?: unknown } | undefined; + /** + * [ADR-0162 Execution item 7] Every registered object, read by the check + * when an approval opens ({@link ApprovalService.judgeOpening}) to learn + * whether any object declares `closedStates`: in an application where + * none does, nothing is read and no approval is refused. Optional: absent, + * the check reads the approval whenever its own record's object declares + * the key. + */ + getAllObjects?(): unknown[]; + }; /** * `ObjectQL.residualOwnerSource`: the registering door's statement for an * artifact residual's owner id, which has no registry row. Read by the same @@ -315,6 +328,17 @@ export interface ApprovalResumeSurface { flowSlotKey?(packageId: string | null, name: string): string | undefined; getFlowSlot?(packageId: string | null, name: string): any | null; getRunFlow?(run: { flowName: string }): any | null; + /** + * [ADR-0162 Execution item 7] The action descriptor a node type publishes + * (ADR-0018), or `undefined` where it publishes none: how the check when an + * approval opens reads whether a node between two steps can pause the run + * of itself (`supportsPause`), following `aliasOf` as the engine's own + * pause gate does. ⚠️ Declares a method `AutomationEngine` ALREADY + * implements publicly (`getActionDescriptor`); it widens no engine surface. + * Optional: absent, every node type but the structural ones counts as one + * that can pause. + */ + getActionDescriptor?(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined; /** * [#35863] A flow name's registrations, oldest first: each body and when it * was registered. Read by {@link ApprovalService.attachFlowRoute} to tell @@ -2661,6 +2685,23 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega this.automation = automation; } + /** + * [ADR-0162 D5, Execution item 7] Whether the host runs this plugin's sweeps: + * the plugin calls {@link noteSweepClockScheduled} once it has scheduled them + * on the host's `job` service. The sweeps are what ends an approval nobody + * is at the door for (ADR-0162 item 8, the reconciler), so on a host with no + * `job` service the first request of every approval a step of which can act + * on an object that declares `closedStates` is refused, saying what is + * missing (seat rulings 7211509661 and 7211531658, the seat's ruling on the + * design note 7210179412). `false` until noted. + */ + private sweepClockScheduled = false; + + /** [ADR-0162 Execution item 7] The plugin scheduled its sweeps on the host's `job` service ({@link sweepClockScheduled}). */ + noteSweepClockScheduled(): void { + this.sweepClockScheduled = true; + } + /** Attach (or replace) the messaging surface used for thread notifications. */ attachMessaging(messaging: ApprovalMessagingSurface): void { this.messaging = messaging; @@ -5107,6 +5148,176 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return Array.isArray(closed) && (closed.includes('approved') || closed.includes('rejected')); } + /** + * [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 + * (`between_steps_json`), or `null` where it carries none. Throws, with what + * is missing, where the approval may not open. + * + * - **Placed by its root run.** The approval is the request's root run + * (ADR-0162 item 7, slice A). A request whose run hands no root run cannot + * be placed: it is not judged and carries no set. A request of an approval + * that already has one is a later request: it is not judged again, since + * refusing it would end the approval between two steps, and it carries the + * set its approval's first request was stamped with. A request opened on + * the record since the root run started that records no root run makes + * this one unplaceable too: not judged, no set. + * - **Nothing read where nothing declares the key.** In an application where + * no object declares `closedStates`, the approval is not read. + * - **Read whole.** The flow the root run was started on and every flow a + * `subflow` or a `map` names, to any depth ({@link judgeApprovalOpening}). + * An approval that cannot be read whole is refused. + * - **Refused** where a step's mirror field is one the object closes on at a + * status of a request in flight and a condition of D5 fails, or where a + * step can act on an object that declares the key and the host runs no + * `job` service. The refusal is a `VALIDATION_FAILED`, whose sentence names + * the flow, the step, the object, the field and what is missing, in the + * run's locale where the plugin carries it ({@link openingRefusalText}). + * The node fails the run with it, which is what the submitter reads. + */ + private async judgeOpening( + input: { + object: string; recordId: string; runId: string; nodeId: string; + flowName?: string; flowKey?: string; runRoot?: boolean; + rootRun?: ApprovalRootRun | null; locale?: string; + }, + context: ExecutionContext, + ): Promise { + const rootRun = input.rootRun; + if (!rootRun?.runId) return null; + + // A later request of the same approval carries its first request's set. + let earlier: any[]; + try { + earlier = await this.engine.find('sys_approval_request', { + where: { root_run_id: rootRun.runId }, + fields: ['id', 'between_steps_json', 'created_at'], + orderBy: [{ field: 'created_at', order: 'asc' }], + limit: 1, context: SYSTEM_CTX, + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read whether a request is its approval\'s first; it opens unjudged and carries no between-two-steps set', { + run: input.runId, rootRun: rootRun.runId, error: err?.message ?? String(err), + }); + return null; + } + if (Array.isArray(earlier) && earlier[0]) { + const stamp = earlier[0].between_steps_json; + return typeof stamp === 'string' && stamp !== '' ? stamp : null; + } + // A request on the record since the root run started that records no root + // run: the plugin cannot tell whether it was this approval's first. + if (rootRun.startedAt) { + try { + const unplaced = await this.engine.find('sys_approval_request', { + where: { + object_name: input.object, record_id: input.recordId, root_run_id: null, + created_at: { $gte: rootRun.startedAt }, + }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + if (Array.isArray(unplaced) && unplaced[0]) return null; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read the record\'s earlier requests; the request opens unjudged and carries no between-two-steps set', { + run: input.runId, rootRun: rootRun.runId, error: err?.message ?? String(err), + }); + return null; + } + } + + // Nothing is read in an application where no object declares the key. + const declares = (object: string | null | undefined): boolean => { + if (!object) return false; + try { return closedValuesOf(this.engine.getSchema?.(object)) !== undefined; } catch { return false; } + }; + let appDeclares: boolean; + let listed: unknown[] | undefined; + try { listed = this.engine.registry?.getAllObjects?.(); } catch { listed = undefined; } + if (Array.isArray(listed)) appDeclares = listed.some((o) => closedValuesOf(o) !== undefined); + else appDeclares = declares(input.object) || declares(rootRun.object); + if (!appDeclares) return null; + + const judgement = await judgeApprovalOpening({ + rootFlow: await this.openingRootFlow(input, rootRun), + rootFlowName: rootRun.flowName, + rootObject: rootRun.object ?? null, + }, { + objectSchema: (name) => { try { return this.engine.getSchema?.(name); } catch { return undefined; } }, + calleeFlow: (name, callerKey) => this.openingCalleeFlow(name, callerKey), + nodeDescriptor: (type) => { + if (typeof this.automation?.getActionDescriptor !== 'function') return 'unread'; + try { return this.automation.getActionDescriptor(type); } catch { return 'unread'; } + }, + hostRunsReconciler: this.sweepClockScheduled, + }); + if (judgement.gaps.length > 0) { + const locale = input.locale ?? (context as { locale?: string } | undefined)?.locale; + this.logger?.warn?.('[approvals] an approval was refused at its first request: the record\'s object closes on its approval field and the approval cannot show it in progress (ADR-0162 D5)', { + object: input.object, record: input.recordId, run: input.runId, rootRun: rootRun.runId, + gaps: judgement.gaps.map((g) => g.kind), + }); + throw new Error(`VALIDATION_FAILED: ${openingRefusalText(judgement.gaps, { object: input.object, record: input.recordId }, locale)}`); + } + if (!judgement.touchesClosedStates) return null; + return JSON.stringify(judgement.between); + } + + /** + * [ADR-0162 Execution item 7] The flow the approval's root run was started + * on, by the key the engine files it under: the request's own run's key + * where that run is the root, else the key the root run is parked under + * (it is parked at the `subflow` or the `map` that started this run), else + * the bare name. `null` where none can be read. + */ + private async openingRootFlow( + input: { flowName?: string; flowKey?: string; runRoot?: boolean }, + rootRun: ApprovalRootRun, + ): Promise { + const automation = this.automation; + if (!automation) return null; + const byKey = (key: string | undefined): any => { + if (!key || typeof automation.getRunFlow !== 'function') return null; + try { return automation.getRunFlow({ flowName: key }); } catch { return null; } + }; + try { + let key: string | undefined = input.runRoot ? (input.flowKey ?? input.flowName) : undefined; + if (!key) { + try { key = (await automation.suspensionOf?.(rootRun.runId))?.flowName; } catch { key = undefined; } + } + const body = byKey(key) ?? (typeof automation.getFlow === 'function' ? await automation.getFlow(rootRun.flowName) : null); + if (!body || typeof body !== 'object') return null; + return { key: key ?? rootRun.flowName, body }; + } catch { + return null; + } + } + + /** + * [ADR-0162 Execution item 7] The flow a `subflow` or a `map` of the flow + * filed under `callerKey` names as `name`: the one flow of a name one + * package holds (or none does), and for a name two packages hold, the + * caller's own package's slot. `null` where that cannot be read, which + * makes the approval one that cannot be read whole. + */ + private async openingCalleeFlow(name: string, callerKey: string): Promise { + const automation = this.automation; + if (!automation) return null; + try { + const slots = typeof automation.getFlowSlots === 'function' ? automation.getFlowSlots(name) : []; + if (slots.length > 1) { + const pkg = this.flowPackageOf(callerKey); + if (!pkg || typeof automation.getFlowSlot !== 'function') return null; + const body = automation.getFlowSlot(pkg, name); + const key = automation.flowSlotKey?.(pkg, name) ?? name; + return body && typeof body === 'object' ? { key, body } : null; + } + const body = typeof automation.getFlow === 'function' ? await automation.getFlow(name) : null; + return body && typeof body === 'object' ? { key: name, body } : null; + } catch { + return null; + } + } + /** * [ADR-0162 Execution item 8] Whether `row` is its approval's first request on * its record: no other request on the record names the same approval. The @@ -5638,6 +5849,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * store can be asked for. `null` or absent records none. */ recordRun?: ApprovalRecordRun | null; + /** + * [ADR-0162 Execution item 7] The run's locale (`AutomationContext.locale`): + * the language of a refused opening's sentence, which the run's failure + * carries to the person who submitted. + */ + locale?: string; }, context: ExecutionContext, ): Promise { @@ -5654,6 +5871,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega throw new Error(`DUPLICATE_REQUEST: a pending approval already exists for ${input.object}/${input.recordId}`); } + // [ADR-0162 D5, Execution item 7] The check when an approval opens, before + // anything is written: a refused opening writes no request, mirrors + // nothing and takes no lock. It answers the between-two-steps set this + // request carries from its opening. + const betweenSteps = await this.judgeOpening(input, context); + // `organizationId` is not on the envelope — see isOverrideActor(). const ctxOrg = (context as any)?.organizationId ?? context?.tenantId ?? input.organizationId ?? null; const nowDate = this.clock.now(); @@ -6048,6 +6271,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega root_run_id: input.rootRun?.runId ?? null, root_run_started_at: input.rootRun?.startedAt ?? null, record_run_id: input.recordRun?.runId ?? null, + // [ADR-0162 Execution item 7] The nodes that stand between two steps of + // the approval, stamped as the request opens ({@link judgeOpening}). + between_steps_json: betweenSteps, node_config_json: JSON.stringify(configSnapshot), organization_id: requestOrg, created_at: now, diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index c757c0d7beb..be3dbb05f21 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -548,6 +548,9 @@ export class ApprovalsServicePlugin implements Plugin { await jobs.schedule(ESCALATION_JOB_NAME, { type: 'interval', intervalMs }, sweep); this.jobService = jobs; this.escalationJobScheduled = true; + // [ADR-0162 Execution item 7] The sweeps run here, so an approval on an + // object that declares `closedStates` may open on this host. + svc.noteSweepClockScheduled(); void sweep().catch((err: any) => { ctx.logger.warn?.('[approvals] boot sweep failed', { error: err?.message }); }); diff --git a/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts index 8179524343b..b98b6ed217b 100644 --- a/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/status-mirror-abandoned-closed-value.integration.test.ts @@ -183,6 +183,10 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i } logger = recordingLogger(); svc = new ApprovalService({ engine: engine as any, logger }); + // [#37766 slice B] The host runs the plugin's sweeps, as one with a `job` + // service does: an approval on a closing object does not open on a host + // that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); automation = new AutomationEngine(silent, new InMemorySuspendedRunStore()); installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); registerApprovalNode(automation as any, svc, silent); @@ -426,8 +430,21 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i // and the earlier step's `approved` stays on the field: the shape of an // approval its opening check did not judge (ADR-0162 Execution item 7). describe("an earlier step's outcome on the field: the approval wrote it, so the field goes down the order", () => { + // [#37766 slice B] The check would refuse this approval at its first + // request (the field declares no `pending`). An approval it did not judge + // is one opened before the object declared `closedStates`: the request + // opens on the object as it stood, and the declaration comes after. + const NO_PENDING = OBJECTS.find((o) => o.name === 'doc_no_pending')!; + const submitBeforeDeclared = async (...args: Parameters) => { + const { closedStates: _later, ...undeclared } = NO_PENDING as typeof NO_PENDING & { closedStates?: unknown }; + engine.registry.registerObject(undeclared as any, 'approvals-test', 'approvals-test'); + try { return await submit(...args); } finally { + engine.registry.registerObject(NO_PENDING as any, 'approvals-test', 'approvals-test'); + } + }; + it('that step in the same run', async () => { - const { id, request } = await submit('doc_no_pending', { atSubmit: 'approved', flow: 'two' }); + const { id, request } = await submitBeforeDeclared('doc_no_pending', { atSubmit: 'approved', flow: 'two' }); await approve(request, 'u_mgr'); expect(await statusOf('doc_no_pending', id)).toBe('approved'); const second = await pendingOn(id); @@ -436,7 +453,7 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i }); it('that step in a child run', async () => { - const { id, request } = await submit('doc_no_pending', { atSubmit: 'draft', flow: 'child_first' }); + const { id, request } = await submitBeforeDeclared('doc_no_pending', { atSubmit: 'draft', flow: 'child_first' }); await approve(request, 'u_mgr'); expect(await statusOf('doc_no_pending', id)).toBe('approved'); const second = await pendingOn(id); @@ -446,7 +463,7 @@ describe('ADR-0162 D5 — an abandoned approval never writes a closed value on i }); it('that step in the parent of the run whose request is abandoned', async () => { - const { id, request } = await submit('doc_no_pending', { atSubmit: 'draft', flow: 'parent_first' }); + const { id, request } = await submitBeforeDeclared('doc_no_pending', { atSubmit: 'draft', flow: 'parent_first' }); await approve(request, 'u_mgr'); expect(await statusOf('doc_no_pending', id)).toBe('approved'); const second = await pendingOn(id); diff --git a/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts index 1e3e7fe96ba..8cbc2659781 100644 --- a/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/status-mirror-closing-field-refusal.integration.test.ts @@ -183,6 +183,10 @@ describe('[ADR-0162 item 8] a refused write of the status mirror on a field the messaging: { emit: async (e: any) => { emits.push(e); } } as any, }); (svc as any).organizationAdministrators = async (org: unknown) => ({ ids: org === ORG ? ['org_admin'] : [] }); + // [#37766 slice B] The host runs the plugin's sweeps, as one with a `job` + // service does: an approval on a closing object does not open on a host + // that runs none (ADR-0162 item 7), which is not what this file pins. + svc.noteSweepClockScheduled(); svc.attachAutomation(automation as any); registerApprovalNode(automation as any, svc, logger as any); bindApprovalLockHook(ql as any, logger as any); 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 f606582d10c..7b71d3b95cf 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -118,7 +118,7 @@ export const SysApprovalRequest = ObjectSchema.create({ searchableFields: [ 'process_name', 'process_package', 'process_label', 'object_name', 'record_id', 'submitter_comment', 'status', 'cancel_reason', 'current_step', 'current_step_label', 'pending_approvers', 'pending_approver_labels', - 'flow_run_id', 'flow_node_id', 'root_run_id', 'record_run_id', 'node_config_json', + 'flow_run_id', 'flow_node_id', 'root_run_id', 'record_run_id', 'between_steps_json', 'node_config_json', ], // Curated built-in list views — render as segmented tabs in the console. @@ -554,6 +554,23 @@ export const SysApprovalRequest = ObjectSchema.create({ group: 'State', }), + // [ADR-0162 Execution item 7] The nodes that stand between two steps of the + // request's approval: a JSON list of `{ flow, node }`, the flow by the key + // the engine files it under. The check when an approval opens works the set + // out at the approval's first request and stamps it on every request of + // the approval as it opens, so that a stop or a pause of the run can later + // be placed against it (ADR-0162 item 8). Engine-written at open and never + // re-derived; null on a request of an approval no step of which can act on + // an object that declares `closedStates`, and on one the plugin could not + // place. + between_steps_json: Field.textarea({ + label: 'Between Steps', + required: false, + readonly: true, + description: 'Flow nodes that stand between two steps of the approval this request belongs to.', + group: 'State', + }), + node_config_json: Field.textarea({ label: 'Node Config', required: false, 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 15e13591861..2088ab9929f 100644 --- a/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ar.objects.generated.ts @@ -117,6 +117,10 @@ export const arObjects: NonNullable = { label: "تشغيل السجل", help: "تشغيل الأتمتة الذي يحمل سجل هذا الطلب." }, + between_steps_json: { + 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 f7a6e752006..8bffeec4815 100644 --- a/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/de.objects.generated.ts @@ -117,6 +117,10 @@ export const deObjects: NonNullable = { label: "Datensatzausführung", help: "Automatisierungsausführung, die den Datensatz dieser Anfrage trägt." }, + between_steps_json: { + label: "Zwischen Schritten", + help: "Flussknoten, die zwischen zwei Schritten der Genehmigung stehen, zu der diese Anfrage gehört." + }, 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 22a0e13f2e2..b13662521df 100644 --- a/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/en.objects.generated.ts @@ -117,6 +117,10 @@ export const enObjects: NonNullable = { label: "Record Run", help: "Automation run that carries the record this request is on." }, + between_steps_json: { + label: "Between Steps", + help: "Flow nodes that stand between two steps of the approval this request belongs to." + }, 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 415a592b4b0..fc110876cf8 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 @@ -117,6 +117,10 @@ export const esESObjects: NonNullable = { label: "Ejecución del registro", help: "Ejecución de automatización que lleva el registro de esta solicitud." }, + between_steps_json: { + label: "Entre pasos", + help: "Nodos del flujo que están entre dos pasos de la aprobación a la que pertenece esta solicitud." + }, 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 b02c1beb118..7f5d81ac7f9 100644 --- a/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/fr.objects.generated.ts @@ -117,6 +117,10 @@ export const frObjects: NonNullable = { label: "Exécution de l’enregistrement", help: "Exécution d’automatisation qui porte l’enregistrement de cette demande." }, + between_steps_json: { + label: "Entre les étapes", + help: "Nœuds du flux situés entre deux étapes de l'approbation à laquelle appartient cette demande." + }, 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 e3106fa79b9..59912ac12c6 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 @@ -117,6 +117,10 @@ export const jaJPObjects: NonNullable = { label: "レコード実行", help: "この申請の対象レコードを担う自動化実行。" }, + between_steps_json: { + 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 b0ebc188746..e8e20789290 100644 --- a/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ko.objects.generated.ts @@ -117,6 +117,10 @@ export const koObjects: NonNullable = { label: "레코드 실행", help: "이 요청이 걸린 레코드를 담고 있는 자동화 실행입니다." }, + between_steps_json: { + label: "단계 사이", + help: "이 요청이 속한 승인에서 두 단계 사이에 있는 플로 노드입니다." + }, node_config_json: { label: "노드 구성", help: "노드 기반 요청의 승인 노드 구성(승인자/동작) 스냅숏입니다." diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index a95b39cd32a..ee99b8e5e41 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -122,6 +122,18 @@ const enSentences = { approvalSlaBreachedBody: 'A decision on {{object}} {{record}} is overdue.', approvalStatusMirrorRefusedTitle: 'Approval status not written', approvalStatusMirrorRefusedBody: 'The approval status of {{object}} {{record}} was refused by a rule or hook of the app: {{reason}} Change that rule or hook so the status can be written.', + approvalOpeningRefusedLead: 'The approval of {{object}} {{record}} was not started: the object closes on its approval field, and the approval cannot show itself in progress there.', + approvalOpeningNoPendingOption: 'Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) does not declare the value pending; add it to the field\'s options.', + approvalOpeningClosesInFlight: '{{object}} closes on {{value}} of field {{field}} (step {{step}} of flow {{flow}}), a status of an approval in progress; remove {{value}} from the object\'s closedStates.', + approvalOpeningStateMachine: 'The state_machine rule {{rule}} on field {{field}} of {{object}} (step {{step}} of flow {{flow}}) declares the moves out of {{value}} without pending; add pending to them.', + approvalOpeningReadonlyWhen: 'Field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a readonlyWhen; remove it.', + approvalOpeningOptionVisibleWhen: 'The option {{value}} of field {{field}} of {{object}} (step {{step}} of flow {{flow}}) carries a visibleWhen; remove it.', + approvalOpeningOtherField: 'Step {{step}} of flow {{flow}} can act on {{object}} but mirrors onto field {{other}}; every step that can act on {{object}} must mirror onto {{field}}.', + approvalOpeningNoField: 'Step {{step}} of flow {{flow}} can act on {{object}} but names no approval status field; every step that can act on {{object}} must mirror onto {{field}}.', + approvalOpeningPause: 'Node {{node}} ({{type}}) of flow {{flow}} can pause the run between two approval steps of {{object}}; move it before the first step or after the last.', + approvalOpeningMapApproval: 'The map node {{node}} of flow {{flow}} runs an approval step for each item, and the node does not show that no item is a record; an approval of another record would hold {{object}} between two steps.', + approvalOpeningUnreadableFlow: 'Flow {{flow}}, which the approval runs, could not be read, so the approval cannot be checked.', + approvalOpeningNoJobService: '{{object}} declares closedStates, and this host runs no job service, so nothing would end an approval nobody finishes; install a job service.', approvalSlaBreachedSubmitterTitle: 'Your approval request breached its SLA', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: escalation action '{{action}}' was taken.", approvalApprovedTitle: 'Request approved', @@ -257,6 +269,18 @@ export const zhCNMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}} 的审批决定已逾期。', approvalStatusMirrorRefusedTitle: '审批状态未能写入', approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的审批状态被应用自己的规则或钩子拒绝:{{reason}} 请修改该规则或钩子,使状态可以写入。', + approvalOpeningRefusedLead: '{{object}} {{record}} 的审批没有发起:该对象会在审批字段上关闭,而这次审批无法在该字段上显示「审批中」。', + approvalOpeningNoPendingOption: '{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})没有声明值 pending;请把它加入该字段的选项。', + approvalOpeningClosesInFlight: '{{object}} 在字段 {{field}} 的 {{value}} 上关闭(流程 {{flow}} 的步骤 {{step}}),而这是审批进行中的状态;请把 {{value}} 从对象的 closedStates 中去掉。', + approvalOpeningStateMachine: '{{object}} 字段 {{field}} 上的 state_machine 规则 {{rule}}(流程 {{flow}} 的步骤 {{step}})声明了从 {{value}} 出发的转移,但其中没有 pending;请加上 pending。', + approvalOpeningReadonlyWhen: '{{object}} 的字段 {{field}}(流程 {{flow}} 的步骤 {{step}})带有 readonlyWhen;请去掉它。', + approvalOpeningOptionVisibleWhen: '{{object}} 字段 {{field}} 的选项 {{value}}(流程 {{flow}} 的步骤 {{step}})带有 visibleWhen;请去掉它。', + approvalOpeningOtherField: '流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却把状态写到字段 {{other}};凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。', + approvalOpeningNoField: '流程 {{flow}} 的步骤 {{step}} 可以作用于 {{object}},却没有指定审批状态字段;凡是能作用于 {{object}} 的步骤都必须写到 {{field}}。', + approvalOpeningPause: '流程 {{flow}} 的节点 {{node}}({{type}})可能在 {{object}} 的两个审批步骤之间暂停运行;请把它移到第一步之前或最后一步之后。', + approvalOpeningMapApproval: '流程 {{flow}} 的 map 节点 {{node}} 为每一项运行一个审批步骤,而该节点无法表明所有项都不是记录;另一条记录的审批会让 {{object}} 停在两个步骤之间。', + approvalOpeningUnreadableFlow: '审批要运行的流程 {{flow}} 无法读取,因此无法检查这次审批。', + approvalOpeningNoJobService: '{{object}} 声明了 closedStates,而本宿主没有运行 job 服务,没人完成的审批将无法结束;请安装 job 服务。', approvalSlaBreachedSubmitterTitle: '您的审批请求已超出时限', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已执行升级操作「{{action}}」。', approvalApprovedTitle: '请求已批准', @@ -329,6 +353,18 @@ export const jaJPMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}} の承認判断が期限を過ぎています。', approvalStatusMirrorRefusedTitle: '承認ステータスを書き込めませんでした', approvalStatusMirrorRefusedBody: '{{object}} {{record}} の承認ステータスは、アプリのルールまたはフックに拒否されました:{{reason}} ステータスを書き込めるよう、そのルールまたはフックを変更してください。', + approvalOpeningRefusedLead: '{{object}} {{record}} の承認は開始されませんでした:このオブジェクトは承認フィールドでクローズしますが、この承認はそのフィールドに承認中を表示できません。', + approvalOpeningNoPendingOption: '{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})は値 pending を宣言していません。フィールドの選択肢に追加してください。', + approvalOpeningClosesInFlight: '{{object}} はフィールド {{field}} の {{value}} でクローズします(フロー {{flow}} のステップ {{step}})。これは進行中の承認のステータスです。{{value}} をオブジェクトの closedStates から外してください。', + approvalOpeningStateMachine: '{{object}} のフィールド {{field}} にある state_machine ルール {{rule}}(フロー {{flow}} のステップ {{step}})は {{value}} からの遷移を宣言していますが、pending が含まれていません。pending を追加してください。', + approvalOpeningReadonlyWhen: '{{object}} のフィールド {{field}}(フロー {{flow}} のステップ {{step}})に readonlyWhen があります。削除してください。', + approvalOpeningOptionVisibleWhen: '{{object}} のフィールド {{field}} の選択肢 {{value}}(フロー {{flow}} のステップ {{step}})に visibleWhen があります。削除してください。', + approvalOpeningOtherField: 'フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、フィールド {{other}} にステータスを書き込みます。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。', + approvalOpeningNoField: 'フロー {{flow}} のステップ {{step}} は {{object}} に作用できますが、承認ステータスフィールドを指定していません。{{object}} に作用できるすべてのステップは {{field}} に書き込む必要があります。', + approvalOpeningPause: 'フロー {{flow}} のノード {{node}}({{type}})は {{object}} の二つの承認ステップの間で実行を一時停止する可能性があります。最初のステップの前か最後のステップの後に移動してください。', + approvalOpeningMapApproval: 'フロー {{flow}} の map ノード {{node}} は項目ごとに承認ステップを実行しますが、どの項目もレコードでないことをノードが示していません。別のレコードの承認により {{object}} が二つのステップの間で保留されます。', + approvalOpeningUnreadableFlow: '承認が実行するフロー {{flow}} を読み取れなかったため、承認を確認できません。', + approvalOpeningNoJobService: '{{object}} は closedStates を宣言していますが、このホストでは job サービスが動いていないため、誰も完了しない承認を終わらせるものがありません。job サービスをインストールしてください。', approvalSlaBreachedSubmitterTitle: 'あなたの承認申請が期限を超過しました', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:エスカレーション操作「{{action}}」が実行されました。', approvalApprovedTitle: '申請が承認されました', @@ -401,6 +437,18 @@ export const esESMessages: ApprovalMessages = { approvalSlaBreachedBody: 'La decisión sobre {{object}} {{record}} está vencida.', approvalStatusMirrorRefusedTitle: 'No se escribió el estado de aprobación', approvalStatusMirrorRefusedBody: 'Una regla o un hook de la aplicación rechazó el estado de aprobación de {{object}} {{record}}: {{reason}} Cambie esa regla o ese hook para que el estado pueda escribirse.', + approvalOpeningRefusedLead: 'No se inició la aprobación de {{object}} {{record}}: el objeto se cierra en su campo de aprobación y la aprobación no puede mostrarse en curso en él.', + approvalOpeningNoPendingOption: 'El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) no declara el valor pending; añádalo a las opciones del campo.', + approvalOpeningClosesInFlight: '{{object}} se cierra en {{value}} del campo {{field}} (paso {{step}} del flujo {{flow}}), un estado de una aprobación en curso; quite {{value}} de los closedStates del objeto.', + approvalOpeningStateMachine: 'La regla state_machine {{rule}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) declara las transiciones desde {{value}} sin pending; añada pending.', + approvalOpeningReadonlyWhen: 'El campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un readonlyWhen; quítelo.', + approvalOpeningOptionVisibleWhen: 'La opción {{value}} del campo {{field}} de {{object}} (paso {{step}} del flujo {{flow}}) tiene un visibleWhen; quítelo.', + approvalOpeningOtherField: 'El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero escribe en el campo {{other}}; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.', + approvalOpeningNoField: 'El paso {{step}} del flujo {{flow}} puede actuar sobre {{object}} pero no nombra ningún campo de estado de aprobación; todo paso que pueda actuar sobre {{object}} debe escribir en {{field}}.', + approvalOpeningPause: 'El nodo {{node}} ({{type}}) del flujo {{flow}} puede pausar la ejecución entre dos pasos de aprobación de {{object}}; muévalo antes del primer paso o después del último.', + approvalOpeningMapApproval: 'El nodo map {{node}} del flujo {{flow}} ejecuta un paso de aprobación por cada elemento, y el nodo no muestra que ningún elemento sea un registro; la aprobación de otro registro retendría {{object}} entre dos pasos.', + approvalOpeningUnreadableFlow: 'No se pudo leer el flujo {{flow}}, que la aprobación ejecuta, así que no se puede comprobar la aprobación.', + approvalOpeningNoJobService: '{{object}} declara closedStates y este host no ejecuta ningún servicio job, así que nada terminaría una aprobación que nadie complete; instale un servicio job.', approvalSlaBreachedSubmitterTitle: 'Su solicitud de aprobación ha superado su plazo', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: se ha ejecutado la acción de escalado '{{action}}'.", approvalApprovedTitle: 'Solicitud aprobada', @@ -473,6 +521,18 @@ export const zhHantMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}} 的核准決定已逾期。', approvalStatusMirrorRefusedTitle: '核准狀態未能寫入', approvalStatusMirrorRefusedBody: '{{object}} {{record}} 的核准狀態被應用程式自己的規則或掛鉤拒絕:{{reason}} 請修改該規則或掛鉤,讓狀態可以寫入。', + approvalOpeningRefusedLead: '{{object}} {{record}} 的核准沒有發起:該物件會在核准欄位上關閉,而這次核准無法在該欄位上顯示「核准中」。', + approvalOpeningNoPendingOption: '{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})沒有宣告值 pending;請把它加入該欄位的選項。', + approvalOpeningClosesInFlight: '{{object}} 在欄位 {{field}} 的 {{value}} 上關閉(流程 {{flow}} 的步驟 {{step}}),而這是核准進行中的狀態;請把 {{value}} 從物件的 closedStates 中移除。', + approvalOpeningStateMachine: '{{object}} 欄位 {{field}} 上的 state_machine 規則 {{rule}}(流程 {{flow}} 的步驟 {{step}})宣告了從 {{value}} 出發的轉移,但其中沒有 pending;請加上 pending。', + approvalOpeningReadonlyWhen: '{{object}} 的欄位 {{field}}(流程 {{flow}} 的步驟 {{step}})帶有 readonlyWhen;請移除它。', + approvalOpeningOptionVisibleWhen: '{{object}} 欄位 {{field}} 的選項 {{value}}(流程 {{flow}} 的步驟 {{step}})帶有 visibleWhen;請移除它。', + approvalOpeningOtherField: '流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻把狀態寫到欄位 {{other}};凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。', + approvalOpeningNoField: '流程 {{flow}} 的步驟 {{step}} 可以作用於 {{object}},卻沒有指定核准狀態欄位;凡是能作用於 {{object}} 的步驟都必須寫到 {{field}}。', + approvalOpeningPause: '流程 {{flow}} 的節點 {{node}}({{type}})可能在 {{object}} 的兩個核准步驟之間暫停執行;請把它移到第一步之前或最後一步之後。', + approvalOpeningMapApproval: '流程 {{flow}} 的 map 節點 {{node}} 為每一項執行一個核准步驟,而該節點無法表明所有項目都不是記錄;另一筆記錄的核准會讓 {{object}} 停在兩個步驟之間。', + approvalOpeningUnreadableFlow: '核准要執行的流程 {{flow}} 無法讀取,因此無法檢查這次核准。', + approvalOpeningNoJobService: '{{object}} 宣告了 closedStates,而本主機沒有執行 job 服務,沒有人完成的核准將無法結束;請安裝 job 服務。', approvalSlaBreachedSubmitterTitle: '你的核准請求已逾時', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}:已執行升級動作「{{action}}」。', approvalApprovedTitle: '請求已核准', @@ -545,6 +605,18 @@ export const arMessages: ApprovalMessages = { approvalSlaBreachedBody: 'القرار بشأن {{object}} {{record}} متأخر.', approvalStatusMirrorRefusedTitle: 'لم تُكتب حالة الموافقة', approvalStatusMirrorRefusedBody: 'رفضت قاعدة أو خطّاف في التطبيق حالة الموافقة على {{object}} {{record}}: {{reason}} غيّر تلك القاعدة أو ذلك الخطّاف لكي تُكتب الحالة.', + approvalOpeningRefusedLead: 'لم تبدأ الموافقة على {{object}} {{record}}: الكائن يُغلَق على حقل الموافقة، والموافقة لا تستطيع أن تُظهر فيه أنها جارية.', + approvalOpeningNoPendingOption: 'الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) لا يصرّح بالقيمة pending؛ أضفها إلى خيارات الحقل.', + approvalOpeningClosesInFlight: 'يُغلَق {{object}} على القيمة {{value}} من الحقل {{field}} (الخطوة {{step}} من التدفق {{flow}})، وهي حالة موافقة جارية؛ أزل {{value}} من closedStates للكائن.', + approvalOpeningStateMachine: 'قاعدة state_machine {{rule}} على الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) تصرّح بالانتقالات من {{value}} دون pending؛ أضف pending.', + approvalOpeningReadonlyWhen: 'الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل readonlyWhen؛ أزله.', + approvalOpeningOptionVisibleWhen: 'الخيار {{value}} من الحقل {{field}} في {{object}} (الخطوة {{step}} من التدفق {{flow}}) يحمل visibleWhen؛ أزله.', + approvalOpeningOtherField: 'الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها تكتب الحالة في الحقل {{other}}؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.', + approvalOpeningNoField: 'الخطوة {{step}} من التدفق {{flow}} يمكنها أن تعمل على {{object}} لكنها لا تسمّي حقلًا لحالة الموافقة؛ يجب أن تكتب كل خطوة يمكنها العمل على {{object}} في {{field}}.', + approvalOpeningPause: 'العقدة {{node}} ({{type}}) في التدفق {{flow}} قد توقف التشغيل مؤقتًا بين خطوتَي موافقة على {{object}}؛ انقلها قبل الخطوة الأولى أو بعد الأخيرة.', + approvalOpeningMapApproval: 'عقدة map {{node}} في التدفق {{flow}} تشغّل خطوة موافقة لكل عنصر، والعقدة لا تُظهر أن أي عنصر ليس سجلًا؛ موافقة سجل آخر ستحتجز {{object}} بين خطوتين.', + approvalOpeningUnreadableFlow: 'تعذّرت قراءة التدفق {{flow}} الذي تشغّله الموافقة، لذا لا يمكن فحص الموافقة.', + approvalOpeningNoJobService: 'يصرّح {{object}} بـ closedStates، وهذا المضيف لا يشغّل خدمة job، فلا شيء سينهي موافقة لا يكملها أحد؛ ثبّت خدمة job.', approvalSlaBreachedSubmitterTitle: 'تجاوز طلب الموافقة الخاص بك مهلته', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: نُفِّذ إجراء التصعيد «{{action}}».', approvalApprovedTitle: 'تمت الموافقة على الطلب', @@ -617,6 +689,18 @@ export const frMessages: ApprovalMessages = { approvalSlaBreachedBody: 'La décision sur {{object}} {{record}} est en retard.', approvalStatusMirrorRefusedTitle: 'Statut d’approbation non écrit', approvalStatusMirrorRefusedBody: 'Une règle ou un hook de l’application a refusé le statut d’approbation de {{object}} {{record}} : {{reason}} Modifiez cette règle ou ce hook pour que le statut puisse être écrit.', + approvalOpeningRefusedLead: 'L\'approbation de {{object}} {{record}} n\'a pas été lancée : l\'objet se ferme sur son champ d\'approbation, et l\'approbation ne peut pas s\'y afficher en cours.', + approvalOpeningNoPendingOption: 'Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) ne déclare pas la valeur pending ; ajoutez-la aux options du champ.', + approvalOpeningClosesInFlight: '{{object}} se ferme sur {{value}} du champ {{field}} (étape {{step}} du flux {{flow}}), un statut d\'approbation en cours ; retirez {{value}} des closedStates de l\'objet.', + approvalOpeningStateMachine: 'La règle state_machine {{rule}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) déclare les transitions depuis {{value}} sans pending ; ajoutez pending.', + approvalOpeningReadonlyWhen: 'Le champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un readonlyWhen ; retirez-le.', + approvalOpeningOptionVisibleWhen: 'L\'option {{value}} du champ {{field}} de {{object}} (étape {{step}} du flux {{flow}}) porte un visibleWhen ; retirez-le.', + approvalOpeningOtherField: 'L\'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais écrit dans le champ {{other}} ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.', + approvalOpeningNoField: 'L\'étape {{step}} du flux {{flow}} peut agir sur {{object}} mais ne nomme aucun champ de statut d\'approbation ; toute étape qui peut agir sur {{object}} doit écrire dans {{field}}.', + approvalOpeningPause: 'Le nœud {{node}} ({{type}}) du flux {{flow}} peut mettre l\'exécution en pause entre deux étapes d\'approbation de {{object}} ; placez-le avant la première étape ou après la dernière.', + approvalOpeningMapApproval: 'Le nœud map {{node}} du flux {{flow}} exécute une étape d\'approbation pour chaque élément, et le nœud ne montre pas qu\'aucun élément n\'est un enregistrement ; l\'approbation d\'un autre enregistrement retiendrait {{object}} entre deux étapes.', + approvalOpeningUnreadableFlow: 'Le flux {{flow}}, que l\'approbation exécute, n\'a pas pu être lu ; l\'approbation ne peut donc pas être vérifiée.', + approvalOpeningNoJobService: '{{object}} déclare closedStates et cet hôte n\'exécute aucun service job : rien ne terminerait une approbation que personne n\'achève ; installez un service job.', approvalSlaBreachedSubmitterTitle: 'Votre demande d’approbation a dépassé son délai', approvalSlaBreachedSubmitterBody: '{{object}} {{record}} : l’action d’escalade « {{action}} » a été exécutée.', approvalApprovedTitle: 'Demande approuvée', @@ -689,6 +773,18 @@ export const ptBRMessages: ApprovalMessages = { approvalSlaBreachedBody: 'A decisão sobre {{object}} {{record}} está atrasada.', approvalStatusMirrorRefusedTitle: 'Status de aprovação não gravado', approvalStatusMirrorRefusedBody: 'Uma regra ou um hook do aplicativo recusou o status de aprovação de {{object}} {{record}}: {{reason}} Altere essa regra ou esse hook para que o status possa ser gravado.', + approvalOpeningRefusedLead: 'A aprovação de {{object}} {{record}} não foi iniciada: o objeto é fechado no seu campo de aprovação, e a aprovação não consegue se mostrar em andamento nele.', + approvalOpeningNoPendingOption: 'O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) não declara o valor pending; adicione-o às opções do campo.', + approvalOpeningClosesInFlight: '{{object}} é fechado em {{value}} do campo {{field}} (etapa {{step}} do fluxo {{flow}}), um status de aprovação em andamento; remova {{value}} dos closedStates do objeto.', + approvalOpeningStateMachine: 'A regra state_machine {{rule}} no campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) declara as transições a partir de {{value}} sem pending; adicione pending.', + approvalOpeningReadonlyWhen: 'O campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um readonlyWhen; remova-o.', + approvalOpeningOptionVisibleWhen: 'A opção {{value}} do campo {{field}} de {{object}} (etapa {{step}} do fluxo {{flow}}) tem um visibleWhen; remova-o.', + approvalOpeningOtherField: 'A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas grava no campo {{other}}; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.', + approvalOpeningNoField: 'A etapa {{step}} do fluxo {{flow}} pode agir sobre {{object}}, mas não indica nenhum campo de status de aprovação; toda etapa que pode agir sobre {{object}} deve gravar em {{field}}.', + approvalOpeningPause: 'O nó {{node}} ({{type}}) do fluxo {{flow}} pode pausar a execução entre duas etapas de aprovação de {{object}}; mova-o para antes da primeira etapa ou depois da última.', + approvalOpeningMapApproval: 'O nó map {{node}} do fluxo {{flow}} executa uma etapa de aprovação para cada item, e o nó não mostra que nenhum item é um registro; a aprovação de outro registro reteria {{object}} entre duas etapas.', + approvalOpeningUnreadableFlow: 'O fluxo {{flow}}, que a aprovação executa, não pôde ser lido, então a aprovação não pode ser verificada.', + approvalOpeningNoJobService: '{{object}} declara closedStates e este host não executa nenhum serviço job, então nada encerraria uma aprovação que ninguém conclua; instale um serviço job.', approvalSlaBreachedSubmitterTitle: 'Sua solicitação de aprovação estourou o prazo', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: a ação de escalonamento "{{action}}" foi executada.', approvalApprovedTitle: 'Solicitação aprovada', @@ -761,6 +857,18 @@ export const ruMessages: ApprovalMessages = { approvalSlaBreachedBody: 'Решение по {{object}} {{record}} просрочено.', approvalStatusMirrorRefusedTitle: 'Статус согласования не записан', approvalStatusMirrorRefusedBody: 'Правило или хук приложения отклонили статус согласования для {{object}} {{record}}: {{reason}} Измените это правило или хук, чтобы статус можно было записать.', + approvalOpeningRefusedLead: 'Согласование {{object}} {{record}} не запущено: объект закрывается по своему полю согласования, а согласование не может показать в нём, что оно идёт.', + approvalOpeningNoPendingOption: 'Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) не объявляет значение pending; добавьте его в варианты поля.', + approvalOpeningClosesInFlight: '{{object}} закрывается на значении {{value}} поля {{field}} (шаг {{step}} процесса {{flow}}), а это статус идущего согласования; уберите {{value}} из closedStates объекта.', + approvalOpeningStateMachine: 'Правило state_machine {{rule}} на поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) объявляет переходы из {{value}} без pending; добавьте pending.', + approvalOpeningReadonlyWhen: 'Поле {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет readonlyWhen; уберите его.', + approvalOpeningOptionVisibleWhen: 'Вариант {{value}} поля {{field}} объекта {{object}} (шаг {{step}} процесса {{flow}}) имеет visibleWhen; уберите его.', + approvalOpeningOtherField: 'Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но записывает статус в поле {{other}}; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.', + approvalOpeningNoField: 'Шаг {{step}} процесса {{flow}} может действовать на {{object}}, но не называет поле статуса согласования; каждый шаг, который может действовать на {{object}}, должен записывать в {{field}}.', + approvalOpeningPause: 'Узел {{node}} ({{type}}) процесса {{flow}} может приостановить выполнение между двумя шагами согласования {{object}}; перенесите его до первого шага или после последнего.', + approvalOpeningMapApproval: 'Узел map {{node}} процесса {{flow}} запускает шаг согласования для каждого элемента, и узел не показывает, что ни один элемент не является записью; согласование другой записи задержит {{object}} между двумя шагами.', + approvalOpeningUnreadableFlow: 'Не удалось прочитать процесс {{flow}}, который запускает согласование, поэтому согласование нельзя проверить.', + approvalOpeningNoJobService: '{{object}} объявляет closedStates, а на этом хосте не работает служба job, поэтому согласование, которое никто не завершит, ничто не закончит; установите службу job.', approvalSlaBreachedSubmitterTitle: 'Ваш запрос на согласование нарушил срок', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: выполнено действие эскалации «{{action}}».', approvalApprovedTitle: 'Запрос одобрен', @@ -833,6 +941,18 @@ export const deMessages: ApprovalMessages = { approvalSlaBreachedBody: 'Die Entscheidung zu {{object}} {{record}} ist überfällig.', approvalStatusMirrorRefusedTitle: 'Genehmigungsstatus nicht geschrieben', approvalStatusMirrorRefusedBody: 'Eine Regel oder ein Hook der App hat den Genehmigungsstatus von {{object}} {{record}} abgelehnt: {{reason}} Ändern Sie diese Regel oder diesen Hook, damit der Status geschrieben werden kann.', + approvalOpeningRefusedLead: 'Die Genehmigung von {{object}} {{record}} wurde nicht gestartet: Das Objekt schließt auf seinem Genehmigungsfeld, und die Genehmigung kann sich dort nicht als laufend zeigen.', + approvalOpeningNoPendingOption: 'Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert den Wert pending nicht; fügen Sie ihn den Optionen des Feldes hinzu.', + approvalOpeningClosesInFlight: '{{object}} schließt auf {{value}} des Feldes {{field}} (Schritt {{step}} des Flows {{flow}}), einem Status einer laufenden Genehmigung; entfernen Sie {{value}} aus den closedStates des Objekts.', + approvalOpeningStateMachine: 'Die state_machine-Regel {{rule}} auf dem Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) deklariert die Übergänge aus {{value}} ohne pending; fügen Sie pending hinzu.', + approvalOpeningReadonlyWhen: 'Das Feld {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein readonlyWhen; entfernen Sie es.', + approvalOpeningOptionVisibleWhen: 'Die Option {{value}} des Feldes {{field}} von {{object}} (Schritt {{step}} des Flows {{flow}}) trägt ein visibleWhen; entfernen Sie es.', + approvalOpeningOtherField: 'Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, schreibt aber in das Feld {{other}}; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.', + approvalOpeningNoField: 'Schritt {{step}} des Flows {{flow}} kann auf {{object}} wirken, nennt aber kein Genehmigungsstatusfeld; jeder Schritt, der auf {{object}} wirken kann, muss in {{field}} schreiben.', + approvalOpeningPause: 'Der Knoten {{node}} ({{type}}) des Flows {{flow}} kann den Lauf zwischen zwei Genehmigungsschritten von {{object}} anhalten; verschieben Sie ihn vor den ersten oder hinter den letzten Schritt.', + approvalOpeningMapApproval: 'Der map-Knoten {{node}} des Flows {{flow}} führt für jedes Element einen Genehmigungsschritt aus, und der Knoten zeigt nicht, dass kein Element ein Datensatz ist; die Genehmigung eines anderen Datensatzes würde {{object}} zwischen zwei Schritten festhalten.', + approvalOpeningUnreadableFlow: 'Der Flow {{flow}}, den die Genehmigung ausführt, konnte nicht gelesen werden, daher kann die Genehmigung nicht geprüft werden.', + approvalOpeningNoJobService: '{{object}} deklariert closedStates, und dieser Host betreibt keinen job-Dienst, sodass nichts eine Genehmigung beenden würde, die niemand abschließt; installieren Sie einen job-Dienst.', approvalSlaBreachedSubmitterTitle: 'Ihre Genehmigungsanfrage hat ihre Frist überschritten', approvalSlaBreachedSubmitterBody: '{{object}} {{record}}: Die Eskalationsaktion „{{action}}“ wurde ausgeführt.', approvalApprovedTitle: 'Anfrage genehmigt', @@ -905,6 +1025,18 @@ export const koMessages: ApprovalMessages = { approvalSlaBreachedBody: '{{object}} {{record}}에 대한 결정이 기한을 넘겼습니다.', approvalStatusMirrorRefusedTitle: '승인 상태를 기록하지 못했습니다', approvalStatusMirrorRefusedBody: '앱의 규칙 또는 훅이 {{object}} {{record}}의 승인 상태를 거부했습니다: {{reason}} 상태를 기록할 수 있도록 해당 규칙 또는 훅을 변경하세요.', + approvalOpeningRefusedLead: '{{object}} {{record}}의 승인이 시작되지 않았습니다: 이 개체는 승인 필드에서 닫히는데, 이 승인은 그 필드에 진행 중임을 표시할 수 없습니다.', + approvalOpeningNoPendingOption: '{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})는 값 pending을 선언하지 않습니다. 필드의 옵션에 추가하세요.', + approvalOpeningClosesInFlight: '{{object}}는 필드 {{field}}의 {{value}}에서 닫힙니다(흐름 {{flow}}의 단계 {{step}}). 이는 진행 중인 승인의 상태입니다. 개체의 closedStates에서 {{value}}를 제거하세요.', + approvalOpeningStateMachine: '{{object}}의 필드 {{field}}에 있는 state_machine 규칙 {{rule}}(흐름 {{flow}}의 단계 {{step}})은 {{value}}에서 나가는 전이를 선언하지만 pending이 없습니다. pending을 추가하세요.', + approvalOpeningReadonlyWhen: '{{object}}의 필드 {{field}}(흐름 {{flow}}의 단계 {{step}})에 readonlyWhen이 있습니다. 제거하세요.', + approvalOpeningOptionVisibleWhen: '{{object}}의 필드 {{field}}의 옵션 {{value}}(흐름 {{flow}}의 단계 {{step}})에 visibleWhen이 있습니다. 제거하세요.', + approvalOpeningOtherField: '흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 필드 {{other}}에 상태를 기록합니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.', + approvalOpeningNoField: '흐름 {{flow}}의 단계 {{step}}는 {{object}}에 작용할 수 있지만 승인 상태 필드를 지정하지 않습니다. {{object}}에 작용할 수 있는 모든 단계는 {{field}}에 기록해야 합니다.', + approvalOpeningPause: '흐름 {{flow}}의 노드 {{node}}({{type}})는 {{object}}의 두 승인 단계 사이에서 실행을 일시 중지할 수 있습니다. 첫 단계 앞이나 마지막 단계 뒤로 옮기세요.', + approvalOpeningMapApproval: '흐름 {{flow}}의 map 노드 {{node}}는 항목마다 승인 단계를 실행하며, 노드는 어떤 항목도 레코드가 아님을 보여 주지 않습니다. 다른 레코드의 승인이 {{object}}를 두 단계 사이에 붙잡아 둘 수 있습니다.', + approvalOpeningUnreadableFlow: '승인이 실행하는 흐름 {{flow}}을 읽을 수 없어 승인을 확인할 수 없습니다.', + approvalOpeningNoJobService: '{{object}}는 closedStates를 선언하지만 이 호스트는 job 서비스를 실행하지 않아, 아무도 끝내지 않는 승인을 종료할 수단이 없습니다. job 서비스를 설치하세요.', approvalSlaBreachedSubmitterTitle: '승인 요청이 기한을 넘겼습니다', approvalSlaBreachedSubmitterBody: "{{object}} {{record}}: 에스컬레이션 작업 '{{action}}'이(가) 실행되었습니다.", approvalApprovedTitle: '요청 승인됨', 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 c2b46cb3ee0..085246ac1d1 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 @@ -117,6 +117,10 @@ export const ptBRObjects: NonNullable = { label: "Execução do registro", help: "Execução de automação que carrega o registro desta solicitação." }, + between_steps_json: { + label: "Entre etapas", + help: "Nós do fluxo que ficam entre duas etapas da aprovação à qual esta solicitação pertence." + }, 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 b6cabc06994..d8bcf649534 100644 --- a/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-approvals/src/translations/ru.objects.generated.ts @@ -117,6 +117,10 @@ export const ruObjects: NonNullable = { label: "Запуск записи", help: "Запуск автоматизации, который несёт запись этого запроса." }, + between_steps_json: { + 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 09fdcc49087..ea9abebff29 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 @@ -117,6 +117,10 @@ export const zhCNObjects: NonNullable = { label: "记录运行", help: "承载此请求所在记录的自动化运行。" }, + between_steps_json: { + 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 16384bf84d7..ef80bead5ac 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 @@ -117,6 +117,10 @@ export const zhHantObjects: NonNullable = { label: "記錄執行", help: "承載此請求所在記錄的自動化執行。" }, + between_steps_json: { + label: "步驟之間", + help: "審批中位於兩個步驟之間的流程節點。" + }, node_config_json: { label: "節點設定", help: "由節點驅動之請求的核准節點設定(核准人/行為)快照。"