Treasury & Bank Transfer Management System — سامانه مدیریت خزانه‌داری و حواله‌های بانکی

1 import {afterEach,describe,expect,it,vi} from 'vitest';
2 import {mkdtempSync,rmSync} from 'node:fs';
3 import {tmpdir} from 'node:os';
4 import {join} from 'node:path';
5 import type {BankAdapter} from '../../domain/bank-adapter';
6 import type {TreasuryStore} from './store';
7 import {TreasuryService} from './treasury-service';
8 import {LocalStore} from '../local/local-store';
9 import {SqliteStore} from '../local/sqlite-store';
10
11 const paths:string[]=[];
12 const iban='IR062960000000100324200001';
13 afterEach(()=>{for(const p of paths.splice(0))rmSync(p,{recursive:true,force:true})});
14 const noopPoll=vi.fn();
15 function fixture(kind:'local'|'sqlite'){
16 const dir=mkdtempSync(join(tmpdir(),'tf-reserve-'));paths.push(dir);
17 const name=join(dir,kind==='local'?'ledger.json':'ledger.sqlite');
18 const store:TreasuryStore=kind==='local'?new LocalStore(name):new SqliteStore(name);
19 const maker=new TreasuryService(store,{tenantId:'local',userId:'maker',role:'MAKER'});
20 maker.createAccount({id:'a1',name:'source',iban,bankName:'synthetic'});
21 maker.createBeneficiary({id:'b1',name:'payee',iban,whitelisted:true});
22 maker.createPayment({id:'p1',sourceAccountId:'a1',beneficiaryId:'b1',
23 amountIrr:2000,paymentDate:'2026-10-23',clientReference:'RESERVED',description:''});
24 maker.submitPayment('p1');
25 const checker=new TreasuryService(store,{tenantId:'local',userId:'checker',role:'CHECKER'});
26 checker.approvePayment('p1');
27 checker.queuePayment('p1');
28 return {store,checker,name,close:()=>{if(store instanceof SqliteStore)store.close()}};
29 }
30 describe.each(['local','sqlite'] as const)('%s durable no-retry bank dispatch',kind=>{
31 it('reserves before the first bank call and blocks a simultaneous second send',async()=>{
32 const {store,checker,name,close}=fixture(kind);
33 let finish:(value:{outcome:'ACCEPTED';bankReference:string})=>void=()=>{};
34 const request=new Promise<{outcome:'ACCEPTED';bankReference:string}>(resolve=>{finish=resolve});
35 const adapter:BankAdapter={submit:vi.fn(()=>request),poll:noopPoll};
36 const initial=checker.dispatchPayment('p1',adapter);
37 expect(checker.getPayment('p1').state).toBe('DISPATCHING');
38 const readOnly=kind==='local'?new LocalStore(name):new SqliteStore(name);
39 const persisted=readOnly.snapshot().payments.find(p=>p.id==='p1');
40 expect(persisted?.state).toBe('DISPATCHING');
41 if(readOnly instanceof SqliteStore)readOnly.close();
42 await expect(checker.dispatchPayment('p1',adapter)).rejects.toThrow('payment not eligible for dispatch');
43 expect(adapter.submit).toHaveBeenCalledTimes(1);
44 finish({outcome:'ACCEPTED',bankReference:'SYNTH-TRACKING-1'});
45 const done=await initial;
46 expect(done.state).toBe('SUBMITTED');
47 expect(checker.listAudit().filter(x=>x.action==='PAYMENT_DISPATCH_RESERVED')).toHaveLength(1);
48 expect(checker.listAudit().filter(x=>x.action==='PAYMENT_BANK_ACCEPTED')).toHaveLength(1);
49 close();
50 });
51 it('marks transport exceptions UNKNOWN and never permits automatic retry',async()=>{
52 const {checker,close}=fixture(kind);
53 const adapter:BankAdapter={submit:vi.fn().mockRejectedValue(Error('synthetic timeout')),poll:noopPoll};
54 await expect(checker.dispatchPayment('p1',adapter)).rejects.toThrow(/manual review/i);
55 expect(checker.getPayment('p1').state).toBe('UNKNOWN');
56 await expect(checker.dispatchPayment('p1',adapter)).rejects.toThrow('payment not eligible for dispatch');
57 expect(adapter.submit).toHaveBeenCalledTimes(1);
58 expect(checker.listAudit().filter(x=>x.action==='PAYMENT_BANK_UNKNOWN')).toHaveLength(1);
59 close();
60 });
61 it('prevents any external submission if reservation cannot be stored',async()=>{
62 const {store,close}=fixture(kind);
63 const fault:TreasuryStore={snapshot:()=>store.snapshot(),update:()=>{throw Error('SYNTHETIC_DISK_FAILURE')}};
64 const checker=new TreasuryService(fault,{tenantId:'local',userId:'checker',role:'CHECKER'});
65 const adapter:BankAdapter={submit:vi.fn(),poll:noopPoll};
66 await expect(checker.dispatchPayment('p1',adapter)).rejects.toThrow('SYNTHETIC_DISK_FAILURE');
67 expect(adapter.submit).not.toHaveBeenCalled();
68 expect(store.snapshot().payments.find(p=>p.id==='p1')?.state).toBe('QUEUED');
69 close();
70 });
71 it('refuses automatic second submission after post-bank storage fails',async()=>{
72 const {store,close}=fixture(kind);
73 let updates=0;
74 const fault:TreasuryStore={
75 snapshot:()=>store.snapshot(),
76 update:mutate=>{
77 updates++;
78 if(updates===2)throw Error('SYNTHETIC_COMMIT_FAILURE');
79 return store.update(mutate);
80 }
81 };
82 const checker=new TreasuryService(fault,{tenantId:'local',userId:'checker',role:'CHECKER'});
83 const adapter:BankAdapter={submit:vi.fn().mockResolvedValue({outcome:'ACCEPTED',bankReference:'SYNTH-BR'}),poll:noopPoll};
84 await expect(checker.dispatchPayment('p1',adapter)).rejects.toThrow('SYNTHETIC_COMMIT_FAILURE');
85 expect(store.snapshot().payments.find(p=>p.id==='p1')?.state).toBe('DISPATCHING');
86 await expect(checker.dispatchPayment('p1',adapter)).rejects.toThrow('payment not eligible for dispatch');
87 expect(adapter.submit).toHaveBeenCalledTimes(1);
88 close();
89 });
90 });