Add extra wage cycles, recheck bank tickers and apply first loan instalments

This commit is contained in:
unimatrixgit 2026-11-15 22:13:52 +01:00
commit ff06ac894e
7 changed files with 184 additions and 74 deletions

View file

@ -13,3 +13,12 @@ test('Failures release the lease without marking a slot complete; retry does not
test('Disabled and future tasks do not acquire a run record',async()=>{
const db=new BankFixture();try{const scheduler=new CentralScheduler(db,[{key:'future',slot:()=>null,run:()=>{throw Error('Must not run');}}]);assert.deepEqual(await scheduler.runDue(),{tasks:[]});assert.equal((await db.first('SELECT COUNT(*) n FROM pb_scheduler_tasks')).n,0);}finally{db.close();}
});
test('manual recheck invokes every ticker with its original cutoff, even when its slot already succeeded',async()=>{
const db=new BankFixture(),calls=[];const tasks=['bank_settlement','credit_support','standing_instructions','staff_payroll','tariff_publications','statement_index','statement_archives'].map(key=>({key,slot:()=>40,run:async cutoff=>calls.push([key,cutoff])}));
try{const scheduler=new CentralScheduler(db,tasks);await scheduler.runDue();assert.equal(calls.length,7);await scheduler.runDue();assert.equal(calls.length,7);const result=await scheduler.runDue({recheck:true});assert.equal(calls.length,14);assert(result.tasks.every(t=>t.state==='completed'));assert(calls.every(([,cutoff])=>cutoff===40));}finally{db.close();}
});
test('manual recheck respects an existing lease and checks authority before claiming a ticker',async()=>{
const db=new BankFixture();let release,entered,calls=0;const started=new Promise(r=>entered=r),wait=new Promise(r=>release=r),tasks=[{key:'loan_ticker',slot:()=>50,async run(){calls++;entered();await wait;}}];
try{const a=new CentralScheduler(db,tasks),b=new CentralScheduler(db,tasks),run=a.runDue({recheck:true});await started;assert.equal((await b.runDue({recheck:true})).tasks[0].state,'not_due_or_running');release();await run;await assert.rejects(b.runDue({recheck:true,beforeTask:async()=>{throw Error('Access revoked');}}));assert.equal(calls,1);}finally{db.close();}
});

View file

@ -3,22 +3,22 @@ async function setup({liquidity=1000000}={}){const db=new BankFixture(),users=['
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){let l=await offered(f);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 own collateral 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 release collateral 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(Number(pledge.balance_minor),25000);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor),105000);const payment=action(l.id,'repay',{amount:'1000.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(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[pledge.id])).balance_minor),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();}});
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);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('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,'1000.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);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(Number((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE type_code='106'")).balance_minor),25000);}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 as its collateral, 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=24999 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('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,((100000+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('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();}});
@ -27,3 +27,12 @@ test('multiple queued repayments cannot overbook the debt and concurrent workers
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();}
});

View file

@ -1,5 +1,9 @@
import test from 'node:test';import assert from 'node:assert/strict';import {creditQuote,creditScore} from '../node/postbank-credit-model.mjs';
test('launch grants have exact principal, zero interest and user-selected instalments',()=>{const q=creditQuote({productKey:'grant_start',monthly:'250.00'});assert.equal(q.months,10);assert.equal(q.totalRepayment,'2500.00');assert.equal(q.totalInterest,'0.00');assert.equal(q.schedule.at(-1).balance,'0.00');assert.throws(()=>creditQuote({productKey:'grant_start',monthly:'1.00'}));});
test('fixed effective annual rates amortise to zero with exact minor-unit conservation',()=>{for(const [key,amount,months]of [['personal_loan','10000.00',12],['business_loan','50000.00',24],['civic_loan','10000.00',6],['personal_overdraft','500.00',1]]){const q=creditQuote({productKey:key,amount,months}),minor=s=>BigInt(s.replace('.',''));assert.equal(q.schedule.at(-1).balance,'0.00');assert.equal(q.schedule.reduce((s,r)=>s+minor(r.principal),0n),minor(amount));assert.equal(minor(q.totalRepayment),minor(amount)+minor(q.totalInterest));}});
test('fixed effective annual rates amortise to zero with exact minor-unit conservation',()=>{for(const [key,amount,months]of [['personal_loan','10000.00',12],['business_loan','50000.00',24],['civic_loan','10000.00',6],['personal_overdraft','500.00',1]]){const q=creditQuote({productKey:key,amount,months}),minor=s=>BigInt(s.replace('.',''));assert.equal(q.schedule.at(-1).balance,'0.00');assert.equal(q.schedule.reduce((s,r)=>s+minor(r.principal),0n)+minor(q.firstInstalment),minor(amount));assert.equal(minor(q.totalRepayment),minor(amount)+minor(q.totalInterest));}});
test('simulator rejects unsupported products, amounts and terms',()=>{assert.throws(()=>creditQuote({productKey:'personal_loan',amount:1000,months:12}));assert.throws(()=>creditQuote({productKey:'personal_loan',amount:'1000000.00',months:12}));assert.throws(()=>creditQuote({productKey:'civic_loan',amount:'10000.00',months:24}));});
test('new customers start neutral; denials have bounded, recoverable impact and arrears matter',()=>{assert.equal(creditScore().score,600);assert.equal(creditScore({denials:[0]}).score,585);assert.equal(creditScore({denials:[0,0,0,0]}).denialPenalty,45);assert.equal(creditScore({denials:[91]}).denialPenalty,0);assert.ok(creditScore({overdueMinor:100n}).score<600);});
test('five-percent first instalment rounds up to cents and is included once in total repayment',()=>{
const q=creditQuote({productKey:'personal_loan',amount:'1000.01',months:3}),minor=s=>BigInt(s.replace('.',''));assert.equal(q.firstInstalment,'50.01');assert.equal(q.remainingPrincipal,'950.00');assert.equal(q.schedule.reduce((sum,r)=>sum+minor(r.amount),0n)+minor(q.firstInstalment),minor(q.totalRepayment));assert.equal(minor(q.totalRepayment),100001n+minor(q.totalInterest));const zero=creditQuote({productKey:'personal_loan',amount:'1000.00',months:3},{annualBps:0});assert.equal(zero.totalRepayment,'1000.00');assert.equal(zero.totalInterest,'0.00');
});

View file

@ -4,7 +4,7 @@ async function fixture(){const db=new BankFixture(),user={id:randomUUID(),userna
const application=f=>({requestId:randomUUID(),accountId:String(f.account.id),productKey:'grant_start',monthly:'250.00',motivation:'Initial launch activity and supplies',accepted:true,termsVersion:CREDIT_VERSION});
test('credit simulation and grant acceptance do not disburse or touch collateral before engine activation',async()=>{const f=await fixture();try{const b=application(f),q=await f.credit.simulate(f.user,{accountId:b.accountId,productKey:b.productKey,monthly:b.monthly});assert.equal(q.quote.totalInterest,'0.00');assert.equal(q.collateral,'0.00');assert.equal(q.score.limitedHistory,true);const result=await f.credit.apply(f.user,b);assert.equal(result.state,'approved_pending');assert.equal((await f.credit.apply(f.user,b)).replayed,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor,0);assert.equal((await f.db.first('SELECT outstanding_minor FROM pb_credit_loans')).outstanding_minor,0);assert.equal((await f.credit.overview(f.user)).loans.length,1);assert.equal((await f.credit.overview(f.other)).loans.length,0);await assert.rejects(f.credit.apply(f.user,{...b,requestId:randomUUID()}),e=>e.status===409);await assert.rejects(f.credit.apply(f.user,{...b,motivation:'A changed application using the same ID'}),e=>e.status===409);}finally{f.db.close();}});
test('credit submissions recheck ownership, terms, product eligibility and permissions',async()=>{const f=await fixture();try{const b=application(f);await assert.rejects(f.credit.apply(f.other,b),e=>e.status===403);await assert.rejects(f.credit.apply(f.user,{...b,termsVersion:'obsolete'}));await assert.rejects(f.credit.simulate(f.user,{accountId:b.accountId,productKey:'business_loan',amount:'10000.00',months:12}));await assert.rejects(f.credit.apply(f.user,b,{revalidate:async()=>{f.revoke();return f.user;}}),e=>e.status===403);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,0);}finally{f.db.close();}});
test('ordinary loan application captures exact quote and 25 percent DM collateral without charging',async()=>{const f=await fixture();try{const b={...application(f),productKey:'personal_loan',amount:'1000.00',months:12};const q=await f.credit.simulate(f.user,{accountId:b.accountId,productKey:b.productKey,amount:b.amount,months:b.months});assert.equal(q.collateral,'250.00');await f.credit.apply(f.user,b);const row=await f.db.first('SELECT * FROM pb_credit_loans');assert.equal(row.state,'submitted');assert.equal(row.collateral_minor,25000);assert.equal(row.outstanding_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}});
test('ordinary loan application captures exact quote and 5 percent first instalment without charging',async()=>{const f=await fixture();try{const b={...application(f),productKey:'personal_loan',amount:'1000.00',months:12};const q=await f.credit.simulate(f.user,{accountId:b.accountId,productKey:b.productKey,amount:b.amount,months:b.months});assert.equal(q.collateral,'0.00');assert.equal(q.firstInstalment,'50.00');assert.equal(q.remainingPrincipal,'950.00');await f.credit.apply(f.user,b);const row=await f.db.first('SELECT * FROM pb_credit_loans');assert.equal(row.state,'submitted');assert.equal(row.collateral_minor,0);assert.equal(row.first_instalment_minor,5000);assert.equal(row.outstanding_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}});
test('credit API provides simulations with fresh authority while financial intake remains closed',async()=>{const f=await fixture();try{const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>f.user,authority:f.authority});const request=(path,body,origin='https://cp.dunerealms.com')=>new Request('https://cp.dunerealms.com'+path,body?{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify(body)}:{});assert.equal((await api(request('/api/bank/credit/overview'))).status,200);const body={accountId:String(f.account.id),productKey:'grant_start',monthly:'250.00'};assert.equal((await api(request('/api/bank/credit/simulate',body))).status,200);assert.equal((await api(request('/api/bank/credit/simulate',body,'https://evil.invalid'))).status,403);assert.equal((await api(request('/api/bank/credit/apply',application(f)))).status,409);assert.equal((await api(request('/api/bank/admin/credit'))).status,403);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});
@ -18,7 +18,7 @@ test('Pro borrowing limits follow the actual account package and are rechecked a
await assert.rejects(f.credit.simulate(f.user,request),/limits/);
await assert.rejects(f.credit.simulate(f.user,{...request,packageKey:'pb_pro'}),/valid simulation/);
await f.db.query("UPDATE pb_packages SET package_key='pb_pro',monthly_minor=1500");
const quote=await f.credit.simulate(f.user,request);assert.equal(quote.quote.amount,'75000.00');assert.equal(quote.collateral,'18750.00');
const quote=await f.credit.simulate(f.user,request);assert.equal(quote.quote.amount,'75000.00');assert.equal(quote.collateral,'0.00');assert.equal(quote.firstInstalment,'3750.00');
const overview=await f.credit.overview(f.user),products=overview.accounts.find(a=>a.id===String(f.account.id)).products;
assert.equal(products.find(p=>p.key==='personal_loan').max,'75000.00');assert.equal(products.find(p=>p.key==='personal_overdraft').max,'7500.00');assert.equal(products.find(p=>p.key==='personal_refinance').max,'300000.00');assert.equal(products.find(p=>p.key==='grant_advance').max,'10000.00');assert.equal(products.find(p=>p.key==='personal_card').revolving,true);
await assert.rejects(f.credit.simulate(f.user,{...request,amount:'75000.01'}),/limits/);

View file

@ -101,3 +101,40 @@ test('payment authorization is checked inside the salary transaction after its i
const result=await f.cycle.run(f.user,await f.payload());assert.equal(result.paid,0);assert.equal(result.failed,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.bank.first("SELECT COUNT(*) n FROM pb_payroll_items WHERE state='pending'")).n,1);
}finally{f.bank.close();}
});
test('additional full cycles pay again with independent receipts while monthly payroll stays frozen',async()=>{
const f=await fixture();try{
await f.cycle.run(f.user,await f.payload());
for(let i=0;i<2;i++){
const preview=await f.cycle.previewAdditional();assert.equal(preview.canRun,true);assert.equal(preview.pendingCount,1);
const input={mode:'additional',requestId:randomUUID(),period:preview.period,previewKey:preview.previewKey,reason:'Authorised additional full wages',confirmed:true};
const result=await f.cycle.run(f.user,input);assert.equal(result.additional,true);assert.equal(result.paid,1);assert.equal((await f.cycle.run(f.user,input)).replayed,true);
}
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_payroll_runs')).n,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_payroll_additional_runs')).n,2);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,6);
assert.equal((await f.bank.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);assert.equal((await f.cycle.preview()).canRun,false);assert.equal((await f.payroll.process({rollout:true})).paid,0);
const overview=await f.payroll.overview();assert.equal(overview.records.filter(r=>r.additional).length,2);
}finally{f.bank.close();}
});
test('concurrent additional confirmations from one preview create only one extra cycle',async()=>{
const f=await fixture();try{const preview=await f.cycle.previewAdditional(),input={mode:'additional',requestId:randomUUID(),period:preview.period,previewKey:preview.previewKey,reason:'Concurrent additional wage test',confirmed:true};const results=await Promise.allSettled([f.cycle.run(f.user,input),f.cycle.run(f.user,{...input,requestId:randomUUID()})]);assert.equal(results.filter(r=>r.status==='fulfilled').length,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_payroll_additional_runs')).n,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,2);}finally{f.bank.close();}
});
test('partial additional cycle resumes its unpaid recipients without creating another full payment',async()=>{
const f=await fixture();try{
const second={...f.state.people[0],id:randomUUID(),username:'Second officer',minecraft_uuid:randomUUID()};f.state.people.push(second);
const original=f.cycle.payroll.pay.bind(f.cycle.payroll);f.cycle.payroll.pay=async(period,actor,options)=>{if(actor===second.id)throw Error('Temporary payment failure');return original(period,actor,options);};
const payload=async()=>{const p=await f.cycle.previewAdditional();return{mode:'additional',requestId:randomUUID(),period:p.period,previewKey:p.previewKey,reason:'Retry additional wage cycle',confirmed:true};};
const first=await f.cycle.run(f.user,await payload());assert.equal(first.paid,1);assert.equal(first.failed,1);assert.equal((await f.cycle.previewAdditional()).pendingCount,1);f.cycle.payroll.pay=original;
const retry=await f.cycle.run(f.user,await payload());assert.equal(retry.cycleId,first.cycleId);assert.equal(retry.paid,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,4);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_payroll_additional_runs')).n,1);
}finally{f.bank.close();}
});
test('additional cycles reject stale policy previews and preserve intent audit before any payment',async()=>{
const f=await fixture();try{
const p=await f.cycle.previewAdditional(),input={mode:'additional',requestId:randomUUID(),period:p.period,previewKey:p.previewKey,reason:'Additional payroll validation',confirmed:true};
await f.bank.query("UPDATE pb_financial_policies SET version=2 WHERE policy_key='payroll'");await assert.rejects(f.cycle.run(f.user,input),e=>e.status===409);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_payroll_additional_runs')).n,0);
const current=await f.cycle.previewAdditional();input.previewKey=current.previewKey;const original=f.cycle.payroll.pay.bind(f.cycle.payroll);f.cycle.payroll.pay=async(...args)=>{const audit=await f.bank.first('SELECT action,details FROM pb_audit WHERE id=?',[input.requestId]);assert.equal(audit.action,'payroll_additional_cycle_run');assert.equal(JSON.parse(audit.details).state,'started');return original(...args);};await f.cycle.run(f.user,input);
f.state.principal='department_head';await assert.rejects(f.cycle.run(f.user,{...input,requestId:randomUUID()}),e=>e.status===403);
}finally{f.bank.close();}
});

View file

@ -9,9 +9,10 @@ class Node{
remove(){this.parent.children=this.parent.children.filter(n=>n!==this);}
}
const all=node=>node.children.flatMap(child=>[child,...all(child)]);
async function fixture(work,{canRun=true,enabled=true,state='not_started',post=async()=>({paid:1,failed:0}),active=()=>true}={}){
async function fixture(work,{canRun=true,enabled=true,state='not_started',post=async()=>({paid:1,failed:0}),active=()=>true,additional=false}={}){
const previous=globalThis.document;globalThis.document={createElement:tag=>new Node(tag)};
const host=new Node('main'),calls=[],data={policy:{version:1,value:{enabled:true,payDay:28}},ranks:[],eligibleCount:1,records:[],cycle:{period:'2026-11',previewKey:'a'.repeat(64),state,enabled,canRun,pendingCount:1,paidCount:0,netMinor:'280000',taxMinor:'302344',employerCostMinor:'582344',issuerBalanceMinor:'-582344',recipients:[{name:'Officer <QA>',netMinor:'280000'}]}};
if(additional)data.additionalCycle={...data.cycle,mode:'additional',state:'new_cycle',canRun:true};
const api={request:async(path,input)=>{calls.push({path,input});return input?post(input):data;}};
const nodes=()=>all(host),button=label=>nodes().find(n=>n.tagName==='BUTTON'&&n.textContent===label);
try{await renderPayroll(host,{api,isActive:active});await work({host,calls,nodes,button});}finally{globalThis.document=previous;}
@ -35,3 +36,5 @@ test('completed and disabled cycles show a disabled Run Wage Cycle button',async
await fixture(async({button,host})=>{assert.equal(button('Run Wage Cycle').disabled,true);assert(host.textContent.includes('cannot be paid again'));},{canRun:false,state:'completed'});
await fixture(async({button,host})=>{assert.equal(button('Run Wage Cycle').disabled,true);assert(host.textContent.includes('Enable and save payroll settings'));},{canRun:false,enabled:false});
});
test('completed monthly payroll offers an independent additional payment with explicit confirmation',()=>fixture(async({button,nodes,calls,host})=>{assert.equal(button('Run Wage Cycle').disabled,true);assert.equal(button('Run Additional Wage Cycle').disabled,false);button('Run Additional Wage Cycle').onclick();const form=nodes().find(n=>n.tagName==='FORM'&&n.textContent.includes('Confirm ADDITIONAL'));assert(host.textContent.includes('EXTRA full wage payment'));await form.onsubmit(event);assert.equal(calls.filter(c=>c.input).length,0);const controls=all(form);controls.find(n=>n.tagName==='INPUT'&&n.type!=='checkbox').value='Authorised extra wages';controls.find(n=>n.type==='checkbox').checked=true;await form.onsubmit(event);assert.equal(calls.filter(c=>c.input).length,1);assert.equal(calls.find(c=>c.input).input.mode,'additional');},{canRun:false,state:'completed',additional:true}));

View file

@ -12,6 +12,6 @@ test('A general bank manager cannot run the scheduler without a pinned control i
});
test('Big Four manual runs require same-origin confirmation and cannot override a calendar',async()=>{
const f=fixture();try{assert.equal((await f.send({confirmed:true},'https://evil.invalid')).status,403);assert.equal((await f.send({confirmed:true,force:true})).status,400);assert.equal(f.calls(),0);
assert.equal((await f.send()).status,200);assert.equal((await f.send()).status,200);assert.equal(f.calls(),1);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_audit WHERE action='central_scheduler_run'")).n,2);
assert.equal((await f.send()).status,200);assert.equal((await f.send()).status,200);assert.equal(f.calls(),2);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_audit WHERE action='central_scheduler_run'")).n,2);
}finally{f.db.close();}
});