web/website/tests/postbank-credit-ui.test.mjs

50 lines
13 KiB
JavaScript

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 {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs';
import test from 'node:test';import assert from 'node:assert/strict';import {mountPostbankCredit,creditTheme,creditReviewSelection} from '../control-panel/public/cp-v2/cp-v2-postbank-credit.mjs';
class Node{constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.attrs={};this.classList={add:()=>{}};this.value='';this.disabled=false;this.dataset={};this._text='';}set textContent(v){this._text=String(v);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}append(...nodes){for(const n of nodes){n.parent=this;this.children.push(n);if(this.tagName==='SELECT'&&!this.value)this.value=n.value;}}prepend(...nodes){for(const n of nodes)n.parent=this;this.children.unshift(...nodes);}get firstElementChild(){return this.children[0]||null;}get elements(){return all(this).filter(n=>['INPUT','SELECT','TEXTAREA','BUTTON'].includes(n.tagName));}replaceChildren(...nodes){this._text='';this.children=[];this.append(...nodes);}setAttribute(k,v){this.attrs[k]=String(v);}closest(){return null;}remove(){if(this.parent)this.parent.children=this.parent.children.filter(n=>n!==this);}focus(){}reportValidity(){return true;}}
const all=n=>n.children.flatMap(c=>[c,...all(c)]),settle=async()=>{for(let i=0;i<6;i++)await new Promise(r=>setImmediate(r));};
async function fixture(run,{enabled=false,uncertain=false,validateApplication=null,includeGrant=false,loans=[],pageId="loan-centre",reviewSearch="",detailState="disbursed"}={}){const prior=globalThis.document;globalThis.document={head:new Node('head'),querySelector:()=>null,createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};let applyAttempts=0;const host=new Node('div'),calls=[],products=[...(includeGrant?[{key:'grant_start',name:'Launch Start',group:'grants',kinds:['person'],amount:'2500.00',annualBps:0}]:[]),{key:'personal_loan',name:'Personal Loan',group:'personal',kinds:['person'],min:'1000.00',max:'25000.00',annualBps:839,terms:[3,6]},{key:'business_loan',name:'Business Loan',group:'professional',kinds:['clan'],min:'5000.00',max:'100000.00',annualBps:450,terms:[6,12]}],accounts=[{id:'1',name:'Personal current',number:'DR25102000000005',kind:'person',canApply:true},{id:'2',name:'Clan current',number:'DR14105000000004',kind:'clan',canApply:true}],fetcher=async(path,options={})=>{calls.push({path,...options});if(path.includes('/details?'))return Response.json({quote:{annualRate:'0.00',totalRepayment:'10000.00'},collateral:'0.00',settlement:'10000.00',schedule:[],state:detailState});if(path.endsWith('/apply')&&validateApplication){try{const result=await validateApplication(JSON.parse(options.body));if(!uncertain||applyAttempts++>0)return Response.json(result);}catch(error){return Response.json({message:error.message},{status:error.status||400});}}if(path.endsWith('/apply')&&uncertain&&applyAttempts++===0)return Response.json({message:'Uncertain result'},{status:503});return Response.json(path.endsWith('/simulate')?{quote:{monthly:'100.00',annualRate:'8.39',months:12,totalInterest:'200.00',totalRepayment:'1200.00',schedule:[]},collateral:'250.00',notice:'No financial change'}:{accounts,products,loans,applications:loans,canManage:enabled,processing:enabled?'active':'not_active',intakeEnabled:enabled,termsVersion:CREDIT_VERSION});};const dispose=mountPostbankCredit(host,pageId,{fetcher,reviewSearch});try{await settle();await run({host,calls,nodes:()=>all(host)});}finally{dispose();globalThis.document=prior;}}
test('borrowing tabs filter product cards and simulation replaces the catalogue rather than appearing below it',()=>fixture(async({nodes,calls})=>{const tabs=nodes().filter(n=>n.attrs.role==='tab');assert.equal(tabs.length,2);assert.equal(nodes().filter(n=>n.tagName==='SELECT').length,0);assert.ok(nodes().some(n=>n.className?.includes('pb-choice-card')&&n.className.includes('pb-plan-flow')));tabs[1].onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.ok(!nodes().some(n=>n.tagName==='H5'&&n.textContent==='Personal Loan'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();assert.ok(!nodes().some(n=>n.className?.includes('pb-credit-products')));assert.ok(nodes().some(n=>n.className==='pb-credit-calculator'));const form=nodes().find(n=>n.tagName==='FORM');await form.onsubmit({preventDefault(){}});assert.equal(JSON.parse(calls.find(c=>c.method==='POST').body).accountId,'2');assert.ok(nodes().some(n=>n.className==='pb-credit-monthly'&&n.textContent==='100.00 DM'));nodes().find(n=>n.tagName==='INPUT').oninput();assert.ok(!nodes().some(n=>n.className==='pb-credit-monthly'));nodes().find(n=>n.tagName==='BUTTON'&&n.textContent.startsWith('← Back')).onclick();assert.ok(nodes().some(n=>n.tagName==='H5'&&n.textContent==='Business Loan'));assert.equal(calls.filter(c=>c.method==='POST').length,1);}));
test('credit groups reuse the banking package palette',()=>{assert.equal(creditTheme({key:'grant_start'}),'start');assert.equal(creditTheme({key:'grant_build'}),'connect');assert.equal(creditTheme({key:'grant_advance'}),'scale');assert.equal(creditTheme({key:'business_loan'}),'connect');assert.equal(creditTheme({key:'civic_loan'}),'civic');assert.equal(creditTheme({key:'personal_refinance',group:'refinancing'}),'scale');});
test('application confirmation and uncertain retry retain the same request and frozen disclosures',()=>fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});let form=nodes().find(n=>n.className==='pb-credit-action-form');const motivation=all(form).find(n=>n.tagName==='TEXTAREA'),check=all(form).find(n=>n.type==='checkbox');motivation.value='A genuine loan purpose';await form.onsubmit({preventDefault(){}});assert.equal(calls.filter(c=>c.path.endsWith('/apply')).length,0);check.checked=true;await form.onsubmit({preventDefault(){}});assert.equal(motivation.disabled,true);assert.ok(all(form).some(n=>n.tagName==='BUTTON'&&n.textContent==='Retry same instruction'));await form.onsubmit({preventDefault(){}});const posts=calls.filter(c=>c.path.endsWith('/apply'));assert.equal(posts.length,2);assert.equal(posts[0].body,posts[1].body);assert.equal(JSON.parse(posts[0].body).accountId,'1');assert.equal(JSON.parse(posts[0].body).motivation,'A genuine loan purpose');},{enabled:true,uncertain:true}));
test('bank oversight menus require staff view permission rather than ordinary personal banking',async()=>{const {visibleCPItem}=await import('../control-panel/public/cp-v2/cp-v2-access.mjs');for(const id of ['bank-dashboard','company-finance','loan-administration']){assert.equal(visibleCPItem({permissions:['web.bank.personal.view']},'bank',{id}),false);assert.equal(visibleCPItem({permissions:['web.bank.staff.view']},'bank',{id}),true);}assert.equal(visibleCPItem({permissions:['web.bank.personal.view']},'bank',{id:'loan-centre'}),true);});
test('the real credit form payload is accepted by the strict application service without stray confirmation fields',async()=>{const db=new BankFixture(),user={id:randomUUID(),username:'UI contract borrower'},entity={id:randomUUID(),kind:'person',key:user.id,name:user.username},authority=async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]});try{await new PostbankService(db,authority).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const credit=new PostbankCredit(db,authority);await fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});const form=nodes().find(n=>n.className==='pb-credit-action-form');all(form).find(n=>n.tagName==='TEXTAREA').value='Testing the new submitted credit flow';all(form).find(n=>n.type==='checkbox').checked=true;await form.onsubmit({preventDefault(){}});const payload=JSON.parse(calls.find(c=>c.path.endsWith('/apply')).body);assert.equal(Object.hasOwn(payload,'confirmed'),false);assert.equal(payload.accepted,true);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,1);assert.equal((await db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.ok(nodes().some(n=>!n.hidden&&n.textContent.includes('Application recorded for bank review.')));},{enabled:true,validateApplication:body=>credit.apply(user,body)});}finally{db.close();}});
test('autoaccepted grants show no motivation field and submit without a motivation property',()=>fixture(async({nodes,calls})=>{nodes().find(n=>n.tagName==='BUTTON'&&n.textContent==='Simulate repayments').onclick();await nodes().find(n=>n.tagName==='FORM').onsubmit({preventDefault(){}});assert.equal(nodes().filter(n=>n.tagName==='TEXTAREA').length,0);const form=nodes().find(n=>n.className==='pb-credit-action-form');all(form).find(n=>n.type==='checkbox').checked=true;await form.onsubmit({preventDefault(){}});const payload=JSON.parse(calls.find(c=>c.path.endsWith('/apply')).body);assert.equal(payload.productKey,'grant_start');assert.equal(Object.hasOwn(payload,'motivation'),false);assert.equal(payload.accepted,true);},{enabled:true,includeGrant:true}));
const personalLoan={id:'11111111-1111-4111-8111-111111111111',productKey:'grant_advance',state:'active',principal:'10000.00',outstanding:'10000.00',monthly:'834.00'};
test('My Credit links to an authorised J.A.R.V.I.S. dossier instead of fetching inline ticket details',()=>fixture(async({nodes,calls})=>{
const link=nodes().find(n=>n.tagName==='A'&&n.textContent==='Open J.A.R.V.I.S. dossier →');assert(link);assert.equal(link.href,'/?codexLoan='+personalLoan.id+'#bank/bank-loans');assert.equal(calls.some(c=>c.path.includes('/details?')),false);assert.equal(calls.filter(c=>c.method==='POST').length,0);
},{pageId:'bank-loans',loans:[personalLoan]}));
test('a personal J.A.R.V.I.S. dossier loads full contract details without changing the bank workflow',()=>fixture(async({nodes,calls})=>{
assert(nodes().some(n=>n.tagName==='H3'&&n.textContent==='Credit application dossier'));assert(nodes().some(n=>n.tagName==='DL'&&n.textContent.includes('Settlement estimate today')&&n.textContent.includes('10000.00 DM')));assert(calls.some(c=>c.path==='/api/bank/credit/details?loanId='+personalLoan.id));assert.equal(calls.filter(c=>c.method==='POST').length,0);
},{pageId:'bank-loans',loans:[personalLoan],reviewSearch:'?codexLoan='+personalLoan.id}));
const linkedLoan={id:'bfaaccf2-a33e-4fa1-a64e-995c19b388cb',entity:'Independent applicant',productKey:'civic_loan',state:'submitted',principal:'50000.00',canReview:true,createdAt:1,score:{score:600,band:'Standard',flags:[]},motivation:'A considered public project'};
test('Support decision links open only the linked contract without submitting a decision',()=>fixture(async({nodes,calls})=>{
assert.equal(calls[0].path,'/api/bank/admin/credit?loanId='+linkedLoan.id);
assert.ok(calls.some(c=>c.path==='/api/bank/admin/credit/details?loanId='+linkedLoan.id));
assert.ok(nodes().some(n=>n.tagName==='H3'&&n.textContent==='Confirm approval'));
assert.ok(nodes().some(n=>n.tagName==='FORM'&&n.textContent.includes('Reason')));
assert.equal(calls.filter(c=>c.method==='POST').length,0);
},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'}));
test('an already decided Support application cannot offer another approval',()=>fixture(async({nodes,calls})=>{
assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application'));
assert.ok(nodes().some(n=>n.textContent.includes('already offered')));
assert.equal(calls.filter(c=>c.method==='POST').length,0);
},{pageId:'loan-administration',loans:[linkedLoan],enabled:true,detailState:'offered',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=decline'}));
test('Support review selection rejects invalid identities, duplicate parameters and unknown actions',()=>{
assert.equal(creditReviewSelection('?creditApplication=bad&creditDecision=approve'),null);
assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=approve&creditDecision=decline'),null);
assert.equal(creditReviewSelection('?creditApplication='+linkedLoan.id+'&creditDecision=pay'),null);
});
test('a self-review link explains why confirmation is blocked and keeps the J.A.R.V.I.S. dossier pending',()=>fixture(async({nodes,calls})=>{
assert.ok(nodes().some(n=>n.attrs.role==='status'&&n.textContent.includes('A different bank manager')));
assert.ok(nodes().some(n=>n.textContent.includes('J.A.R.V.I.S. dossier remains pending')));
assert.ok(!nodes().some(n=>n.tagName==='BUTTON'&&n.textContent==='Approve application'));
assert.equal(calls.filter(c=>c.method==='POST').length,0);
},{pageId:'loan-administration',loans:[{...linkedLoan,canReview:false}],enabled:true,detailState:'submitted',reviewSearch:'?creditApplication='+linkedLoan.id+'&creditDecision=approve'}));