import {createHash} from 'node:crypto';import {BankError} from './postbank-service.mjs';import {bankNumber,money,minorAmount} from './postbank-catalogue.mjs';import {canDebitAccount} from './postbank-authorisations.mjs';import {creditID,creditMovement,creditSchedule,dueMonth,currentPayoff,creditNotice,cents} from './postbank-credit-ledger.mjs'; const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),day=86400000; export class PostbankCreditEngine{ constructor(db,central,authority,{clock=Date.now,resolveUser=null}={}){this.db=db;this.central=central;this.authority=authority;this.clock=clock;this.resolveUser=resolveUser||(id=>central.prepare("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(id).first());} async lock(loanId,work){const meta=await this.db.first('SELECT client_number,entity_id FROM pb_credit_loans WHERE id=?',[loanId]);if(!meta)throw new BankError('Credit contract not found.',404);return this.db.transaction(async tx=>{await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[meta.entity_id]);await tx.first('SELECT client_number FROM pb_clients WHERE client_number=? FOR UPDATE',[meta.client_number]);const loan=await tx.first('SELECT * FROM pb_credit_loans WHERE id=? FOR UPDATE',[loanId]);return work(tx,loan);});} async accounts(tx,loan){const ids=[loan.account_id,...loan.collateral_account_id?[loan.collateral_account_id]:[]];const rows=await tx.query('SELECT * FROM pb_accounts WHERE system_key=? OR id IN ('+ids.map(()=>'?').join(',')+') ORDER BY id FOR UPDATE',['sys_web_treasury',...ids]);const bank=rows.find(a=>a.system_key==='sys_web_treasury'),current=rows.find(a=>String(a.id)===String(loan.account_id)),collateral=rows.find(a=>String(a.id)===String(loan.collateral_account_id));if(!bank||bank.state!=='active'||!current)throw new BankError('The lending treasury or borrower account is unavailable.',503);return {bank,current,collateral};} async event(tx,loan,requestId,actor,action,details,fingerprint=''){await tx.query('INSERT INTO pb_credit_events(request_id,loan_id,actor_id,action,fingerprint,details,created_at) VALUES(?,?,?,?,?,?,?)',[requestId,loan.id,actor,action,fingerprint||createHash('sha256').update(action+loan.id+requestId).digest('hex'),JSON.stringify(details),this.clock()]);await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[requestId,actor,action,loan.entity_id,JSON.stringify({loanId:loan.id,...details}),this.clock()]);} async replay(tx,input,user,fingerprint){const old=await tx.first('SELECT * FROM pb_credit_events WHERE request_id=?',[input.requestId]);if(!old)return false;if(old.actor_id!==user.id||old.fingerprint!==fingerprint)throw new BankError('This request reference was already used for a different instruction.',409);return true;} validate(input,actions){if(!input||!uuid(input.requestId)||!uuid(input.loanId)||!actions.includes(input.action)||input.confirmed!==true||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.length>500||/[\x00-\x1f]/.test(input.reason))throw new BankError('Confirm the credit action with a reason of 5–500 characters.');} async currentAuthority(user,loan,tx,{manage=false,borrow=false,pay=false}={}){const c=await this.authority(user,{bank:tx});if(manage&&!c.manageAdmin||borrow&&!c.entities.some(e=>e.id===loan.entity_id&&e.canActivate)||pay&&!canDebitAccount(c,loan.entity_id,loan.account_id))throw new BankError('Your authority for this credit action is not valid.',403);return c;} async releaseHolds(tx,loan,accounts){for(const [a,n]of [[accounts.bank,BigInt(loan.treasury_hold_minor||0)],[accounts.current,BigInt(loan.borrower_hold_minor||0)]]){if(n){if(BigInt(a.reserved_minor)user}={}){ this.validate(input,['approve','decline','withdraw']);if(Object.keys(input).some(k=>!['requestId','loanId','action','confirmed','reason','riskOverride'].includes(k)))throw new BankError('Unexpected credit action fields.');const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.loanId,input.action,input.reason,!!input.riskOverride])).digest('hex'); return this.lock(input.loanId,async(tx,loan)=>{const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.currentAuthority(fresh,loan,tx,input.action==='withdraw'?{borrow:true}:{manage:true});if(await this.replay(tx,input,user,fingerprint))return {ok:true,replayed:true}; if(input.action==='withdraw'){if(!['submitted','approved_pending','offered','payout_queued'].includes(loan.state))throw new BankError('This contract cannot be withdrawn.',409);await this.releaseHolds(tx,loan,await this.accounts(tx,loan));await tx.query("UPDATE pb_credit_loans SET state='withdrawn',updated_at=?,version=version+1 WHERE id=?",[this.clock(),loan.id]);if(loan.product_key.startsWith('grant_'))await tx.query('DELETE FROM pb_credit_grants WHERE loan_id=?',[loan.id]);} else{if(loan.state!=='submitted')throw new BankError('Only a submitted application can be reviewed.',409);if(user.id===loan.created_by||rights.entities.some(e=>e.id===loan.entity_id&&e.canActivate))throw new BankError('A different bank manager must review a client you control.',403);const score=JSON.parse(loan.score_json);if(input.action==='approve'&&(score.score<400||score.flags?.includes('High Monthly Commitments'))&&input.riskOverride!==true)throw new BankError('Review and explicitly confirm the risk override before approval.',409); const state=input.action==='decline'?'declined':'approved_pending';await tx.query('UPDATE pb_credit_loans SET state=?,reviewed_by=?,decision_reason=?,updated_at=?,version=version+1 WHERE id=?',[state,user.id,input.reason.trim(),this.clock(),loan.id]);loan.state=state;if(state==='approved_pending')await this.reserveOffer(tx,loan);await creditNotice(tx,loan,'decision:'+input.requestId,state==='declined'?'Credit application declined':loan.state==='offered'?'Credit offer ready':'Credit approved — awaiting bank liquidity',input.reason.trim(),this.clock());} await this.event(tx,loan,input.requestId,user.id,'credit_'+input.action,{reason:input.reason.trim(),riskOverride:!!input.riskOverride},fingerprint);return {ok:true,replayed:false}; }); } async accept(user,input,{revalidate=async()=>user}={}){ this.validate(input,['accept']);if(Object.keys(input).some(k=>!['requestId','loanId','action','confirmed','reason','expectedVersion'].includes(k))||!Number.isInteger(input.expectedVersion))throw new BankError('Refresh and accept the current offer.');const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.loanId,input.expectedVersion,'accept'])).digest('hex'); return this.lock(input.loanId,async(tx,loan)=>{const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.currentAuthority(fresh,loan,tx,{borrow:true});if(await this.replay(tx,input,user,fingerprint))return {ok:true,replayed:true};if(loan.state!=='offered'||Number(loan.version)!==input.expectedVersion||Number(loan.offer_expires_at)<=this.clock())throw new BankError('This offer changed or expired. Refresh before accepting.',409);if(loan.reviewed_by===user.id)throw new BankError('A different bank manager must approve your borrowing.',403);const a=await this.accounts(tx,loan),refinance=JSON.parse(loan.refinance_json||'[]'),carry=refinance.reduce((sum,l)=>sum+BigInt(l.collateralMinor||0),0n),required=BigInt(loan.first_instalment_minor||0)||(BigInt(loan.collateral_minor)>carry?BigInt(loan.collateral_minor)-carry:0n);if(a.current.state!=='active'||BigInt(a.current.balance_minor)-BigInt(a.current.reserved_minor){ if(loan.state!=='payout_queued'||Number(loan.queued_at)>cutoff)return false;const actor=await this.resolveUser(loan.accepted_by||loan.created_by),a=await this.accounts(tx,loan);let authorised=false;try{if(actor){await this.currentAuthority(actor,loan,tx,{borrow:true});authorised=true;}}catch{} if(!authorised||a.current.state!=='active'){await this.releaseHolds(tx,loan,a);await tx.query("UPDATE pb_credit_loans SET state='withdrawn',decision_reason='Borrowing authority expired before disbursement',updated_at=? WHERE id=?",[this.clock(),loan.id]);if(loan.product_key.startsWith('grant_'))await tx.query('DELETE FROM pb_credit_grants WHERE loan_id=?',[loan.id]);return false;} const refinanced=JSON.parse(loan.refinance_json||'[]');for(const r of refinanced){const old=await tx.first('SELECT * FROM pb_credit_loans WHERE id=? AND client_number=? FOR UPDATE',[r.id,loan.client_number]);const payoff=old&&await currentPayoff(tx,old,this.clock());if(!old||!['active','arrears'].includes(old.state)||payoff.total!==BigInt(r.payoffMinor)){await this.releaseHolds(tx,loan,a);await tx.query("UPDATE pb_credit_loans SET state='expired',decision_reason='Refinanced balances changed; request a new quotation',updated_at=? WHERE id=?",[this.clock(),loan.id]);return false;}} const now=this.clock(),collateral=BigInt(loan.collateral_minor),carry=refinanced.reduce((sum,r)=>sum+BigInt(r.collateralMinor||0),0n);if(collateral||carry)a.collateral=await this.collateralAccount(tx,loan); const firstInstalment=BigInt(loan.first_instalment_minor||0); if(firstInstalment){if(BigInt(loan.borrower_hold_minor||0)!==firstInstalment)throw new BankError('The first instalment must be reserved before this loan is issued.',409);await creditMovement(tx,{key:loan.id+':first-instalment',actor:actor.id,source:a.current,target:a.bank,amount:firstInstalment,reference:'First loan instalment · '+loan.id,now,held:true});} else if(BigInt(loan.borrower_hold_minor||0))await creditMovement(tx,{key:loan.id+':pledge',actor:actor.id,source:a.current,target:a.collateral,amount:BigInt(loan.borrower_hold_minor),reference:'Loan collateral · '+loan.id,now,held:true}); await creditMovement(tx,{key:loan.id+':payout',actor:actor.id,source:a.bank,target:a.current,amount:BigInt(loan.principal_minor),reference:'Credit disbursement · '+loan.id,now,held:true}); for(const r of refinanced){await creditMovement(tx,{key:loan.id+':refinance:'+r.id,actor:actor.id,source:a.current,target:a.bank,amount:BigInt(r.payoffMinor),reference:'Refinancing settlement · '+r.id,now});await tx.query("UPDATE pb_credit_loans SET state='refinanced',outstanding_minor=0,collateral_minor=0,replaced_by=?,updated_at=? WHERE id=?",[loan.id,now,r.id]);await tx.query("UPDATE pb_credit_instalments SET state='refinanced' WHERE loan_id=? AND state IN ('pending','late')",[r.id]);await this.event(tx,{...loan,id:r.id},creditID(loan.id+':replaces:'+r.id),actor.id,'credit_refinanced',{replacement:loan.id,settlement:money(r.payoffMinor)});} if(carry>collateral)await creditMovement(tx,{key:loan.id+':collateral-adjustment',actor:actor.id,source:a.collateral,target:a.current,amount:carry-collateral,reference:'Refinancing collateral adjustment · '+loan.id,now}); const quote=JSON.parse(loan.quote_json);if(quote.concession?.eventKey)await tx.query('INSERT INTO pb_credit_concessions(event_key,loan_id,created_at) VALUES(?,?,?)',[quote.concession.eventKey,loan.id,now]); const schedule=creditSchedule(BigInt(loan.principal_minor)-firstInstalment,Number(loan.annual_bps),Number(loan.months),loan.product_key.startsWith('grant_')?BigInt(loan.monthly_minor):null);for(const row of schedule)await tx.query("INSERT INTO pb_credit_instalments(loan_id,sequence_no,due_at,principal_minor,interest_minor,state,accrual_at,accrual_remaining_minor) VALUES(?,?,?,?,?,'pending',?,?)",[loan.id,row.number,dueMonth(now,row.number),String(row.principal),String(row.interest),dueMonth(now,row.number-1),String(row.interest)]); await tx.query("UPDATE pb_credit_loans SET state='active',outstanding_minor=principal_minor-first_instalment_minor,treasury_hold_minor=0,borrower_hold_minor=0,accepted_at=?,next_due_at=?,updated_at=?,version=version+1 WHERE id=?",[now,dueMonth(now,1),now,loan.id]);await this.event(tx,loan,creditID(loan.id+':disbursed'),actor.id,'credit_disbursed',{principal:money(loan.principal_minor),firstInstalment:money(firstInstalment),remainingPrincipal:money(BigInt(loan.principal_minor)-firstInstalment),collateral:money(collateral)});await creditNotice(tx,loan,'disbursed','Credit disbursed','Your credit is active. Principal '+money(loan.principal_minor)+' DM; first instalment '+money(firstInstalment)+' DM already paid; remaining principal '+money(BigInt(loan.principal_minor)-firstInstalment)+' DM; monthly repayment '+money(loan.monthly_minor)+' DM.',now);return true; });} async requestRepayment(user,input,{revalidate=async()=>user}={}){ this.validate(input,['repay','recover']);if(Object.keys(input).some(k=>!['requestId','loanId','action','confirmed','reason','amount'].includes(k)))throw new BankError('Unexpected repayment fields.');let amount;try{amount=minorAmount(input.amount);}catch(e){throw new BankError(e.message);}const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.loanId,input.action,String(amount),input.reason])).digest('hex'); return this.lock(input.loanId,async(tx,loan)=>{const old=await tx.first('SELECT * FROM pb_credit_actions WHERE id=?',[input.requestId]);if(old){if(old.actor_id!==user.id||old.fingerprint!==fingerprint)throw new BankError('This repayment reference was already used.',409);return {ok:true,replayed:true,state:old.state};}const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.currentAuthority(fresh,loan,tx,input.action==='recover'?{manage:true}:{pay:true});if(!['active','arrears'].includes(loan.state))throw new BankError('This contract is not active.',409);const a=await this.accounts(tx,loan),payoff=await currentPayoff(tx,loan,this.clock());const pending=await tx.first("SELECT COALESCE(SUM(amount_minor),0) total,COALESCE(SUM(CASE WHEN kind='recover' THEN amount_minor ELSE 0 END),0) recoveries FROM pb_credit_actions WHERE loan_id=? AND state='queued'",[loan.id]);if(amount+BigInt(pending.total)>payoff.total)throw new BankError('Maximum additional repayment: '+money(payoff.total>BigInt(pending.total)?payoff.total-BigInt(pending.total):0n)+' DM. Pending repayments or recoveries: '+money(pending.total)+' DM.',409);const source=input.action==='recover'?a.collateral:a.current;if(input.action==='recover'&&(loan.state!=='arrears'||amount+BigInt(pending.recoveries)>BigInt(loan.collateral_minor)||!source))throw new BankError('Recovery is limited to pledged DM on a contract in arrears.',409);if(!source||BigInt(source.balance_minor)-BigInt(source.reserved_minor)payoff.total)throw new BankError('The settlement balance changed.',409);await creditMovement(tx,{key,actor,source:recovery?a.collateral:a.current,target:a.bank,amount,reference:(recovery?'Collateral recovery':'Loan repayment')+' · '+loan.id,now,held});let remaining=amount,paidCapital=0n; for(const row of payoff.rows){const interest=BigInt(row.interest_minor)-BigInt(row.paid_interest),payInterest=remaining? AND state='pending' ORDER BY sequence_no",[loan.id,valuedAt]); const first=future[0],day=t=>Math.floor(Number(t)/86400000),periodStart=first?dueMonth(Number(loan.accepted_at),Number(first.sequence_no)-1):valuedAt,fraction=first?Math.max(0,Math.min(1,(day(first.due_at)-day(valuedAt))/Math.max(1,day(first.due_at)-day(periodStart)))):1; const revised=outstanding>0n&&future.length?creditSchedule(outstanding,Number(loan.annual_bps),future.length,loan.product_key.startsWith('grant_')?BigInt(loan.monthly_minor):null,{firstFraction:fraction}):[]; revisedMonthly=revised[0]?.amount||0n; for(let i=0;i{const current=await tx.first('SELECT * FROM pb_credit_actions WHERE id=? FOR UPDATE',[action.id]);if(!current||current.state!=='queued'||Number(current.created_at)>cutoff)return false;const prior=await tx.first("SELECT id FROM pb_credit_actions WHERE loan_id=? AND state='queued' AND (created_atBigInt(loan.collateral_minor))||!source||BigInt(source.reserved_minor)payoff.total){if(source&&BigInt(source.reserved_minor)>=amount)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[String(amount),source.id]);await tx.query("UPDATE pb_credit_actions SET state='rejected',processed_at=?,failure='Authority or settlement balance changed' WHERE id=?",[this.clock(),current.id]);return false;}await this.applyRepayment(tx,loan,a,amount,'action:'+current.id,actor.id,{recovery:current.kind==='recover',held:true,valueAt:Number(current.created_at)});await tx.query("UPDATE pb_credit_actions SET state='posted',processed_at=? WHERE id=?",[this.clock(),current.id]);return true;});} async automaticRepayment(loanId,cutoff){return this.lock(loanId,async(tx,loan)=>{if(!['active','arrears'].includes(loan.state)||!loan.next_due_at||Number(loan.next_due_at)>cutoff)return false;const a=await this.accounts(tx,loan),due=await tx.query("SELECT * FROM pb_credit_instalments WHERE loan_id=? AND due_at<=? AND state IN ('pending','late') ORDER BY sequence_no",[loan.id,cutoff]);if(!due.length)return false;const amount=due.reduce((sum,r)=>sum+BigInt(r.principal_minor)-BigInt(r.paid_principal)+BigInt(r.interest_minor)-BigInt(r.paid_interest),0n);if(amount<=0n)return false;if(a.current.state!=='active'||BigInt(a.current.balance_minor)-BigInt(a.current.reserved_minor)r.sequence_no).join('-'),loan.accepted_by||loan.created_by);return true;});} async process({cutoff=this.clock()}={}){ let offered=0,disbursed=0,repaid=0,expired=0,reminded=0,failed=0;const handle=async job=>{try{return await job();}catch{failed++;return false;}}; for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state='offered' AND offer_expires_at<=? ORDER BY offer_expires_at LIMIT 25",[cutoff]))await handle(()=>this.lock(row.id,async(tx,loan)=>{if(loan.state!=='offered'||Number(loan.offer_expires_at)>cutoff)return;await this.releaseHolds(tx,loan,await this.accounts(tx,loan));await tx.query("UPDATE pb_credit_loans SET state='expired',updated_at=? WHERE id=?",[this.clock(),loan.id]);expired++;})); for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state='approved_pending' AND updated_at<=? ORDER BY created_at LIMIT 25",[cutoff]))if(await handle(()=>this.lock(row.id,(tx,loan)=>loan.state==='approved_pending'?this.reserveOffer(tx,loan,cutoff):false)))offered++; for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state='payout_queued' AND queued_at<=? ORDER BY queued_at LIMIT 25",[cutoff]))if(await handle(()=>this.payout(row.id,cutoff)))disbursed++; for(const row of await this.db.query("SELECT id,loan_id FROM pb_credit_actions WHERE state='queued' AND created_at<=? ORDER BY created_at,id LIMIT 25",[cutoff]))if(await handle(()=>this.processAction(row,cutoff)))repaid++; for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state IN ('active','arrears') AND next_due_at<=? ORDER BY next_due_at LIMIT 25",[cutoff]))if(await handle(()=>this.automaticRepayment(row.id,cutoff)))repaid++; for(const row of await this.db.query("SELECT l.id FROM pb_credit_loans l WHERE l.state='active' AND l.next_due_at>? AND l.next_due_at<=? AND NOT EXISTS (SELECT 1 FROM pb_credit_notices n WHERE n.notice_key=CONCAT(l.id,':upcoming:',l.next_due_at)) ORDER BY l.next_due_at LIMIT 25",[cutoff,cutoff+3*day]))await handle(()=>this.lock(row.id,async(tx,loan)=>{if(loan.state!=='active'||Number(loan.next_due_at)<=cutoff||Number(loan.next_due_at)>cutoff+3*day)return;const key='upcoming:'+loan.next_due_at;if(await tx.first('SELECT id FROM pb_credit_notices WHERE notice_key=?',[loan.id+':'+key]))return;await creditNotice(tx,loan,key,'Upcoming credit repayment','Your repayment of '+money(loan.monthly_minor)+' DM is due on '+new Date(Number(loan.next_due_at)).toISOString().slice(0,10)+'. Keep this amount available in the linked current account.',this.clock());reminded++;})); return {offered,disbursed,repaid,expired,reminded,failed}; } }