forked from unimatrix/web
30 lines
8.3 KiB
JavaScript
30 lines
8.3 KiB
JavaScript
import {createHash} from 'node:crypto';
|
||
import {BankError} from './postbank-service.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 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.'};}
|
||
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');
|
||
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);
|
||
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]);
|
||
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.'};
|
||
});
|
||
}
|
||
}
|

Staff