MC/website/node/postbank-credit-model.mjs
2026-11-27 23:43:05 +00:00

42 lines
6.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {BankError} from './postbank-service.mjs';
import {minorAmount,money} from './postbank-catalogue.mjs';
export const CREDIT_VERSION='postbank-credit-2026-11-15-first-instalment';
export const CREDIT_PRODUCTS=Object.freeze([
{key:'grant_start',name:'Launch Start',group:'grants',kinds:['person'],amount:'2500.00',min:'2500.00',max:'2500.00',annualBps:0,maxMonths:12,automatic:true,art:'postbank-grant-start-v1.png'},
{key:'grant_build',name:'Launch Build',group:'grants',kinds:['person'],amount:'5000.00',min:'5000.00',max:'5000.00',annualBps:0,maxMonths:12,automatic:true,art:'postbank-grant-build-v1.png'},
{key:'grant_advance',name:'Launch Advance',group:'grants',kinds:['person'],amount:'10000.00',min:'10000.00',max:'10000.00',annualBps:0,maxMonths:12,automatic:true,art:'postbank-grant-advance-v1.png'},
{key:'personal_loan',name:'Personal Loan',group:'personal',kinds:['person'],min:'1000.00',max:'25000.00',annualBps:839,terms:[3,6,9,12]},
{key:'personal_overdraft',name:'One-Month Advance',group:'personal',kinds:['person'],min:'250.00',max:'2500.00',annualBps:1039,terms:[1]},
{key:'personal_card',name:'Personal Credit Line',group:'personal',kinds:['person'],min:'250.00',max:'5000.00',annualBps:839,terms:[1],revolving:true},
{key:'business_loan',name:'Business Loan',group:'professional',kinds:['clan','company'],min:'5000.00',max:'100000.00',annualBps:450,terms:[3,6,12,18,24]},
{key:'civic_loan',name:'Civic Loan',group:'professional',kinds:['house','office'],min:'5000.00',max:'100000.00',annualBps:350,terms:[3,6,12]},
{key:'personal_refinance',name:'Personal Refinancing',group:'refinancing',kinds:['person'],min:'0.01',max:'100000.00',annualBps:1200,terms:[3,6,9,12,18,24]},
{key:'business_refinance',name:'Business Refinancing',group:'refinancing',kinds:['clan','company'],min:'0.01',max:'500000.00',annualBps:650,terms:[3,6,12,18,24]},
{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 creditProductsForPackage(packageKey){return CREDIT_PRODUCTS.map(p=>packageKey==='pb_pro'&&p.kinds.includes('person')&&!p.automatic&&!p.revolving?{...p,max:money(minorAmount(p.max)*3n),packageBenefit:'Pro · 3× borrowing limit'}:p);}
export function creditQuote({productKey,amount,months,monthly},{annualBps=null,packageKey=null}={}){
const product=creditProductsForPackage(packageKey).find(p=>p.key===productKey)||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(principal<minorAmount(product.min)||principal>minorAmount(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 firstInstalment=product.group==='grants'?0n:(principal+19n)/20n,repaymentPrincipal=principal-firstInstalment;
if(repaymentPrincipal<=0n)throw new BankError('Use direct repayment when the first instalment covers the entire balance.');
const rate=Math.expm1(Math.log1p(rateBps/10000)/12);
if(!payment)payment=rate?BigInt(Math.ceil(Number(repaymentPrincipal)*rate/(1-Math.pow(1+rate,-n)))):(repaymentPrincipal+BigInt(n)-1n)/BigInt(n);
let remaining=repaymentPrincipal,totalInterest=0n,total=firstInstalment;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),firstInstalment:money(firstInstalment),remainingPrincipal:money(repaymentPrincipal),firstInstalmentBps:product.group==='grants'?0:500,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=[]}={}){
const history=earnedMonths.length>=3,median=a=>{const v=a.map(Number).sort((a,b)=>a-b);return v.length?v[Math.floor(v.length/2)]:0;},income=median(earnedMonths),expenses=median(expenseMonths),net=Math.max(0,income-expenses);
const payment=paid+late?Math.round(350*paid/(paid+late)):210;
const flow=history?(net>0?Math.min(250,150+Math.round(100*net/Math.max(1,income))):60):150;
const burden=history?monthlyDebtMinor===0n?200:Math.max(0,200-Math.round(Number(monthlyDebtMinor)/Math.max(1,net)*200)):120;
const stability=Math.min(100,60+Math.floor(ageDays/7)),behaviour=60;
const penalty=Math.min(45,denials.reduce((n,days)=>n+Math.max(0,15-Math.floor(days/30)*5),0));
let score=payment+flow+burden+stability+behaviour-penalty;if(overdueMinor>0n)score-=100;score=Math.max(0,Math.min(1000,score));const flags=[];if(!history)flags.push('Insufficient History');if(overdueMinor>0n)flags.push('Existing Arrears');if(penalty)flags.push('Recent Declines');if(history&&Number(monthlyDebtMinor)>net*.35)flags.push('High Monthly Commitments');if(history&&Math.min(...earnedMonths.map(Number))<income*.5)flags.push('Irregular Income');return {score,band:riskBand(score),limitedHistory:!history,monthlyIncome:money(BigInt(Math.round(income))),monthlyExpenses:money(BigInt(Math.round(expenses))),monthlyCapacity:money(BigInt(Math.round(net))),denialPenalty:penalty,components:{payment,flow,burden,stability,behaviour},flags};
}