Treasury & Bank Transfer Management System — سامانه مدیریت خزانهداری و حوالههای بانکی
dev/v7-production-failclosed-20261021
ci/public-windows-bridge-probe-20261017
ci/windows-dispatch-bootstrap-20261016
ci/windows-dual-app-lab-20261016
dev/v7-production-failclosed-20261021
feature/reconciliation-guard-20261013
main
phase-1-foundation
phase-1-implementation
phase-2-treasury-core
phase-3-banking-reconciliation
phase-4-operations-enterprise-ux
phase-5-hardening-release
phase-6-production-platform
phase-7-production-infrastructure-bank-golive
phase-7-sql-readonly-ux-20261015
transfer-exe-to-drive-20261006
| 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,LocalStoreData} 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 | /** Append audit into the same store transaction as its financial mutation. */ |
| 21 | private appendAuditTo(d:LocalStoreData,action:string,entity:string){ |
| 22 | d.audit.push({ |
| 23 | tenantId:this.actor.tenantId, |
| 24 | seq:d.audit.length+1, |
| 25 | actor:this.actor.userId, |
| 26 | action,entity,at:Date.now() |
| 27 | }); |
| 28 | } |
| 29 | |
| 30 | private appendAudit(action:string,entity:string){ |
| 31 | this.store.update(d=>{this.appendAuditTo(d,action,entity);return d;}); |
| 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 | this.appendAuditTo(d,'ACCOUNT_CREATED',account.id); |
| 60 | return d; |
| 61 | }); |
| 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 | this.appendAuditTo(d,'BENEFICIARY_CREATED',beneficiary.id); |
| 78 | return d; |
| 79 | }); |
| 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 | // Recheck all financial preconditions against the snapshot acquired *under* |
| 102 | // the store write transaction. Preflight reads above can race another |
| 103 | // desktop/process writer, particularly across multiple SQLite connections. |
| 104 | const accounts=d.accounts.filter(x=>x.tenantId===payment.tenantId); |
| 105 | const beneficiaries=d.beneficiaries.filter(x=>x.tenantId===payment.tenantId); |
| 106 | const prior=d.payments.filter(x=>x.tenantId===payment.tenantId); |
| 107 | if(!accounts.some(x=>x.id===payment.sourceAccountId))throw new Error('source account not found'); |
| 108 | const currentBeneficiary=beneficiaries.find(x=>x.id===payment.beneficiaryId); |
| 109 | if(!currentBeneficiary)throw new Error('beneficiary not found'); |
| 110 | const normalizedReference=payment.clientReference.toLowerCase(); |
| 111 | if(prior.some(x=>x.id===payment.id||x.clientReference.trim().toLowerCase()===normalizedReference)){ |
| 112 | throw new Error('duplicate payment reference'); |
| 113 | } |
| 114 | const currentGuard=evaluatePaymentGuard({ |
| 115 | sourceAccountId:payment.sourceAccountId, |
| 116 | beneficiaryId:payment.beneficiaryId, |
| 117 | iban:currentBeneficiary.iban, |
| 118 | amountIrr:payment.amountIrr, |
| 119 | clientReference:payment.clientReference, |
| 120 | paymentDate:payment.paymentDate |
| 121 | },prior.map(x=>({ |
| 122 | sourceAccountId:x.sourceAccountId,beneficiaryId:x.beneficiaryId, |
| 123 | iban:beneficiaries.find(b=>b.id===x.beneficiaryId)?.iban??'', |
| 124 | amountIrr:x.amountIrr,clientReference:x.clientReference,paymentDate:x.paymentDate |
| 125 | }))); |
| 126 | if(!currentGuard.ok)throw new Error(currentGuard.code==='DUPLICATE_PAYMENT' |
| 127 | ? 'duplicate payment' : currentGuard.code==='DUPLICATE_REFERENCE' |
| 128 | ? 'duplicate payment reference' : 'invalid Iranian IBAN'); |
| 129 | d.payments.push(payment); |
| 130 | this.appendAuditTo(d,'PAYMENT_CREATED',payment.id); |
| 131 | return d; |
| 132 | }); |
| 133 | return payment; |
| 134 | } |
| 135 | |
| 136 | submitPayment(id:string){ |
| 137 | const payment=this.getPayment(id); |
| 138 | if(payment.makerId!==this.actor.userId||payment.state!=='DRAFT') throw new Error('forbidden'); |
| 139 | const beneficiary=this.listBeneficiaries().find(x=>x.id===payment.beneficiaryId); |
| 140 | const settled=this.listPayments().filter(x=>x.paymentDate===payment.paymentDate&&x.state==='SETTLED').reduce((sum,x)=>sum+x.amountIrr,0); |
| 141 | const policy=evaluatePaymentPolicy({ |
| 142 | tenantId:payment.tenantId, |
| 143 | beneficiaryId:payment.beneficiaryId, |
| 144 | amountIrr:payment.amountIrr, |
| 145 | todayTotalIrr:settled, |
| 146 | transactionLimitIrr:Number.MAX_SAFE_INTEGER, |
| 147 | dailyLimitIrr:Number.MAX_SAFE_INTEGER, |
| 148 | whitelist:new Set(beneficiary?.whitelisted?[`${payment.tenantId}:${payment.beneficiaryId}`]:[]) |
| 149 | }); |
| 150 | if(!policy.allowed) throw new Error(policy.reason); |
| 151 | return this.changeState(id,transitionPayment(payment.state,'SUBMIT'),'PAYMENT_SUBMITTED',payment); |
| 152 | } |
| 153 | |
| 154 | approvePayment(id:string){ |
| 155 | if(this.actor.role!=='CHECKER')throw new Error('checker role required'); |
| 156 | const payment=this.getPayment(id); |
| 157 | if(!canApprove({actorId:this.actor.userId,makerId:payment.makerId},payment.version)) throw new Error('maker cannot approve own payment'); |
| 158 | if(payment.state!=='PENDING_APPROVAL') throw new Error('payment not pending approval'); |
| 159 | return this.store.update(d=>{ |
| 160 | const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id); |
| 161 | if(!row) throw new Error('payment not found'); |
| 162 | if(row.state!=='PENDING_APPROVAL'||row.version!==payment.version){ |
| 163 | throw new Error('payment not pending approval'); |
| 164 | } |
| 165 | if(!canApprove({actorId:this.actor.userId,makerId:row.makerId},row.version)){ |
| 166 | throw new Error('maker cannot approve own payment'); |
| 167 | } |
| 168 | row.state=transitionPayment(row.state,'APPROVE'); |
| 169 | row.approvedVersion=row.version; |
| 170 | d.audit.push({tenantId:this.actor.tenantId,seq:d.audit.length+1,actor:this.actor.userId,action:'PAYMENT_APPROVED',entity:id,at:Date.now()}); |
| 171 | return d; |
| 172 | }).payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id)!; |
| 173 | } |
| 174 | |
| 175 | private changeState(id:string,state:LocalPayment['state'],action:string,expected:LocalPayment){ |
| 176 | return this.store.update(d=>{ |
| 177 | const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id); |
| 178 | if(!row) throw new Error('payment not found'); |
| 179 | // A state transition from a preflight snapshot must not overwrite a |
| 180 | // concurrent approval, bank outcome or revised payment version. |
| 181 | if(row.state!==expected.state||row.version!==expected.version){ |
| 182 | throw new Error('stale payment state'); |
| 183 | } |
| 184 | if(action==='PAYMENT_SUBMITTED'&&row.makerId!==this.actor.userId)throw new Error('forbidden'); |
| 185 | if(action==='PAYMENT_QUEUED'&&row.approvedVersion!==row.version){ |
| 186 | throw new Error('payment not eligible for queue'); |
| 187 | } |
| 188 | row.state=state; |
| 189 | this.appendAuditTo(d,action,id); |
| 190 | return d; |
| 191 | }).payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id)!; |
| 192 | } |
| 193 | |
| 194 | queuePayment(id:string){ |
| 195 | if(this.actor.role!=='CHECKER'&&this.actor.role!=='TREASURY_ADMIN')throw new Error('checker or admin role required'); |
| 196 | const payment=this.getPayment(id); |
| 197 | if(payment.state!=='APPROVED'||payment.approvedVersion!==payment.version) throw new Error('payment not eligible for queue'); |
| 198 | return this.changeState(id,transitionPayment(payment.state,'QUEUE'),'PAYMENT_QUEUED',payment); |
| 199 | } |
| 200 | |
| 201 | async dispatchPayment(id:string,adapter:BankAdapter){ |
| 202 | if(this.actor.role!=='CHECKER'&&this.actor.role!=='TREASURY_ADMIN')throw new Error('checker or admin role required'); |
| 203 | // Reserve once in durable storage BEFORE any external bank request. |
| 204 | // The QUEUED -> DISPATCHING transition is atomic across SQLite writers. |
| 205 | // A crash at any point leaves DISPATCHING/UNKNOWN for manual reconciliation; |
| 206 | // neither state is eligible for automatic re-dispatch. |
| 207 | const reserved=this.store.update(d=>{ |
| 208 | const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id); |
| 209 | if(!row||row.state!=='QUEUED'||row.approvedVersion!==row.version){ |
| 210 | throw new Error('payment not eligible for dispatch'); |
| 211 | } |
| 212 | row.state=transitionPayment(row.state,'BEGIN_DISPATCH'); |
| 213 | this.appendAuditTo(d,'PAYMENT_DISPATCH_RESERVED',id); |
| 214 | return d; |
| 215 | }).payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id)!; |
| 216 | const registry=new BankDispatchRegistry(); |
| 217 | const dispatch=registry.begin({tenantId:reserved.tenantId,paymentId:reserved.id,version:reserved.version}); |
| 218 | let result:Awaited<ReturnType<BankAdapter['submit']>>; |
| 219 | try{ |
| 220 | result=await adapter.submit({tenantId:reserved.tenantId,paymentId:reserved.id, |
| 221 | version:reserved.version,idempotencyKey:dispatch.idempotencyKey}); |
| 222 | registry.record(dispatch.idempotencyKey,result.outcome); |
| 223 | }catch{ |
| 224 | // The bank might have accepted the request before the transport failed. |
| 225 | // Conservatively mark UNKNOWN rather than rolling back to QUEUED. |
| 226 | this.store.update(d=>{ |
| 227 | const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id); |
| 228 | if(!row)throw new Error('payment not found'); |
| 229 | if(row.state==='DISPATCHING'&&row.version===reserved.version){ |
| 230 | row.state=transitionPayment(row.state,'UNKNOWN_RESULT'); |
| 231 | this.appendAuditTo(d,'PAYMENT_BANK_UNKNOWN',id); |
| 232 | } |
| 233 | return d; |
| 234 | }); |
| 235 | throw new Error('bank dispatch outcome unknown: manual review required'); |
| 236 | } |
| 237 | return this.store.update(d=>{ |
| 238 | const row=d.payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id); |
| 239 | if(!row||row.state!=='DISPATCHING'||row.version!==reserved.version){ |
| 240 | throw new Error('stale dispatch reservation: manual review required'); |
| 241 | } |
| 242 | row.state=transitionPayment(row.state,result.outcome==='REJECTED'?'FAIL' |
| 243 | :result.outcome==='UNKNOWN'?'UNKNOWN_RESULT':'DISPATCH'); |
| 244 | row.bankReference=result.bankReference; |
| 245 | this.appendAuditTo(d,'PAYMENT_BANK_'+result.outcome,id); |
| 246 | return d; |
| 247 | }).payments.find(x=>x.tenantId===this.actor.tenantId&&x.id===id)!; |
| 248 | } |
| 249 | |
| 250 | async pollPaymentStatus(id:string,adapter:BankAdapter){ |
| 251 | if(this.actor.role!=='CHECKER'&&this.actor.role!=='TREASURY_ADMIN')throw new Error('checker or admin role required'); |
| 252 | const payment=this.getPayment(id); |
| 253 | if(payment.state!=='SUBMITTED'||!payment.bankReference) throw new Error('payment not eligible for polling'); |
| 254 | const outcome=await adapter.poll(payment.bankReference); |
| 255 | if(outcome==='ACCEPTED'||outcome==='SUBMITTED'){ |
| 256 | this.appendAudit('PAYMENT_BANK_'+outcome,id); |
| 257 | return this.getPayment(id); |
| 258 | } |
| 259 | if(outcome==='REJECTED') return this.changeState(id,transitionPayment(payment.state,'FAIL'),'PAYMENT_BANK_REJECTED',payment); |
| 260 | return this.changeState(id,transitionPayment(payment.state,'UNKNOWN_RESULT'),'PAYMENT_BANK_UNKNOWN',payment); |
| 261 | } |
| 262 | |
| 263 | getDashboard(){return dashboard(this.actor.tenantId,this.listPayments())} |
| 264 | } |
| 265 |