forked from unimatrix/web
Unify credit product cards and add account tabs with focused simulator
This commit is contained in:
parent
e6c8cfacd4
commit
70f3219c19
3 changed files with 23 additions and 7 deletions
|
|
@ -1,6 +1,7 @@
|
|||
import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs';
|
||||
import {createUserAPI} from './cp-v2-user-api.mjs';
|
||||
import {packageBrand} from './cp-v2-postbank-foundation.mjs';
|
||||
export const creditTheme=p=>({grant_start:'start',grant_build:'connect',grant_advance:'scale',personal_loan:'flow',personal_overdraft:'start',personal_card:'public',business_loan:'connect',civic_loan:'civic'}[p.key]||(p.group==='refinancing'?'scale':'flow'));
|
||||
const title={'loan-centre':'Loans & Grants','bank-loans':'My Credit','loan-administration':'Credit Management'},human=s=>String(s).replace(/_/g,' ').replace(/\b[a-z]/g,c=>c.toUpperCase());
|
||||
function field(name,input){const label=el('label',undefined,'pb-transfer-field');label.append(el('span',name),input);return label;}
|
||||
function option(select,label,value){const o=el('option',label);o.value=value;select.append(o);}
|
||||
|
|
@ -10,15 +11,21 @@ export function mountPostbankCredit(host,id,{fetcher=fetch}={}){
|
|||
const frame=createCPV2ContentPage({host,title:title[id],description:id==='loan-centre'?'Explore launch grants and credit, compare repayments and review the full cost.':id==='bank-loans'?'Your applications, borrowing and repayment records, kept separate for each banking client.':'Review applications, evidence and client-specific borrowing risk.',reload:()=>void load()});
|
||||
async function load(){if(busy)return;busy=true;frame.status.hidden=false;frame.status.textContent='Loading authorised credit records…';try{view=await api.request(id==='loan-administration'?'/api/bank/admin/credit':'/api/bank/credit/overview');if(!active)return;frame.content.replaceChildren();if(id==='loan-centre')catalogue();else if(id==='bank-loans')myCredit();else management();frame.status.hidden=true;frame.diagnostics.textContent='Central API · Independent bank database · '+new Date().toLocaleString('en-GB');}catch(e){if(active)frame.status.textContent=e.message;}finally{busy=false;}}
|
||||
function catalogue(){
|
||||
frame.content.append(el('p','Compare the full repayment cost before borrowing. Simulations do not move money. Application intake and disbursements open after underwriting and repayment processing are enabled.','pb-muted'));
|
||||
frame.content.append(el('p','Choose your borrowing account and compare the full repayment cost. A simulation never moves money.','pb-muted'));
|
||||
const accounts=view.accounts.filter(a=>a.canApply);if(!accounts.length){frame.content.append(el('p','Activate an eligible personal or organisational current account in My Products first.'));return;}
|
||||
const select=el('select');for(const a of accounts)option(select,a.name,a.id);frame.content.append(field('Borrowing account',select));const products=el('div',undefined,'pb-credit-products'),simulation=el('section',undefined,'pb-credit-simulation');frame.content.append(products,simulation);
|
||||
function renderProducts(){products.replaceChildren();simulation.replaceChildren();const a=accounts.find(a=>a.id===select.value);for(const [group,label]of [['grants','Launch Grants'],['personal','Personal Loans'],['professional','Business & Civic Loans'],['refinancing','Refinancing']]){const choices=view.products.filter(p=>p.group===group&&p.kinds.includes(a.kind));if(!choices.length)continue;const section=el('section',undefined,'pb-credit-category'),cards=el('div',undefined,'pb-package-choices');section.append(el('h2',label),cards);for(const p of choices){const card=el('section',undefined,'pb-credit-product pb-plan-'+(group==='grants'?'flow':group==='refinancing'?'scale':'civic')),brand=packageBrand({key:group==='grants'?'pb_start':group==='refinancing'?'pb_scale':'pb_connect',name:p.name});card.append(brand,el('strong',p.amount?p.amount+' DM':p.min+'–'+p.max+' DM'),el('p',(p.annualBps/100).toFixed(2)+'% annual interest'),el('p',group==='grants'?'No collateral · choose your monthly repayment':'25% blocked DM collateral · client funds only'));const choose=el('button',group==='refinancing'||p.revolving?'Integration in preparation':'Simulate repayments');choose.type='button';choose.disabled=group==='refinancing'||!!p.revolving;choose.onclick=()=>simulator(p,a,simulation);card.append(choose);cards.append(card);}products.append(section);}}
|
||||
select.onchange=renderProducts;renderProducts();
|
||||
let selected=accounts[0];const tabs=el('div',undefined,'pb-credit-account-tabs'),stage=el('section',undefined,'pb-credit-stage');tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Borrowing account');stage.id='pb-credit-account-panel';stage.setAttribute('role','tabpanel');const buttons=[];
|
||||
for(const account of accounts){const button=el('button',undefined,'pb-credit-account-tab');button.type='button';button.setAttribute('role','tab');button.id='pb-credit-account-tab-'+buttons.length;button.setAttribute('aria-controls',stage.id);button.append(el('strong',account.holder||account.name),el('small',account.name+' · '+account.number.replace(/(.{4})/g,'$1 ').trim()));button.onclick=()=>{if(busy)return;selected=account;renderProducts();};buttons.push({button,account});tabs.append(button);}
|
||||
frame.content.append(tabs,stage);
|
||||
function renderProducts(){for(const {button,account} of buttons){const chosen=account.id===selected.id;button.setAttribute('aria-selected',String(chosen));button.tabIndex=chosen?0:-1;if(chosen)stage.setAttribute('aria-labelledby',button.id);}stage.replaceChildren();const products=el('div',undefined,'pb-credit-products');stage.append(products);for(const [group,label]of [['grants','Launch Grants'],['personal','Personal Loans'],['professional','Business & Civic Loans'],['refinancing','Refinancing']]){const choices=view.products.filter(p=>p.group===group&&p.kinds.includes(selected.kind));if(!choices.length)continue;const section=el('section',undefined,'pb-credit-category'),cards=el('div',undefined,'pb-package-choices');section.append(el('h2',label),cards);
|
||||
for(const product of choices){const theme=creditTheme(product),card=el('section',undefined,'pb-choice-card pb-credit-product pb-plan-'+theme),brand=packageBrand({key:'pb_'+theme,name:product.name}),price=el('div',undefined,'pb-credit-price');price.append(el('strong',product.amount?product.amount+' DM':product.min+'–'+product.max+' DM'),el('small',(product.annualBps/100).toFixed(2)+'% annual interest'));const list=el('ul');for(const text of group==='grants'?['No collateral required','Choose your monthly repayment','Up to 12 monthly instalments']:['Fixed repayment schedule','25% blocked DM collateral','Client funds only'])list.append(el('li',text));const choose=el('button',group==='refinancing'||product.revolving?'Coming soon':'Simulate repayments','pb-credit-simulate');choose.type='button';choose.disabled=group==='refinancing'||!!product.revolving;choose.onclick=()=>{if(busy)return;stage.replaceChildren();simulator(product,selected,stage,renderProducts);};card.append(brand,price,list,choose);cards.append(card);}products.append(section);}
|
||||
}
|
||||
tabs.onkeydown=e=>{const index=buttons.findIndex(b=>b.button===e.target);if(index<0||!['ArrowLeft','ArrowRight','Home','End'].includes(e.key)||busy)return;e.preventDefault();const next=e.key==='Home'?0:e.key==='End'?buttons.length-1:(index+(e.key==='ArrowRight'?1:-1)+buttons.length)%buttons.length;buttons[next].button.onclick();buttons[next].button.focus();};renderProducts();
|
||||
}
|
||||
function simulator(product,account,host){
|
||||
host.replaceChildren(el('h2',product.name+' · Repayment Simulator'));const form=el('form',undefined,'pb-transfer-form'),amount=el('input'),term=el('select'),monthly=el('input'),send=el('button','Calculate repayments'),result=el('div'),message=el('p');amount.type=monthly.type='text';amount.inputMode=monthly.inputMode='decimal';amount.required=monthly.required=true;amount.value=product.amount||product.min;monthly.value=product.amount?String(Math.ceil(Number(product.amount)/12)):'';send.type='submit';if(product.group==='grants'){amount.readOnly=true;form.append(field('Grant amount · DM',amount),field('Your monthly repayment · DM',monthly));}else{for(const m of product.terms)option(term,m+' months',String(m));form.append(field('Loan amount · DM',amount),field('Repayment period',term));}form.append(send,message);host.append(form,result);
|
||||
form.onsubmit=async e=>{e.preventDefault();if(busy||!form.reportValidity())return;busy=true;send.disabled=true;message.textContent='Calculating…';try{const body={accountId:account.id,productKey:product.key,...(product.group==='grants'?{monthly:monthly.value}:{amount:amount.value,months:Number(term.value)})},data=await api.request('/api/bank/credit/simulate',body);if(!active)return;message.textContent='';result.replaceChildren();const metrics=el('div',undefined,'pb-admin-metrics');for(const [label,value]of [['Monthly repayment',data.quote.monthly+' DM'],['Total interest',data.quote.totalInterest+' DM'],['Total repayment',data.quote.totalRepayment+' DM'],['Required collateral',data.collateral+' DM']]){const card=el('section');card.append(el('small',label),el('strong',value));metrics.append(card);}result.append(metrics,el('p',data.notice),el('p','History: '+(data.score.limitedHistory?'Limited banking history; staff review is required for ordinary loans.':data.score.band+' risk')));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 s of data.quote.schedule){const tr=el('tr');for(const value of [s.number,s.amount,s.principal,s.interest,s.balance])tr.append(el('td',String(value)));rows.append(tr);}detail.append(wrap);result.append(detail,el('p','Application intake is not open yet. This quotation does not create a loan.','pb-muted'));}catch(e){if(active)message.textContent=e.message;}finally{busy=false;if(active)send.disabled=false;}};
|
||||
function simulator(product,account,host,back){
|
||||
const navigation=el('div',undefined,'pb-credit-step'),returnButton=el('button','← Back to credit products');returnButton.type='button';returnButton.onclick=()=>{if(!busy)back();};navigation.append(returnButton,el('span','1. Choose credit / 2. Simulate repayments'));host.append(navigation,el('h2',product.name));
|
||||
const layout=el('div',undefined,'pb-credit-calculator'),form=el('form',undefined,'pb-transfer-form pb-credit-inputs'),amount=el('input'),term=el('select'),monthly=el('input'),send=el('button','Calculate repayments','pb-credit-simulate'),result=el('aside',undefined,'pb-credit-quote'),message=el('p');result.setAttribute('aria-live','polite');result.append(el('h3','Your repayment estimate'),el('p','Choose your amount and repayment period to see your monthly payment and total cost.'));amount.type=monthly.type='text';amount.inputMode=monthly.inputMode='decimal';amount.required=monthly.required=true;amount.value=product.amount||product.min;monthly.value=product.amount?Math.ceil(Number(product.amount)/12).toFixed(2):'';send.type='submit';form.append(el('p',(account.holder||account.name)+' · '+account.number,'pb-muted'));if(product.group==='grants'){amount.readOnly=true;form.append(field('Grant amount · DM',amount),field('Monthly repayment · DM',monthly));}else{for(const m of product.terms)option(term,m+' months',String(m));form.append(field('Loan amount · DM',amount),field('Repayment period',term));}form.append(send,message);layout.append(form,result);host.append(layout);const details=el('div',undefined,'pb-credit-quote-details');host.append(details);
|
||||
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',(product.annualBps/100).toFixed(2)+'%'],['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,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 myCredit(){const {wrap,body}=grid(['Application','Product','Status','Principal · DM','Outstanding · DM','Monthly · DM','Details']);for(const l of view.loans){const tr=el('tr'),cell=el('td'),d=el('details');d.append(el('summary','+ Application'),el('p',l.motivation),el('p',l.annualRate+'% annual interest · '+l.months+' months'),el('p',l.decision||'No bank decision recorded.'));cell.append(d);for(const value of [l.id,human(l.productKey),human(l.state),l.principal,l.outstanding,l.monthly])tr.append(el('td',value));tr.append(cell);body.append(tr);}frame.content.append(wrap);if(!view.loans.length)frame.content.append(el('p','No applications or loans are registered for your authorised banking clients.'));}
|
||||
function management(){frame.content.append(el('p','Credit review workspace. Decisions, disbursements, repayments and collateral movements are not active yet. No financial action is offered here.','pb-muted'));const {wrap,body}=grid(['Client','Product','Submitted','Amount · DM','State','Review']);for(const l of view.applications){const tr=el('tr'),cell=el('td'),d=el('details');d.append(el('summary','+ Review evidence'),el('p',l.motivation),el('p','Credit score: '+l.score.score+' / 1000 · '+l.score.band+(l.score.limitedHistory?' · Limited history':'')),el('p','Required collateral: '+l.collateral+' DM'),el('p','Monthly repayment: '+l.monthly+' DM'));cell.append(d);for(const value of [l.entity,human(l.productKey),new Date(l.createdAt).toLocaleDateString('en-GB'),l.principal,human(l.state)])tr.append(el('td',value));tr.append(cell);body.append(tr);}frame.content.append(wrap);if(!view.applications.length)frame.content.append(el('p','No credit applications are awaiting review.'));}
|
||||
|
|
|
|||
|
|
@ -226,3 +226,6 @@
|
|||
|
||||
|
||||
.pb-reserve-public{max-width:1500px;margin:30px auto;padding:0 24px}.pb-reserve-public .cp-v2-template-heading{padding:36px;border:1px solid #bc9dce;border-radius:16px;background:linear-gradient(120deg,#30283d,#17372d);margin-bottom:24px}.pb-reserve-information{display:grid;gap:12px;padding:24px;margin:24px 0;border:1px solid #9d86b7;border-left:4px solid #c8a166;border-radius:14px;background:linear-gradient(120deg,#302d3c,#15362b);font-family:Arial,sans-serif}.pb-reserve-information strong{font-size:22px;color:#e8cf8d}.pb-reserve-information code{color:#c7b0dd}.pb-reserve-information p{margin:0;line-height:1.7}
|
||||
|
||||
/* Credit products use the same package-card vocabulary and palette as accounts. */
|
||||
.pb-credit-product.pb-choice-card{display:flex;padding:30px 26px 26px;gap:24px;background:radial-gradient(ellipse at 95% 0%,color-mix(in srgb,var(--pb-glow) 22%,transparent),transparent 66%),linear-gradient(145deg,var(--pb-tint),#102b24 70%);border-color:color-mix(in srgb,var(--pb-accent) 48%,#12362b);color:#e7e7d6;cursor:default}.pb-credit-product .pb-package-brand{color:var(--pb-accent)}.pb-credit-price{display:grid;gap:8px}.pb-credit-price strong{font-size:25px;color:var(--pb-accent)}.pb-credit-price small{color:#c4d3c5}.pb-credit-product ul{padding-left:20px;margin:0;line-height:1.8;flex:1}.pb-credit-product .pb-credit-simulate,.pb-credit-inputs .pb-credit-simulate{align-self:center;justify-self:center;margin:8px auto 0;display:block}.pb-credit-account-tabs{display:flex;gap:12px;margin:24px 0;flex-wrap:wrap}.pb-credit-account-tab{display:grid;gap:7px;text-align:left;min-width:210px;padding:16px 20px;border-radius:12px}.pb-credit-account-tab small{font-size:12px;font-weight:normal;color:#b9cfc4}.pb-credit-account-tab[aria-selected=true]{background:#2e4b3e;border-color:#ebce7b;box-shadow:inset 0 -3px #ebce7b}.pb-credit-step{display:flex;justify-content:space-between;align-items:center;gap:20px;margin:26px 0;color:#bacec1;font:14px Arial,sans-serif}.pb-credit-calculator{display:grid;grid-template-columns:minmax(0,1fr) minmax(300px,.85fr);gap:28px;align-items:start;font-family:Arial,sans-serif}.pb-credit-inputs{display:grid;grid-template-columns:1fr;gap:24px;padding:28px;margin:0}.pb-credit-quote{position:sticky;top:24px;padding:30px;border:1px solid #8e9168;border-radius:16px;background:linear-gradient(145deg,#304b3e,#132e25);box-shadow:inset 0 1px #ffffff20}.pb-credit-monthly{display:block;font:700 40px Arial,sans-serif;color:#f0d68c;margin:14px 0 28px}.pb-credit-quote dl{display:grid;grid-template-columns:1fr auto;gap:16px;border-top:1px solid #64725b;padding-top:22px}.pb-credit-quote dt{color:#c1d1c5}.pb-credit-quote dd{margin:0;text-align:right;font-weight:600}.pb-credit-quote-details{margin-top:28px}
|
||||
|
|
|
|||
6
website/tests/postbank-credit-ui.test.mjs
Normal file
6
website/tests/postbank-credit-ui.test.mjs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
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;}}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){const prior=globalThis.document;globalThis.document={createElement:t=>new Node(t),createElementNS:(ns,t)=>new Node(t)};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});return Response.json(path.endsWith('/simulate')?{quote:{monthly:'100.00',months:12,totalInterest:'200.00',totalRepayment:'1200.00',schedule:[]},collateral:'250.00',notice:'No financial change'}:{accounts,products,loans:[]});};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');});
|
||||
Loading…
Reference in a new issue

Staff