MC/website/tests/postbank-credit-engine.test.mjs
2026-11-27 23:43:05 +00:00

38 lines
20 KiB
JavaScript

import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankCredit} from '../node/postbank-credit.mjs';import {PostbankCreditEngine} from '../node/postbank-credit-engine.mjs';import {dueMonth} from '../node/postbank-credit-ledger.mjs';import {BANK_VERSION,bankNumber} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs';
async function setup({liquidity=1000000}={}){const db=new BankFixture(),users=['borrower','reviewer','intruder'].map(username=>({id:randomUUID(),username})),entity={id:randomUUID(),kind:'person',key:users[0].id,name:'Borrower'},state={time:Date.parse('2026-11-14T10:00:00Z'),borrow:true,manage:true},clock=()=>state.time,authority=async u=>({entities:[{...entity,canView:u.id===users[0].id,canActivate:u.id===users[0].id&&state.borrow,canPay:u.id===users[0].id&&state.borrow}],readAdmin:u.id===users[1].id,manageAdmin:u.id===users[1].id&&state.manage});await new PostbankService(db,authority,{clock}).activate(users[0],{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const account=await db.first("SELECT * FROM pb_accounts WHERE type_code='102'");await db.query('UPDATE pb_accounts SET balance_minor=30000 WHERE id=?',[account.id]);const r=await db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_web_treasury','979','Website Bank Treasury',?,'active',1)",[liquidity]);await db.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('979',r.insertId),r.insertId]);return {db,users,entity,state,clock,authority,account,bank:r.insertId,credit:new PostbankCredit(db,authority,{clock}),engine:new PostbankCreditEngine(db,{},authority,{clock,resolveUser:async id=>users.find(u=>u.id===id)})};}
async function apply(f,grant=false){const input={requestId:randomUUID(),accountId:String(f.account.id),productKey:grant?'grant_start':'personal_loan',amount:'1000.00',months:3,...grant?{monthly:'250.00'}:{},motivation:'Meaningful borrowing purpose',accepted:true,termsVersion:CREDIT_VERSION};await f.credit.apply(f.users[0],input);return input.requestId;}
const action=(id,action,extra={})=>({requestId:randomUUID(),loanId:id,action,reason:'Confirmed credit instruction',confirmed:true,...extra});
async function offered(f){const id=await apply(f);await f.engine.decision(f.users[1],action(id,'approve'));return await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[id]);}
async function active(f,{legacy=false}={}){let l=await offered(f);if(legacy){await f.db.query('UPDATE pb_credit_loans SET first_instalment_minor=0,collateral_minor=25000 WHERE id=?',[l.id]);l=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[l.id]);}await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));assert.equal((await f.engine.process({cutoff:f.clock()})).disbursed,1);return await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[l.id]);}
test('ordinary loan reserves treasury, requires an own-funds first instalment and posts once with a balanced ledger',async()=>{const f=await setup();try{const loan=await offered(f);assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.bank])).reserved_minor),100000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);const acceptance=action(loan.id,'accept',{expectedVersion:Number(loan.version)});await f.engine.accept(f.users[0],acceptance);assert.equal((await f.engine.accept(f.users[0],acceptance)).replayed,true);assert.equal(await f.engine.payout(loan.id,f.clock()-1),false);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.engine.process()).disbursed,1);assert.equal((await f.engine.process()).disbursed,0);}finally{f.db.close();}});
test('disbursement and full early repayment preserve cash and deduct the first instalment without future interest',async()=>{const f=await setup();try{const l=await active(f);assert.equal(l.state,'active');const pledge=await f.db.first("SELECT * FROM pb_accounts WHERE type_code='106'");assert.equal(pledge,null);assert.equal(Number(l.outstanding_minor),95000);assert.equal(Number(l.first_instalment_minor),5000);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor),125000);const payment=action(l.id,'repay',{amount:'950.00'});await f.engine.requestRepayment(f.users[0],payment);assert.equal((await f.engine.requestRepayment(f.users[0],payment)).replayed,true);await f.engine.process({cutoff:f.clock()});const done=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[l.id]);assert.equal(done.state,'repaid');assert.equal(Number(done.outstanding_minor),0);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='106'")).n,0);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.bank])).balance_minor),1000000);}finally{f.db.close();}});
test('grant autoaccepts without collateral, waits for liquidity and creates one amortising contract',async()=>{const f=await setup({liquidity:0});try{const id=await apply(f,true);const waiting=await f.engine.process();assert.equal(waiting.disbursed,0);assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[id])).state,'approved_pending');await f.db.query('UPDATE pb_accounts SET balance_minor=1000000 WHERE id=?',[f.bank]);assert.equal((await f.engine.process()).disbursed,1);assert.equal((await f.engine.process()).disbursed,0);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='106'")).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_instalments WHERE loan_id=?',[id])).n,10);await assert.rejects(apply(f,true),e=>e.status===409);}finally{f.db.close();}});
test('permissions revoked after acceptance release reservations without paying and self-review is denied',async()=>{const f=await setup();try{const l=await offered(f);await assert.rejects(f.engine.decision(f.users[0],action(l.id,'approve')),e=>e.status===403);await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));f.state.borrow=false;await f.engine.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'withdrawn');assert.equal(Number((await f.db.first('SELECT SUM(reserved_minor) n FROM pb_accounts')).n),0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}});
test('monthly collection has seven-day grace, no penalty, and staff recovery stays within pledged DM',async()=>{const f=await setup();try{const l=await active(f,{legacy:true});await f.db.query('UPDATE pb_accounts SET balance_minor=0 WHERE id=?',[f.account.id]);f.state.time=dueMonth(f.clock(),1);await f.engine.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'active');f.state.time+=7*86400000;await f.engine.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'arrears');await assert.rejects(f.engine.requestRepayment(f.users[1],action(l.id,'recover',{amount:'250.01'})),e=>e.status===409);await f.engine.requestRepayment(f.users[1],action(l.id,'recover',{amount:'10.00'}));await f.engine.process();assert.equal(Number((await f.db.first('SELECT collateral_minor FROM pb_credit_loans WHERE id=?',[l.id])).collateral_minor),24000);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);}finally{f.db.close();}});
test('refinancing replaces all old interest-bearing contracts without paying extra cash or losing history',async()=>{const f=await setup();try{const old=await active(f),balance=Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor),body={requestId:randomUUID(),accountId:String(f.account.id),productKey:'personal_refinance',amount:'999999.00',months:6,motivation:'Consolidate current borrowing',accepted:true,termsVersion:CREDIT_VERSION};const quote=await f.credit.simulate(f.users[0],{accountId:body.accountId,productKey:body.productKey,amount:body.amount,months:6});assert.equal(quote.quote.amount,'950.00');await f.credit.apply(f.users[0],body);await f.engine.decision(f.users[1],action(body.requestId,'approve'));const offer=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[body.requestId]);await f.engine.accept(f.users[0],action(offer.id,'accept',{expectedVersion:Number(offer.version)}));assert.equal((await f.engine.process()).disbursed,1);const replaced=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[old.id]);assert.equal(replaced.state,'refinanced');assert.equal(replaced.replaced_by,body.requestId);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor),balance-4750);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,2);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='106'")).n,0);}finally{f.db.close();}});
test('a failed payout audit rolls back borrower, treasury, collateral and contract together',async()=>{const f=await setup();try{const l=await offered(f);await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));f.db.sqlite.exec("CREATE TRIGGER fail_credit_disbursement BEFORE INSERT ON pb_credit_events WHEN NEW.action='credit_disbursed' BEGIN SELECT RAISE(ABORT,'injected failure'); END;");assert.equal((await f.engine.process()).failed,1);assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'payout_queued');assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.bank])).balance_minor),1000000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='106'")).n,0);f.db.sqlite.exec('DROP TRIGGER fail_credit_disbursement');assert.equal((await f.engine.process()).disbursed,1);assert.equal((await f.engine.process()).disbursed,0);}finally{f.db.close();}});
test('payment-only authority cannot apply for or inspect borrowing, and competing workers do not duplicate payouts',async()=>{const f=await setup();try{const delegated=new PostbankCredit(f.db,async()=>({entities:[{...f.entity,canView:true,canPay:true,canActivate:false}]}));assert.equal((await delegated.overview(f.users[2])).loans.length,0);await assert.rejects(delegated.simulate(f.users[2],{accountId:String(f.account.id),productKey:'personal_loan',amount:'1000.00',months:3}),e=>e.status===403);const l=await offered(f);await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));const [a,b]=await Promise.all([f.engine.process(),f.engine.process()]);assert.equal(a.disbursed+b.disbursed,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,2);}finally{f.db.close();}});
test('offer acceptance cannot use borrowed money for its first instalment, and expired offers release bank liquidity',async()=>{const f=await setup();try{const loan=await offered(f);await f.db.query('UPDATE pb_accounts SET balance_minor=4999 WHERE id=?',[f.account.id]);await assert.rejects(f.engine.accept(f.users[0],action(loan.id,'accept',{expectedVersion:Number(loan.version)})),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.account.id])).reserved_minor),0);f.state.time+=8*86400000;assert.equal((await f.engine.process()).expired,1);assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.bank])).reserved_minor),0);}finally{f.db.close();}});
test('a bank manager cannot approve their own controlled borrowing even when they have bank-management rights',async()=>{const f=await setup();try{const id=await apply(f),privileged=new PostbankCreditEngine(f.db,{},async u=>({...await f.authority(u),manageAdmin:true}),{clock:f.clock});await assert.rejects(privileged.decision(f.users[0],action(id,'approve')),e=>e.status===403&&/different bank manager/.test(e.message));assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[id])).state,'submitted');assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.bank])).reserved_minor),0);}finally{f.db.close();}});
test('upcoming reminders are deduplicated and blocked accounts still allow contract inspection',async()=>{const f=await setup();try{const l=await active(f);f.state.time=dueMonth(f.clock(),1)-2*86400000;assert.equal((await f.engine.process()).reminded,1);assert.equal((await f.engine.process()).reminded,0);await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.account.id]);const details=await f.credit.details(f.users[0],l.id);assert.ok(details.notices.some(n=>n.subject==='Upcoming credit repayment'));assert.equal(details.schedule.length,3);await assert.rejects(f.credit.details(f.users[2],l.id),e=>e.status===403);}finally{f.db.close();}});
test('mid-month settlement charges earned interest only and preserves the reserved repayment value date',async()=>{const f=await setup();try{const loan=await active(f),first=await f.db.first('SELECT * FROM pb_credit_instalments WHERE loan_id=? AND sequence_no=1',[loan.id]);f.state.time+=15*86400000;const detail=await f.credit.details(f.users[0],loan.id),interest=Math.round(Number(first.interest_minor)/2);assert.equal(detail.settlement,((95000+interest)/100).toFixed(2));assert.ok(interest>0&&interest<Number(first.interest_minor));await f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:detail.settlement}));f.state.time+=20*3600000;assert.equal((await f.engine.process()).repaid,1);assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[loan.id])).state,'repaid');assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.bank])).balance_minor),1000000+interest);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);}finally{f.db.close();}});
test('partial early payments reprice only the remaining period and do not double-charge earned interest',async()=>{const f=await setup();try{const loan=await active(f);f.state.time+=15*86400000;await f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:'100.00'}));assert.equal((await f.engine.process()).failed,0);const updated=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[loan.id]),sum=await f.db.first('SELECT SUM(principal_minor-paid_principal) n FROM pb_credit_instalments WHERE loan_id=?',[loan.id]);assert.equal(Number(sum.n),Number(updated.outstanding_minor));assert.ok(Number(updated.monthly_minor)<Number(loan.monthly_minor));f.state.time+=5*86400000;const payoff=await f.credit.details(f.users[0],loan.id);await f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:payoff.settlement}));await f.engine.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[loan.id])).state,'repaid');assert.equal(Number((await f.db.first('SELECT SUM(reserved_minor) n FROM pb_accounts')).n),0);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);}finally{f.db.close();}});
test('scheduled instalments after a partial prepayment collect each remaining cent exactly once',async()=>{const f=await setup();try{const loan=await active(f);f.state.time+=15*86400000;await f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:'100.00'}));await f.engine.process();const schedule=await f.db.query('SELECT due_at FROM pb_credit_instalments WHERE loan_id=? ORDER BY sequence_no',[loan.id]);for(const row of schedule){f.state.time=Number(row.due_at);assert.equal((await f.engine.process()).failed,0);}const final=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[loan.id]);assert.equal(final.state,'repaid');assert.equal(Number(final.outstanding_minor),0);const interest=Number((await f.db.first('SELECT SUM(paid_interest) n FROM pb_credit_instalments WHERE loan_id=?',[loan.id])).n);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.bank])).balance_minor),1000000+interest);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);}finally{f.db.close();}});
test('multiple queued repayments cannot overbook the debt and concurrent workers process them in value order',async()=>{const f=await setup();try{const loan=await active(f);f.state.time+=15*86400000;await f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:'400.00'}));f.state.time+=1;await f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:'400.00'}));await assert.rejects(f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:'250.00'})),e=>e.status===409&&/Maximum additional repayment/.test(e.message));const work=await Promise.all([f.engine.process(),f.engine.process()]);assert.equal(work.reduce((n,r)=>n+r.repaid,0),2);assert.equal(work.reduce((n,r)=>n+r.failed,0),0);assert.equal(Number((await f.db.first('SELECT SUM(reserved_minor) n FROM pb_accounts')).n),0);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);}finally{f.db.close();}});
test('contract details disclose queued repayments and the exact remaining repayment capacity',async()=>{
const f=await setup();try{const loan=await active(f);const before=await f.credit.details(f.users[0],loan.id);assert.equal(before.queuedRepayments,'0.00');await f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:'100.00'}));const details=await f.credit.details(f.users[0],loan.id);assert.equal(details.queuedRepayments,'100.00');assert.equal(Number(details.maximumRepayment),Number(details.settlement)-100);await assert.rejects(f.engine.requestRepayment(f.users[0],action(loan.id,'repay',{amount:details.settlement})),/Maximum additional repayment/);}finally{f.db.close();}
});
test('first instalment is paid from own funds before issue and is deducted from the repayment schedule',async()=>{
const f=await setup();try{
const loan=await offered(f);await f.db.query('UPDATE pb_accounts SET balance_minor=5000 WHERE id=?',[f.account.id]);await f.engine.accept(f.users[0],action(loan.id,'accept',{expectedVersion:Number(loan.version)}));
assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.account.id])).reserved_minor),5000);
const query=f.db.query.bind(f.db),order=[];f.db.query=async(sql,args=[])=>{if(sql.startsWith('INSERT INTO pb_orders')){order.push(args[6]);if(String(args[6]).startsWith('Credit disbursement'))assert.equal(Number((await query('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id]))[0].balance_minor),0);}return query(sql,args);};
assert.equal(await f.engine.payout(loan.id,f.clock()),true);assert.match(order[0],/^First loan instalment/);assert.match(order[1],/^Credit disbursement/);const issued=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[loan.id]);assert.equal(Number(issued.outstanding_minor),95000);assert.equal(Number(issued.collateral_minor),0);const future=await f.db.first('SELECT SUM(principal_minor) n FROM pb_credit_instalments WHERE loan_id=?',[loan.id]);assert.equal(Number(future.n)+Number(issued.first_instalment_minor),100000);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='106'")).n,0);assert.equal(await f.engine.payout(loan.id,f.clock()),false);assert.equal(order.length,2);
}finally{f.db.close();}
});