web/website/node/postbank-credit-engine.mjs
2026-11-27 23:43:05 +00:00

77 lines
28 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)<n)throw new BankError('Credit reservations need reconciliation.',409);a.reserved_minor=String(BigInt(a.reserved_minor)-n);await tx.query('UPDATE pb_accounts SET reserved_minor=? WHERE id=?',[a.reserved_minor,a.id]);}}loan.treasury_hold_minor='0';loan.borrower_hold_minor='0';await tx.query('UPDATE pb_credit_loans SET treasury_hold_minor=0,borrower_hold_minor=0 WHERE id=?',[loan.id]);}
async reserveOffer(tx,loan,at=this.clock()){
const {bank}=await this.accounts(tx,loan),amount=BigInt(loan.principal_minor);if(BigInt(bank.balance_minor)-BigInt(bank.reserved_minor)<amount)return false;
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[String(amount),bank.id]);const grant=loan.product_key.startsWith('grant_'),state=grant?'payout_queued':'offered';await tx.query('UPDATE pb_credit_loans SET state=?,treasury_hold_minor=?,queued_at=?,offer_expires_at=?,updated_at=?,version=version+1 WHERE id=?',[state,String(amount),grant?at:null,grant?null:this.clock()+7*day,this.clock(),loan.id]);Object.assign(loan,{state,treasury_hold_minor:String(amount),queued_at:grant?at:null});return true;
}
async decision(user,input,{revalidate=async()=>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)<required)throw new BankError('The borrower account needs '+money(required)+' DM of its own funds for the '+(BigInt(loan.first_instalment_minor||0)?'first instalment':'agreed collateral')+' before this offer can be accepted.',409);if(required)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[String(required),a.current.id]);await tx.query("UPDATE pb_credit_loans SET state='payout_queued',borrower_hold_minor=?,accepted_by=?,accepted_at=?,queued_at=?,updated_at=?,version=version+1 WHERE id=?",[String(required),user.id,this.clock(),this.clock(),this.clock(),loan.id]);await this.event(tx,loan,input.requestId,user.id,'offer_accepted',BigInt(loan.first_instalment_minor||0)?{firstInstalmentReserved:money(required)}:{collateralReserved:money(required)},fingerprint);return {ok:true,state:'payout_queued'};});
}
async collateralAccount(tx,loan){if(loan.collateral_account_id)return tx.first('SELECT * FROM pb_accounts WHERE id=?',[loan.collateral_account_id]);let a=await tx.first("SELECT * FROM pb_accounts WHERE client_number=? AND type_code='106' ORDER BY id LIMIT 1 FOR UPDATE",[loan.client_number]);if(!a){const current=await tx.first('SELECT package_id FROM pb_accounts WHERE id=?',[loan.account_id]),insert=await tx.query("INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,state,created_at) VALUES(?,?,'106','Blocked Collateral Account','blocked',?)",[loan.client_number,current.package_id,this.clock()]);await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('106',Number(insert.insertId)),insert.insertId]);a=await tx.first('SELECT * FROM pb_accounts WHERE id=?',[insert.insertId]);}await tx.query('UPDATE pb_credit_loans SET collateral_account_id=? WHERE id=?',[a.id,loan.id]);loan.collateral_account_id=a.id;return a;}
async payout(loanId,cutoff){return this.lock(loanId,async(tx,loan)=>{
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)<amount)throw new BankError('Insufficient unreserved funds.',409);await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[String(amount),source.id]);await tx.query("INSERT INTO pb_credit_actions(id,loan_id,actor_id,kind,amount_minor,state,fingerprint,reason,created_at) VALUES(?,?,?,?,?,'queued',?,?,?)",[input.requestId,loan.id,user.id,input.action,String(amount),fingerprint,input.reason.trim(),this.clock()]);await this.event(tx,loan,input.requestId,user.id,'credit_'+input.action+'_queued',{amount:money(amount),reason:input.reason.trim()},fingerprint);return {ok:true,state:'queued'};});
}
async applyRepayment(tx,loan,a,amount,key,actor,{recovery=false,held=false,valueAt=this.clock()}={}){
const now=this.clock(),valuedAt=Math.min(now,Number(valueAt)),payoff=await currentPayoff(tx,loan,valuedAt);if(amount>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<interest?remaining:interest;remaining-=payInterest;const principal=BigInt(row.principal_minor)-BigInt(row.paid_principal),payCapital=remaining<principal?remaining:principal;remaining-=payCapital;paidCapital+=payCapital;const pi=BigInt(row.paid_interest)+payInterest,pp=BigInt(row.paid_principal)+payCapital,state=pi===BigInt(row.interest_minor)&&pp===BigInt(row.principal_minor)?'paid':row.state;await tx.query('UPDATE pb_credit_instalments SET paid_interest=?,paid_principal=?,state=?,paid_at=? WHERE loan_id=? AND sequence_no=?',[String(pi),String(pp),state,state==='paid'?now:null,loan.id,row.sequence_no]);if(!remaining)break;}
if(payoff.current){const row=payoff.current,paid=remaining<payoff.accrued?remaining:payoff.accrued;remaining-=paid;await tx.query('UPDATE pb_credit_instalments SET paid_interest=paid_interest+?,accrued_interest_minor=?,accrual_remaining_minor=?,accrual_at=? WHERE loan_id=? AND sequence_no=?',[String(paid),String(payoff.accrued-paid),String(row.unearned),Math.max(valuedAt,Number(row.accrual_at||0)),loan.id,row.sequence_no]);}
paidCapital+=remaining;const outstanding=BigInt(loan.outstanding_minor)-paidCapital,collateral=BigInt(loan.collateral_minor)-(recovery?amount:0n);if(outstanding<0n||collateral<0n)throw new BankError('Credit balances need reconciliation.',409);
let revisedMonthly=null;
if(remaining){
const future=await tx.query("SELECT sequence_no,due_at,paid_interest FROM pb_credit_instalments WHERE loan_id=? AND due_at>? 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<future.length;i++){const row=future[i],forecast=revised[i]?.interest||0n;await tx.query('UPDATE pb_credit_instalments SET principal_minor=?,interest_minor=?,state=?,accrual_at=?,accrual_remaining_minor=?,accrued_interest_minor=0 WHERE loan_id=? AND sequence_no=?',[String(revised[i]?.principal||0n),String(BigInt(row.paid_interest)+forecast),revised[i]?'pending':'settled',i===0?valuedAt:Number(future[i-1].due_at),String(forecast),loan.id,row.sequence_no]);}
}
const next=await tx.first("SELECT MIN(due_at) due FROM pb_credit_instalments WHERE loan_id=? AND state IN ('pending','late')",[loan.id]);const settled=outstanding===0n;if(settled){await tx.query("UPDATE pb_credit_instalments SET state='settled' WHERE loan_id=? AND state IN ('pending','late')",[loan.id]);if(collateral){if(!a.collateral)throw new BankError('Collateral account missing.',409);await creditMovement(tx,{key:loan.id+':release',actor,source:a.collateral,target:a.current,amount:collateral,reference:'Collateral released · '+loan.id,now});}}
const stillLate=await tx.first("SELECT COUNT(*) n FROM pb_credit_instalments WHERE loan_id=? AND state IN ('pending','late') AND due_at<=?",[loan.id,now-7*day]);if(revisedMonthly!==null)await tx.query('UPDATE pb_credit_loans SET monthly_minor=? WHERE id=?',[String(revisedMonthly),loan.id]);await tx.query('UPDATE pb_credit_loans SET outstanding_minor=?,collateral_minor=?,state=?,next_due_at=?,updated_at=?,version=version+1 WHERE id=?',[String(outstanding),settled?'0':String(collateral),settled?'repaid':Number(stillLate.n)?'arrears':'active',settled?null:next?.due||null,now,loan.id]);await this.event(tx,loan,creditID(key+':event'),actor,recovery?'collateral_recovered':'credit_repayment',{amount:money(amount),principal:money(paidCapital),remaining:money(outstanding),valueAt:valuedAt});return {outstanding:money(outstanding),settled};
}
async processAction(action,cutoff){return this.lock(action.loan_id,async(tx,loan)=>{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_at<? OR (created_at=? AND id<?)) ORDER BY created_at,id LIMIT 1",[loan.id,current.created_at,current.created_at,current.id]);if(prior)return false;const a=await this.accounts(tx,loan),source=current.kind==='recover'?a.collateral:a.current,actor=await this.resolveUser(current.actor_id);let allowed=false;try{if(actor){await this.currentAuthority(actor,loan,tx,current.kind==='recover'?{manage:true}:{pay:true});allowed=true;}}catch{}const amount=BigInt(current.amount_minor),payoff=await currentPayoff(tx,loan,Number(current.created_at));if(!allowed||!['active','arrears'].includes(loan.state)||current.kind==='recover'&&(loan.state!=='arrears'||amount>BigInt(loan.collateral_minor))||!source||BigInt(source.reserved_minor)<amount||amount>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)<amount){await tx.query("UPDATE pb_credit_instalments SET state='late' WHERE loan_id=? AND due_at<=? AND state='pending'",[loan.id,cutoff]);if(Number(due[0].due_at)+7*day<=cutoff){await tx.query("UPDATE pb_credit_loans SET state='arrears',updated_at=? WHERE id=?",[this.clock(),loan.id]);await creditNotice(tx,loan,'arrears:'+due[0].sequence_no,'Credit in arrears','The seven-day grace period has ended. Fund the repayment account or contact credit management. Only the agreed DM collateral is pledged; no automatic penalty or inventory seizure applies.',this.clock());}await creditNotice(tx,loan,'late:'+due[0].sequence_no,'Repayment not collected','Your credit repayment of '+money(amount)+' DM could not be collected. Fund the linked current account. No automatic penalty has been added.',this.clock());return false;}await this.applyRepayment(tx,loan,a,amount,'instalment:'+loan.id+':'+due.map(r=>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};
}
}