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 45103481..82769a94 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 @@ -17,17 +17,31 @@ export function mountPostbankCredit(host,id,{fetcher=fetch}={}){ 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);} + 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',product.revolving?'Coming soon':'Simulate repayments','pb-credit-simulate');choose.type='button';choose.disabled=!!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,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 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));if(product.group==='refinancing')form.append(el('p','We calculate the exact settlement of all interest-bearing loans for this client. Grants remain separate.'));else form.append(field('Loan amount · DM',amount));form.append(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;}}}; + 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 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.'));} + function instruction(host,label,path,makeBody,{reason=true,amount=false,risk=false,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; + } + 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); + } + 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 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.intakeEnabled; + 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 above and authorise the collateral reservation before disbursement.'});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. Early repayment has no future interest charge.'});} + if(enabled&&staff){if(d.state==='submitted'&&loan.canReview){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')});instruction(body,'Decline application','/api/bank/admin/credit/decision',()=>({loanId:loan.id,action:'decline'}));}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.')); + }catch(error){if(active){body.textContent=error.message;loaded=false;}}}; + } + function myCredit(){const {wrap,body}=grid(['Application','Product','Status','Principal · DM','Outstanding · DM','Monthly · DM','Details']);for(const loan of view.loans){const tr=el('tr'),cell=el('td');contractDetails(cell,loan);for(const value of [loan.id,human(loan.productKey),human(loan.state),loan.principal,loan.outstanding,loan.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',view.processing==='active'?'Review the evidence before deciding. Treasury funds are reserved for approved offers; the borrower must accept before disbursement.':'Credit processing is not active yet.','pb-muted'));const {wrap,body}=grid(['Client','Product','Submitted','Amount · DM','State','Review']);for(const loan of view.applications){const tr=el('tr'),cell=el('td');cell.append(el('p','Credit score: '+loan.score.score+' / 1000 · '+loan.score.band+(loan.score.limitedHistory?' · Limited history':'')),el('p',loan.score.flags.join(' · ')));contractDetails(cell,loan,true);for(const value of [loan.entity,human(loan.productKey),new Date(loan.createdAt).toLocaleDateString('en-GB'),loan.principal,human(loan.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.'));} void load();return()=>{active=false;abort.abort();frame.root.remove();}; } diff --git a/website/control-panel/public/cp-v2/v2.css b/website/control-panel/public/cp-v2/v2.css index 53de89df..8dee1985 100644 --- a/website/control-panel/public/cp-v2/v2.css +++ b/website/control-panel/public/cp-v2/v2.css @@ -229,3 +229,6 @@ /* 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} + +.pb-credit-action-form{display:grid;gap:18px;margin:22px 0;padding:24px;border:1px solid #63846b;border-radius:14px;background:linear-gradient(140deg,#1e4033,#102c24);font:15px Arial,sans-serif}.pb-credit-action-form textarea{min-height:100px;resize:vertical}.pb-credit-action-form .pb-transfer-field:has(input[type=checkbox]){display:flex;gap:12px;align-items:center}.pb-credit-action-form input[type=checkbox]{width:20px;height:20px;flex:none}.pb-credit-action-form button{justify-self:start}.pb-credit-product.pb-choice-card{border-radius:17px}.pb-credit-products .pb-package-choices{grid-template-columns:repeat(auto-fit,minmax(min(260px,100%),1fr))} +.pb-credit-notice{padding:18px;border-left:4px solid #c7ae65;background:#263f31;border-radius:8px;margin:14px 0}.pb-credit-notice-alert{border-left-color:#df837c;background:#492b2a}.pb-credit-notice-alert strong{color:#ffc0b7} diff --git a/website/docs/postbank-credit.md b/website/docs/postbank-credit.md new file mode 100644 index 00000000..621172e9 --- /dev/null +++ b/website/docs/postbank-credit.md @@ -0,0 +1,28 @@ +# Postbank credit processing + +Website-only credit engine, using the existing central identity API and the independent bank database. No game database, Java code or inventory is modified. + +## Activation + +`POSTBANK_CREDIT_ENABLED=true` enables application/actions endpoints and the credit section of the existing four-hour Brussels bank ticker. Missing/false keeps financial intake closed while read-only records and simulations work. Deploy and verify the additive schema migration before enabling. No sample customer contract, test credit or balance reset is seeded. + +## Products and cash movement + +- Launch grants: one per personal client, zero interest, borrower-selected monthly repayment within the published term. Consent queues acceptance; bank liquidity is still required. +- Personal, Business and Civic loans: staff review, seven-day offer, separate borrower acceptance, then payout on the bank ticker. A manager cannot approve their own controlled client. +- 25% own-DM collateral is reserved before payout and moved to blocked type106. No inventory collateral. Corporate/Civic obligations and collateral remain within their own client identity. +- Refinancing replaces all active interest-bearing contracts for one client; zero-interest grants remain separate. Historical contracts and ledger entries are retained; no additional cash is paid out. Current payoff changes invalidate the queued refinance rather than overpay. +- Election concessions use actual current winning terms, not provisional/custom ranks. Personal discount is limited to the first5,000DM per eligible election event; corporate concessions require a real CEO change. Reuse is prevented by an atomic event claim. +- Revolving credit cards remain a separately planned product, not an active card/payment facility. + +All principal, interest and recovery receipts return to the Website Bank Treasury. The treasury cannot disburse reserved or unavailable money. Neither P&O nor the Federal Reserve is a borrower or ordinary loan funding source. + +## Processing and audit + +Monthly instalments start one month after payout. Early settlement excludes future interest. A seven-day grace period precedes arrears; no invented automatic penalty. Staff recovery is limited to the contract's pledged DM. Full settlement releases remaining collateral. Upcoming/failed/arrears messages are visible with contract details; this does not claim external email delivery. + +Canonical entity/client/account locks, exact minor-unit amounts, stable request IDs, payload fingerprints, paired ledger legs and same-transaction credit/global audit records protect mutations. Current user authority is checked again before queued payout or manual recovery/repayment. Browser retries keep the same instruction after an uncertain result. + +Credit scoring is advisory and private to the borrower and authorised bank staff. Completed-month cash flow excludes own-client transfers and system/grant/loan/treasury/test credits. Limited history stays explicit; ordinary lending is not automatically approved from the score. Declines have a bounded, recovering impact; waiting for bank liquidity is not a decline. + +Future game adapter requirements are described in `postbank-contract.mjs`. It must map verified game identity to the existing bank client and call the same services; it must not maintain another debt ledger. diff --git a/website/node/postbank-api.mjs b/website/node/postbank-api.mjs index 75362b76..c7677e3f 100644 --- a/website/node/postbank-api.mjs +++ b/website/node/postbank-api.mjs @@ -1,3 +1,4 @@ +import {PostbankCreditEngine} from './postbank-credit-engine.mjs'; import {PostbankAuthorisations} from './postbank-authorisations.mjs'; import {createReserveLedger} from './postbank-reserve-ledger.mjs'; import {PostbankCredit} from './postbank-credit.mjs'; @@ -13,7 +14,8 @@ import {POSTBANK_CONTRACTS} from './postbank-contract.mjs'; export function createPostbankApi(central,bank,settings={},deps={}){ const auth=deps.authenticate||(request=>identity(request,central)),authority=deps.authority||createPostbankAuthority(central,{bank}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority}); - const credit=bank?new PostbankCredit(bank,authority,deps):null; + const credit=bank?new PostbankCredit(bank,authority,{...deps,central}):null; + const creditEnabled=settings.POSTBANK_CREDIT_ENABLED==='true',creditEngine=bank?new PostbankCreditEngine(bank,central,authority,deps):null; const admin=bank?new PostbankAdmin(bank,central,authority,deps):null; const beneficiaries=bank?new PostbankBeneficiaries(bank,deps):null; const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null; @@ -27,7 +29,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401); if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503); try{await reconcilePostbankClans(central,bank);}catch{return reply({message:'The bank could not verify the current organisation registry. Please retry shortly.'},503);} - if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive','/api/bank/authorisations','/api/bank/authorisations/lookup'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400); + if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive','/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/credit/details'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400); if(path==='/api/bank/statements/archive'){ if(request.method!=='GET')return reply({message:'Method not allowed.'},405); if([...url.searchParams.keys()].some(k=>!['accountId','page'].includes(k))||url.searchParams.getAll('accountId').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Select an archive account.'},400); @@ -57,18 +59,32 @@ export function createPostbankApi(central,bank,settings={},deps={}){ if(url.search)return reply({message:'Account overrides are not accepted.'},400); const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); // Rebuild with fresh authority so a revoked organisational scope cannot leak records. - return reply(await credit.overview(fresh)); + return reply({...await credit.overview(fresh),intakeEnabled:creditEnabled}); } - if(!['/api/bank/credit/simulate','/api/bank/credit/apply'].includes(path))return reply({message:'Credit route not found.'},404); + if(path==='/api/bank/credit/details'&&request.method==='GET'){ + if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400);const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'))); + } + if(!['/api/bank/credit/simulate','/api/bank/credit/apply','/api/bank/credit/action'].includes(path))return reply({message:'Credit route not found.'},404); if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415); if(url.search)return reply({message:'Account overrides are not accepted.'},400); const raw=await request.text();if(raw.length>7000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the credit form.'},400);} - if(path.endsWith('/apply'))return reply({message:'Credit application intake opens after underwriting and repayment processing are deployed. No application or payment was made.',state:'not_active'},409); - const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.simulate(fresh,input)); + if(!path.endsWith('/simulate')&&!creditEnabled)return reply({message:'Credit application intake is not open yet. No application or payment was made.',state:'not_active'},409); + const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403); + if(path.endsWith('/apply'))return reply(await credit.apply(fresh,input,{revalidate:()=>auth(request)})); + if(path.endsWith('/action')){const options={revalidate:()=>auth(request)};if(input.action==='accept')return reply(await creditEngine.accept(fresh,input,options));if(input.action==='withdraw')return reply(await creditEngine.decision(fresh,input,options));if(input.action==='repay')return reply(await creditEngine.requestRepayment(fresh,input,options));return reply({message:'Unknown credit action.'},400);} + return reply(await credit.simulate(fresh,input)); }catch(error){return reply({message:error.status?error.message:'The credit operation could not be confirmed.'},error.status||503);} } + if(path==='/api/bank/admin/credit/details'){ + if(request.method!=='GET')return reply({message:'Method not allowed.'},405);if([...url.searchParams.keys()].some(k=>k!=='loanId')||url.searchParams.getAll('loanId').length!==1)return reply({message:'Choose one credit contract.'},400); + try{const fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);return reply(await credit.details(fresh,url.searchParams.get('loanId'),true));}catch(error){return reply({message:error.status?error.message:'Credit details could not be confirmed.'},error.status||503);} + } + if(['/api/bank/admin/credit/decision','/api/bank/admin/credit/recover'].includes(path)){ + if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);if(!creditEnabled)return reply({message:'Credit processing is not active.'},409); + try{const raw=await request.text();if(raw.length>2500)return reply({message:'Request too large.'},413);const input=JSON.parse(raw),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed.'},403);if(!(await authority(fresh)).manageAdmin)return reply({message:'Bank management permission is required.'},403);const recovery=path.endsWith('/recover');if(recovery?input.action!=='recover':!['approve','decline'].includes(input.action))return reply({message:'Unknown staff credit action.'},400);return reply(await (recovery?creditEngine.requestRepayment(fresh,input,{revalidate:()=>auth(request)}):creditEngine.decision(fresh,input,{revalidate:()=>auth(request)})));}catch(error){return reply({message:error.status?error.message:'The credit instruction could not be confirmed.'},error.status||503);} + } if(['/api/bank/authorisations','/api/bank/authorisations/lookup','/api/bank/authorisations/change','/api/bank/admin/authorisations','/api/bank/admin/authorisations/lookup','/api/bank/admin/authorisations/change'].includes(path)){ const staff=path.startsWith('/api/bank/admin/'); try{ @@ -98,7 +114,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ else if(path==='/api/bank/admin/taxes/overview')result=await admin.taxOverview(user); else if(path==='/api/bank/admin/taxes/recipients')result=await admin.taxRecipients(user,input.q); else if(path==='/api/bank/admin/treasuries')result=await admin.treasuries(user,input); - else if(path==='/api/bank/admin/credit')result=await credit.staff(user); + else if(path==='/api/bank/admin/credit')result={...await credit.staff(user),processing:creditEnabled?'active':'not_active'}; else if(path==='/api/bank/admin/accounts')result=await admin.accounts(user,input.entityId); else if(path==='/api/bank/admin/activity')result=await admin.activity(user,input); else if(path==='/api/bank/admin/audit')result=await admin.audit(user,input); @@ -133,7 +149,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Complete the transfer form.'},400);} try{return reply(await payments.transfer(user,body,{revalidate:()=>auth(request)}));}catch(error){return reply({message:error.status?error.message:'The transfer result could not be confirmed. Keep the same payment reference when retrying.'},error.status||503);} } - if(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:POSTBANK_CONTRACTS}); + if(path==='/api/bank/contracts'&&request.method==='GET')return reply({contracts:{...POSTBANK_CONTRACTS,loans:{...POSTBANK_CONTRACTS.loans,state:creditEnabled?'active':'prepared'}}}); if(['/api/bank/activate','/api/bank/packages/change','/api/bank/accounts/options'].includes(path)){ if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); diff --git a/website/node/postbank-contract.mjs b/website/node/postbank-contract.mjs index 3be0686d..96a35ef2 100644 --- a/website/node/postbank-contract.mjs +++ b/website/node/postbank-contract.mjs @@ -1,9 +1,10 @@ export const POSTBANK_CONTRACTS=Object.freeze({ statements:{title:'Monthly account statement archive',state:'active',request:{method:'GET',path:'/api/bank/statements/archive',fields:['accountId','page']},response:{records:'closed months with ready/preparing status and download metadata'},note:'The trusted bank ticker automatically seeds and prepares closed-month PDF statements. Users only list and download already archived files through GET /api/bank/statements?accountId=...&month=.... No user generation endpoint. Brussels month boundaries; ledger history remains preserved. Recoverable worker claims, 25 statements per tick and one-minute continuation while a backlog remains.'}, server:{title:'Game server link',state:'not_linked',request:{method:'POST',path:'/api/bank/integrations/game/payments',fields:['requestId','sourceAccount','targetNumber','amount','reference','mode','gameReceipt']},response:{paymentId:'unique payment reference',state:'queued | posted | rejected'},note:'Future trusted server-to-server payment instructions only. The central bank authorises, reserves and posts; Java must not duplicate accounting or own bank balances. Standard instructions follow the same four-hour Brussels windows; instant instructions post immediately within bank limits. requestId is retained on retries and fulfilment waits for a confirmed posted bank result. No game link or request is enabled by this placeholder. Server credentials must never be supplied by a browser.'}, - mandates:{title:'Account authorisations',state:'planned',request:{method:'POST',path:'/api/bank/authorisations',fields:['accountNumber','clientNumber','permissions','startsAt','expiresAt','confirmed']},response:{authorisationId:'new authorisation reference',state:'active | pending'},note:'Creation, editing and revocation of mandates are deferred. Existing imported authority remains checked by the central API.'}, - collateral:{title:'Blocked collateral',state:'prepared',request:{method:'GET',path:'/api/bank/credit/overview',fields:[]},response:{accounts:'client-owned blocked type106 collateral accounts'},note:'Not an investment product. Borrowers cannot transfer collateral out. Only authorised credit repayment/release and bank staff recovery actions can move it, with ledger entries and audit.'}, - loans:{title:'Credit applications',state:'planned',request:{method:'POST',path:'/api/bank/loans/applications',fields:['requestId','accountNumber','amount','motivation','confirmed']},response:{applicationId:'application reference',state:'submitted'},note:'Credit applications, approvals, payouts and repayments are deferred.'}, + mandates:{title:'Account authorisations',state:'active',request:{method:'POST',path:'/api/bank/authorisations/change',fields:['requestId','accountId','action','kind','key','canPay','expiresAt','version','confirmed']},response:{ok:'confirmed mandate change',replayed:'idempotent retry'},note:'Per-account user/rank mandates. Protected system and collateral accounts cannot be assigned through this route. Current membership and expiry are rechecked before payment settlement.'}, + collateral:{title:'Blocked collateral',state:'prepared',request:{method:'GET',path:'/api/bank/credit/overview',fields:[]},response:{accounts:'loan records and pledged DM amounts; type106 accounts are read through normal authorised bank views'},note:'Not an investment product. Borrowers cannot transfer collateral out. Only authorised credit repayment/release and bank staff recovery actions can move it, with ledger entries and audit.'}, + loans:{title:'Credit applications',state:'prepared',request:{method:'POST',path:'/api/bank/credit/apply',fields:['requestId','accountId','productKey','amount','months','monthly','motivation','accepted','termsVersion']},response:{applicationId:'application reference',state:'submitted | approved_pending'},note:'Authoritative central API. Ordinary credit needs staff review and separate borrower acceptance. Launch grants need explicit borrower consent. Treasury liquidity and collateral are reserved before the four-hour ticker disburses. The deployed activation flag controls intake.'}, + gameCredit:{title:'Future game credit interface',state:'not_linked',request:{method:'POST',path:'/api/bank/integrations/game/credit',fields:['requestId','playerUuid','action','loanId','productKey','amount','months','monthly','motivation','confirmed']},response:{applicationId:'bank-owned contract reference',state:'submitted | queued | active | rejected'},note:'Contract for a future trusted game adapter only, not an implemented browser endpoint. Map a verified game identity to its existing central user/client; delegate to the same credit services and idempotency, never calculate debt in Java or write game balances. No game call is made.'}, companies:{title:'Company registration link',state:'prepared',request:{method:'POST',path:'/api/bank/integrations/entities',fields:['sourceEventId','kind','externalKey','displayName']},response:{entityId:'bank entity reference',state:'not_activated'},note:'Trusted central company-registry event, not a browser endpoint. No companies are invented. Existing approved companies are read from the central registry.'}, economy:{title:'Cost-of-living index',state:'baseline',request:{method:'GET',path:'/api/bank/integrations/economy-index',fields:[]},response:{index:100,base:100,source:'baseline',observedAt:null},note:'No live economy feed is linked. P&O uses the published baseline until an independently verified index is integrated.'} }); diff --git a/website/node/postbank-credit-concessions.mjs b/website/node/postbank-credit-concessions.mjs new file mode 100644 index 00000000..92f722a0 --- /dev/null +++ b/website/node/postbank-credit-concessions.mjs @@ -0,0 +1,16 @@ +// Rate concessions are derived from authoritative elections / CEO handovers, never cosmetic ranks. +export async function refinanceConcession(central,bank,account,user,principal,now,loans){ + if(!central||loans.some(l=>Number(l.created_at)>=now))return null; + const rows=async(sql,args)=>(await central.prepare(sql).bind(...args).all()).results||[]; + let event; + if(['person','house','office'].includes(account.kind)){ + const terms=await rows("SELECT id,office,faction,starts_at,expires_at FROM political_office_terms WHERE user_id=? AND outcome='winner' AND starts_at<=? AND expires_at>? ORDER BY starts_at DESC LIMIT 20",[user.id,now,now]); + event=terms.find(t=>loans.every(l=>Number(l.created_at)500000n?principal-500000n:0n)+principal-1n)/principal):350,limit:account.kind==='person'?'5000.00':null}; + }else if(account.kind==='company'){ + const events=await rows("SELECT e.id,e.details_json,e.created_at FROM corrino_company_events e JOIN corrino_companies c ON c.id=e.company_id WHERE e.company_id=? AND e.action='appoint-ceo' AND c.ceo_account_id=? AND c.status='active' ORDER BY e.created_at DESC LIMIT 20",[account.external_key,user.id]); + const change=events.find(e=>{let d;try{d=JSON.parse(e.details_json);}catch{return false;}return d.ceoId===user.id&&d.previousCeoId&&d.previousCeoId!==user.id&&loans.every(l=>Number(l.created_at)typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s),day=86400000; +export class PostbankCreditEngine{ + constructor(db,central,authority,{clock=Date.now,resolveUser=null}={}){this.db=db;this.central=central;this.authority=authority;this.clock=clock;this.resolveUser=resolveUser||(id=>central.prepare("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(id).first());} + async lock(loanId,work){const meta=await this.db.first('SELECT client_number,entity_id FROM pb_credit_loans WHERE id=?',[loanId]);if(!meta)throw new BankError('Credit contract not found.',404);return this.db.transaction(async tx=>{await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[meta.entity_id]);await tx.first('SELECT client_number FROM pb_clients WHERE client_number=? FOR UPDATE',[meta.client_number]);const loan=await tx.first('SELECT * FROM pb_credit_loans WHERE id=? FOR UPDATE',[loanId]);return work(tx,loan);});} + async accounts(tx,loan){const ids=[loan.account_id,...loan.collateral_account_id?[loan.collateral_account_id]:[]];const rows=await tx.query('SELECT * FROM pb_accounts WHERE system_key=? OR id IN ('+ids.map(()=>'?').join(',')+') ORDER BY id FOR UPDATE',['sys_web_treasury',...ids]);const bank=rows.find(a=>a.system_key==='sys_web_treasury'),current=rows.find(a=>String(a.id)===String(loan.account_id)),collateral=rows.find(a=>String(a.id)===String(loan.collateral_account_id));if(!bank||bank.state!=='active'||!current)throw new BankError('The lending treasury or borrower account is unavailable.',503);return {bank,current,collateral};} + async event(tx,loan,requestId,actor,action,details,fingerprint=''){await tx.query('INSERT INTO pb_credit_events(request_id,loan_id,actor_id,action,fingerprint,details,created_at) VALUES(?,?,?,?,?,?,?)',[requestId,loan.id,actor,action,fingerprint||createHash('sha256').update(action+loan.id+requestId).digest('hex'),JSON.stringify(details),this.clock()]);await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[requestId,actor,action,loan.entity_id,JSON.stringify({loanId:loan.id,...details}),this.clock()]);} + async replay(tx,input,user,fingerprint){const old=await tx.first('SELECT * FROM pb_credit_events WHERE request_id=?',[input.requestId]);if(!old)return false;if(old.actor_id!==user.id||old.fingerprint!==fingerprint)throw new BankError('This request reference was already used for a different instruction.',409);return true;} + validate(input,actions){if(!input||!uuid(input.requestId)||!uuid(input.loanId)||!actions.includes(input.action)||input.confirmed!==true||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.length>500||/[\x00-\x1f]/.test(input.reason))throw new BankError('Confirm the credit action with a reason of 5–500 characters.');} + async currentAuthority(user,loan,tx,{manage=false,borrow=false,pay=false}={}){const c=await this.authority(user,{bank:tx});if(manage&&!c.manageAdmin||borrow&&!c.entities.some(e=>e.id===loan.entity_id&&e.canActivate)||pay&&!canDebitAccount(c,loan.entity_id,loan.account_id))throw new BankError('Your authority for this credit action is not valid.',403);return c;} + async releaseHolds(tx,loan,accounts){for(const [a,n]of [[accounts.bank,BigInt(loan.treasury_hold_minor||0)],[accounts.current,BigInt(loan.borrower_hold_minor||0)]]){if(n){if(BigInt(a.reserved_minor)user}={}){ + this.validate(input,['approve','decline','withdraw']);if(Object.keys(input).some(k=>!['requestId','loanId','action','confirmed','reason','riskOverride'].includes(k)))throw new BankError('Unexpected credit action fields.');const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.loanId,input.action,input.reason,!!input.riskOverride])).digest('hex'); + return this.lock(input.loanId,async(tx,loan)=>{const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.currentAuthority(fresh,loan,tx,input.action==='withdraw'?{borrow:true}:{manage:true});if(await this.replay(tx,input,user,fingerprint))return {ok:true,replayed:true}; + if(input.action==='withdraw'){if(!['submitted','approved_pending','offered','payout_queued'].includes(loan.state))throw new BankError('This contract cannot be withdrawn.',409);await this.releaseHolds(tx,loan,await this.accounts(tx,loan));await tx.query("UPDATE pb_credit_loans SET state='withdrawn',updated_at=?,version=version+1 WHERE id=?",[this.clock(),loan.id]);if(loan.product_key.startsWith('grant_'))await tx.query('DELETE FROM pb_credit_grants WHERE loan_id=?',[loan.id]);} + else{if(loan.state!=='submitted')throw new BankError('Only a submitted application can be reviewed.',409);if(user.id===loan.created_by||rights.entities.some(e=>e.id===loan.entity_id&&e.canActivate))throw new BankError('A different bank manager must review a client you control.',403);const score=JSON.parse(loan.score_json);if(input.action==='approve'&&(score.score<400||score.flags?.includes('High Monthly Commitments'))&&input.riskOverride!==true)throw new BankError('Review and explicitly confirm the risk override before approval.',409); + const state=input.action==='decline'?'declined':'approved_pending';await tx.query('UPDATE pb_credit_loans SET state=?,reviewed_by=?,decision_reason=?,updated_at=?,version=version+1 WHERE id=?',[state,user.id,input.reason.trim(),this.clock(),loan.id]);loan.state=state;if(state==='approved_pending')await this.reserveOffer(tx,loan);await creditNotice(tx,loan,'decision:'+input.requestId,state==='declined'?'Credit application declined':loan.state==='offered'?'Credit offer ready':'Credit approved — awaiting bank liquidity',input.reason.trim(),this.clock());} + await this.event(tx,loan,input.requestId,user.id,'credit_'+input.action,{reason:input.reason.trim(),riskOverride:!!input.riskOverride},fingerprint);return {ok:true,replayed:false}; + }); + } + async accept(user,input,{revalidate=async()=>user}={}){ + this.validate(input,['accept']);if(Object.keys(input).some(k=>!['requestId','loanId','action','confirmed','reason','expectedVersion'].includes(k))||!Number.isInteger(input.expectedVersion))throw new BankError('Refresh and accept the current offer.');const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.loanId,input.expectedVersion,'accept'])).digest('hex'); + return this.lock(input.loanId,async(tx,loan)=>{const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.currentAuthority(fresh,loan,tx,{borrow:true});if(await this.replay(tx,input,user,fingerprint))return {ok:true,replayed:true};if(loan.state!=='offered'||Number(loan.version)!==input.expectedVersion||Number(loan.offer_expires_at)<=this.clock())throw new BankError('This offer changed or expired. Refresh before accepting.',409);if(loan.reviewed_by===user.id)throw new BankError('A different bank manager must approve your borrowing.',403);const a=await this.accounts(tx,loan),refinance=JSON.parse(loan.refinance_json||'[]'),carry=refinance.reduce((sum,l)=>sum+BigInt(l.collateralMinor||0),0n),required=BigInt(loan.collateral_minor)>carry?BigInt(loan.collateral_minor)-carry:0n;if(a.current.state!=='active'||BigInt(a.current.balance_minor)-BigInt(a.current.reserved_minor){ + if(loan.state!=='payout_queued'||Number(loan.queued_at)>cutoff)return false;const actor=await this.resolveUser(loan.accepted_by||loan.created_by),a=await this.accounts(tx,loan);let authorised=false;try{if(actor){await this.currentAuthority(actor,loan,tx,{borrow:true});authorised=true;}}catch{} + if(!authorised||a.current.state!=='active'){await this.releaseHolds(tx,loan,a);await tx.query("UPDATE pb_credit_loans SET state='withdrawn',decision_reason='Borrowing authority expired before disbursement',updated_at=? WHERE id=?",[this.clock(),loan.id]);if(loan.product_key.startsWith('grant_'))await tx.query('DELETE FROM pb_credit_grants WHERE loan_id=?',[loan.id]);return false;} + const refinanced=JSON.parse(loan.refinance_json||'[]');for(const r of refinanced){const old=await tx.first('SELECT * FROM pb_credit_loans WHERE id=? AND client_number=? FOR UPDATE',[r.id,loan.client_number]);const payoff=old&&await currentPayoff(tx,old,this.clock());if(!old||!['active','arrears'].includes(old.state)||payoff.total!==BigInt(r.payoffMinor)){await this.releaseHolds(tx,loan,a);await tx.query("UPDATE pb_credit_loans SET state='expired',decision_reason='Refinanced balances changed; request a new quotation',updated_at=? WHERE id=?",[this.clock(),loan.id]);return false;}} + const now=this.clock(),collateral=BigInt(loan.collateral_minor),carry=refinanced.reduce((sum,r)=>sum+BigInt(r.collateralMinor||0),0n);if(collateral||carry)a.collateral=await this.collateralAccount(tx,loan); + if(BigInt(loan.borrower_hold_minor||0))await creditMovement(tx,{key:loan.id+':pledge',actor:actor.id,source:a.current,target:a.collateral,amount:BigInt(loan.borrower_hold_minor),reference:'Loan collateral · '+loan.id,now,held:true}); + await creditMovement(tx,{key:loan.id+':payout',actor:actor.id,source:a.bank,target:a.current,amount:BigInt(loan.principal_minor),reference:'Credit disbursement · '+loan.id,now,held:true}); + for(const r of refinanced){await creditMovement(tx,{key:loan.id+':refinance:'+r.id,actor:actor.id,source:a.current,target:a.bank,amount:BigInt(r.payoffMinor),reference:'Refinancing settlement · '+r.id,now});await tx.query("UPDATE pb_credit_loans SET state='refinanced',outstanding_minor=0,collateral_minor=0,replaced_by=?,updated_at=? WHERE id=?",[loan.id,now,r.id]);await tx.query("UPDATE pb_credit_instalments SET state='refinanced' WHERE loan_id=? AND state IN ('pending','late')",[r.id]);await this.event(tx,{...loan,id:r.id},creditID(loan.id+':replaces:'+r.id),actor.id,'credit_refinanced',{replacement:loan.id,settlement:money(r.payoffMinor)});} + if(carry>collateral)await creditMovement(tx,{key:loan.id+':collateral-adjustment',actor:actor.id,source:a.collateral,target:a.current,amount:carry-collateral,reference:'Refinancing collateral adjustment · '+loan.id,now}); + const quote=JSON.parse(loan.quote_json);if(quote.concession?.eventKey)await tx.query('INSERT INTO pb_credit_concessions(event_key,loan_id,created_at) VALUES(?,?,?)',[quote.concession.eventKey,loan.id,now]); + const schedule=creditSchedule(BigInt(loan.principal_minor),Number(loan.annual_bps),Number(loan.months),loan.product_key.startsWith('grant_')?BigInt(loan.monthly_minor):null);for(const row of schedule)await tx.query("INSERT INTO pb_credit_instalments(loan_id,sequence_no,due_at,principal_minor,interest_minor,state) VALUES(?,?,?,?,?,'pending')",[loan.id,row.number,dueMonth(now,row.number),String(row.principal),String(row.interest)]); + await tx.query("UPDATE pb_credit_loans SET state='active',outstanding_minor=principal_minor,treasury_hold_minor=0,borrower_hold_minor=0,accepted_at=?,next_due_at=?,updated_at=?,version=version+1 WHERE id=?",[now,dueMonth(now,1),now,loan.id]);await this.event(tx,loan,creditID(loan.id+':disbursed'),actor.id,'credit_disbursed',{principal:money(loan.principal_minor),collateral:money(collateral)});await creditNotice(tx,loan,'disbursed','Credit disbursed','Your credit is active. Principal '+money(loan.principal_minor)+' DM; monthly repayment '+money(loan.monthly_minor)+' DM.',now);return true; + });} + async requestRepayment(user,input,{revalidate=async()=>user}={}){ + this.validate(input,['repay','recover']);if(Object.keys(input).some(k=>!['requestId','loanId','action','confirmed','reason','amount'].includes(k)))throw new BankError('Unexpected repayment fields.');let amount;try{amount=minorAmount(input.amount);}catch(e){throw new BankError(e.message);}const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.loanId,input.action,String(amount),input.reason])).digest('hex'); + return this.lock(input.loanId,async(tx,loan)=>{const old=await tx.first('SELECT * FROM pb_credit_actions WHERE id=?',[input.requestId]);if(old){if(old.actor_id!==user.id||old.fingerprint!==fingerprint)throw new BankError('This repayment reference was already used.',409);return {ok:true,replayed:true,state:old.state};}const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.currentAuthority(fresh,loan,tx,input.action==='recover'?{manage:true}:{pay:true});if(!['active','arrears'].includes(loan.state))throw new BankError('This contract is not active.',409);const a=await this.accounts(tx,loan),payoff=await currentPayoff(tx,loan,this.clock());if(amount>payoff.total)throw new BankError('The repayment exceeds the current settlement balance.',409);const source=input.action==='recover'?a.collateral:a.current;if(input.action==='recover'&&(loan.state!=='arrears'||amount>BigInt(loan.collateral_minor)||!source))throw new BankError('Recovery is limited to pledged DM on a contract in arrears.',409);if(!source||BigInt(source.balance_minor)-BigInt(source.reserved_minor)payoff.total)throw new BankError('The settlement balance changed.',409);await creditMovement(tx,{key,actor,source:recovery?a.collateral:a.current,target:a.bank,amount,reference:(recovery?'Collateral recovery':'Loan repayment')+' · '+loan.id,now,held});let remaining=amount,paidCapital=0n; + for(const row of payoff.rows){const interest=BigInt(row.interest_minor)-BigInt(row.paid_interest),payInterest=remaining? AND state='pending' ORDER BY sequence_no",[loan.id,now]);const revised=outstanding>0n&&future.length?creditSchedule(outstanding,Number(loan.annual_bps),future.length,loan.product_key.startsWith('grant_')?BigInt(loan.monthly_minor):null):[];for(let i=0;i{const current=await tx.first('SELECT * FROM pb_credit_actions WHERE id=? FOR UPDATE',[action.id]);if(!current||current.state!=='queued'||Number(current.created_at)>cutoff)return false;const a=await this.accounts(tx,loan),source=current.kind==='recover'?a.collateral:a.current,actor=await this.resolveUser(current.actor_id);let allowed=false;try{if(actor){await this.currentAuthority(actor,loan,tx,current.kind==='recover'?{manage:true}:{pay:true});allowed=true;}}catch{}const amount=BigInt(current.amount_minor),payoff=await currentPayoff(tx,loan,this.clock());if(!allowed||!['active','arrears'].includes(loan.state)||!source||BigInt(source.reserved_minor)payoff.total){if(source&&BigInt(source.reserved_minor)>=amount)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[String(amount),source.id]);await tx.query("UPDATE pb_credit_actions SET state='rejected',processed_at=?,failure='Authority or settlement balance changed' WHERE id=?",[this.clock(),current.id]);return false;}await this.applyRepayment(tx,loan,a,amount,'action:'+current.id,actor.id,{recovery:current.kind==='recover',held:true});await tx.query("UPDATE pb_credit_actions SET state='posted',processed_at=? WHERE id=?",[this.clock(),current.id]);return true;});} + async automaticRepayment(loanId,cutoff){return this.lock(loanId,async(tx,loan)=>{if(!['active','arrears'].includes(loan.state)||!loan.next_due_at||Number(loan.next_due_at)>cutoff)return false;const a=await this.accounts(tx,loan),due=await tx.query("SELECT * FROM pb_credit_instalments WHERE loan_id=? AND due_at<=? AND state IN ('pending','late') ORDER BY sequence_no",[loan.id,cutoff]);if(!due.length)return false;const amount=due.reduce((sum,r)=>sum+BigInt(r.principal_minor)-BigInt(r.paid_principal)+BigInt(r.interest_minor)-BigInt(r.paid_interest),0n);if(amount<=0n)return false;if(a.current.state!=='active'||BigInt(a.current.balance_minor)-BigInt(a.current.reserved_minor)r.sequence_no).join('-'),loan.accepted_by||loan.created_by);return true;});} + async process({cutoff=this.clock()}={}){ + let offered=0,disbursed=0,repaid=0,expired=0,reminded=0,failed=0;const handle=async job=>{try{return await job();}catch{failed++;return false;}}; + for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state='offered' AND offer_expires_at<=? ORDER BY offer_expires_at LIMIT 25",[cutoff]))await handle(()=>this.lock(row.id,async(tx,loan)=>{if(loan.state!=='offered'||Number(loan.offer_expires_at)>cutoff)return;await this.releaseHolds(tx,loan,await this.accounts(tx,loan));await tx.query("UPDATE pb_credit_loans SET state='expired',updated_at=? WHERE id=?",[this.clock(),loan.id]);expired++;})); + for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state='approved_pending' AND updated_at<=? ORDER BY created_at LIMIT 25",[cutoff]))if(await handle(()=>this.lock(row.id,(tx,loan)=>loan.state==='approved_pending'?this.reserveOffer(tx,loan,cutoff):false)))offered++; + for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state='payout_queued' AND queued_at<=? ORDER BY queued_at LIMIT 25",[cutoff]))if(await handle(()=>this.payout(row.id,cutoff)))disbursed++; + for(const row of await this.db.query("SELECT id,loan_id FROM pb_credit_actions WHERE state='queued' AND created_at<=? ORDER BY created_at LIMIT 25",[cutoff]))if(await handle(()=>this.processAction(row,cutoff)))repaid++; + for(const row of await this.db.query("SELECT id FROM pb_credit_loans WHERE state IN ('active','arrears') AND next_due_at<=? ORDER BY next_due_at LIMIT 25",[cutoff]))if(await handle(()=>this.automaticRepayment(row.id,cutoff)))repaid++; + for(const row of await this.db.query("SELECT l.id FROM pb_credit_loans l WHERE l.state='active' AND l.next_due_at>? AND l.next_due_at<=? AND NOT EXISTS (SELECT 1 FROM pb_credit_notices n WHERE n.notice_key=CONCAT(l.id,':upcoming:',l.next_due_at)) ORDER BY l.next_due_at LIMIT 25",[cutoff,cutoff+3*day]))await handle(()=>this.lock(row.id,async(tx,loan)=>{if(loan.state!=='active'||Number(loan.next_due_at)<=cutoff||Number(loan.next_due_at)>cutoff+3*day)return;const key='upcoming:'+loan.next_due_at;if(await tx.first('SELECT id FROM pb_credit_notices WHERE notice_key=?',[loan.id+':'+key]))return;await creditNotice(tx,loan,key,'Upcoming credit repayment','Your repayment of '+money(loan.monthly_minor)+' DM is due on '+new Date(Number(loan.next_due_at)).toISOString().slice(0,10)+'. Keep this amount available in the linked current account.',this.clock());reminded++;})); + return {offered,disbursed,repaid,expired,reminded,failed}; + } +} diff --git a/website/node/postbank-credit-ledger.mjs b/website/node/postbank-credit-ledger.mjs new file mode 100644 index 00000000..c443cb5d --- /dev/null +++ b/website/node/postbank-credit-ledger.mjs @@ -0,0 +1,16 @@ +import {createHash} from 'node:crypto';import {BankError} from './postbank-service.mjs';import {money} from './postbank-catalogue.mjs'; +export const cents=value=>{if(typeof value!=='string'||!/^\d+\.\d{2}$/.test(value))throw new BankError('Invalid monetary value.');return BigInt(value.replace('.',''));}; +export const creditID=value=>{const h=createHash('sha256').update('postbank-credit:'+value).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);}; +export function creditSchedule(principal,annualBps,months,monthly=null){ + if(principal<=0n||principal>100000000n||!Number.isInteger(months)||months<1||months>60||!Number.isInteger(annualBps)||annualBps<0||annualBps>10000)throw new BankError('Invalid repayment schedule.'); + const rate=Math.expm1(Math.log1p(annualBps/10000)/12),payment=monthly??(rate?BigInt(Math.ceil(Number(principal)*rate/(1-Math.pow(1+rate,-months)))):(principal+BigInt(months)-1n)/BigInt(months));let remaining=principal;const result=[]; + for(let i=1;i<=months;i++){const interest=BigInt(Math.round(Number(remaining)*rate));let amount=i===months?remaining+interest:payment;if(amount>remaining+interest)amount=remaining+interest;const capital=amount-interest;if(capital<=0n)throw new BankError('Repayment does not cover interest.');remaining-=capital;result.push({number:i,principal:capital,interest,amount,balance:remaining});if(!remaining)break;}return result; +} +export function dueMonth(start,offset){const d=new Date(start),first=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+offset,1,d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds())),last=new Date(Date.UTC(first.getUTCFullYear(),first.getUTCMonth()+1,0)).getUTCDate();first.setUTCDate(Math.min(d.getUTCDate(),last));return first.getTime();} +export async function creditMovement(tx,{key,actor,source,target,amount,reference,now,held=false}){ + const debit=BigInt(source.balance_minor)-amount,credit=BigInt(target.balance_minor)+amount,reserved=BigInt(source.reserved_minor||0)-(held?amount:0n);if(amount<=0n||String(source.id)===String(target.id)||debit<0n||credit>9223372036854775807n||reserved<0n||!held&&debitsum+BigInt(r.interest_minor)-BigInt(r.paid_interest),0n);return {principal:BigInt(loan.outstanding_minor),interest,total:BigInt(loan.outstanding_minor)+interest,rows};} +export async function creditNotice(tx,loan,key,subject,body,now){const id=creditID('notice:'+loan.id+':'+key);await tx.query('INSERT INTO pb_credit_notices(id,client_number,loan_id,notice_key,subject,body,created_at) VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=VALUES(id)',[id,loan.client_number,loan.id,loan.id+':'+key,subject,body,now]);} +export const showSchedule=rows=>rows.map(r=>({number:r.number,principal:money(r.principal),interest:money(r.interest),amount:money(r.amount),balance:money(r.balance)})); diff --git a/website/node/postbank-credit-model.mjs b/website/node/postbank-credit-model.mjs index 1b79bef6..db781321 100644 --- a/website/node/postbank-credit-model.mjs +++ b/website/node/postbank-credit-model.mjs @@ -15,17 +15,17 @@ export const CREDIT_PRODUCTS=Object.freeze([ {key:'civic_refinance',name:'Civic Refinancing',group:'refinancing',kinds:['house','office'],min:'0.01',max:'500000.00',annualBps:550,terms:[3,6,12]} ].map(Object.freeze)); export function creditProduct(key){const p=CREDIT_PRODUCTS.find(p=>p.key===key);if(!p)throw new BankError('Choose a credit product.');return p;} -export function creditQuote({productKey,amount,months,monthly}){ - const product=creditProduct(productKey);let principal;try{principal=minorAmount(product.amount||amount);}catch(e){throw new BankError(e.message);} +export function creditQuote({productKey,amount,months,monthly},{annualBps=null}={}){ + const product=creditProduct(productKey),rateBps=annualBps??product.annualBps;if(!Number.isInteger(rateBps)||rateBps<0||rateBps>10000)throw new BankError('Invalid credit rate.');let principal;try{principal=minorAmount(product.amount||amount);}catch(e){throw new BankError(e.message);} if(principalminorAmount(product.max))throw new BankError('Choose an amount within this product’s limits.'); let n=Number(months),payment; if(product.group==='grants'){let requested;try{requested=minorAmount(monthly);}catch{throw new BankError('Choose your monthly repayment.');}n=Number((principal+requested-1n)/requested);if(n<1||n>product.maxMonths)throw new BankError('Choose a monthly repayment that clears the grant within 12 months.');payment=requested;} else if(!Number.isInteger(n)||!product.terms.includes(n))throw new BankError('Choose an available repayment period.'); - const rate=Math.expm1(Math.log1p(product.annualBps/10000)/12); + const rate=Math.expm1(Math.log1p(rateBps/10000)/12); if(!payment)payment=BigInt(Math.ceil(Number(principal)*rate/(1-Math.pow(1+rate,-n)))); let remaining=principal,totalInterest=0n,total=0n;const schedule=[]; for(let i=1;i<=n;i++){const interest=BigInt(Math.round(Number(remaining)*rate));let due=i===n?remaining+interest:payment;if(due>remaining+interest)due=remaining+interest;const capital=due-interest;if(capital<=0n)throw new BankError('The repayment must exceed accrued interest.');remaining-=capital;totalInterest+=interest;total+=due;schedule.push({number:i,amount:money(due),principal:money(capital),interest:money(interest),balance:money(remaining)});} - return {productKey:product.key,name:product.name,group:product.group,revolving:!!product.revolving,amount:money(principal),annualRate:(product.annualBps/100).toFixed(2),months:n,monthly:schedule[0].amount,totalInterest:money(totalInterest),totalRepayment:money(total),schedule,termsVersion:CREDIT_VERSION}; + return {productKey:product.key,name:product.name,group:product.group,revolving:!!product.revolving,amount:money(principal),annualRate:(rateBps/100).toFixed(2),months:n,monthly:schedule[0].amount,totalInterest:money(totalInterest),totalRepayment:money(total),schedule,termsVersion:CREDIT_VERSION}; } export const riskBand=score=>score>=850?'Very Low':score>=700?'Low':score>=550?'Moderate':score>=400?'High':'Very High'; export function creditScore({ageDays=0,earnedMonths=[],expenseMonths=[],paid=0,late=0,overdueMinor=0n,monthlyDebtMinor=0n,denials=[]}={}){ diff --git a/website/node/postbank-credit.mjs b/website/node/postbank-credit.mjs index e50a4c00..fd836916 100644 --- a/website/node/postbank-credit.mjs +++ b/website/node/postbank-credit.mjs @@ -1,30 +1,58 @@ import {createHash} from 'node:crypto'; import {BankError} from './postbank-service.mjs'; +import {currentPayoff} from './postbank-credit-ledger.mjs'; +import {refinanceConcession} from './postbank-credit-concessions.mjs'; import {money,minorAmount} from './postbank-catalogue.mjs'; import {CREDIT_PRODUCTS,CREDIT_VERSION,creditProduct,creditQuote,creditScore} from './postbank-credit-model.mjs'; const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s); -const accountSQL='SELECT a.*,e.id entity_id,e.kind,e.active entity_active,e.created_at entity_created,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id'; +const accountSQL='SELECT a.*,e.id entity_id,e.kind,e.external_key,e.display_name entity_name,e.active entity_active,e.created_at entity_created,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id'; const eligible=a=>a&&Number(a.entity_active)===1&&a.state==='active'&&a.package_state==='active'&&!a.system_key&&['102','105','107','108'].includes(a.type_code)&&['person','clan','company','house','office'].includes(a.kind); export class PostbankCredit{ - constructor(db,authority,{clock=Date.now}={}){this.db=db;this.authority=authority;this.clock=clock;} - async account(user,id){if(typeof id!=='string'||!/^\d{1,12}$/.test(id))throw new BankError('Choose a borrowing account.');const a=await this.db.first(accountSQL+' WHERE a.id=?',[id]),context=await this.authority(user);if(!eligible(a)||!context.entities.some(e=>e.id===a.entity_id&&e.canPay))throw new BankError('You cannot apply for credit for this account.',403);return a;} - async overview(user){const c=await this.authority(user),ids=c.entities.filter(e=>e.canView).map(e=>e.id);if(!ids.length)return {accounts:[],loans:[],products:CREDIT_PRODUCTS,termsVersion:CREDIT_VERSION};const rows=await this.db.query(accountSQL+' WHERE e.id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id',ids),clients=[...new Set(rows.map(a=>a.client_number))];const loans=clients.length?await this.db.query('SELECT * FROM pb_credit_loans WHERE client_number IN ('+clients.map(()=>'?').join(',')+') ORDER BY created_at DESC LIMIT 100',clients):[];return {accounts:rows.filter(eligible).map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,kind:a.kind,canApply:c.entities.some(e=>e.id===a.entity_id&&e.canPay)})),loans:loans.map(l=>({id:l.id,accountId:String(l.account_id),productKey:l.product_key,state:l.state,principal:money(l.principal_minor),outstanding:money(l.outstanding_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),createdAt:Number(l.created_at),motivation:l.motivation,decision:l.decision_reason||null})),products:CREDIT_PRODUCTS,termsVersion:CREDIT_VERSION};} - async staff(user){const rights=await this.authority(user);if(!rights.readAdmin)throw new BankError('Bank administration view permission is required.',403);const rows=await this.db.query('SELECT l.*,e.display_name entity_name FROM pb_credit_loans l JOIN pb_entities e ON e.id=l.entity_id ORDER BY l.created_at DESC LIMIT 100');return {canManage:!!rights.manageAdmin,applications:rows.map(l=>({id:l.id,entity:l.entity_name,productKey:l.product_key,state:l.state,principal:money(l.principal_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),collateral:money(l.collateral_minor),createdAt:Number(l.created_at),motivation:l.motivation,score:JSON.parse(l.score_json),quote:JSON.parse(l.quote_json)})),processing:'not_active'};} - async score(account,db=this.db){const now=this.clock(),denials=await db.query("SELECT updated_at FROM pb_credit_loans WHERE client_number=? AND state='declined' AND updated_at>=?",[account.client_number,now-90*86400000]),loans=await db.query("SELECT monthly_minor FROM pb_credit_loans WHERE client_number=? AND state IN ('active','arrears')",[account.client_number]);return creditScore({ageDays:Math.max(0,Math.floor((now-Number(account.entity_created))/86400000)),monthlyDebtMinor:loans.reduce((sum,l)=>sum+BigInt(l.monthly_minor),0n),denials:denials.map(l=>Math.floor((now-Number(l.updated_at))/86400000))});} - async simulate(user,input){if(!input||Object.keys(input).some(k=>!['accountId','productKey','amount','months','monthly'].includes(k)))throw new BankError('Choose valid simulation details.');const a=await this.account(user,input.accountId),product=creditProduct(input.productKey);if(!product.kinds.includes(a.kind))throw new BankError('This credit product is not available to this client.');if(product.group==='refinancing')throw new BankError('Refinancing requires verified existing loan balances. This flow is not open yet.',409);if(product.revolving)throw new BankError('The revolving credit flow is not open yet.',409);const quote=creditQuote(input),collateral=product.group==='grants'?0n:(minorAmount(quote.amount)+3n)/4n;return {quote,collateral:money(collateral),score:await this.score(a),disbursement:'not_active',notice:'Simulation only. No application, collateral movement or payment has been made.'};} + constructor(db,authority,{clock=Date.now,central=null}={}){this.db=db;this.authority=authority;this.clock=clock;this.central=central;} + async account(user,id,store=this.db){if(typeof id!=='string'||!/^\d{1,12}$/.test(id))throw new BankError('Choose a borrowing account.');const a=await store.first(accountSQL+' WHERE a.id=?',[id]),context=await this.authority(user,{bank:store});if(!eligible(a)||!context.entities.some(e=>e.id===a.entity_id&&e.canActivate))throw new BankError('You cannot apply for credit for this account.',403);return a;} + async overview(user){const c=await this.authority(user),ids=c.entities.filter(e=>e.canActivate).map(e=>e.id);if(!ids.length)return {accounts:[],loans:[],products:CREDIT_PRODUCTS,termsVersion:CREDIT_VERSION};const rows=await this.db.query(accountSQL+' WHERE e.id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id',ids),clients=[...new Set(rows.map(a=>a.client_number))];const loans=clients.length?await this.db.query('SELECT * FROM pb_credit_loans WHERE client_number IN ('+clients.map(()=>'?').join(',')+') ORDER BY created_at DESC LIMIT 100',clients):[];return {accounts:rows.filter(eligible).map(a=>({id:String(a.id),name:a.display_name,holder:a.entity_name,number:a.account_number,kind:a.kind,canApply:c.entities.some(e=>e.id===a.entity_id&&e.canActivate)})),loans:loans.map(l=>({id:l.id,accountId:String(l.account_id),productKey:l.product_key,state:l.state,principal:money(l.principal_minor),outstanding:money(l.outstanding_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),createdAt:Number(l.created_at),version:Number(l.version),collateral:money(l.collateral_minor),nextDueAt:l.next_due_at?Number(l.next_due_at):null,motivation:l.motivation,decision:l.decision_reason||null})),products:CREDIT_PRODUCTS,termsVersion:CREDIT_VERSION};} + async staff(user){const rights=await this.authority(user);if(!rights.readAdmin)throw new BankError('Bank administration view permission is required.',403);const rows=await this.db.query('SELECT l.*,e.display_name entity_name FROM pb_credit_loans l JOIN pb_entities e ON e.id=l.entity_id ORDER BY l.created_at DESC LIMIT 100');return {canManage:!!rights.manageAdmin,applications:rows.map(l=>({id:l.id,entity:l.entity_name,productKey:l.product_key,state:l.state,principal:money(l.principal_minor),monthly:money(l.monthly_minor),annualRate:(l.annual_bps/100).toFixed(2),months:Number(l.months),collateral:money(l.collateral_minor),createdAt:Number(l.created_at),version:Number(l.version),outstanding:money(l.outstanding_minor),createdBy:l.created_by,canReview:l.created_by!==user.id&&!rights.entities.some(e=>e.id===l.entity_id&&e.canActivate),motivation:l.motivation,score:JSON.parse(l.score_json),quote:JSON.parse(l.quote_json)})),processing:'not_active'};} + async details(user,loanId,staff=false){ + if(!uuid(loanId))throw new BankError('Choose a valid credit contract.');const loan=await this.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[loanId]);if(!loan)throw new BankError('Credit contract not found.',404);if(staff){if(!(await this.authority(user)).readAdmin)throw new BankError('Credit-management access denied.',403);}else if(!(await this.authority(user)).entities.some(e=>e.id===loan.entity_id&&e.canActivate))throw new BankError('Credit-contract access denied.',403); + const schedule=await this.db.query('SELECT sequence_no,due_at,principal_minor,interest_minor,paid_principal,paid_interest,state FROM pb_credit_instalments WHERE loan_id=? ORDER BY sequence_no',[loanId]),events=await this.db.query('SELECT action,details,created_at FROM pb_credit_events WHERE loan_id=? ORDER BY created_at DESC LIMIT 30',[loanId]),payoff=await currentPayoff(this.db,loan,this.clock()); + const notices=await this.db.query('SELECT subject,body,created_at FROM pb_credit_notices WHERE loan_id=? ORDER BY created_at DESC LIMIT 10',[loanId]);return {notices:notices.map(n=>({subject:n.subject,body:n.body,createdAt:Number(n.created_at)})),id:loan.id,replacedBy:loan.replaced_by||null,state:loan.state,version:Number(loan.version),settlement:money(payoff.total),collateral:money(loan.collateral_minor),decision:loan.decision_reason||null,quote:JSON.parse(loan.quote_json),schedule:schedule.map(r=>({number:Number(r.sequence_no),dueAt:Number(r.due_at),principal:money(r.principal_minor),interest:money(r.interest_minor),paid:money(BigInt(r.paid_principal)+BigInt(r.paid_interest)),state:r.state})),events:events.map(r=>({action:r.action,details:JSON.parse(r.details),createdAt:Number(r.created_at)}))}; + } + async score(account,db=this.db,additional=0n,replaced=[]){ + const now=this.clock(),denials=await db.query("SELECT updated_at FROM pb_credit_loans WHERE client_number=? AND state='declined' AND updated_at>=?",[account.client_number,now-90*86400000]),loans=await db.query("SELECT id,monthly_minor,outstanding_minor,state FROM pb_credit_loans WHERE client_number=? AND state IN ('active','arrears')",[account.client_number]); + const instalments=await db.query("SELECT i.state,i.due_at,i.paid_at FROM pb_credit_instalments i JOIN pb_credit_loans l ON l.id=i.loan_id WHERE l.client_number=? AND i.due_at<=? AND i.due_at>=?",[account.client_number,now,now-365*86400000]); + const current=new Date(now),monthStart=Date.UTC(current.getUTCFullYear(),current.getUTCMonth(),1),since=new Date(monthStart);since.setUTCMonth(since.getUTCMonth()-3); + const entries=await db.query("SELECT x.amount_minor,x.created_at,o.mode,a.client_number,CASE WHEN x.amount_minor>0 THEN src.client_number ELSE dst.client_number END counterparty_client FROM pb_entries x JOIN pb_accounts a ON a.id=x.account_id JOIN pb_orders o ON o.id=x.order_id LEFT JOIN pb_accounts src ON src.id=o.source_id LEFT JOIN pb_accounts dst ON dst.id=o.target_id WHERE a.client_number=? AND a.type_code<>'106' AND x.created_at>=? AND x.created_at0n)bucket.income+=n;else bucket.expenses-=n;} + return creditScore({ageDays:Math.max(0,Math.floor((now-Number(account.entity_created))/86400000)),earnedMonths:[...months.values()].map(v=>v.income),expenseMonths:[...months.values()].map(v=>v.expenses),paid:instalments.filter(i=>i.state==='paid'&&Number(i.paid_at)<=Number(i.due_at)+7*86400000).length,late:instalments.filter(i=>i.state==='late'||i.state==='paid'&&Number(i.paid_at)>Number(i.due_at)+7*86400000).length,overdueMinor:loans.filter(l=>l.state==='arrears').reduce((n,l)=>n+BigInt(l.outstanding_minor),0n),monthlyDebtMinor:additional+loans.filter(l=>!replaced.includes(l.id)).reduce((sum,l)=>sum+BigInt(l.monthly_minor),0n),denials:denials.map(l=>Math.floor((now-Number(l.updated_at))/86400000))}); + } + async simulate(user,input,store=this.db){ + if(!input||Object.keys(input).some(k=>!['accountId','productKey','amount','months','monthly'].includes(k)))throw new BankError('Choose valid simulation details.');const a=await this.account(user,input.accountId,store),product=creditProduct(input.productKey);if(!product.kinds.includes(a.kind))throw new BankError('This credit product is not available to this client.');if(product.revolving)throw new BankError('The revolving credit flow is not open yet.',409); + let request={...input},refinanced=[],concession=null; + if(product.group==='refinancing'){ + const old=await store.query("SELECT * FROM pb_credit_loans WHERE client_number=? AND state IN ('active','arrears') ORDER BY id LIMIT 101",[a.client_number]);const loans=old.filter(l=>!l.product_key.startsWith('grant_')); + if(!loans.length)throw new BankError('There are no interest-bearing loans to refinance for this client.',409);if(loans.length>100)throw new BankError('Contact credit management to reconcile these contracts.',409); + for(const l of loans){const payoff=await currentPayoff(store,l,this.clock());refinanced.push({id:l.id,payoffMinor:String(payoff.total),collateralMinor:String(l.collateral_minor),createdAt:Number(l.created_at)});} + const principal=refinanced.reduce((n,l)=>n+BigInt(l.payoffMinor),0n);request.amount=money(principal);concession=await refinanceConcession(this.central,store,a,user,principal,this.clock(),loans); + } + const quote=creditQuote(request,{annualBps:concession?.annualBps});if(concession)quote.concession=concession;const collateral=product.group==='grants'?0n:(minorAmount(quote.amount)+3n)/4n; + return {quote,refinanced,collateral:money(collateral),score:await this.score(a,store,minorAmount(quote.monthly),refinanced.map(l=>l.id)),disbursement:'not_active',notice:product.group==='refinancing'?'Refinancing replaces all interest-bearing contracts for this same client. Grants remain separate; there is no additional cash payout.':'Simulation only. No application, collateral movement or payment has been made.'}; + } async apply(user,input,{revalidate=async()=>user}={}){ if(!input||Object.keys(input).some(k=>!['requestId','accountId','productKey','amount','months','monthly','motivation','accepted','termsVersion'].includes(k))||!uuid(input.requestId)||input.accepted!==true||input.termsVersion!==CREDIT_VERSION||typeof input.motivation!=='string'||input.motivation.trim().length<10||input.motivation.length>4000)throw new BankError('Accept the current credit terms and enter a motivation of 10–4,000 characters.'); - const simulation=await this.simulate(user,{accountId:input.accountId,productKey:input.productKey,amount:input.amount,months:input.months,monthly:input.monthly}),a=await this.account(user,input.accountId),product=creditProduct(input.productKey),quote=simulation.quote,motivation=input.motivation.trim(),fingerprint=createHash('sha256').update(JSON.stringify([user.id,a.id,quote,motivation,CREDIT_VERSION])).digest('hex'); + const a=await this.account(user,input.accountId),motivation=input.motivation.trim(),fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.accountId,input.productKey,input.amount||null,input.months||null,input.monthly||null,motivation,CREDIT_VERSION])).digest('hex'); return this.db.transaction(async tx=>{ - await tx.first('SELECT client_number FROM pb_clients WHERE client_number=? FOR UPDATE',[a.client_number]);const previous=await tx.first('SELECT * FROM pb_credit_events WHERE request_id=?',[input.requestId]);if(previous){if(previous.actor_id!==user.id||previous.fingerprint!==fingerprint)throw new BankError('This application reference was already used.',409);return {applicationId:previous.loan_id,replayed:true};} - const locked=await tx.first(accountSQL+' WHERE a.id=? FOR UPDATE',[a.id]),fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.authority(fresh);if(!eligible(locked)||!rights.entities.some(e=>e.id===locked.entity_id&&e.canPay))throw new BankError('Your borrowing authority changed.',403); - const pending=await tx.first("SELECT id FROM pb_credit_loans WHERE client_number=? AND state IN ('submitted','approved_pending') LIMIT 1",[a.client_number]);if(pending)throw new BankError('An application is already being processed for this client.',409); + await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[a.entity_id]);await tx.first('SELECT client_number FROM pb_clients WHERE client_number=? FOR UPDATE',[a.client_number]);const previous=await tx.first('SELECT * FROM pb_credit_events WHERE request_id=?',[input.requestId]);if(previous){if(previous.actor_id!==user.id||previous.fingerprint!==fingerprint)throw new BankError('This application reference was already used.',409);return {applicationId:previous.loan_id,replayed:true};} + const locked=await tx.first(accountSQL+' WHERE a.id=? FOR UPDATE',[a.id]),fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.authority(fresh,{bank:tx});if(!eligible(locked)||!rights.entities.some(e=>e.id===locked.entity_id&&e.canActivate))throw new BankError('Your borrowing authority changed.',403); + const simulation=await this.simulate(fresh,{accountId:input.accountId,productKey:input.productKey,amount:input.amount,months:input.months,monthly:input.monthly},tx),product=creditProduct(input.productKey),quote=simulation.quote; + const pending=await tx.first("SELECT id FROM pb_credit_loans WHERE client_number=? AND state IN ('submitted','approved_pending','offered','payout_queued') LIMIT 1",[a.client_number]);if(pending)throw new BankError('An application is already being processed for this client.',409); if(product.group==='grants'&&await tx.first('SELECT loan_id FROM pb_credit_grants WHERE client_number=?',[a.client_number]))throw new BankError('This client has already used its launch grant.',409); const now=this.clock(),state=product.group==='grants'?'approved_pending':'submitted'; - await tx.query('INSERT INTO pb_credit_loans(id,client_number,entity_id,account_id,product_key,state,principal_minor,outstanding_minor,monthly_minor,annual_bps,months,collateral_minor,treasury_hold_minor,created_by,motivation,quote_json,score_json,refinance_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,0,?,?,?,?,0,?,?,?,?,?,?,?)',[input.requestId,a.client_number,a.entity_id,a.id,product.key,state,String(minorAmount(quote.amount)),String(minorAmount(quote.monthly)),product.annualBps,quote.months,String(product.group==='grants'?0n:(minorAmount(quote.amount)+3n)/4n),user.id,motivation,JSON.stringify(quote),JSON.stringify(simulation.score),'[]',now,now]); + await tx.query('INSERT INTO pb_credit_loans(id,client_number,entity_id,account_id,product_key,state,principal_minor,outstanding_minor,monthly_minor,annual_bps,months,collateral_minor,treasury_hold_minor,created_by,motivation,quote_json,score_json,refinance_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,0,?,?,?,?,0,?,?,?,?,?,?,?)',[input.requestId,a.client_number,a.entity_id,a.id,product.key,state,String(minorAmount(quote.amount)),String(minorAmount(quote.monthly)),Math.round(Number(quote.annualRate)*100),quote.months,String(product.group==='grants'?0n:(minorAmount(quote.amount)+3n)/4n),user.id,motivation,JSON.stringify(quote),JSON.stringify(simulation.score),JSON.stringify(simulation.refinanced),now,now]); if(product.group==='grants')await tx.query('INSERT INTO pb_credit_grants(client_number,loan_id) VALUES(?,?)',[a.client_number,input.requestId]); - await tx.query('INSERT INTO pb_credit_events(request_id,loan_id,actor_id,action,fingerprint,details,created_at) VALUES(?,?,?,?,?,?,?)',[input.requestId,input.requestId,user.id,'application_submitted',fingerprint,JSON.stringify({state,disbursement:'not_active',termsVersion:CREDIT_VERSION}),now]); - return {applicationId:input.requestId,state,replayed:false,notice:state==='approved_pending'?'Launch grant accepted. Disbursement is not active yet; no money or collateral moved.':'Application recorded for bank review. No money or collateral moved.'}; + await tx.query('INSERT INTO pb_credit_events(request_id,loan_id,actor_id,action,fingerprint,details,created_at) VALUES(?,?,?,?,?,?,?)',[input.requestId,input.requestId,user.id,'application_submitted',fingerprint,JSON.stringify({state,disbursement:'awaiting_bank_processing',termsVersion:CREDIT_VERSION}),now]); + await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'credit_application_submitted',a.entity_id,JSON.stringify({loanId:input.requestId,product:product.key,principal:quote.amount,state}),now]); + return {applicationId:input.requestId,state,replayed:false,notice:state==='approved_pending'?'Launch grant accepted. Disbursement is queued for the next four-hour bank processing window, subject to available bank liquidity.':'Application recorded for bank review. No money or collateral moved.'}; }); } } diff --git a/website/node/postbank-db.mjs b/website/node/postbank-db.mjs index d7f64689..6e6ab8bc 100644 --- a/website/node/postbank-db.mjs +++ b/website/node/postbank-db.mjs @@ -8,13 +8,22 @@ export async function openPostbankDatabase(settings){ const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000}); const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}}); const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}}; - try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);await ensurePostbankIndexes(db);}catch(error){await pool.end();throw error;} + try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);await ensureCreditColumns(db);await ensurePostbankIndexes(db);}catch(error){await pool.end();throw error;} return db; } // Apply only missing indexes to this independent bank database. Concurrent worker // startup can race CREATE INDEX; a duplicate-name result is safe to ignore. -export const POSTBANK_INDEXES=[['pb_statement_archives','pb_statement_worker_due','state,retry_at,lease_until,month,account_id'],['pb_orders','pb_orders_source_period','source_id,created_at,id'],['pb_orders','pb_orders_target_period','target_id,created_at,id'],['pb_orders','pb_orders_queue_period','state,mode,created_at,id'],['pb_entries','pb_entries_account_period','account_id,created_at,id']]; +export const POSTBANK_INDEXES=[['pb_statement_archives','pb_statement_worker_due','state,retry_at,lease_until,month,account_id'],['pb_orders','pb_orders_source_period','source_id,created_at,id'],['pb_orders','pb_orders_target_period','target_id,created_at,id'],['pb_orders','pb_orders_queue_period','state,mode,created_at,id'],['pb_entries','pb_entries_account_period','account_id,created_at,id'],['pb_credit_loans','pb_credit_client_state','client_number,state,created_at'],['pb_credit_loans','pb_credit_payout_due','state,queued_at,id'],['pb_credit_loans','pb_credit_repayment_due','state,next_due_at,id'],['pb_credit_actions','pb_credit_action_due','state,created_at,id'],['pb_credit_events','pb_credit_contract_history','loan_id,created_at']]; export async function ensurePostbankIndexes(db){ for(const [table,name,columns]of POSTBANK_INDEXES){const found=await db.first('SELECT INDEX_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND INDEX_NAME=? LIMIT 1',[table,name]);if(found)continue;try{await db.query(`CREATE INDEX ${name} ON ${table} (${columns})`);}catch(error){if(error.code!=='ER_DUP_KEYNAME'&&error.errno!==1061)throw error;}} } + +// Additive migration for banks that already installed the read-only credit preview. +export const CREDIT_COLUMNS={accepted_by:'CHAR(36) NULL',queued_at:'BIGINT NULL',offer_expires_at:'BIGINT NULL',borrower_hold_minor:'BIGINT NOT NULL DEFAULT 0'}; +export async function ensureCreditColumns(db){ + for(const [column,type] of Object.entries(CREDIT_COLUMNS)){ + const found=await db.first('SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?',['pb_credit_loans',column]);if(found)continue; + try{await db.query(`ALTER TABLE pb_credit_loans ADD COLUMN ${column} ${type}`);}catch(error){if(error.code!=='ER_DUP_FIELDNAME'&&error.errno!==1060)throw error;} + } +} diff --git a/website/node/postbank-payments.mjs b/website/node/postbank-payments.mjs index 3f5aeac3..29da244f 100644 --- a/website/node/postbank-payments.mjs +++ b/website/node/postbank-payments.mjs @@ -1,3 +1,4 @@ +import {PostbankCreditEngine} from './postbank-credit-engine.mjs'; import {canViewAccount,canDebitAccount} from './postbank-authorisations.mjs'; import {reconcilePostbankClans} from './postbank-registry.mjs'; import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs'; @@ -139,12 +140,12 @@ export function standardCycle(now=Date.now()){ return {cutoff:localTimeUTC(p.year,p.month,p.day,hour),nextAt:localTimeUTC(nextLocal.getUTCFullYear(),nextLocal.getUTCMonth()+1,nextLocal.getUTCDate(),nextLocal.getUTCHours())}; } export function startPostbankQueue(central,bank,settings){ - if(settings.POSTBANK_ENABLED!=='true'||!bank)return ()=>{};const service=createPostbankPayments(central,bank);const archives=new PostbankStatementArchive(bank,null,statementSettings(settings));let timer=null,stopped=false,archiveBacklog=false,lastArchiveSeed=0; + if(settings.POSTBANK_ENABLED!=='true'||!bank)return ()=>{};const service=createPostbankPayments(central,bank),credit=settings.POSTBANK_CREDIT_ENABLED==='true'?new PostbankCreditEngine(bank,central,createPostbankAuthority(central,{bank})):null;const archives=new PostbankStatementArchive(bank,null,statementSettings(settings));let timer=null,stopped=false,archiveBacklog=false,lastArchiveSeed=0; const schedule=()=>{if(stopped)return;timer=setTimeout(()=>void run(),Math.max(1000,Math.min(standardCycle().nextAt-Date.now(),archiveBacklog?60000:Infinity)));timer.unref();}; async function run(){ const cutoff=standardCycle().cutoff,skip=[]; try{await reconcilePostbankClans(central,bank);while(!stopped){const result=await service.processQueue({cutoff,skip});if(result.failed){skip.push(...result.failedIds);console.error('Postbank queued payment reconciliation needs attention.');}if(result.attempted<25||skip.length>975)break;await new Promise(resolve=>setTimeout(resolve,1000));}} - catch{console.error('Postbank scheduled settlement needs attention.');}finally{try{if(Date.now()-lastArchiveSeed>3600000){await archives.seed();lastArchiveSeed=Date.now();}const result=await archives.process();archiveBacklog=result.attempted===25;if(result.failed)console.error('Postbank automatic statement archive needs attention.');}catch{console.error('Postbank statement ticker failed.');}schedule();} + catch{console.error('Postbank scheduled settlement needs attention.');}finally{try{if(credit)for(let i=0;i<40&&!stopped;i++){const result=await credit.process({cutoff});if(result.failed){console.error('Postbank credit reconciliation needs attention.');break;}if(result.offered+result.disbursed+result.repaid+result.expired+result.reminded<25)break;await new Promise(resolve=>setTimeout(resolve,1000));}}catch{console.error('Postbank credit ticker needs attention.');}try{if(Date.now()-lastArchiveSeed>3600000){await archives.seed();lastArchiveSeed=Date.now();}const result=await archives.process();archiveBacklog=result.attempted===25;if(result.failed)console.error('Postbank automatic statement archive needs attention.');}catch{console.error('Postbank statement ticker failed.');}schedule();} } // Recover only instructions belonging to the most recent settlement cutoff. // New instructions after that cutoff continue waiting for the next four-hour window. diff --git a/website/node/postbank-schema.sql b/website/node/postbank-schema.sql index 5994a202..11177561 100644 --- a/website/node/postbank-schema.sql +++ b/website/node/postbank-schema.sql @@ -101,7 +101,7 @@ CREATE TABLE IF NOT EXISTS pb_credit_loans ( reviewed_by CHAR(36) NULL, motivation TEXT NOT NULL, decision_reason TEXT NULL, quote_json TEXT NOT NULL, score_json TEXT NOT NULL, refinance_json TEXT NULL, replaced_by CHAR(36) NULL, created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL, - accepted_at BIGINT NULL, next_due_at BIGINT NULL, version INT NOT NULL DEFAULT 1, + accepted_at BIGINT NULL, accepted_by CHAR(36) NULL, queued_at BIGINT NULL, offer_expires_at BIGINT NULL, borrower_hold_minor BIGINT NOT NULL DEFAULT 0, next_due_at BIGINT NULL, version INT NOT NULL DEFAULT 1, FOREIGN KEY(client_number) REFERENCES pb_clients(client_number), FOREIGN KEY(entity_id) REFERENCES pb_entities(id), FOREIGN KEY(account_id) REFERENCES pb_accounts(id), FOREIGN KEY(collateral_account_id) REFERENCES pb_accounts(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; @@ -147,3 +147,15 @@ CREATE TABLE IF NOT EXISTS pb_project_accounts ( FOREIGN KEY(entity_id) REFERENCES pb_entities(id), FOREIGN KEY(client_number) REFERENCES pb_clients(client_number), FOREIGN KEY(account_id) REFERENCES pb_accounts(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS pb_credit_actions ( + id CHAR(36) PRIMARY KEY, loan_id CHAR(36) NOT NULL, actor_id CHAR(36) NOT NULL, + kind VARCHAR(16) NOT NULL, amount_minor BIGINT NOT NULL, state VARCHAR(16) NOT NULL, + fingerprint CHAR(64) NOT NULL, reason VARCHAR(500) NOT NULL, + created_at BIGINT NOT NULL, processed_at BIGINT NULL, failure VARCHAR(200) NULL, + FOREIGN KEY(loan_id) REFERENCES pb_credit_loans(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS pb_credit_concessions ( + event_key VARCHAR(96) PRIMARY KEY, loan_id CHAR(36) NOT NULL UNIQUE, created_at BIGINT NOT NULL, + FOREIGN KEY(loan_id) REFERENCES pb_credit_loans(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/website/node/postbank-service.mjs b/website/node/postbank-service.mjs index a17bc198..091409bb 100644 --- a/website/node/postbank-service.mjs +++ b/website/node/postbank-service.mjs @@ -23,7 +23,7 @@ export class PostbankService{ const client=await this.db.first('SELECT client_number FROM pb_clients WHERE entity_id=?',[e.id]); const packages=client?await this.db.query('SELECT id,package_key,monthly_minor,state FROM pb_packages WHERE client_number=? ORDER BY accepted_at,id',[client.client_number]):[]; const accounts=client?await this.db.query('SELECT a.id,a.account_number,a.type_code,a.display_name,a.balance_minor,a.reserved_minor,a.state,a.package_id,a.system_key,COALESCE(o.balance_guard,0) AS balance_guard FROM pb_accounts a LEFT JOIN pb_account_options o ON o.account_id=a.id WHERE a.client_number=? ORDER BY a.id',[client.client_number]):[]; - entities.push({id:e.id,kind:e.kind,name:e.name,clientNumber:client?.client_number||null,state:client?'active':'not_activated',canActivate:e.canActivate,canPay:e.canPay,expiresAt:e.expiresAt,packages:packages.map(p=>({id:p.id,key:p.package_key,name:PACKAGES.find(s=>s.key===p.package_key)?.name||p.package_key,monthly:money(p.monthly_minor),state:p.state})),accounts:accounts.filter(a=>canViewAccount(context,e.id,a.id)).map(a=>({canPay:canDebitAccount(context,e.id,a.id),id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:a.type_code==='106'?'0.00':money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:a.type_code!=='979'&&!a.system_key,balanceGuard:Boolean(a.balance_guard),monthly:money(a.balance_guard?100:0),state:'configured_pending_billing'}}))}); + entities.push({id:e.id,kind:e.kind,name:e.name,clientNumber:client?.client_number||null,state:client?'active':'not_activated',canActivate:e.canActivate,canPay:e.canPay,expiresAt:e.expiresAt,packages:packages.map(p=>({id:p.id,key:p.package_key,name:PACKAGES.find(s=>s.key===p.package_key)?.name||p.package_key,monthly:money(p.monthly_minor),state:p.state})),accounts:accounts.filter(a=>canViewAccount(context,e.id,a.id)).map(a=>({canPay:a.state==='active'&&a.type_code!=='106'&&canDebitAccount(context,e.id,a.id),id:String(a.id),number:a.account_number,type:a.type_code,name:a.display_name,balance:money(a.balance_minor),available:a.type_code==='106'?'0.00':money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),state:a.state,packageId:a.package_id,options:{balanceGuardEligible:!['979','106'].includes(a.type_code)&&!a.system_key,balanceGuard:Boolean(a.balance_guard),monthly:money(a.balance_guard?100:0),state:'configured_pending_billing'}}))}); } return {entities,catalogue:PACKAGES.map(p=>({...p,monthly:money(p.monthly),extraFee:money(p.extraFee)})),termsVersion:BANK_VERSION,admin:{canView:context.readAdmin,canManage:context.manageAdmin},server:{state:'not_linked',name:'Game server account',message:'The game bank is not connected. No game balances or transactions are imported.'},billing:{state:'planned',message:'Monthly fees are disclosed in the package catalogue. Automated billing is not enabled in this foundation batch.'}}; } @@ -42,7 +42,7 @@ export class PostbankService{ if(!number)throw new BankError('A unique client number could not be allocated. Please select your package again.',503); const packageId=this.makeId(),now=this.clock(); await tx.query('INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,?,?,?,?,?,?)',[packageId,number,choice.key,choice.monthly,BANK_VERSION,user.id,now,'active']); - const types=[choice.code,...(choice.savings?['103']:[]),...(choice.securities?['106']:[])]; + const types=[choice.code,...(choice.savings?['103']:[])]; for(const code of types){ const result=await tx.query('INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,?,?,0,0,?,?)',[number,packageId,code,entity.name+' · '+(code==='103'?'Savings':code==='106'?'Securities':'Current'),code==='106'?'planned':'active',now]); const id=Number(result.insertId);await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber(code,id),id]); @@ -79,13 +79,13 @@ export class PostbankService{ if(activeCurrent.some(a=>a.state!=='active'))throw new BankError('Resolve the account restriction before changing this package.',409); if(activeCurrent.length>1+choice.extra)throw new BankError('This package allows '+(1+choice.extra)+' current accounts. Close additional accounts before switching.',409); for(const a of accounts){ - const removed=(['103','104'].includes(a.type_code)&&!choice.savings)||(a.type_code==='106'&&!choice.securities); + const removed=['103','104'].includes(a.type_code)&&!choice.savings; if(!removed||['closed','dormant'].includes(a.state))continue; if(BigInt(a.balance_minor)!==0n||BigInt(a.reserved_minor)!==0n)throw new BankError('Move the funds and resolve pending payments on '+a.display_name+' before switching. Its account number and history will be retained.',409); if(!['active','planned'].includes(a.state))throw new BankError('Resolve the additional account restriction before switching.',409); await tx.query("UPDATE pb_accounts SET state='dormant' WHERE id=?",[a.id]); } - for(const code of [...(choice.savings?['103']:[]),...(choice.securities?['106']:[])]){ + for(const code of [...(choice.savings?['103']:[])]){ const existing=accounts.find(a=>a.type_code===code&&a.state!=='closed'); const state=code==='106'?'planned':'active'; if(existing){if(existing.state==='dormant')await tx.query('UPDATE pb_accounts SET state=? WHERE id=?',[state,existing.id]);continue;} @@ -114,7 +114,7 @@ export class PostbankService{ if(replay){let stored;try{stored=JSON.parse(replay.details);}catch{}if(replay.actor_id!==user.id||replay.action!=='account_options_changed'||stored?.fingerprint!==fingerprint)throw new BankError('This request number was already used for a different operation.',409);return {ok:true,replayed:true,state:'configured_pending_billing'};} const current=await tx.first('SELECT a.id,a.type_code,a.system_key,c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id=? FOR UPDATE',[input.accountId]); if(!current||current.entity_id!==entity.id)throw new BankError('The account authority changed. Reload and try again.',409); - if(current.type_code==='979'||current.system_key)throw new BankError('Balance Guard does not apply to official accounts.',400); + if(['979','106'].includes(current.type_code)||current.system_key)throw new BankError('Balance Guard does not apply to official or blocked collateral accounts.',400); const previous=await tx.first('SELECT balance_guard FROM pb_account_options WHERE account_id=?',[input.accountId]); if(Boolean(previous?.balance_guard)!==input.expectedBalanceGuard)throw new BankError('The account option changed. Reload before confirming.',409); const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. Reload before confirming.',409); diff --git a/website/tests/postbank-credit-concessions.test.mjs b/website/tests/postbank-credit-concessions.test.mjs new file mode 100644 index 00000000..9a015c79 --- /dev/null +++ b/website/tests/postbank-credit-concessions.test.mjs @@ -0,0 +1,5 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {refinanceConcession} from '../node/postbank-credit-concessions.mjs'; +const bank={first:async()=>null},user={id:'elected-user'},old=[{created_at:1}],account={kind:'person',client_number:'123456789012'},term={id:'actual-term',office:'emperor',faction:'imperium',starts_at:100,expires_at:10000}; +const central=rows=>({prepare(sql){assert.ok(/political_office_terms|corrino_company_events/.test(sql));return {bind(){return this;},async all(){return {results:rows};}};}}); +test('election concession is capped at five thousand DM, requires actual prior debt and cannot be reused',async()=>{const c=await refinanceConcession(central([term]),bank,account,user,1000000n,1000,old);assert.equal(c.annualBps,1020);assert.equal(c.discountedPrincipalLimit,'5000.00');assert.equal(await refinanceConcession(central([]),bank,account,user,1000000n,1000,old),null);assert.equal(await refinanceConcession(central([term]),bank,account,user,1000000n,1000,[{created_at:101}]),null);assert.equal(await refinanceConcession(central([term]),{first:async()=>({loan_id:'used'})},account,user,1000000n,1000,old),null);}); +test('company concession requires a real CEO change to the current applicant, never first appointment',async()=>{const a={...account,kind:'company',external_key:'company'},event={id:'change',created_at:100,details_json:JSON.stringify({ceoId:user.id,previousCeoId:'former-ceo'})};assert.equal((await refinanceConcession(central([event]),bank,a,user,1000000n,1000,old)).annualBps,450);for(const previousCeoId of [null,user.id])assert.equal(await refinanceConcession(central([{...event,details_json:JSON.stringify({ceoId:user.id,previousCeoId})}]),bank,a,user,1000000n,1000,old),null);assert.equal(await refinanceConcession(central([event]),bank,{...a,kind:'clan'},user,1000000n,1000,old),null);}); diff --git a/website/tests/postbank-credit-engine.test.mjs b/website/tests/postbank-credit-engine.test.mjs new file mode 100644 index 00000000..f0ecc931 --- /dev/null +++ b/website/tests/postbank-credit-engine.test.mjs @@ -0,0 +1,19 @@ +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 {PostbankCredit} from '../node/postbank-credit.mjs';import {PostbankCreditEngine} from '../node/postbank-credit-engine.mjs';import {dueMonth} from '../node/postbank-credit-ledger.mjs';import {BANK_VERSION,bankNumber} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; +async function setup({liquidity=1000000}={}){const db=new BankFixture(),users=['borrower','reviewer','intruder'].map(username=>({id:randomUUID(),username})),entity={id:randomUUID(),kind:'person',key:users[0].id,name:'Borrower'},state={time:Date.parse('2026-11-14T10:00:00Z'),borrow:true,manage:true},clock=()=>state.time,authority=async u=>({entities:[{...entity,canView:u.id===users[0].id,canActivate:u.id===users[0].id&&state.borrow,canPay:u.id===users[0].id&&state.borrow}],readAdmin:u.id===users[1].id,manageAdmin:u.id===users[1].id&&state.manage});await new PostbankService(db,authority,{clock}).activate(users[0],{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const account=await db.first("SELECT * FROM pb_accounts WHERE type_code='102'");await db.query('UPDATE pb_accounts SET balance_minor=30000 WHERE id=?',[account.id]);const r=await db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_web_treasury','979','Website Bank Treasury',?,'active',1)",[liquidity]);await db.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('979',r.insertId),r.insertId]);return {db,users,entity,state,clock,authority,account,bank:r.insertId,credit:new PostbankCredit(db,authority,{clock}),engine:new PostbankCreditEngine(db,{},authority,{clock,resolveUser:async id=>users.find(u=>u.id===id)})};} +async function apply(f,grant=false){const input={requestId:randomUUID(),accountId:String(f.account.id),productKey:grant?'grant_start':'personal_loan',amount:'1000.00',months:3,...grant?{monthly:'250.00'}:{},motivation:'Meaningful borrowing purpose',accepted:true,termsVersion:CREDIT_VERSION};await f.credit.apply(f.users[0],input);return input.requestId;} +const action=(id,action,extra={})=>({requestId:randomUUID(),loanId:id,action,reason:'Confirmed credit instruction',confirmed:true,...extra}); +async function offered(f){const id=await apply(f);await f.engine.decision(f.users[1],action(id,'approve'));return await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[id]);} +async function active(f){let l=await offered(f);await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));assert.equal((await f.engine.process({cutoff:f.clock()})).disbursed,1);return await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[l.id]);} +test('ordinary loan reserves treasury, requires own collateral and posts once with a balanced ledger',async()=>{const f=await setup();try{const loan=await offered(f);assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.bank])).reserved_minor),100000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);const acceptance=action(loan.id,'accept',{expectedVersion:Number(loan.version)});await f.engine.accept(f.users[0],acceptance);assert.equal((await f.engine.accept(f.users[0],acceptance)).replayed,true);assert.equal(await f.engine.payout(loan.id,f.clock()-1),false);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.engine.process()).disbursed,1);assert.equal((await f.engine.process()).disbursed,0);}finally{f.db.close();}}); +test('disbursement and full early repayment preserve cash and release collateral without future interest',async()=>{const f=await setup();try{const l=await active(f);assert.equal(l.state,'active');const pledge=await f.db.first("SELECT * FROM pb_accounts WHERE type_code='106'");assert.equal(Number(pledge.balance_minor),25000);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor),105000);const payment=action(l.id,'repay',{amount:'1000.00'});await f.engine.requestRepayment(f.users[0],payment);assert.equal((await f.engine.requestRepayment(f.users[0],payment)).replayed,true);await f.engine.process({cutoff:f.clock()});const done=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[l.id]);assert.equal(done.state,'repaid');assert.equal(Number(done.outstanding_minor),0);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[pledge.id])).balance_minor),0);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.bank])).balance_minor),1000000);}finally{f.db.close();}}); +test('grant autoaccepts without collateral, waits for liquidity and creates one amortising contract',async()=>{const f=await setup({liquidity:0});try{const id=await apply(f,true);const waiting=await f.engine.process();assert.equal(waiting.disbursed,0);assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[id])).state,'approved_pending');await f.db.query('UPDATE pb_accounts SET balance_minor=1000000 WHERE id=?',[f.bank]);assert.equal((await f.engine.process()).disbursed,1);assert.equal((await f.engine.process()).disbursed,0);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='106'")).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_instalments WHERE loan_id=?',[id])).n,10);await assert.rejects(apply(f,true),e=>e.status===409);}finally{f.db.close();}}); +test('permissions revoked after acceptance release reservations without paying and self-review is denied',async()=>{const f=await setup();try{const l=await offered(f);await assert.rejects(f.engine.decision(f.users[0],action(l.id,'approve')),e=>e.status===403);await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));f.state.borrow=false;await f.engine.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'withdrawn');assert.equal(Number((await f.db.first('SELECT SUM(reserved_minor) n FROM pb_accounts')).n),0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}}); +test('monthly collection has seven-day grace, no penalty, and staff recovery stays within pledged DM',async()=>{const f=await setup();try{const l=await active(f);await f.db.query('UPDATE pb_accounts SET balance_minor=0 WHERE id=?',[f.account.id]);f.state.time=dueMonth(f.clock(),1);await f.engine.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'active');f.state.time+=7*86400000;await f.engine.process();assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'arrears');await assert.rejects(f.engine.requestRepayment(f.users[1],action(l.id,'recover',{amount:'250.01'})),e=>e.status===409);await f.engine.requestRepayment(f.users[1],action(l.id,'recover',{amount:'10.00'}));await f.engine.process();assert.equal(Number((await f.db.first('SELECT collateral_minor FROM pb_credit_loans WHERE id=?',[l.id])).collateral_minor),24000);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);}finally{f.db.close();}}); + +test('refinancing replaces all old interest-bearing contracts without paying extra cash or losing history',async()=>{const f=await setup();try{const old=await active(f),balance=Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor),body={requestId:randomUUID(),accountId:String(f.account.id),productKey:'personal_refinance',amount:'999999.00',months:6,motivation:'Consolidate current borrowing',accepted:true,termsVersion:CREDIT_VERSION};const quote=await f.credit.simulate(f.users[0],{accountId:body.accountId,productKey:body.productKey,amount:body.amount,months:6});assert.equal(quote.quote.amount,'1000.00');await f.credit.apply(f.users[0],body);await f.engine.decision(f.users[1],action(body.requestId,'approve'));const offer=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[body.requestId]);await f.engine.accept(f.users[0],action(offer.id,'accept',{expectedVersion:Number(offer.version)}));assert.equal((await f.engine.process()).disbursed,1);const replaced=await f.db.first('SELECT * FROM pb_credit_loans WHERE id=?',[old.id]);assert.equal(replaced.state,'refinanced');assert.equal(replaced.replaced_by,body.requestId);assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor),balance);assert.equal(Number((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,2);assert.equal(Number((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE type_code='106'")).balance_minor),25000);}finally{f.db.close();}}); +test('a failed payout audit rolls back borrower, treasury, collateral and contract together',async()=>{const f=await setup();try{const l=await offered(f);await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));f.db.sqlite.exec("CREATE TRIGGER fail_credit_disbursement BEFORE INSERT ON pb_credit_events WHEN NEW.action='credit_disbursed' BEGIN SELECT RAISE(ABORT,'injected failure'); END;");assert.equal((await f.engine.process()).failed,1);assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[l.id])).state,'payout_queued');assert.equal(Number((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.bank])).balance_minor),1000000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='106'")).n,0);f.db.sqlite.exec('DROP TRIGGER fail_credit_disbursement');assert.equal((await f.engine.process()).disbursed,1);assert.equal((await f.engine.process()).disbursed,0);}finally{f.db.close();}}); +test('payment-only authority cannot apply for or inspect borrowing, and competing workers do not duplicate payouts',async()=>{const f=await setup();try{const delegated=new PostbankCredit(f.db,async()=>({entities:[{...f.entity,canView:true,canPay:true,canActivate:false}]}));assert.equal((await delegated.overview(f.users[2])).loans.length,0);await assert.rejects(delegated.simulate(f.users[2],{accountId:String(f.account.id),productKey:'personal_loan',amount:'1000.00',months:3}),e=>e.status===403);const l=await offered(f);await f.engine.accept(f.users[0],action(l.id,'accept',{expectedVersion:Number(l.version)}));const [a,b]=await Promise.all([f.engine.process(),f.engine.process()]);assert.equal(a.disbursed+b.disbursed,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,2);}finally{f.db.close();}}); + +test('offer acceptance cannot use borrowed money as its collateral, and expired offers release bank liquidity',async()=>{const f=await setup();try{const loan=await offered(f);await f.db.query('UPDATE pb_accounts SET balance_minor=24999 WHERE id=?',[f.account.id]);await assert.rejects(f.engine.accept(f.users[0],action(loan.id,'accept',{expectedVersion:Number(loan.version)})),e=>e.status===409);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.account.id])).reserved_minor),0);f.state.time+=8*86400000;assert.equal((await f.engine.process()).expired,1);assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.bank])).reserved_minor),0);}finally{f.db.close();}}); +test('a bank manager cannot approve their own controlled borrowing even when they have bank-management rights',async()=>{const f=await setup();try{const id=await apply(f),privileged=new PostbankCreditEngine(f.db,{},async u=>({...await f.authority(u),manageAdmin:true}),{clock:f.clock});await assert.rejects(privileged.decision(f.users[0],action(id,'approve')),e=>e.status===403&&/different bank manager/.test(e.message));assert.equal((await f.db.first('SELECT state FROM pb_credit_loans WHERE id=?',[id])).state,'submitted');assert.equal(Number((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.bank])).reserved_minor),0);}finally{f.db.close();}}); +test('upcoming reminders are deduplicated and blocked accounts still allow contract inspection',async()=>{const f=await setup();try{const l=await active(f);f.state.time=dueMonth(f.clock(),1)-2*86400000;assert.equal((await f.engine.process()).reminded,1);assert.equal((await f.engine.process()).reminded,0);await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.account.id]);const details=await f.credit.details(f.users[0],l.id);assert.ok(details.notices.some(n=>n.subject==='Upcoming credit repayment'));assert.equal(details.schedule.length,3);await assert.rejects(f.credit.details(f.users[2],l.id),e=>e.status===403);}finally{f.db.close();}}); diff --git a/website/tests/postbank-credit-ui.test.mjs b/website/tests/postbank-credit-ui.test.mjs index 6fa03c1d..a487f749 100644 --- a/website/tests/postbank-credit-ui.test.mjs +++ b/website/tests/postbank-credit-ui.test.mjs @@ -1,6 +1,8 @@ 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;}} +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){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;}} +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;}} 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})); diff --git a/website/tests/postbank-credit.test.mjs b/website/tests/postbank-credit.test.mjs index c4f01a80..b3513064 100644 --- a/website/tests/postbank-credit.test.mjs +++ b/website/tests/postbank-credit.test.mjs @@ -1,9 +1,11 @@ import {createPostbankApi} from '../node/postbank-api.mjs'; 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 {PostbankCredit} from '../node/postbank-credit.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; -async function fixture(){const db=new BankFixture(),user={id:randomUUID(),username:'Credit fixture'},other={id:randomUUID()},entity={id:randomUUID(),kind:'person',key:user.id,name:user.username};let enabled=true;const authority=async u=>({entities:[{...entity,canView:u.id===user.id,canActivate:u.id===user.id,canPay:enabled&&u.id===user.id}],readAdmin:false,manageAdmin:false}),service=new PostbankService(db,authority);await service.activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const account=await db.first("SELECT * FROM pb_accounts WHERE type_code='102'");return {db,user,other,account,authority,credit:new PostbankCredit(db,authority),revoke:()=>{enabled=false;}};} +async function fixture(){const db=new BankFixture(),user={id:randomUUID(),username:'Credit fixture'},other={id:randomUUID()},entity={id:randomUUID(),kind:'person',key:user.id,name:user.username};let enabled=true;const authority=async u=>({entities:[{...entity,canView:u.id===user.id,canActivate:enabled&&u.id===user.id,canPay:enabled&&u.id===user.id}],readAdmin:false,manageAdmin:false}),service=new PostbankService(db,authority);await service.activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const account=await db.first("SELECT * FROM pb_accounts WHERE type_code='102'");return {db,user,other,account,authority,credit:new PostbankCredit(db,authority),revoke:()=>{enabled=false;}};} const application=f=>({requestId:randomUUID(),accountId:String(f.account.id),productKey:'grant_start',monthly:'250.00',motivation:'Initial launch activity and supplies',accepted:true,termsVersion:CREDIT_VERSION}); test('credit simulation and grant acceptance do not disburse or touch collateral before engine activation',async()=>{const f=await fixture();try{const b=application(f),q=await f.credit.simulate(f.user,{accountId:b.accountId,productKey:b.productKey,monthly:b.monthly});assert.equal(q.quote.totalInterest,'0.00');assert.equal(q.collateral,'0.00');assert.equal(q.score.limitedHistory,true);const result=await f.credit.apply(f.user,b);assert.equal(result.state,'approved_pending');assert.equal((await f.credit.apply(f.user,b)).replayed,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.account.id])).balance_minor,0);assert.equal((await f.db.first('SELECT outstanding_minor FROM pb_credit_loans')).outstanding_minor,0);assert.equal((await f.credit.overview(f.user)).loans.length,1);assert.equal((await f.credit.overview(f.other)).loans.length,0);await assert.rejects(f.credit.apply(f.user,{...b,requestId:randomUUID()}),e=>e.status===409);await assert.rejects(f.credit.apply(f.user,{...b,motivation:'A changed application using the same ID'}),e=>e.status===409);}finally{f.db.close();}}); test('credit submissions recheck ownership, terms, product eligibility and permissions',async()=>{const f=await fixture();try{const b=application(f);await assert.rejects(f.credit.apply(f.other,b),e=>e.status===403);await assert.rejects(f.credit.apply(f.user,{...b,termsVersion:'obsolete'}));await assert.rejects(f.credit.simulate(f.user,{accountId:b.accountId,productKey:'business_loan',amount:'10000.00',months:12}));await assert.rejects(f.credit.apply(f.user,b,{revalidate:async()=>{f.revoke();return f.user;}}),e=>e.status===403);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,0);}finally{f.db.close();}}); test('ordinary loan application captures exact quote and 25 percent DM collateral without charging',async()=>{const f=await fixture();try{const b={...application(f),productKey:'personal_loan',amount:'1000.00',months:12};const q=await f.credit.simulate(f.user,{accountId:b.accountId,productKey:b.productKey,amount:b.amount,months:b.months});assert.equal(q.collateral,'250.00');await f.credit.apply(f.user,b);const row=await f.db.first('SELECT * FROM pb_credit_loans');assert.equal(row.state,'submitted');assert.equal(row.collateral_minor,25000);assert.equal(row.outstanding_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,0);}finally{f.db.close();}}); test('credit API provides simulations with fresh authority while financial intake remains closed',async()=>{const f=await fixture();try{const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>f.user,authority:f.authority});const request=(path,body,origin='https://cp.dunerealms.com')=>new Request('https://cp.dunerealms.com'+path,body?{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify(body)}:{});assert.equal((await api(request('/api/bank/credit/overview'))).status,200);const body={accountId:String(f.account.id),productKey:'grant_start',monthly:'250.00'};assert.equal((await api(request('/api/bank/credit/simulate',body))).status,200);assert.equal((await api(request('/api/bank/credit/simulate',body,'https://evil.invalid'))).status,403);assert.equal((await api(request('/api/bank/credit/apply',application(f)))).status,409);assert.equal((await api(request('/api/bank/admin/credit'))).status,403);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}); + +test('enabled credit API accepts a real request once while rejecting origins and unauthorized decisions',async()=>{const f=await fixture();try{const api=createPostbankApi(null,f.db,{POSTBANK_CREDIT_ENABLED:'true'}, {authenticate:async()=>f.user,authority:f.authority,resolveUser:async()=>f.user}),body=application(f),request=(path,input,origin='https://cp.dunerealms.com')=>new Request('https://cp.dunerealms.com'+path,{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify(input)});assert.equal((await api(request('/api/bank/credit/apply',body,'https://evil.invalid'))).status,403);assert.equal((await api(request('/api/bank/credit/apply',body))).status,200);const replay=await api(request('/api/bank/credit/apply',body));assert.equal((await replay.json()).replayed,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_credit_loans')).n,1);assert.equal((await api(request('/api/bank/admin/credit/decision',{requestId:randomUUID(),loanId:body.requestId,action:'approve',confirmed:true,reason:'Not an authorised manager'}))).status,403);assert.equal((await api(new Request('https://cp.dunerealms.com/api/bank/credit/details?loanId='+body.requestId))).status,200);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});