-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapproval-service.test.ts
More file actions
669 lines (594 loc) · 30.6 KB
/
Copy pathapproval-service.test.ts
File metadata and controls
669 lines (594 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Node-era approval service tests (ADR-0019).
*
* Approval is a flow node — there is no standalone process engine. These tests
* exercise the service directly: opening a node-driven request, recording
* decisions (first_response / unanimous), the public `decide()` resume bridge,
* the read API, and the global record-lock hook.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { ApprovalService } from './approval-service.js';
import { bindApprovalLockHook, unbindAllHooks } from './lifecycle-hooks.js';
interface FakeRow { [k: string]: any }
function makeFakeEngine() {
const tables: Record<string, FakeRow[]> = {};
const ensure = (n: string) => (tables[n] ??= []);
const hooks: Record<string, Array<{ handler: (ctx: any) => any | Promise<any>; object?: string | string[]; packageId?: string }>> = {};
function matches(row: FakeRow, filter: any): boolean {
if (!filter || typeof filter !== 'object') return true;
for (const [k, v] of Object.entries(filter)) {
const rv = row[k];
if (v != null && typeof v === 'object' && '$in' in (v as any)) {
if (!(v as any).$in.includes(rv)) return false;
continue;
}
if (v != null && typeof v === 'object' && '$ne' in (v as any)) {
if (rv === (v as any).$ne) return false;
continue;
}
if (rv !== v) return false;
}
return true;
}
return {
_tables: tables,
_hooks: hooks,
async find(object: string, options?: any) {
const rows = ensure(object).filter(r => matches(r, options?.filter ?? options?.where));
if (options?.orderBy?.[0]) {
const { field, direction } = options.orderBy[0];
rows.sort((a, b) => {
const av = a[field]; const bv = b[field];
if (av === bv) return 0;
const cmp = av > bv ? 1 : -1;
return direction === 'desc' ? -cmp : cmp;
});
}
return rows.slice(0, options?.limit ?? 1000);
},
async insert(object: string, data: any) {
ensure(object).push({ ...data });
return { ...data };
},
async update(object: string, idOrData: any, _opts?: any) {
const data = typeof idOrData === 'object' ? idOrData : _opts;
const id = typeof idOrData === 'object' ? idOrData.id : idOrData;
const table = ensure(object);
const i = table.findIndex(r => r.id === id);
if (i >= 0) table[i] = { ...table[i], ...data };
return table[i];
},
async delete(object: string, options?: any) {
const table = ensure(object);
const id = options?.where?.id ?? options?.id;
const i = table.findIndex(r => r.id === id);
if (i >= 0) table.splice(i, 1);
return { id };
},
// ── hook surface (for the record-lock hook) ──
registerHook(event: string, handler: (ctx: any) => any, options?: any) {
(hooks[event] ??= []).push({ handler, object: options?.object, packageId: options?.packageId });
},
unregisterHooksByPackage(packageId: string): number {
let n = 0;
for (const ev of Object.keys(hooks)) {
const before = hooks[ev].length;
hooks[ev] = hooks[ev].filter(h => h.packageId !== packageId);
n += before - hooks[ev].length;
}
return n;
},
async fire(event: string, ctx: any) {
for (const h of hooks[event] ?? []) {
if (h.object) {
const objs = Array.isArray(h.object) ? h.object : [h.object];
if (!objs.includes(ctx.object)) continue;
}
await h.handler(ctx);
}
},
};
}
const CTX = { userId: 'u1', tenantId: 't1', roles: [], permissions: [] } as any;
const SYS = { isSystem: true, roles: [], permissions: [] } as any;
function nodeConfig(approvers: string[], extra: Record<string, any> = {}) {
return {
approvers: approvers.map(v => ({ type: 'user' as const, value: v })),
behavior: 'first_response' as const,
lockRecord: true,
...extra,
};
}
function openInput(approvers: string[], extra: Record<string, any> = {}, configExtra: Record<string, any> = {}) {
return {
object: 'opportunity',
recordId: 'opp1',
runId: 'run_1',
nodeId: 'approve_step',
flowName: 'deal_approval',
config: nodeConfig(approvers, configExtra),
record: { id: 'opp1', amount: 100 },
...extra,
};
}
describe('ApprovalService (node era)', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: ApprovalService;
let n = 0;
const baseTime = new Date('2026-01-15T10:00:00Z').getTime();
beforeEach(() => {
engine = makeFakeEngine();
n = 0;
svc = new ApprovalService({
engine: engine as any,
clock: { now: () => new Date(baseTime + (n++) * 1000) },
});
});
// ── openNodeRequest ─────────────────────────────────────────────
it('openNodeRequest: creates a pending request + submit action with flow correlation', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
expect(req.status).toBe('pending');
expect(req.process_name).toBe('flow:deal_approval');
expect(req.flow_run_id).toBe('run_1');
expect(req.flow_node_id).toBe('approve_step');
expect(req.pending_approvers).toEqual(['u9']);
expect(engine._tables['sys_approval_request']).toHaveLength(1);
expect(engine._tables['sys_approval_action'][0].action).toBe('submit');
});
it('openNodeRequest: snapshots the node config on the row', async () => {
await svc.openNodeRequest(openInput(['u9']), CTX);
const raw = engine._tables['sys_approval_request'][0];
expect(JSON.parse(raw.node_config_json)).toMatchObject({ behavior: 'first_response', lockRecord: true });
});
it('openNodeRequest: deduplicates a pending request per (object, record)', async () => {
await svc.openNodeRequest(openInput(['u9']), CTX);
await expect(svc.openNodeRequest(openInput(['u9'], { runId: 'run_2' }), CTX))
.rejects.toThrow(/DUPLICATE_REQUEST/);
});
it('openNodeRequest: requires object, recordId, runId', async () => {
await expect(svc.openNodeRequest(openInput(['u9'], { object: '' }), CTX)).rejects.toThrow(/VALIDATION_FAILED/);
await expect(svc.openNodeRequest(openInput(['u9'], { recordId: '' }), CTX)).rejects.toThrow(/VALIDATION_FAILED/);
await expect(svc.openNodeRequest(openInput(['u9'], { runId: '' }), CTX)).rejects.toThrow(/VALIDATION_FAILED/);
});
it('openNodeRequest: mirrors status onto the business record when configured', async () => {
engine._tables['opportunity'] = [{ id: 'opp1', amount: 100 }];
await svc.openNodeRequest(openInput(['u9'], {}, { approvalStatusField: 'approval_status' }), CTX);
expect(engine._tables['opportunity'][0].approval_status).toBe('pending');
});
// ── decideNode ──────────────────────────────────────────────────
it('decideNode: first_response approve finalizes immediately', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const out = await svc.decideNode(req.id, { decision: 'approve', actorId: 'u9' }, SYS);
expect(out.finalized).toBe(true);
expect(out.decision).toBe('approve');
expect(out.runId).toBe('run_1');
expect(out.nodeId).toBe('approve_step');
expect(out.request.status).toBe('approved');
});
it('decideNode: reject finalizes as rejected', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const out = await svc.decideNode(req.id, { decision: 'reject', actorId: 'u9', comment: 'no' }, SYS);
expect(out.finalized).toBe(true);
expect(out.request.status).toBe('rejected');
});
it('decideNode: unanimous holds until every approver acts', async () => {
const req = await svc.openNodeRequest(openInput(['u1', 'u2'], {}, { behavior: 'unanimous' }), CTX);
const first = await svc.decideNode(req.id, { decision: 'approve', actorId: 'u1' }, SYS);
expect(first.finalized).toBe(false);
expect(first.request.pending_approvers).toEqual(['u2']);
const second = await svc.decideNode(req.id, { decision: 'approve', actorId: 'u2' }, SYS);
expect(second.finalized).toBe(true);
expect(second.request.status).toBe('approved');
});
it('decideNode: blocks a non-approver in a non-system context', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await expect(
svc.decideNode(req.id, { decision: 'approve', actorId: 'mallory' }, { isSystem: false, roles: [], permissions: [] } as any),
).rejects.toThrow(/FORBIDDEN/);
});
it('decideNode: rejects a decision on a non-pending request', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await svc.decideNode(req.id, { decision: 'approve', actorId: 'u9' }, SYS);
await expect(svc.decideNode(req.id, { decision: 'approve', actorId: 'u9' }, SYS)).rejects.toThrow(/INVALID_STATE/);
});
it('decideNode: mirrors the terminal status onto the business record', async () => {
engine._tables['opportunity'] = [{ id: 'opp1', amount: 100 }];
const req = await svc.openNodeRequest(openInput(['u9'], {}, { approvalStatusField: 'approval_status' }), CTX);
await svc.decideNode(req.id, { decision: 'approve', actorId: 'u9' }, SYS);
expect(engine._tables['opportunity'][0].approval_status).toBe('approved');
});
// ── decide(): public contract + resume bridge ───────────────────
it('decide: resumes the owning run down the matching branch on finalize', async () => {
const resumed: any[] = [];
svc.attachAutomation({ async resume(runId, signal) { resumed.push({ runId, signal }); } });
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const out = await svc.decide(req.id, { decision: 'approve', actorId: 'u9' }, SYS);
expect(out.finalized).toBe(true);
expect(out.resumed).toBe(true);
expect(out.runId).toBe('run_1');
expect(resumed).toHaveLength(1);
expect(resumed[0]).toMatchObject({ runId: 'run_1', signal: { branchLabel: 'approve' } });
});
it('decide: does not resume while a unanimous request is still pending', async () => {
const resumed: any[] = [];
svc.attachAutomation({ async resume(runId) { resumed.push(runId); } });
const req = await svc.openNodeRequest(openInput(['u1', 'u2'], {}, { behavior: 'unanimous' }), CTX);
const out = await svc.decide(req.id, { decision: 'approve', actorId: 'u1' }, SYS);
expect(out.finalized).toBe(false);
expect(out.resumed).toBe(false);
expect(resumed).toHaveLength(0);
});
it('decide: finalizes even when no automation is attached (resumed=false)', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const out = await svc.decide(req.id, { decision: 'reject', actorId: 'u9' }, SYS);
expect(out.finalized).toBe(true);
expect(out.resumed).toBe(false);
});
// ── read API ────────────────────────────────────────────────────
it('listRequests: filters by approver and status', async () => {
await svc.openNodeRequest(openInput(['u9']), CTX);
const pending = await svc.listRequests({ status: 'pending', approverId: 'u9' }, SYS);
expect(pending).toHaveLength(1);
const none = await svc.listRequests({ approverId: 'nobody' }, SYS);
expect(none).toHaveLength(0);
});
it('listRequests: approverId accepts a list and matches ANY identity', async () => {
await svc.openNodeRequest(openInput(['u9']), CTX);
// None of these identities individually except the last is the approver.
const hit = await svc.listRequests(
{ status: 'pending', approverId: ['someone-else', 'user@example.com', 'u9'] },
SYS,
);
expect(hit).toHaveLength(1);
// A list with no matching identity returns nothing.
const miss = await svc.listRequests({ approverId: ['a', 'b', 'role:viewer'] }, SYS);
expect(miss).toHaveLength(0);
// Empty / whitespace-only ids are ignored, not treated as a match-all.
const ignored = await svc.listRequests({ approverId: ['', ' '] }, SYS);
expect(ignored).toHaveLength(1);
});
it('listActions: returns the audit trail for a request', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await svc.decideNode(req.id, { decision: 'approve', actorId: 'u9' }, SYS);
const actions = await svc.listActions(req.id, SYS);
expect(actions.map(a => a.action)).toEqual(['submit', 'approve']);
});
it('getRequest: returns null for an unknown id', async () => {
expect(await svc.getRequest('nope', SYS)).toBeNull();
});
// ── recall ──────────────────────────────────────────────────────
it('recall: submitter withdraws a pending request', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const out = await svc.recall(req.id, { actorId: 'u1', comment: 'changed my mind' }, CTX);
expect(out.request.status).toBe('recalled');
expect(out.request.completed_at).toBeTruthy();
expect(out.request.pending_approvers).toEqual([]);
const actions = await svc.listActions(req.id, SYS);
expect(actions.map(a => a.action)).toEqual(['submit', 'recall']);
expect(actions[1].comment).toBe('changed my mind');
});
it('recall: blocks a non-submitter in a non-system context', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await expect(svc.recall(req.id, { actorId: 'u9' }, { roles: [], permissions: [] } as any))
.rejects.toThrow(/FORBIDDEN/);
});
it('recall: rejects a recall on a non-pending request', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await svc.decideNode(req.id, { decision: 'approve', actorId: 'u9' }, SYS);
await expect(svc.recall(req.id, { actorId: 'u1' }, SYS)).rejects.toThrow(/INVALID_STATE/);
});
it('recall: resumes the owning run down the reject branch with decision=recall', async () => {
const resumed: any[] = [];
svc.attachAutomation({ async resume(runId, signal) { resumed.push({ runId, signal }); } });
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const out = await svc.recall(req.id, { actorId: 'u1' }, CTX);
expect(out.resumed).toBe(true);
expect(resumed[0]).toMatchObject({
runId: 'run_1',
signal: { branchLabel: 'reject', output: { decision: 'recall' } },
});
});
it('recall: mirrors `recalled` onto the business record when configured', async () => {
engine._tables['opportunity'] = [{ id: 'opp1', amount: 100 }];
const req = await svc.openNodeRequest(openInput(['u9'], {}, { approvalStatusField: 'approval_status' }), CTX);
await svc.recall(req.id, { actorId: 'u1' }, CTX);
expect(engine._tables['opportunity'][0].approval_status).toBe('recalled');
});
// ── inbox display fields ────────────────────────────────────────
it('rows expose submitted_at as an alias of created_at', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
expect(req.submitted_at).toBeTruthy();
expect(req.submitted_at).toBe(req.created_at);
const listed = await svc.listRequests({ status: 'pending' }, SYS);
expect(listed[0].submitted_at).toBe(listed[0].created_at);
});
it('rows carry authored flow/node labels when provided', async () => {
const req = await svc.openNodeRequest(
openInput(['u9'], { flowLabel: 'Deal Approval', nodeLabel: 'Manager Review' }), CTX,
);
expect(req.process_label).toBe('Deal Approval');
expect(req.step_label).toBe('Manager Review');
});
it('rows fall back to prettified machine names when labels are absent', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
expect(req.process_label).toBe('Deal Approval'); // from `flow:deal_approval`
expect(req.step_label).toBe('Approve Step'); // from `approve_step`
});
it('listRequests enriches record_title and submitter_name', async () => {
engine._tables['opportunity'] = [{ id: 'opp1', name: 'Acme Renewal', amount: 100 }];
engine._tables['sys_user'] = [{ id: 'u1', name: 'Ada Lovelace', email: 'ada@example.com' }];
await svc.openNodeRequest(openInput(['u9']), CTX); // submitter_id = u1 (CTX.userId)
const rows = await svc.listRequests({ status: 'pending' }, SYS);
expect(rows[0].record_title).toBe('Acme Renewal');
expect(rows[0].submitter_name).toBe('Ada Lovelace');
});
it('enrichment falls back to the payload snapshot when the record is gone', async () => {
await svc.openNodeRequest(
openInput(['u9'], { record: { id: 'opp1', name: 'Snapshot Title', amount: 1 } }), CTX,
);
const rows = await svc.listRequests({ status: 'pending' }, SYS);
expect(rows[0].record_title).toBe('Snapshot Title');
});
it('enrichment resolves lookup foreign keys in the payload to record titles', async () => {
(engine as any).getSchema = (name: string) =>
name === 'opportunity'
? { label: 'Opportunity', fields: { name: {}, account: { type: 'lookup', reference: 'account' } } }
: name === 'account' ? { label: 'Account', fields: { name: {} } } : undefined;
engine._tables['opportunity'] = [{ id: 'opp1', name: 'Acme Renewal', account: 'acc1' }];
engine._tables['account'] = [{ id: 'acc1', name: 'Acme Corp' }];
await svc.openNodeRequest(openInput(['u9'], { record: { id: 'opp1', name: 'Acme Renewal', account: 'acc1' } }), CTX);
const rows = await svc.listRequests({ status: 'pending' }, SYS);
expect(rows[0].object_label).toBe('Opportunity');
expect(rows[0].payload_display).toEqual({ account: 'Acme Corp' });
});
it('enrichment maps user-id approvers to display names', async () => {
engine._tables['sys_user'] = [{ id: 'u9', name: 'Grace Hopper', email: 'grace@example.com' }];
await svc.openNodeRequest(openInput(['u9']), CTX);
const rows = await svc.listRequests({ status: 'pending' }, SYS);
expect(rows[0].pending_approver_names).toEqual({ u9: 'Grace Hopper' });
});
it('listActions resolves actor display names', async () => {
engine._tables['sys_user'] = [
{ id: 'u1', name: 'Ada Lovelace', email: 'ada@example.com' },
{ id: 'u9', name: 'Grace Hopper', email: 'grace@example.com' },
];
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await svc.decideNode(req.id, { decision: 'approve', actorId: 'u9' }, SYS);
const actions = await svc.listActions(req.id, SYS);
expect(actions.map(a => (a as any).actor_name)).toEqual(['Ada Lovelace', 'Grace Hopper']);
});
// ── thread interactions ─────────────────────────────────────────
it('reassign: hands the slot to a new approver and audits the move', async () => {
const req = await svc.openNodeRequest(openInput(['u9', 'u2']), CTX);
const out = await svc.reassign(req.id, { actorId: 'u9', to: 'u7' }, CTX);
expect(out.request.pending_approvers).toEqual(['u7', 'u2']);
const actions = await svc.listActions(req.id, SYS);
expect(actions.at(-1)).toMatchObject({ action: 'reassign', actor_id: 'u9', comment: 'u9 → u7' });
});
it('reassign: notifies the new approver via messaging', async () => {
const emitted: any[] = [];
svc.attachMessaging({ async emit(input) { emitted.push(input); } });
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await svc.reassign(req.id, { actorId: 'u9', to: 'u7' }, CTX);
expect(emitted).toHaveLength(1);
expect(emitted[0]).toMatchObject({ topic: 'approval.reassigned', audience: ['u7'] });
});
it('reassign: blocks a non-holder and duplicate targets', async () => {
const req = await svc.openNodeRequest(openInput(['u9', 'u2']), CTX);
await expect(svc.reassign(req.id, { actorId: 'intruder', to: 'u7' }, CTX)).rejects.toThrow(/FORBIDDEN/);
await expect(svc.reassign(req.id, { actorId: 'u9', to: 'u2' }, CTX)).rejects.toThrow(/VALIDATION_FAILED/);
});
it('remind: notifies pending approvers, audits, and throttles repeats', async () => {
const emitted: any[] = [];
svc.attachMessaging({ async emit(input) { emitted.push(input); } });
const req = await svc.openNodeRequest(openInput(['u9', 'u2']), CTX);
const out = await svc.remind(req.id, { actorId: 'u1' }, CTX); // u1 = submitter (CTX.userId)
expect(out.notified).toBe(2);
expect(emitted[0]).toMatchObject({ topic: 'approval.reminder', audience: ['u9', 'u2'] });
const actions = await svc.listActions(req.id, SYS);
expect(actions.at(-1)?.action).toBe('remind');
// The fake clock steps 1s per call — well inside the 4h cool-down.
await expect(svc.remind(req.id, { actorId: 'u1' }, CTX)).rejects.toThrow(/THROTTLED/);
});
it('remind: only the submitter may nudge', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await expect(svc.remind(req.id, { actorId: 'u9' }, { roles: [], permissions: [] } as any))
.rejects.toThrow(/FORBIDDEN/);
});
it('requestInfo: keeps the request pending and notifies the submitter', async () => {
const emitted: any[] = [];
svc.attachMessaging({ async emit(input) { emitted.push(input); } });
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const out = await svc.requestInfo(req.id, { actorId: 'u9', comment: 'Need the Q3 numbers' }, CTX);
expect(out.request.status).toBe('pending');
expect(out.request.pending_approvers).toEqual(['u9']);
expect(emitted[0]).toMatchObject({ topic: 'approval.request_info', audience: ['u1'] });
const actions = await svc.listActions(req.id, SYS);
expect(actions.at(-1)).toMatchObject({ action: 'request_info', comment: 'Need the Q3 numbers' });
});
it('comment: submitter and approver may reply; outsiders may not', async () => {
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
await svc.comment(req.id, { actorId: 'u1', comment: 'Numbers attached.' }, CTX);
await svc.comment(req.id, { actorId: 'u9', comment: 'Thanks, reviewing.' }, CTX);
await expect(svc.comment(req.id, { actorId: 'outsider', comment: 'hi' }, { roles: [], permissions: [] } as any))
.rejects.toThrow(/FORBIDDEN/);
const actions = await svc.listActions(req.id, SYS);
expect(actions.filter(a => a.action === 'comment')).toHaveLength(2);
});
// ── SLA escalation (ADR-0042) ───────────────────────────────────
function makeOverdue(reqId: string) {
// Push created_at into the past so a small timeoutHours is breached.
const row = engine._tables['sys_approval_request'].find(r => r.id === reqId)!;
row.created_at = new Date(baseTime - 10 * 3600_000).toISOString();
}
it('runEscalations: notify action messages approvers + escalateTo + submitter, once', async () => {
const emitted: any[] = [];
svc.attachMessaging({ async emit(input) { emitted.push(input); } });
const req = await svc.openNodeRequest(
openInput(['u9'], {}, { escalation: { timeoutHours: 2, action: 'notify', escalateTo: 'boss', notifySubmitter: true } }), CTX,
);
makeOverdue(req.id);
const first = await svc.runEscalations();
expect(first.escalated).toBe(1);
expect(emitted.map(e => e.topic)).toEqual(['approval.sla_breached', 'approval.sla_breached']);
expect(emitted[0].audience).toEqual(['u9', 'boss']);
expect(emitted[1].audience).toEqual(['u1']); // submitter
const actions = await svc.listActions(req.id, SYS);
expect(actions.at(-1)).toMatchObject({ action: 'escalate', actor_id: 'system:sla', comment: 'notify → boss' });
// Single-shot: second sweep is a no-op.
const second = await svc.runEscalations();
expect(second.escalated).toBe(0);
expect(emitted).toHaveLength(2);
});
it('runEscalations: auto_approve decides as system:sla and resumes the flow', async () => {
const resumed: any[] = [];
svc.attachAutomation({ async resume(runId, signal) { resumed.push({ runId, signal }); } });
const req = await svc.openNodeRequest(
openInput(['u9'], {}, { escalation: { timeoutHours: 1, action: 'auto_approve', notifySubmitter: false } }), CTX,
);
makeOverdue(req.id);
const out = await svc.runEscalations();
expect(out.escalated).toBe(1);
const fresh = await svc.getRequest(req.id, SYS);
expect(fresh?.status).toBe('approved');
expect(resumed[0]).toMatchObject({ runId: 'run_1', signal: { branchLabel: 'approve' } });
const actions = await svc.listActions(req.id, SYS);
expect(actions.map(a => a.action)).toEqual(['submit', 'escalate', 'approve']);
expect(actions.at(-1)?.actor_id).toBe('system:sla');
});
it('runEscalations: auto_reject decides as system:sla', async () => {
const req = await svc.openNodeRequest(
openInput(['u9'], {}, { escalation: { timeoutHours: 1, action: 'auto_reject', notifySubmitter: false } }), CTX,
);
makeOverdue(req.id);
await svc.runEscalations();
const fresh = await svc.getRequest(req.id, SYS);
expect(fresh?.status).toBe('rejected');
});
it('runEscalations: reassign replaces the approver set with escalateTo', async () => {
const req = await svc.openNodeRequest(
openInput(['u9', 'u2'], {}, { escalation: { timeoutHours: 1, action: 'reassign', escalateTo: 'boss', notifySubmitter: false } }), CTX,
);
makeOverdue(req.id);
await svc.runEscalations();
const fresh = await svc.getRequest(req.id, SYS);
expect(fresh?.status).toBe('pending');
expect(fresh?.pending_approvers).toEqual(['boss']);
});
it('runEscalations: skips requests that are not yet due or have no SLA', async () => {
await svc.openNodeRequest(
openInput(['u9'], {}, { escalation: { timeoutHours: 1000, action: 'auto_approve' } }), CTX,
);
await svc.openNodeRequest(openInput(['u9'], { recordId: 'opp2', record: { id: 'opp2' } }), CTX);
const out = await svc.runEscalations();
expect(out.scanned).toBe(2);
expect(out.escalated).toBe(0);
});
// ── SLA + flow steps ────────────────────────────────────────────
it('rows expose sla_due_at when the node declares escalation.timeoutHours', async () => {
const req = await svc.openNodeRequest(
openInput(['u9'], {}, { escalation: { timeoutHours: 48, action: 'notify', notifySubmitter: true } }), CTX,
);
expect(req.sla_due_at).toBe(new Date(Date.parse(req.created_at!) + 48 * 3600_000).toISOString());
const noSla = await svc.openNodeRequest(openInput(['u9'], { recordId: 'opp2', record: { id: 'opp2' } }), CTX);
expect(noSla.sla_due_at).toBeUndefined();
});
it('getRequest attaches flow_steps from the owning flow graph', async () => {
svc.attachAutomation({
async getFlow(name: string) {
if (name !== 'deal_approval') return null;
return {
name: 'deal_approval',
nodes: [
{ id: 'start', type: 'start', label: 'Start' },
{ id: 'approve_step', type: 'approval', label: 'Manager Approval' },
{ id: 'gate', type: 'decision', label: 'Big?' },
{ id: 'exec_step', type: 'approval', label: 'Executive Approval' },
{ id: 'end', type: 'end', label: 'End' },
],
edges: [
{ id: 'e1', source: 'start', target: 'approve_step' },
{ id: 'e2', source: 'approve_step', target: 'gate', label: 'approve' },
{ id: 'e3', source: 'gate', target: 'exec_step', label: 'true' },
{ id: 'e4', source: 'exec_step', target: 'end', label: 'approve' },
],
};
},
});
const req = await svc.openNodeRequest(openInput(['u9']), CTX);
const fresh = await svc.getRequest(req.id, SYS);
expect(fresh?.flow_steps).toEqual([
{ id: 'approve_step', label: 'Manager Approval', state: 'current' },
{ id: 'exec_step', label: 'Executive Approval', state: 'upcoming' },
]);
});
it('enrichment resolves an email submitter via sys_user.email', async () => {
engine._tables['sys_user'] = [{ id: 'u7', name: 'Grace Hopper', email: 'grace@example.com' }];
await svc.openNodeRequest(openInput(['u9'], { submitterId: 'grace@example.com' }), CTX);
const rows = await svc.listRequests({ status: 'pending' }, SYS);
expect(rows[0].submitter_name).toBe('Grace Hopper');
});
});
describe('record-lock hook (node era)', () => {
let engine: ReturnType<typeof makeFakeEngine>;
let svc: ApprovalService;
let n = 0;
const baseTime = new Date('2026-01-15T10:00:00Z').getTime();
beforeEach(async () => {
engine = makeFakeEngine();
n = 0;
svc = new ApprovalService({ engine: engine as any, clock: { now: () => new Date(baseTime + (n++) * 1000) } });
bindApprovalLockHook(engine as any);
await svc.openNodeRequest(openInput(['u9'], {}, { approvalStatusField: 'approval_status' }), CTX);
});
it('blocks a user edit to a record with a pending approval', async () => {
await expect(
engine.fire('beforeUpdate', {
object: 'opportunity',
input: { id: 'opp1', data: { amount: 200 } },
session: { isSystem: false, roles: [], userId: 'u1' },
}),
).rejects.toThrow(/RECORD_LOCKED/);
});
it('allows a status-mirror write (only the approvalStatusField changes)', async () => {
await expect(
engine.fire('beforeUpdate', {
object: 'opportunity',
input: { id: 'opp1', data: { approval_status: 'approved' } },
session: { isSystem: false, roles: [] },
}),
).resolves.toBeUndefined();
});
it('allows engine self-writes (system session)', async () => {
await expect(
engine.fire('beforeUpdate', {
object: 'opportunity',
input: { id: 'opp1', data: { amount: 200 } },
session: { isSystem: true, roles: [] },
}),
).resolves.toBeUndefined();
});
it('allows an admin override', async () => {
await expect(
engine.fire('beforeUpdate', {
object: 'opportunity',
input: { id: 'opp1', data: { amount: 200 } },
session: { isSystem: false, roles: ['admin'] },
}),
).resolves.toBeUndefined();
});
it('does not lock records without a pending request', async () => {
await expect(
engine.fire('beforeUpdate', {
object: 'opportunity',
input: { id: 'other_record', data: { amount: 200 } },
session: { isSystem: false, roles: [] },
}),
).resolves.toBeUndefined();
});
it('unbindAllHooks removes the lock hook', () => {
expect(unbindAllHooks(engine as any)).toBe(1);
expect(engine._hooks['beforeUpdate']).toHaveLength(0);
});
});