MC/website/tests/postbank-payments.test.mjs

25 lines
10 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 {PostbankPayments,standardCycle} from '../node/postbank-payments.mjs';import {createPostbankApi} from '../node/postbank-api.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
async function setup(){
const db=new BankFixture(),users=[0,1,2].map((n)=>({id:randomUUID(),username:'citizen_'+n})),entities=users.map((u)=>({id:randomUUID(),kind:'person',key:u.id,name:u.username}));let revoked=false;
const authority=async u=>({entities:entities.map(e=>({...e,canView:e.key===u.id,canActivate:e.key===u.id,canPay:e.key===u.id&&!revoked})),readAdmin:false,manageAdmin:false});
const packages=new PostbankService(db,authority);for(let i=0;i<users.length;i++)await packages.activate(users[i],{entityId:entities[i].id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});
const records=await db.query('SELECT a.*,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number ORDER BY a.id');const current=i=>records.find(a=>a.entity_id===entities[i].id&&a.type_code==='102'),savings=i=>records.find(a=>a.entity_id===entities[i].id&&a.type_code==='103');
await db.query('UPDATE pb_accounts SET balance_minor=10000 WHERE id=?',[current(0).id]);
const service=new PostbankPayments(db,authority,{resolveUser:async id=>users.find(u=>u.id===id),clock:()=>Date.parse('2026-11-13T20:00:00Z')});
const input=(extra={})=>({requestId:randomUUID(),sourceAccount:String(current(0).id),targetNumber:savings(0).account_number,amount:'10.00',reference:'Fixture transfer',mode:'standard',confirmed:false,...extra});
return {db,users,entities,current,savings,authority,service,input,revoke:()=>{revoked=true;}};
}
test('queued own transfer reserves funds and two workers post exactly once with balanced entries',async()=>{const f=await setup();try{const body=f.input(),r=await f.service.transfer(f.users[0],body);assert.equal(r.state,'queued');assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,1000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.service.transfer(f.users[0],body)).replayed,true);const results=await Promise.all([f.service.processQueue(),f.service.processQueue()]);assert.equal(results.reduce((n,r)=>n+r.posted,0),1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]),b=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.savings(0).id]);assert.equal(a.balance_minor,9000);assert.equal(a.reserved_minor,0);assert.equal(b.balance_minor,1000);assert.equal((await f.db.first('SELECT SUM(amount_minor) total FROM pb_entries')).total,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,2);}finally{f.db.close();}});
test('concurrent instructions cannot spend reserved money or reuse a request for different details',async()=>{const f=await setup();try{const results=await Promise.allSettled(Array.from({length:8},()=>f.service.transfer(f.users[0],f.input({amount:'30.00'}))));assert.equal(results.filter(r=>r.status==='fulfilled').length,3);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.reserved_minor,9000);assert.equal(a.balance_minor,10000);const one=f.input({amount:'1.00'});await f.service.transfer(f.users[0],one);await assert.rejects(f.service.transfer(f.users[0],{...one,reference:'Changed'}),e=>e.status===409);await f.service.processQueue();assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).balance_minor,900);}finally{f.db.close();}});
test('external payments require confirmation and only actual operators can debit accounts',async()=>{const f=await setup();try{await assert.rejects(f.service.transfer(f.users[0],f.input({targetNumber:f.current(1).account_number})));await assert.rejects(f.service.transfer(f.users[1],f.input({confirmed:true})),e=>e.status===403);const r=await f.service.transfer(f.users[0],f.input({targetNumber:f.current(1).account_number,confirmed:true,mode:'instant'}));assert.equal(r.state,'posted');const account=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(1).id]);assert.equal(account.balance_minor,1000);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).balance_minor,9000);}finally{f.db.close();}});
test('instant package allowance is atomic, counts unique instructions and never silently falls back',async()=>{const f=await setup();try{for(let i=0;i<5;i++){const body=f.input({mode:'instant',amount:'1.00'});await f.service.transfer(f.users[0],body);assert.equal((await f.service.transfer(f.users[0],body)).replayed,true);}await assert.rejects(f.service.transfer(f.users[0],f.input({mode:'instant'})),e=>e.status===409);assert.equal((await f.db.first('SELECT * FROM pb_instant_usage')).used,5);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,5);}finally{f.db.close();}});
test('revoked queued authority releases the reservation without moving money',async()=>{const f=await setup();try{const body=f.input();await f.service.transfer(f.users[0],body);f.revoke();const r=await f.service.processQueue();assert.equal(r.rejected,1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.balance_minor,10000);assert.equal(a.reserved_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.db.first('SELECT * FROM pb_orders')).state,'rejected');}finally{f.db.close();}});
test('failed ledger posting rolls back both balances, instant usage and the instruction',async()=>{const f=await setup();try{f.db.sqlite.exec("CREATE TRIGGER fail_entry BEFORE INSERT ON pb_entries BEGIN SELECT RAISE(ABORT,'injected ledger failure'); END;");await assert.rejects(f.service.transfer(f.users[0],f.input({mode:'instant'})));assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).balance_minor,10000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_instant_usage')).n,0);}finally{f.db.close();}});
test('recipient lookup is literal and statements expose only authorised account records',async()=>{const f=await setup();try{const r=await f.service.recipients(f.users[0],f.current(1).account_number);assert.equal(r.length,1);assert.equal(r[0].number,f.current(1).account_number);assert.equal((await f.service.recipients(f.users[0],'citizen_1')).length,2);assert.deepEqual(await f.service.recipients(f.users[0],'citizen%'),[]);await f.service.transfer(f.users[0],f.input({mode:'instant'}));const statement=await f.service.activity(f.users[0],{accountId:String(f.current(0).id)});assert.equal(statement.records[0].balanceAfter,'90.00');assert.equal(statement.records[0].direction,'debit');await assert.rejects(f.service.activity(f.users[1],{accountId:String(f.current(0).id)}),e=>e.status===403);assert.equal((await f.service.activity(f.users[2])).records.length,0);}finally{f.db.close();}});
test('planned, dormant and system accounts cannot be payment sources or beneficiaries',async()=>{const f=await setup();try{await f.db.query("UPDATE pb_accounts SET system_key='sys_payroll_po' WHERE id=?",[f.savings(0).id]);const opts=await f.service.accounts(f.users[0]);assert.equal(opts.find(a=>a.id===String(f.savings(0).id)).canReceive,false);await assert.rejects(f.service.transfer(f.users[0],f.input()),e=>e.status===409);await f.db.query("UPDATE pb_accounts SET system_key=NULL,state='dormant' WHERE id=?",[f.savings(0).id]);await assert.rejects(f.service.transfer(f.users[0],f.input()),e=>e.status===409);}finally{f.db.close();}});
test('bank transfer routes reject wrong origin, identity overrides and fractional JSON numbers',async()=>{const f=await setup();try{const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>f.users[0],authority:f.authority}),base='https://cp.dunerealms.com';const request=(body,origin=base)=>new Request(base+'/api/bank/transfers',{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal((await api(request(f.input(),'https://other.invalid'))).status,403);assert.equal((await api(request(f.input({amount:10.1})))).status,400);assert.equal((await api(new Request(base+'/api/bank/activity?actor=other'))).status,400);assert.equal((await api(new Request(base+'/api/bank/transfer-options'))).status,200);}finally{f.db.close();}});
test('one failed queued posting retains its hold without blocking another instruction',async()=>{const f=await setup();try{const bad=f.input(),good=f.input();await f.service.transfer(f.users[0],bad);await f.service.transfer(f.users[0],good);f.db.sqlite.exec("CREATE TRIGGER fail_one_entry BEFORE INSERT ON pb_entries WHEN NEW.order_id='"+bad.requestId+"' BEGIN SELECT RAISE(ABORT,'isolated ledger fault'); END;");const result=await f.service.processQueue();assert.equal(result.failed,1);assert.equal(result.posted,1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.balance_minor,9000);assert.equal(a.reserved_minor,1000);assert.equal((await f.db.first('SELECT * FROM pb_orders WHERE id=?',[bad.requestId])).state,'queued');f.db.sqlite.exec('DROP TRIGGER fail_one_entry');assert.equal((await f.service.processQueue()).posted,1);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,0);}finally{f.db.close();}});
test('standard settlement uses four-hour Brussels windows and leaves newer instructions reserved',async()=>{assert.deepEqual(standardCycle(Date.parse('2026-11-13T20:30:00Z')),{cutoff:Date.parse('2026-11-13T19:00:00Z'),nextAt:Date.parse('2026-11-13T23:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-10-25T02:30:00Z')),{cutoff:Date.parse('2026-10-24T22:00:00Z'),nextAt:Date.parse('2026-10-25T03:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-03-29T01:30:00Z')),{cutoff:Date.parse('2026-03-28T23:00:00Z'),nextAt:Date.parse('2026-03-29T02:00:00Z')});const f=await setup();try{await f.service.transfer(f.users[0],f.input());const tooEarly=await f.service.processQueue({cutoff:Date.parse('2026-11-13T19:00:00Z')});assert.equal(tooEarly.attempted,0);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,1000);assert.equal((await f.service.processQueue({cutoff:Date.parse('2026-11-13T23:00:00Z')})).posted,1);}finally{f.db.close();}});