diff --git a/docs/design/INGAME-GUI-FUTURE.md b/docs/design/INGAME-GUI-FUTURE.md new file mode 100644 index 00000000..08c6c6a3 --- /dev/null +++ b/docs/design/INGAME-GUI-FUTURE.md @@ -0,0 +1,57 @@ +# Future ingame GUI extension + +User specification, 17 November 2026. Deferred until the ingame phase. This is +not approval to implement, install, upgrade servers or deploy. Continue the +current website work first. Existing implementation reference: [Native GUI](../Native-GUI.md). + +## Scope and sequence + +Extend the existing DuneRealms GUI. Inspect `gui-common`, `NativeMenus`, +`MenuSession` and current menu integrations before planning changes. Inventory +the actions that actually exist; planned functions must not appear operational. +Ingame exposes basic functions; advanced administration opens the website. + +Before implementation, prepare updated Java and Bedrock wireframes without +artwork and obtain design approval. Any production installation or deployment +requires a separate instruction. + +## Shared player menu + +1. Transportation: world travel, homes, spawn and teleport requests. +2. Communication: chat channels, private messages and replies. +3. Exchange: browse, offer and buy items. +4. Faction: local Home Block, claims and war gameplay. +5. Separate payment action: `/pay `. +6. Website buttons for advanced management. + +## Two renderers, one action system + +Keep existing native Floodgate forms for Bedrock. Investigate MC GUI as an +optional HTML/CSS renderer for Java, retaining native Java dialogs as fallback. +Check current MC GUI version and resource-pack requirements against the actual +server version at that time. Do not automatically upgrade the server. + +Both renderers share menu definitions, data, actions and permission checks. +Reuse existing gameplay and authority systems. Keep colours, labels, category +order, supported artwork and navigation consistent; pixel-identical screens +are not required. + +## Interaction and appearance + +Every action must work with one ordinary click or tap. No required right-click, +shift-click, hover or drag-and-drop. Show details after selecting an entry. +Provide visible quantity, confirm and cancel buttons, with consistent Back and +Close positions. Purchases and other consequential actions need explicit +confirmation screens. + +After design approval, Java can have suitable backgrounds, frames, category art, +item cards, active tabs and recognisable locked buttons. Keep animation and +sound subtle. + +## Authority and execution + +Use LuckPerms-compatible `dunegui.*` nodes per category and action. Visibility +never grants authority: the existing action rechecks permissions, deeds, +ownership, balance and all other domain conditions. Retain owner-bound sessions +and prevent duplicate execution. Do not create a second gameplay or permission +system for the richer renderer. diff --git a/website/control-panel/public/cp-v2/cp-v2-credit-dossier.css b/website/control-panel/public/cp-v2/cp-v2-credit-dossier.css new file mode 100644 index 00000000..75fac161 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-credit-dossier.css @@ -0,0 +1,8 @@ +.pb-credit-dossier-header{position:relative;isolation:isolate;overflow:hidden;margin:22px 0;padding:clamp(24px,4vw,40px)!important;border:1px solid #b59a59!important;border-radius:18px!important;background:linear-gradient(105deg,#173c35f5,#16343de8),url('https://www.dunerealms.com/assets/postbank-transfer-hall-v1.png') center/cover!important;box-shadow:inset 0 1px 0 #efd59b33,0 12px 28px #0002} +.pb-credit-dossier-header:after{content:'';position:absolute;z-index:-1;right:24px;top:22px;width:130px;height:130px;background:url('https://www.dunerealms.com/assets/imperial-seal-128.png') center/contain no-repeat;opacity:.13;pointer-events:none} +.pb-credit-dossier-header>small{display:block;color:#cfb574;letter-spacing:.14em;font:700 11px/1.6 Arial,sans-serif}.pb-credit-dossier-header h3{margin:12px 0 16px;font:700 clamp(23px,3vw,32px)/1.25 Georgia,serif;color:#efd698}.pb-credit-dossier-header>strong{display:block;overflow-wrap:anywhere;font:600 14px/1.8 system-ui,sans-serif;letter-spacing:.03em;color:#d1d7c5}.pb-credit-dossier-header>p{margin:12px 0 0;line-height:1.7} +.pb-credit-contract-panel{min-width:0;padding:18px 0;display:flow-root}.pb-credit-detail-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;margin:8px 0 24px}.pb-credit-fact-card{position:relative;min-width:0;padding:24px;border:1px solid #9c8952;border-radius:14px;background:linear-gradient(130deg,#244339e8,#0e2a24f5);box-shadow:inset 0 1px 0 #e9d39826}.pb-credit-fact-card:nth-child(2){background:linear-gradient(130deg,#223e47,#112d30)}.pb-credit-fact-card:nth-child(4){background:linear-gradient(130deg,#343b36,#142f29)}.pb-credit-fact-card h4{margin:0 0 15px;color:#ecd291;font:700 21px/1.35 Georgia,serif}.pb-credit-fact-card p{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.8}.pb-credit-fact-card dl{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:12px 18px;margin:0;font:14px/1.7 system-ui,sans-serif}.pb-credit-fact-card dt{color:#c1cbbd}.pb-credit-fact-card dd{margin:0;color:#efdc9e;font-weight:650;text-align:right;overflow-wrap:anywhere} +.pb-credit-dossier-reference{padding:13px 17px;border-left:3px solid #9b8b58;color:#bfcbbd;overflow-wrap:anywhere;font:12px/1.8 system-ui,sans-serif}.pb-credit-limit-note{padding:18px 22px;border:1px solid #5d785c;border-radius:12px;background:#19362c;line-height:1.8}.pb-credit-contract-panel>.pb-credit-notice{padding:22px 26px;border-radius:12px;line-height:1.8;margin:18px 0}.pb-credit-contract-panel>.pb-credit-action-form{margin:22px 0;padding:24px;border:1px solid #8d8357;border-radius:14px;background:linear-gradient(130deg,#1c3b31,#122e27)}.pb-credit-contract-panel>.pb-credit-action-form input[type=checkbox]{width:18px!important;height:18px!important;min-height:0!important;margin:0 10px 0 0!important;vertical-align:middle;accent-color:#cfb36d}.pb-credit-contract-panel>.pb-credit-action-form button{display:block;max-width:100%;margin-top:18px;padding:12px 22px;border:1px solid #b39a58;border-radius:8px;background:#1e453c;color:#efda9b;font-weight:700;cursor:pointer}.pb-credit-contract-panel>.pb-credit-action-form button:disabled{opacity:.55;cursor:default}.pb-credit-contract-panel>details{margin-top:22px;padding:16px 20px;border:1px solid #586e52;border-radius:10px;background:#102d24}.pb-credit-contract-panel .pb-ledger-scroll{margin-top:22px} +@media(max-width:700px){.pb-credit-detail-grid{grid-template-columns:minmax(0,1fr);gap:14px}.pb-credit-fact-card{padding:20px}.pb-credit-fact-card dl{grid-template-columns:minmax(0,1fr)}.pb-credit-fact-card dd{text-align:left;margin-top:-8px}.pb-credit-dossier-header:after{width:90px;height:90px;right:12px;top:16px}.pb-credit-contract-panel>.pb-credit-action-form{padding:20px}} + +.pb-credit-contract-panel>.pb-credit-action-form{display:grid;gap:16px}.pb-credit-action-form label:has(input[type=checkbox]){display:grid;grid-template-columns:20px minmax(0,1fr);gap:12px;align-items:start}.pb-credit-action-form label:has(input[type=checkbox])>span{grid-column:2;grid-row:1;line-height:1.7}.pb-credit-action-form label:has(input[type=checkbox])>input{grid-column:1;grid-row:1;margin-top:3px!important}.pb-credit-action-form :focus-visible{outline:2px solid #edcf81;outline-offset:3px} diff --git a/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs b/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs index 6c1d77c1..a62bd167 100644 --- a/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-postbank-credit.mjs @@ -14,6 +14,7 @@ export function creditReviewSelection(search=''){ } export function codexLoanSelection(search=''){const query=new URLSearchParams(search);const id=query.get('codexLoan');return query.getAll('codexLoan').length===1&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id||'')?id.toLowerCase():null;} export function mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalThis.location?.search||''}={}){ + if(!document.querySelector('link[data-credit-dossier]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-credit-dossier.css',import.meta.url).href;css.dataset.creditDossier='';document.head.append(css);} const review=id==='loan-administration'?creditReviewSelection(reviewSearch):null,dossierId=codexLoanSelection(reviewSearch)||review?.loanId||null; const abort=new AbortController(),api=createUserAPI(fetcher,abort.signal);let active=true,busy=false,view,notice=null; 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()}); @@ -42,11 +43,11 @@ export function mountPostbankCredit(host,id,{fetcher=fetch,reviewSearch=globalTh function applicationForm(host,product,account,values,data){ const grant=product.group==='grants',box=el('section',undefined,'pb-box'),motivation=el('textarea');motivation.required=!grant;motivation.minLength=10;motivation.maxLength=4000;box.append(el('h3',grant?'Accept your launch grant':'Request this credit'));const form=instruction(box,product.group==='grants'?'Accept launch grant':'Submit for bank review','/api/bank/credit/apply',()=>({...values,...(grant?{}:{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.')});if(!grant)form.prepend(field('Purpose and repayment plan',motivation));host.append(box); } - function dossier(){const staff=id==='loan-administration',loan=(staff?view.applications:view.loans).find(row=>row.id.toLowerCase()===dossierId);const back=el('a',staff?'← Credit Management':'← My Credit');back.href='/#bank/'+(staff?'loan-administration':'bank-loans');frame.content.append(back);if(!loan){frame.content.append(el('p','This J.A.R.V.I.S. dossier is unavailable to your account.'));return;}const header=el('section',undefined,'pb-box');header.append(el('small','CODEX · IMPERIAL POSTBANK'),el('h3','Credit application dossier'),el('strong',loan.codex?.reference||codexLoanReference(loan.id)),el('p','Status: '+human(loan.codex?.status||codexLoanStatus(loan.state))+' · Bank state: '+human(loan.state)),el('p',human(loan.productKey)+' · '+loan.principal+' DM'));if(staff)header.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band),el('p',loan.score.flags.join(' · ')));frame.content.append(header);const details=contractDetails(frame.content,loan,staff);queueMicrotask(()=>{if(active){details.open=true;void details.ontoggle();}});} + function dossier(){const staff=id==='loan-administration',loan=(staff?view.applications:view.loans).find(row=>row.id.toLowerCase()===dossierId);const back=el('a',staff?'← Credit Management':'← My Credit');back.href='/#bank/'+(staff?'loan-administration':'bank-loans');frame.content.append(back);if(!loan){frame.content.append(el('p','This J.A.R.V.I.S. dossier is unavailable to your account.'));return;}const header=el('section',undefined,'pb-box pb-credit-dossier-header');header.append(el('small','J.A.R.V.I.S. · IMPERIAL POSTBANK'),el('h3','Credit application dossier'),el('strong',loan.codex?.reference||codexLoanReference(loan.id)),el('p','Status: '+human(loan.codex?.status||codexLoanStatus(loan.state))+' · Bank state: '+human(loan.state)),el('p',human(loan.productKey)+' · '+loan.principal+' DM'));if(staff)header.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band),el('p',loan.score.flags.join(' · ')));frame.content.append(header);const details=contractDetails(frame.content,loan,staff);queueMicrotask(()=>{if(active){details.open=true;void details.ontoggle();}});} function contractDetails(host,loan,staff=false,detailRow=null){ if(!dossierId){const link=el('a','Open J.A.R.V.I.S. dossier →');link.href='/?codexLoan='+encodeURIComponent(loan.id)+'#bank/'+(staff?'loan-administration':'bank-loans');const reference=el('small',loan.codex?.reference||codexLoanReference(loan.id));host.append(reference,link);return link;} - let loaded=false;const expand=el('details'),summary=el('summary','+ Contract details & actions'),body=el('div');body.className='pb-credit-contract-panel';body.id='credit-contract-'+loan.id;summary.setAttribute('aria-controls',body.id);if(detailRow){detailRow.firstElementChild.append(body);expand.append(summary);}else expand.append(summary,body);host.append(expand);expand.ontoggle=async()=>{if(detailRow)detailRow.hidden=!expand.open;summary.setAttribute('aria-expanded',String(expand.open));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 · First instalment: '+(d.quote.firstInstalment||'0.00')+' DM'+(d.collateral!=='0.00'?' · Historical pledged collateral: '+d.collateral+' DM':'')),el('p','Settlement estimate today: '+d.settlement+' DM'),el('p',d.decision||'No decision recorded.'));if(d.codex){body.append(el('p','J.A.R.V.I.S. dossier: '+d.codex.reference+' · '+human(d.codex.status)));}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; - if(!staff&&d.maximumRepayment!==undefined)body.append(el('p','Queued repayments / recoveries: '+d.queuedRepayments+' DM · Maximum additional repayment today: '+d.maximumRepayment+' DM. Available account funds are checked separately.')); + let loaded=false;const expand=el('details'),summary=el('summary','+ Contract details & actions'),body=el('div');body.className='pb-credit-contract-panel';body.id='credit-contract-'+loan.id;summary.setAttribute('aria-controls',body.id);if(detailRow){detailRow.firstElementChild.append(body);expand.append(summary);}else expand.append(summary,body);host.append(expand);expand.ontoggle=async()=>{if(detailRow)detailRow.hidden=!expand.open;summary.setAttribute('aria-expanded',String(expand.open));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;const facts=el('div',undefined,'pb-credit-detail-grid'),card=(title,copy)=>{const node=el('section',undefined,'pb-credit-fact-card');node.append(el('h4',title),copy);facts.append(node);return node;};card('Application',el('p',loan.motivation||'No motivation was provided.'));const terms=el('dl');for(const [label,value]of [['Annual interest',d.quote.annualRate+'%'],['Total repayment',d.quote.totalRepayment+' DM'],['First instalment',(d.quote.firstInstalment||'0.00')+' DM']])terms.append(el('dt',label),el('dd',value));if(typeof d.collateral==='string'&&d.collateral!=='0.00')terms.append(el('dt','Historical pledged collateral'),el('dd',d.collateral+' DM'));card('Contract terms',terms);const settlement=el('dl');settlement.append(el('dt','Settlement estimate today'),el('dd',d.settlement+' DM'));card('Settlement',settlement);card('Recorded decision',el('p',d.decision||'No decision recorded.'));body.replaceChildren(facts);if(d.codex){body.append(el('p','J.A.R.V.I.S. dossier: '+d.codex.reference+' · '+human(d.codex.status),'pb-credit-dossier-reference'));}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; + if(!staff&&d.maximumRepayment!==undefined)body.append(el('p','Queued repayments / recoveries: '+d.queuedRepayments+' DM · Maximum additional repayment today: '+d.maximumRepayment+' DM. Available account funds are checked separately.','pb-credit-limit-note')); if(enabled&&!staff){if(d.state==='offered')instruction(body,'Accept credit offer','/api/bank/credit/action',()=>({loanId:loan.id,action:'accept',expectedVersion:d.version,reason:'Accepted the disclosed credit offer'}),{reason:false,confirmation:'I accept the full repayment cost and authorise the first instalment from my own funds before the loan is issued. It reduces my remaining debt.'});if(['submitted','approved_pending','offered','payout_queued'].includes(d.state))instruction(body,'Withdraw application','/api/bank/credit/action',()=>({loanId:loan.id,action:'withdraw'}));if(['active','arrears'].includes(d.state))instruction(body,'Make a repayment','/api/bank/credit/action',()=>({loanId:loan.id,action:'repay'}),{amount:true,confirmation:'Debit the linked current account at the next four-hour bank window. Earned interest is charged; future interest is waived. Confirmed reserved funds retain their bank value date.'});} if(enabled&&staff){if(d.state==='submitted'&&loan.canReview){const approveForm=instruction(body,'Approve application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'approve'}),{risk:loan.score.score<400||loan.score.flags.includes('High Monthly Commitments')});const declineForm=instruction(body,'Reject application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'decline'}));if(review?.loanId===loan.id){const selected=review.action==='approve'?approveForm:declineForm;selected.classList.add('pb-credit-selected-decision');selected.prepend(el('h3',review.action==='approve'?'Confirm approval':'Confirm rejection'));queueMicrotask(()=>{if(active){selected.scrollIntoView?.({block:'center',behavior:'smooth'});selected.querySelector?.('textarea')?.focus();}});}}if(d.state==='arrears')instruction(body,'Recover pledged collateral','/api/bank/admin/credit/recover',()=>({loanId:loan.id,action:'recover'}),{amount:true,confirmation:'Recover only this contract’s pledged DM to reduce its debt. No inventory is involved.'});} if(d.schedule.length){const {wrap,body:rows}=grid(['Due date','Principal · DM','Interest · DM','Paid · DM','Status']);for(const row of d.schedule){const tr=el('tr');for(const value of [new Date(row.dueAt).toLocaleDateString('en-GB'),row.principal,row.interest,row.paid,human(row.state)])tr.append(el('td',value));rows.append(tr);}body.append(wrap);}else body.append(el('p','The repayment schedule starts only when funds are disbursed.'));const history=el('details');history.append(el('summary','Dossier history'));if(Array.isArray(d.events)&&d.events.length){const {wrap,body:rows}=grid(['Recorded','Action']);for(const event of d.events){const row=el('tr');row.append(el('td',new Date(event.createdAt).toLocaleString('en-GB')),el('td',human(event.action)));rows.append(row);}history.append(wrap);}else history.append(el('p',Array.isArray(d.events)?'No dossier events are recorded.':'Dossier history is unavailable.'));body.append(history);if(review?.loanId===loan.id&&(!enabled||!loan.canReview||d.state!=='submitted')){const explanation=d.state!=='submitted'?'This application is already '+human(d.state).toLowerCase()+'.':!enabled?'Credit decisions are unavailable for your account or processing is paused.':'A different bank manager must review this application because you submitted it or control its borrowing account. No decision has been recorded; the J.A.R.V.I.S. dossier remains pending.';const message=el('aside',explanation,'pb-credit-notice');message.setAttribute('role','status');body.prepend(message);queueMicrotask(()=>{if(active)message.scrollIntoView?.({block:'center'});});} diff --git a/website/tests/postbank-credit-ui.test.mjs b/website/tests/postbank-credit-ui.test.mjs index 5baae930..b39aea87 100644 --- a/website/tests/postbank-credit-ui.test.mjs +++ b/website/tests/postbank-credit-ui.test.mjs @@ -2,7 +2,7 @@ import {randomUUID} from 'node:crypto';import {BankFixture} from './postbank-fix 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={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;}} +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');}); @@ -20,7 +20,7 @@ test('My Credit links to an authorised J.A.R.V.I.S. dossier instead of fetching },{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.textContent.includes('Settlement estimate today: 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); + 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'};