Repository navigation
Expand file tree
/
Copy pathexclude-submitter.integration.test.ts
More file actions
569 lines (522 loc) · 32.3 KB
/
Copy pathexclude-submitter.integration.test.ts
File metadata and controls
569 lines (522 loc) · 32.3 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
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#25573] An approval node's `excludeSubmitter: true` keeps the request's
* submitter from approving it (ruling 6377888641, letter B).
*
* ## The defect
*
* A two-level admission approval routed step 1 to a `field` approver (the
* category manager on the record) and step 2 to a `position`. When the
* category manager submitted the admission themselves, step 1 resolved to the
* submitter and they approved their own request. The spec carries the step
* option `excludeSubmitter` (#25609) and refuses it beside
* `onEmptyApprovers: 'auto_approve'` (#25635, letter A); this is the runtime
* that honours it.
*
* ## What this pins
*
* Driven through the real `ApprovalService` on a real `ObjectQL` over
* `SqlDriver` (better-sqlite3, in-memory, real DDL), with the real
* administrator resolution reading a bound security catalog:
*
* - the submitter is off the slate on a `field` step and on a `position` step,
* and the emptied slate takes the node's `onEmptyApprovers` route (the
* administrators by default, the declared `fallbackApprovers`, or the `fail`
* refusal), never the submitter;
* - a slate minus the submitter keeps everyone else, per_group tags included;
* - the email slot and an out-of-office hop that lands on the submitter are
* the submitter too;
* - the fallback slate and the administrators' slate are screened the same
* way, and an organization whose only administrator is the submitter gets
* the slate that names no one;
* - the request records the route on its timeline, as data the approvals door
* renders in the reader's language;
* - after the open: the decision refuses the submitter's approval (the
* privileged override included) and keeps their rejection; the reassign door
* refuses to hand the slot back to them; an SLA escalation leaves them off;
* - CONTROLS: the option off leaves every slate, timeline and decision as
* before; the option on with a slate that never named the submitter writes
* no note;
* - a request that opens on the slate naming no one says so on its timeline
* and tells its submitter, and the submitter's refused approval names the
* remedy — only when no one else is on the slate.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import {
bindSecurityCatalogReader, createMemoryI18n, type SecurityCatalogEntry, type SecurityCatalogReader,
} from '@objectstack/core';
import { ApprovalService } from './approval-service.js';
import { ApprovalsServicePlugin } from './approvals-plugin.js';
import { ApprovalsTranslations } from './translations/index.js';
import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js';
const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any;
const ORG = 'org_a';
/** An organization whose only administrator is the submitter. */
const SOLO_ORG = 'org_solo';
const as = (userId: string, org: string, permissions: string[] = []) =>
({ userId, tenantId: org, positions: [], permissions }) as any;
const SUB = as('u_sub', ORG);
const USERS = ['u_sub', 'u_owner', 'u_admin', 'u_alice', 'u_bob', 'u_fallback', 'u_dir', 'u_away']
.map((id) => ({ id, name: id, email: `${id}@example.com` }));
const MEMBERS: Array<[string, string, string]> = [
['u_sub', ORG, 'member'],
['u_owner', ORG, 'owner'],
['u_admin', ORG, 'admin'],
['u_alice', ORG, 'member'],
['u_bob', ORG, 'member'],
['u_fallback', ORG, 'member'],
['u_dir', ORG, 'member'],
['u_away', ORG, 'member'],
['u_sub', SOLO_ORG, 'owner'],
];
const GRANTS: Array<[string, string, string]> = [
['u_owner', 'organization_admin', ORG],
['u_admin', 'organization_admin_no_bypass', ORG],
['u_sub', 'organization_admin', SOLO_ORG],
];
/** `sys_user_position`: who holds which position, per organization. */
const POSITIONS: Array<[string, string, string]> = [
['u_sub', 'category_manager', ORG],
['u_sub', 'buyer', ORG],
['u_alice', 'buyer', ORG],
['u_dir', 'procurement_director', ORG],
['u_sub', 'treasury', ORG],
];
const text = (name: string) => ({ name, label: name, type: 'text' as const });
const objectDef = (name: string, fields: string[]) => ({
name,
label: name,
fields: Object.fromEntries([
['id', { ...text('id'), primaryKey: true }],
...fields.map((f) => [f, text(f)]),
]),
});
function catalogServing(names: string[]): SecurityCatalogReader {
const entry = (name: string): SecurityCatalogEntry => ({
type: 'permission', name, definition: { name }, source: 'registry',
});
return {
async resolve(type, name) {
return type === 'permission' && names.includes(name) ? entry(name) : undefined;
},
async list(type) {
return type === 'permission' ? names.map(entry) : [];
},
};
}
async function packageObjects(): Promise<any[]> {
let manifest: any;
const ctx: any = {
getService: (name: string) => {
if (name === 'manifest') return { register: (m: any) => { manifest = m; } };
throw new Error(`no service '${name}'`);
},
logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
};
await new ApprovalsServicePlugin().init(ctx);
return manifest.objects;
}
const ON = { excludeSubmitter: true };
const FIELD_STEP = [{ type: 'field', value: 'category_manager' }];
const POSITION_STEP = [{ type: 'position', value: 'category_manager' }];
describe('[#25573] excludeSubmitter keeps the submitter from approving their own request', () => {
let engine: ObjectQL;
let svc: ApprovalService;
let now = Date.parse('2026-10-24T09:00:00.000Z');
/** Open a step on a fresh admission whose category manager is `manager`. */
const open = async (
key: string, approvers: any[], extra: Record<string, unknown> = {},
{ org = ORG, manager = 'u_sub' }: { org?: string; manager?: string } = {},
): Promise<any> => {
const record = { id: `ADM_${key}`, title: key, category_manager: manager };
await engine.insert('srm_admission', record, { context: SYSTEM } as any);
return svc.openNodeRequest({
object: 'srm_admission', recordId: record.id, runId: `run_${key}`, nodeId: 'category_review',
flowName: 'admission', config: { approvers, behavior: 'first_response', ...extra } as any,
submitterId: 'u_sub', record, organizationId: org,
}, as('u_sub', org));
};
const actionsOf = async (requestId: string): Promise<any[]> => engine.find('sys_approval_action', {
where: { request_id: requestId }, context: SYSTEM,
});
const notesOf = async (requestId: string) =>
(await actionsOf(requestId)).filter((a) => a.action === 'comment' && !a.actor_id).map((a) => a.comment);
const snapshotOf = async (requestId: string) => {
const [row]: any[] = await engine.find('sys_approval_request', { where: { id: requestId }, context: SYSTEM });
return JSON.parse(row.node_config_json);
};
const EXCLUDED = "The request's submitter was removed from its approvers because this step sets excludeSubmitter";
const NO_ONE_ELSE = 'No one else can approve this request yet. An organization administrator must add a member '
+ 'who can approve it, then reassign the request to them.';
beforeAll(async () => {
engine = new ObjectQL();
engine.registerDriver(new SqlDriver({
client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true,
}), true);
await engine.init();
const defs = [
objectDef('sys_user', ['name', 'email']),
objectDef('sys_member', ['user_id', 'organization_id', 'role']),
objectDef('sys_user_position', ['user_id', 'position', 'organization_id']),
objectDef('sys_user_permission_set', ['user_id', 'permission_set', 'organization_id']),
objectDef('srm_admission', ['title', 'category_manager']),
...(await packageObjects()),
];
for (const def of defs) engine.registry.registerObject(def as any, 'approvals-test', 'approvals-test');
await engine.syncSchemas();
await relaxTenantColumns(engine, ['sys_user', 'srm_admission']);
bindSecurityCatalogReader(engine, catalogServing(['organization_admin', 'organization_admin_no_bypass']));
for (const u of USERS) await engine.insert('sys_user', u, { context: SYSTEM } as any);
for (const [i, [user_id, organization_id, role]] of MEMBERS.entries()) {
await engine.insert('sys_member', { id: `m_${i}`, user_id, organization_id, role }, { context: SYSTEM } as any);
}
for (const [i, [user_id, permission_set, organization_id]] of GRANTS.entries()) {
await engine.insert('sys_user_permission_set', { id: `ups_${i}`, user_id, permission_set, organization_id },
{ context: SYSTEM } as any);
}
for (const [i, [user_id, position, organization_id]] of POSITIONS.entries()) {
await engine.insert('sys_user_position', { id: `pos_${i}`, user_id, position, organization_id },
{ context: SYSTEM } as any);
}
svc = new ApprovalService({
engine: engine as any,
clock: { now: () => new Date(now += 1000) },
logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any,
});
});
afterAll(async () => {
try { await engine?.destroy(); } catch { /* noop */ }
});
describe('at the open', () => {
it('a field step that resolves to the submitter opens on the administrators, never on the submitter', async () => {
const row = await open('field', FIELD_STEP, ON);
expect([...row.pending_approvers].sort()).toEqual(['u_admin', 'u_owner']);
expect(await notesOf(row.id)).toEqual([
"Routed to this organization's administrators because the approver slate named no one: the only approver "
+ "it resolved to was the request's submitter, whom excludeSubmitter removes.",
`${EXCLUDED}; this organization's administrators decide it.`,
]);
});
it('a position step held only by the submitter opens on the declared fallbackApprovers', async () => {
const row = await open('position', POSITION_STEP, {
...ON, onEmptyApprovers: 'fallback', fallbackApprovers: [{ type: 'user', value: 'u_fallback' }],
});
expect(row.pending_approvers).toEqual(['u_fallback']);
expect(await notesOf(row.id)).toEqual([`${EXCLUDED}; the declared fallbackApprovers decide it.`]);
expect((await snapshotOf(row.id)).__submitterExclusionNote).toMatchObject({ route: 'fallback' });
});
it("onEmptyApprovers: 'fail' refuses, naming the exclusion", async () => {
await expect(open('fail', FIELD_STEP, { ...ON, onEmptyApprovers: 'fail' })).rejects.toThrow(
/^NO_APPROVERS: .* other than the request's submitter, whom the node's excludeSubmitter removes, /,
);
});
it('a slate minus the submitter keeps everyone else, and the per_group tally reads only them', async () => {
const row = await open('shared', [
{ type: 'position', value: 'buyer', group: 'buying' },
{ type: 'position', value: 'procurement_director', group: 'direction' },
], { ...ON, behavior: 'per_group' });
expect([...row.pending_approvers].sort()).toEqual(['u_alice', 'u_dir']);
expect((await snapshotOf(row.id)).__approverGroups).toEqual({ u_alice: ['buying'], u_dir: ['direction'] });
expect(await notesOf(row.id)).toEqual([`${EXCLUDED}; the remaining approvers decide it.`]);
});
it("the submitter's email slot and an out-of-office hop onto the submitter are the submitter too", async () => {
await engine.insert('sys_approval_delegation', {
id: 'dlg_away', delegator_id: 'u_away', delegate_id: 'u_sub', reason: 'leave', organization_id: ORG,
valid_from: '2026-09-01T00:00:00.000Z', valid_until: '2026-12-31T00:00:00.000Z',
created_at: '2026-09-01T00:00:00.000Z', updated_at: '2026-09-01T00:00:00.000Z',
}, { context: SYSTEM } as any);
const row = await open('addresses', [
{ type: 'user', value: 'u_sub@example.com' },
{ type: 'user', value: 'u_away' },
{ type: 'user', value: 'u_bob' },
], ON);
expect(row.pending_approvers).toEqual(['u_bob']);
});
it('the fallback slate is screened too: one naming only the submitter degrades to the administrators', async () => {
const row = await open('fallback_self', POSITION_STEP, {
...ON, onEmptyApprovers: 'fallback', fallbackApprovers: [{ type: 'position', value: 'treasury' }],
});
expect([...row.pending_approvers].sort()).toEqual(['u_admin', 'u_owner']);
expect((await snapshotOf(row.id)).__submitterExclusionNote).toMatchObject({ route: 'administrators' });
});
it('an organization whose only administrator is the submitter opens on the slate that names no one', async () => {
const row = await open('solo', FIELD_STEP, ON, { org: SOLO_ORG });
expect(row.pending_approvers).toEqual([]);
expect(await notesOf(row.id)).toEqual([`${EXCLUDED}, and no one else could take it.`, NO_ONE_ELSE]);
// …and the submitter, that organization's administrator, cannot take it
// through the override either.
await expect(svc.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any,
as('u_sub', SOLO_ORG, ['organization_admin']))).rejects.toThrow(/^FORBIDDEN: 'u_sub' submitted this request/);
});
it('the note is data the approvals door renders in the reader\'s language', async () => {
const i18n = createMemoryI18n();
for (const [locale, data] of Object.entries(ApprovalsTranslations)) {
i18n.loadTranslations(locale, data as Record<string, unknown>);
}
const reader = new ApprovalService({
engine: engine as any,
clock: { now: () => new Date(now += 1000) },
logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any,
i18nServiceSource: () => i18n,
});
const row = await open('zh', [{ type: 'position', value: 'buyer' }], ON);
const served = await reader.listActions(row.id, { ...SUB, locale: 'zh-CN' });
expect(served.filter((a) => a.action === 'comment' && !a.actor_id).map((a) => a.comment))
.toEqual(['本步骤设置了 excludeSubmitter,提交人已从审批人中移除;由其余审批人决定。']);
// A read, never a write.
expect(await notesOf(row.id)).toEqual([`${EXCLUDED}; the remaining approvers decide it.`]);
});
});
describe('after the open', () => {
it("the decision refuses the submitter's approval and keeps their rejection", async () => {
const row = await open('decide', [{ type: 'user', value: 'u_bob' }], ON);
// A slot in the submitter's hands, the way a later staffing puts it there.
await engine.update('sys_approval_request', { id: row.id, pending_approvers: 'u_sub,u_bob' },
{ context: SYSTEM } as any);
await expect(svc.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, SUB))
.rejects.toThrow(/^FORBIDDEN: 'u_sub' submitted this request, and its approval step sets excludeSubmitter/);
expect((await actionsOf(row.id)).map((a) => a.action)).toEqual(['submit']);
const out = await svc.decide(row.id, { decision: 'reject', comment: 'Over budget.', actorId: 'u_sub' } as any, SUB);
expect(out.request.status).toBe('rejected');
});
it('the reassign door refuses to hand the slot back to the submitter, by id or by a position only they hold', async () => {
const row = await open('reassign', [{ type: 'user', value: 'u_bob' }], ON);
const bob = as('u_bob', ORG);
for (const to of ['u_sub', 'u_sub@example.com', 'position:category_manager']) {
await expect(svc.reassign(row.id, { actorId: 'u_bob', to } as any, bob), to)
.rejects.toThrow(/^VALIDATION_FAILED: cannot reassign to .*the request's submitter, and this approval step sets excludeSubmitter/);
}
// A position the submitter shares hands the slot to the others.
const moved = await svc.reassign(row.id, { actorId: 'u_bob', to: 'position:buyer' } as any, bob);
expect(moved.request.pending_approvers).toEqual(['position:buyer']);
});
it('an SLA escalation leaves the submitter off the new slate, and one onto the submitter alone is not applied', async () => {
const overdue = async (row: any) => engine.update('sys_approval_request',
{ id: row.id, created_at: new Date(now - 10 * 3600_000).toISOString() }, { context: SYSTEM } as any);
const shared = await open('esc_shared', [{ type: 'user', value: 'u_bob' }], {
...ON, escalation: { timeoutHours: 1, action: 'reassign', escalateTo: 'buyer', notifySubmitter: false },
});
const alone = await open('esc_alone', [{ type: 'user', value: 'u_bob' }], {
...ON, escalation: { timeoutHours: 1, action: 'reassign', escalateTo: 'u_sub', notifySubmitter: false },
});
await overdue(shared);
await overdue(alone);
await svc.runEscalations();
expect((await svc.getRequest(shared.id, SYSTEM))?.pending_approvers).toEqual(['u_alice']);
expect((await svc.getRequest(alone.id, SYSTEM))?.pending_approvers).toEqual(['u_bob']);
expect((await actionsOf(alone.id)).find((a) => a.action === 'escalate')?.comment).toContain(
"not applied: the target is the request's submitter, whom the step's excludeSubmitter keeps off the slate",
);
});
});
describe('controls', () => {
it('the option off: the submitter stays on the slate, no note, and their approval stands', async () => {
const row = await open('off', FIELD_STEP);
expect(row.pending_approvers).toEqual(['u_sub']);
expect(await notesOf(row.id)).toEqual([]);
const out = await svc.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, SUB);
expect(out.request.status).toBe('approved');
});
it('the option on with a slate that never named the submitter: unchanged, and no note', async () => {
const row = await open('elsewhere', FIELD_STEP, ON, { manager: 'u_bob' });
expect(row.pending_approvers).toEqual(['u_bob']);
expect(await notesOf(row.id)).toEqual([]);
expect((await snapshotOf(row.id)).__submitterExclusionNote).toBeUndefined();
const out = await svc.decide(row.id, { decision: 'approve', actorId: 'u_bob' } as any, as('u_bob', ORG));
expect(out.request.status).toBe('approved');
});
it('the option off: the reassign door hands the slot to the submitter as before', async () => {
const row = await open('reassign_off', [{ type: 'user', value: 'u_bob' }]);
const moved = await svc.reassign(row.id, { actorId: 'u_bob', to: 'u_sub' } as any, as('u_bob', ORG));
expect(moved.request.pending_approvers).toEqual(['u_sub']);
});
});
// [Maintainer ruling 2026-11-17, option B] The administrator override is
// never the means by which its actor takes a slot on their own request. On
// the same real engine and directory: `u_sub` holds `category_manager` and
// `treasury` alone and shares `buyer` with `u_alice`; `procurement_director`
// is `u_dir`'s. The submitter acts here as an organization administrator.
describe('the override reassign and the submitter', () => {
const submitterAdmin = {
userId: 'u_sub', tenantId: ORG,
positions: ['category_manager', 'buyer', 'treasury'], permissions: ['organization_admin'],
} as any;
const otherAdmin = as('u_owner', ORG, ['organization_admin']);
const BY_SUBMITTER =
/^VALIDATION_FAILED: cannot reassign to '.+' — (it names the request's submitter|the request's submitter holds position '.+'), and a reassign the submitter makes through the administrator override/;
const slateOf = async (id: string) => (await svc.getRequest(id, SYSTEM))?.pending_approvers;
it('refuses every slot the submitter-administrator could take: their id, their email, a position only they hold, and a position they share', async () => {
const row = await open('own_override', [{ type: 'user', value: 'u_bob' }]);
for (const to of ['u_sub', 'u_sub@example.com', 'position:treasury', 'position:buyer']) {
await expect(svc.reassign(row.id, { actorId: 'u_sub', to } as any, submitterAdmin), to)
.rejects.toThrow(BY_SUBMITTER);
}
expect(await slateOf(row.id)).toEqual(['u_bob']);
expect((await actionsOf(row.id)).map((a) => a.action)).toEqual(['submit']);
});
it('refuses the shared position to the submitter-administrator with excludeSubmitter on too', async () => {
const row = await open('own_override_on', [{ type: 'user', value: 'u_bob' }], ON);
await expect(svc.reassign(row.id, { actorId: 'u_sub', to: 'position:buyer' } as any, submitterAdmin))
.rejects.toThrow(BY_SUBMITTER);
expect(await slateOf(row.id)).toEqual(['u_bob']);
});
it('refuses a different administrator\'s override reassign to a position only the submitter holds', async () => {
const row = await open('other_override_only', [{ type: 'user', value: 'u_bob' }]);
await expect(svc.reassign(row.id, { actorId: 'u_owner', to: 'position:treasury' } as any, otherAdmin))
.rejects.toThrow(/^VALIDATION_FAILED: cannot reassign to 'position:treasury' — the only holder of position 'treasury' in this request's organization is the request's submitter, and a reassign made through the administrator override/);
expect(await slateOf(row.id)).toEqual(['u_bob']);
});
it('CONTROL: a different administrator may override-reassign to a position the submitter shares with others', async () => {
const row = await open('other_override_shared', [{ type: 'user', value: 'u_bob' }]);
const moved = await svc.reassign(row.id, { actorId: 'u_owner', to: 'position:buyer' } as any, otherAdmin);
expect(moved.request.pending_approvers).toEqual(['position:buyer']);
});
it('CONTROL: the submitter-administrator may override-reassign to a position they do not hold', async () => {
const row = await open('own_override_elsewhere', [{ type: 'user', value: 'u_bob' }]);
const moved = await svc.reassign(row.id, { actorId: 'u_sub', to: 'position:procurement_director' } as any, submitterAdmin);
expect(moved.request.pending_approvers).toEqual(['position:procurement_director']);
});
});
// A request no one can decide tells its submitter so, and the refusal of the
// submitter's own approval names what to do instead of an approver who does
// not exist. The ruled outcome is unchanged: they still cannot approve it.
describe('a request no one but its submitter can decide names the remedy', () => {
const sent: any[] = [];
const soloAdmin = as('u_sub', SOLO_ORG, ['organization_admin']);
beforeAll(() => {
svc.attachMessaging({ emit: (async (input: any) => { sent.push(input); }) as any });
});
it('the slate that names no one: the timeline says so, the submitter is told, and the refusal names the remedy', async () => {
const row = await open('solo_told', FIELD_STEP, ON, { org: SOLO_ORG });
expect(row.pending_approvers).toEqual([]);
expect((await notesOf(row.id)).at(-1)).toBe(NO_ONE_ELSE);
const told = sent.filter((e) => e.source?.id === row.id);
expect(told.map((e) => [e.topic, e.audience, e.keyedText.titleKey, e.keyedText.bodyKey])).toEqual([
['approval.comment', ['u_sub'], 'messages.approvalNoApproverTitle', 'messages.approvalNoApprover'],
]);
expect(told[0].payload.body).toBe(NO_ONE_ELSE);
await expect(svc.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, soloAdmin)).rejects.toThrow(
"FORBIDDEN: 'u_sub' submitted this request, and its approval step sets excludeSubmitter, so they cannot "
+ `approve it. ${NO_ONE_ELSE}`,
);
});
it('the override refusal names the literal a member must hold, when only it is left on the slate', async () => {
const row = await open('solo_literal', FIELD_STEP, {}, { org: SOLO_ORG });
await engine.update('sys_approval_request', { id: row.id, pending_approvers: 'position:legal' },
{ context: SYSTEM } as any);
await expect(svc.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, soloAdmin)).rejects.toThrow(
"through the administrator override. No one else can approve this request yet. An organization "
+ "administrator must add a member who holds position 'legal'; that member can then decide it. To "
+ 'withdraw it instead, reject it or recall it.',
);
});
// [#36308] The refusal names the position as the timeline note does,
// through the same resolver: the decider's pack label, else the declared
// label, else the name (the pin above, on a service that knows no label).
// The sentence stays the English the note stores.
it('the refusal names a labelled position by the decider\'s pack label, else its declared label', async () => {
const i18n = createMemoryI18n();
for (const [locale, data] of Object.entries(ApprovalsTranslations)) {
i18n.loadTranslations(locale, data as Record<string, unknown>);
}
i18n.loadTranslations('zh-CN', { positions: { legal: { label: '法务' } } });
const labelled = new ApprovalService({
engine: engine as any,
clock: { now: () => new Date(now += 1000) },
logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any,
i18nServiceSource: () => i18n,
positionLabelSource: async (name) => (name === 'legal' ? 'Legal Counsel' : undefined),
});
const row = await open('solo_labelled', FIELD_STEP, {}, { org: SOLO_ORG });
await engine.update('sys_approval_request', { id: row.id, pending_approvers: 'position:legal,team:ops' },
{ context: SYSTEM } as any);
const remedy = (who: string) => 'No one else can approve this request yet. An organization administrator must '
+ `add a member who holds ${who}; that member can then decide it. To withdraw it instead, reject it or recall it.`;
await expect(labelled.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, { ...soloAdmin, locale: 'zh-CN' }))
.rejects.toThrow(remedy("position '法务', team 'ops'"));
await expect(labelled.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, { ...soloAdmin, locale: 'ja-JP' }))
.rejects.toThrow(remedy("position 'Legal Counsel', team 'ops'"));
await expect(labelled.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, soloAdmin))
.rejects.toThrow(remedy("position 'Legal Counsel', team 'ops'"));
});
// [#36463] The end user's half rides beside the English: the thrown
// error's `userMessage`, the same refusal in the decider's language (the
// REST door carries it to the wire). The `message` is the English above.
it('each refusal carries the decider\'s language as its userMessage, the message keeping its English', async () => {
const i18n = createMemoryI18n();
for (const [locale, data] of Object.entries(ApprovalsTranslations)) {
i18n.loadTranslations(locale, data as Record<string, unknown>);
}
i18n.loadTranslations('zh-CN', { positions: { legal: { label: '法务' } } });
const labelled = new ApprovalService({
engine: engine as any,
clock: { now: () => new Date(now += 1000) },
logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any,
i18nServiceSource: () => i18n,
positionLabelSource: async (name) => (name === 'legal' ? 'Legal Counsel' : undefined),
});
const refusalOf = (requestId: string, context: any): Promise<any> =>
labelled.decide(requestId, { decision: 'approve', actorId: 'u_sub' } as any, context).then(
() => { throw new Error('expected a refusal'); }, (err) => err);
const zhRemedy = '目前还没有其他人能审批此请求。组织管理员需要添加一名担任岗位「法务」、团队「ops」的成员,之后由该成员决定。';
const overridden = await open('solo_user_message', FIELD_STEP, {}, { org: SOLO_ORG });
await engine.update('sys_approval_request', { id: overridden.id, pending_approvers: 'position:legal,team:ops' },
{ context: SYSTEM } as any);
const zhOverride = await refusalOf(overridden.id, { ...soloAdmin, locale: 'zh-CN' });
expect(zhOverride.message).toBe("FORBIDDEN: 'u_sub' submitted this request and holds no slot on it, so they cannot "
+ 'approve it through the administrator override. No one else can approve this request yet. An organization '
+ "administrator must add a member who holds position '法务', team 'ops'; that member can then decide it. To "
+ 'withdraw it instead, reject it or recall it.');
expect(zhOverride.userMessage).toBe(`此请求由您提交,且您不在其审批人之列,因此不能以管理员身份代为批准它。${zhRemedy}如需撤销,请驳回或撤回该请求。`);
const excluded = await open('solo_user_message_excluded', FIELD_STEP, ON, { org: SOLO_ORG });
await engine.update('sys_approval_request', { id: excluded.id, pending_approvers: 'position:legal,team:ops' },
{ context: SYSTEM } as any);
expect((await refusalOf(excluded.id, { ...soloAdmin, locale: 'zh-CN' })).userMessage)
.toBe(`此请求由您提交,而其审批步骤不允许提交人批准自己的请求,因此您不能批准它。${zhRemedy}`);
// A decider who asked in no language reads the English, which names no id.
const plain = await refusalOf(overridden.id, soloAdmin);
expect(plain.userMessage).toBe('You submitted this request and hold no slot on it, so you cannot approve it '
+ 'through the administrator override. No one else can approve this request yet. An organization administrator '
+ "must add a member who holds position 'Legal Counsel', team 'ops'; that member can then decide it. To withdraw "
+ 'it instead, reject it or recall it.');
});
it('the excludeSubmitter refusal names a labelled position the same way', async () => {
const labelled = new ApprovalService({
engine: engine as any,
clock: { now: () => new Date(now += 1000) },
logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any,
positionLabelSource: async (name) => (name === 'legal' ? 'Legal Counsel' : undefined),
});
const row = await open('solo_excluded_labelled', FIELD_STEP, ON, { org: SOLO_ORG });
await engine.update('sys_approval_request', { id: row.id, pending_approvers: 'position:legal' },
{ context: SYSTEM } as any);
await expect(labelled.decide(row.id, { decision: 'approve', actorId: 'u_sub' } as any, soloAdmin)).rejects.toThrow(
"FORBIDDEN: 'u_sub' submitted this request, and its approval step sets excludeSubmitter, so they cannot "
+ 'approve it. No one else can approve this request yet. An organization administrator must add a member '
+ "who holds position 'Legal Counsel'; that member can then decide it.",
);
});
it('CONTROL: with another approver on the slate, both refusals keep naming that approver', async () => {
const excluded = await open('ctl_excluded', [{ type: 'user', value: 'u_bob' }], ON);
await engine.update('sys_approval_request', { id: excluded.id, pending_approvers: 'u_sub,u_bob' },
{ context: SYSTEM } as any);
await expect(svc.decide(excluded.id, { decision: 'approve', actorId: 'u_sub' } as any, SUB)).rejects.toThrow(
'so they cannot approve it. Another approver on the step decides it; if the submitter holds the only '
+ 'slot, reassign it to someone else.',
);
const overridden = await open('ctl_override', FIELD_STEP, {}, { org: SOLO_ORG });
await engine.update('sys_approval_request', { id: overridden.id, pending_approvers: 'u_bob' },
{ context: SYSTEM } as any);
await expect(svc.decide(overridden.id, { decision: 'approve', actorId: 'u_sub' } as any, soloAdmin))
.rejects.toThrow('through the administrator override. An approver on the step decides it. To move it');
// [#36463] …and the end user's half names that approver too (a service with no i18n reads the English).
await expect(svc.decide(excluded.id, { decision: 'approve', actorId: 'u_sub' } as any, SUB)).rejects.toMatchObject({
userMessage: 'You submitted this request, and its approval step keeps its submitter from approving it, so you '
+ 'cannot approve it. Another approver on the step decides it; if you hold the only slot, reassign it to someone else.',
});
expect(sent.filter((e) => e.source?.id === excluded.id && e.topic === 'approval.comment')).toEqual([]);
});
});
});