Fix credit form confirmation field rejected by application API

This commit is contained in:
unimatrixgit 2026-11-14 19:49:47 +01:00
commit 265ef62ab8
2 changed files with 7 additions and 4 deletions

View file

@ -27,12 +27,12 @@ export function mountPostbankCredit(host,id,{fetcher=fetch}={}){
const stale=()=>{result.replaceChildren(el('h3','Update your estimate'),el('p','Your selection changed. Calculate again for the current repayment cost.'));details.replaceChildren();};amount.oninput=monthly.oninput=term.onchange=stale;
form.onsubmit=async e=>{e.preventDefault();if(busy||!form.reportValidity())return;busy=true;send.disabled=true;returnButton.disabled=true;message.textContent='Calculating…';const values={accountId:account.id,productKey:product.key,...(product.group==='grants'?{monthly:monthly.value}:{amount:amount.value,months:Number(term.value)})};amount.disabled=monthly.disabled=term.disabled=true;try{const data=await api.request('/api/bank/credit/simulate',values);if(!active)return;message.textContent='';result.replaceChildren(el('small','Estimated monthly repayment'),el('strong',data.quote.monthly+' DM','pb-credit-monthly'));const totals=el('dl');for(const [label,value]of [['Repayment period',data.quote.months+' months'],['Annual interest',data.quote.annualRate+'%'],['Total interest',data.quote.totalInterest+' DM'],['Total repayment',data.quote.totalRepayment+' DM'],['Required collateral',data.collateral+' DM']])totals.append(el('dt',label),el('dd',value));result.append(totals,el('p','Simulation only · no application or payment','pb-muted'));details.replaceChildren(el('p',data.notice));const detail=el('details'),{wrap,body:rows}=grid(['Instalment','Payment · DM','Principal · DM','Interest · DM','Outstanding · DM']);detail.append(el('summary','+ Full repayment schedule'));for(const row of data.quote.schedule){const tr=el('tr');for(const value of [row.number,row.amount,row.principal,row.interest,row.balance])tr.append(el('td',String(value)));rows.append(tr);}detail.append(wrap);details.append(detail);if(view.intakeEnabled)applicationForm(details,product,account,values,data);else details.append(el('p','Application intake is not open yet. This quotation does not create a loan.','pb-muted'));}catch(error){if(active){message.textContent=error.message;result.replaceChildren(el('h3','Estimate unavailable'),el('p','Review your details and try again.'));details.replaceChildren();}}finally{busy=false;if(active){send.disabled=returnButton.disabled=false;amount.disabled=monthly.disabled=term.disabled=false;}}};
}
function instruction(host,label,path,makeBody,{reason=true,amount=false,risk=false,confirmation='I have reviewed and confirm this instruction.'}={}){
function instruction(host,label,path,makeBody,{reason=true,amount=false,risk=false,confirmationField='confirmed',confirmation='I have reviewed and confirm this instruction.'}={}){
const form=el('form',undefined,'pb-credit-action-form'),reasonField=el('textarea'),amountField=el('input'),riskField=el('input'),check=el('input'),send=el('button',label),message=el('p');reasonField.minLength=5;reasonField.maxLength=500;reasonField.required=reason;if(reason)form.append(field('Reason',reasonField));amountField.type='text';amountField.inputMode='decimal';amountField.required=amount;if(amount)form.append(field('Amount · DM',amountField));riskField.type='checkbox';if(risk)form.append(field('I have reviewed the risk flags and explicitly authorise this override.',riskField));check.type='checkbox';check.required=true;form.append(field(confirmation,check));send.type='submit';form.append(send,message);host.append(form);let pending=null;
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity()||!check.checked)return;busy=true;send.disabled=true;if(!pending)pending={requestId:crypto.randomUUID(),...makeBody(),confirmed:true,...reason?{reason:reasonField.value.trim()}:{} ,...amount?{amount:amountField.value}:{} ,...risk?{riskOverride:riskField.checked}:{}};reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=true;for(const control of form.elements||[])if(control!==send)control.disabled=true;message.textContent='Submitting…';try{await api.request(path,pending);if(!active)return;pending=null;message.textContent='Instruction accepted.';busy=false;await load();}catch(error){if(active){message.textContent=error.uncertain?'Result not confirmed. Retry this same instruction; do not create a new one.':error.message;if(!error.uncertain){pending=null;reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=false;for(const control of form.elements||[])control.disabled=false;}send.textContent=pending?'Retry same instruction':label;}}finally{busy=false;if(active)send.disabled=false;}};return form;
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity()||!check.checked)return;busy=true;send.disabled=true;if(!pending)pending={requestId:crypto.randomUUID(),...makeBody(),[confirmationField]:true,...reason?{reason:reasonField.value.trim()}:{} ,...amount?{amount:amountField.value}:{} ,...risk?{riskOverride:riskField.checked}:{}};reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=true;for(const control of form.elements||[])if(control!==send)control.disabled=true;message.textContent='Submitting…';try{await api.request(path,pending);if(!active)return;pending=null;message.textContent='Instruction accepted.';busy=false;await load();}catch(error){if(active){message.textContent=error.uncertain?'Result not confirmed. Retry this same instruction; do not create a new one.':error.message;if(!error.uncertain){pending=null;reasonField.disabled=amountField.disabled=riskField.disabled=check.disabled=false;for(const control of form.elements||[])control.disabled=false;}send.textContent=pending?'Retry same instruction':label;}}finally{busy=false;if(active)send.disabled=false;}};return form;
}
function applicationForm(host,product,account,values,data){
const box=el('section',undefined,'pb-box'),motivation=el('textarea');motivation.required=true;motivation.minLength=10;motivation.maxLength=4000;box.append(el('h3','Request this credit'));const form=instruction(box,product.group==='grants'?'Accept launch grant':'Submit for bank review','/api/bank/credit/apply',()=>({...values,motivation:motivation.value.trim(),accepted:true,termsVersion:view.termsVersion}),{reason:false,confirmation:'I accept the credit terms: '+data.quote.amount+' DM, '+data.quote.annualRate+'% annually, '+data.quote.monthly+' DM per month. '+(product.group==='grants'?'Disbursement is queued; this grant must be repaid.':'A bank decision and separate offer acceptance are required before funding.')});form.prepend(field('Purpose and repayment plan',motivation));host.append(box);
const box=el('section',undefined,'pb-box'),motivation=el('textarea');motivation.required=true;motivation.minLength=10;motivation.maxLength=4000;box.append(el('h3','Request this credit'));const form=instruction(box,product.group==='grants'?'Accept launch grant':'Submit for bank review','/api/bank/credit/apply',()=>({...values,motivation:motivation.value.trim(),accepted:true,termsVersion:view.termsVersion}),{reason:false,confirmationField:'accepted',confirmation:'I accept the credit terms: '+data.quote.amount+' DM, '+data.quote.annualRate+'% annually, '+data.quote.monthly+' DM per month. '+(product.group==='grants'?'Disbursement is queued; this grant must be repaid.':'A bank decision and separate offer acceptance are required before funding.')});form.prepend(field('Purpose and repayment plan',motivation));host.append(box);
}
function contractDetails(host,loan,staff=false){
let loaded=false;const expand=el('details'),summary=el('summary','+ Contract details & actions'),body=el('div');expand.append(summary,body);host.append(expand);expand.ontoggle=async()=>{if(!expand.open||loaded)return;loaded=true;body.textContent='Loading current contract…';try{const d=await api.request((staff?'/api/bank/admin/credit/details':'/api/bank/credit/details')+'?loanId='+encodeURIComponent(loan.id));if(!active)return;body.replaceChildren(el('p',loan.motivation),el('p','Annual rate: '+d.quote.annualRate+'% · Total repayment: '+d.quote.totalRepayment+' DM · Collateral: '+d.collateral+' DM'),el('p','Settlement estimate today: '+d.settlement+' DM'),el('p',d.decision||'No decision recorded.'));if(d.replacedBy)body.append(el('p','Replaced by refinancing contract '+d.replacedBy+'. Original history is retained.'));for(const notice of d.notices||[]){const box=el('aside',undefined,'pb-credit-notice'+(d.state==='arrears'?' pb-credit-notice-alert':''));box.append(el('strong',notice.subject),el('p',notice.body));body.append(box);}const enabled=staff?view.processing==='active'&&view.canManage:view.intakeEnabled;

View file

@ -1,10 +1,13 @@
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} 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 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}={}){const prior=globalThis.document;globalThis.document={createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};let applyAttempts=0;const host=new Node('div'),calls=[],products=[{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.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:[],intakeEnabled:enabled,termsVersion:'credit-test'});};const dispose=mountPostbankCredit(host,'loan-centre',{fetcher});try{await settle();await run({host,calls,nodes:()=>all(host)});}finally{dispose();globalThis.document=prior;}}
async function fixture(run,{enabled=false,uncertain=false,validateApplication=null}={}){const prior=globalThis.document;globalThis.document={createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};let applyAttempts=0;const host=new Node('div'),calls=[],products=[{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.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:[],intakeEnabled:enabled,termsVersion:CREDIT_VERSION});};const dispose=mountPostbankCredit(host,'loan-centre',{fetcher});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);},{enabled:true,validateApplication:body=>credit.apply(user,body)});}finally{db.close();}});