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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/37766-opening-check.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions packages/plugins/plugin-approvals/src/approval-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, unknown> } = {}) {
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>('objectql');
automation = kernel.getService<AutomationEngine>('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<string, unknown> = {}) =>
automation.execute(flow, { object, record: await read(object, id), userId: 'owner', ...extra } as any) as Promise<any>;
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');
});
});
Loading
Loading