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

1 import {createBankAccount,createBeneficiary} from '../../domain/core/master-data';
2 import {evaluatePaymentPolicy} from '../../domain/core/policy';
3 import {canApprove} from '../../domain/approvals/approval-policy';
4 import {transitionPayment} from '../../domain/payments/payment-state';
5 import {dashboard} from '../../domain/operations/dashboard';
6 import type {BankAdapter} from '../../domain/bank-adapter';
7 import {BankDispatchRegistry} from '../../domain/bank-adapter';
8 import {validateIranianIban} from '../../domain/iran/iban';
9 import {evaluatePaymentGuard} from '../../domain/payments/payment-guard';
10 import type {TreasuryStore} from './store';
11 import type {ActorContext,LocalAccount,LocalAudit,LocalBeneficiary,LocalPayment} from './types';
12
13 export class TreasuryService{
14 constructor(private readonly store:TreasuryStore,private readonly actor:ActorContext){}
15
16 private own<T extends {tenantId:string}>(rows:T[]){
17 return rows.filter(x=>x.tenantId===this.actor.tenantId);
18 }
19
20 private appendAudit(action:string,entity:string){
21 this.store.update(d=>{
22 d.audit.push({
23 tenantId:this.actor.tenantId,
24 seq:d.audit.length+1,
25 actor:this.actor.userId,
26 action,
27 entity,
28 at:Date.now()
29 });
30 return d;
31 });
32 }
33
34 listAccounts(){return this.own(this.store.snapshot().accounts)}
35 listBeneficiaries(){return this.own(this.store.snapshot().beneficiaries)}
36 listPayments(){return this.own(this.store.snapshot().payments)}
37 listAudit():LocalAudit[]{return this.own(this.store.snapshot().audit).sort((a,b)=>a.seq-b.seq)}
38
39 getPayment(id:string){
40 const p=this.listPayments().find(x=>x.id===id);
41 if(!p) throw new Error('payment not found');
42 return p;
43 }
44
45 createAccount(input:{id:string;name:string;iban:string;bankName:string}){
46 if(!input.name.trim()||!input.bankName.trim()) throw new Error('account fields required');
47 createBankAccount({tenantId:this.actor.tenantId,id:input.id,iban:input.iban});
48 const account:LocalAccount={
49 ...input,
50 name:input.name.trim(),
51 bankName:input.bankName.trim(),
52 iban:input.iban.replace(/\s/g,'').toUpperCase(),
53 tenantId:this.actor.tenantId,
54 status:'ACTIVE'
55 };
56 this.store.update(d=>{
57 if(d.accounts.some(x=>x.tenantId===account.tenantId&&x.id===account.id)) throw new Error('duplicate account');
58 d.accounts.push(account);
59 return d;
60 });
61 this.appendAudit('ACCOUNT_CREATED',account.id);
62 return account;
63 }
64
65 createBeneficiary(input:{id:string;name:string;iban:string;whitelisted:boolean}){
66 if(!validateIranianIban(input.iban)) throw new Error('invalid Iranian IBAN');
67 createBeneficiary({tenantId:this.actor.tenantId,id:input.id,name:input.name,accountTenantId:this.actor.tenantId});
68 const beneficiary:LocalBeneficiary={
69 ...input,
70 name:input.name.trim(),
71 iban:input.iban.replace(/\s/g,'').toUpperCase(),
72 tenantId:this.actor.tenantId
73 };
74 this.store.update(d=>{
75 if(d.beneficiaries.some(x=>x.tenantId===beneficiary.tenantId&&x.id===beneficiary.id)) throw new Error('duplicate beneficiary');
76 d.beneficiaries.push(beneficiary);
77 return d;
78 });
79 this.appendAudit('BENEFICIARY_CREATED',beneficiary.id);
80 return beneficiary;
81 }
82
83 createPayment(input:{id:string;sourceAccountId:string;beneficiaryId:string;amountIrr:number;paymentDate:string;clientReference:string;description:string}){
84 if(!Number.isSafeInteger(input.amountIrr)||input.amountIrr<=0) throw new Error('invalid amount');
85 if(!input.paymentDate||!input.clientReference.trim()) throw new Error('payment fields required');
86 if(!this.listAccounts().some(x=>x.id===input.sourceAccountId)) throw new Error('source account not found');
87 const beneficiary=this.listBeneficiaries().find(x=>x.id===input.beneficiaryId);
88 if(!beneficiary) throw new Error('beneficiary not found');
89 const guard=evaluatePaymentGuard({sourceAccountId:input.sourceAccountId,beneficiaryId:input.beneficiaryId,iban:beneficiary.iban,amountIrr:input.amountIrr,clientReference:input.clientReference,paymentDate:input.paymentDate},this.listPayments().map(p=>({sourceAccountId:p.sourceAccountId,beneficiaryId:p.beneficiaryId,iban:this.listBeneficiaries().find(b=>b.id===p.beneficiaryId)?.iban??'',amountIrr:p.amountIrr,clientReference:p.clientReference,paymentDate:p.paymentDate})));
90 if(!guard.ok) throw new Error(guard.code==='DUPLICATE_PAYMENT'?'duplicate payment':guard.code==='DUPLICATE_REFERENCE'?'duplicate payment reference':'invalid Iranian IBAN');
91 const payment:LocalPayment={
92 ...input,
93 clientReference:input.clientReference.trim(),
94 description:input.description.trim(),
95 tenantId:this.actor.tenantId,
96 makerId:this.actor.userId,
97 version:1,
98 state:'DRAFT'
99 };
100 this.store.update(d=>{
101 if(d.payments.some(x=>x.tenantId===payment.tenantId&&(x.id===payment.id||x.clientReference===payment.clientReference))) throw new Error('duplicate payment reference');
102 d.payments.push(payment);
103 return d;
104 });
105 this.appendAudit('PAYMENT_CREATED',payment.id);
106 return payment;
107 }
108
109 submitPayment(id:string){
110 const payment=this.getPayment(id);
111 if(payment.makerId!==this.actor.userId||payment.state!=='DRAFT') throw new Error('forbidden');
112 const beneficiary=this.listBeneficiaries().find(x=>x.id===payment.beneficiaryId);
113 const settled=this.listPayments().filter(x=>x.paymentDate===payment.paymentDate&&x.state==='SETTLED').reduce((sum,x)=>sum+x.amountIrr,0);
114 const policy=evaluatePaymentPolicy({
115 tenantId:payment.tenantId,
116 beneficiaryId:payment.beneficiaryId,
117 amountIrr:payment.amountIrr,
118 todayTotalIrr:settled,
119 transactionLimitIrr:Number.MAX_SAFE_INTEGER,
120 dailyLimitIrr:Number.MAX_SAFE_INTEGER,
121 whitelist:new Set(beneficiary?.whitelisted?[`${payment.tenantId}:${payment.beneficiaryId}`]:[])
122 });
123 if(!policy.allowed) throw new Error(policy.reason);
124 return this.changeState(id,transitionPayment(payment.state,'SUBMIT'),'PAYMENT_SUBMITTED');
125 }
126
127 approvePayment(id:string){
128 const payment=this.getPayment(id);
129 if(!canApprove({actorId:this.actor.userId,makerId:payment.makerId},payment.version)) throw new Error('maker cannot approve own payment');
130 if(payment.state!=='PENDING_APPROVAL') throw new Error('payment not pending approval');
131 return this.store.update(d=>{
132 const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id);
133 if(!row) throw new Error('payment not found');
134 row.state=transitionPayment(row.state,'APPROVE');
135 row.approvedVersion=row.version;
136 d.audit.push({tenantId:this.actor.tenantId,seq:d.audit.length+1,actor:this.actor.userId,action:'PAYMENT_APPROVED',entity:id,at:Date.now()});
137 return d;
138 }).payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id)!;
139 }
140
141 private changeState(id:string,state:LocalPayment['state'],action:string){
142 return this.store.update(d=>{
143 const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id);
144 if(!row) throw new Error('payment not found');
145 row.state=state;
146 d.audit.push({tenantId:this.actor.tenantId,seq:d.audit.length+1,actor:this.actor.userId,action,entity:id,at:Date.now()});
147 return d;
148 }).payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id)!;
149 }
150
151 queuePayment(id:string){
152 const payment=this.getPayment(id);
153 if(payment.state!=='APPROVED'||payment.approvedVersion!==payment.version) throw new Error('payment not eligible for queue');
154 return this.changeState(id,transitionPayment(payment.state,'QUEUE'),'PAYMENT_QUEUED');
155 }
156
157 async dispatchPayment(id:string,adapter:BankAdapter){
158 const payment=this.getPayment(id);
159 if(payment.state!=='QUEUED'||payment.approvedVersion!==payment.version) throw new Error('payment not eligible for dispatch');
160 const registry=new BankDispatchRegistry();
161 const dispatch=registry.begin({tenantId:payment.tenantId,paymentId:payment.id,version:payment.version});
162 const result=await adapter.submit({tenantId:payment.tenantId,paymentId:payment.id,version:payment.version,idempotencyKey:dispatch.idempotencyKey});
163 registry.record(dispatch.idempotencyKey,result.outcome);
164 return this.store.update(d=>{
165 const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id);
166 if(!row) throw new Error('payment not found');
167 row.state=transitionPayment(row.state,'DISPATCH');
168 row.bankReference=result.bankReference;
169 if(result.outcome==='REJECTED') row.state=transitionPayment(row.state,'FAIL');
170 else if(result.outcome==='UNKNOWN') row.state=transitionPayment(row.state,'UNKNOWN_RESULT');
171 d.audit.push({tenantId:this.actor.tenantId,seq:d.audit.length+1,actor:this.actor.userId,action:'PAYMENT_BANK_'+result.outcome,entity:id,at:Date.now()});
172 return d;
173 }).payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id)!;
174 }
175
176 async pollPaymentStatus(id:string,adapter:BankAdapter){
177 const payment=this.getPayment(id);
178 if(payment.state!=='SUBMITTED'||!payment.bankReference) throw new Error('payment not eligible for polling');
179 const outcome=await adapter.poll(payment.bankReference);
180 if(outcome==='ACCEPTED'||outcome==='SUBMITTED'){
181 this.appendAudit('PAYMENT_BANK_'+outcome,id);
182 return this.getPayment(id);
183 }
184 if(outcome==='REJECTED') return this.changeState(id,transitionPayment(payment.state,'FAIL'),'PAYMENT_BANK_REJECTED');
185 return this.changeState(id,transitionPayment(payment.state,'UNKNOWN_RESULT'),'PAYMENT_BANK_UNKNOWN');
186 }
187
188 getDashboard(){return dashboard(this.actor.tenantId,this.listPayments())}
189 }
190