forked from unimatrix/web
63 lines
16 KiB
JavaScript
63 lines
16 KiB
JavaScript
import {createHash} from 'node:crypto';
|
||
import {BankError} from './postbank-service.mjs';
|
||
import {currentPayoff,cents} 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,creditProductsForPackage,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.external_key,e.display_name entity_name,e.active entity_active,e.created_at entity_created,p.state package_state,p.package_key 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,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,packageKey:a.package_key,products:creditProductsForPackage(a.package_key),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,{loanId}={}){if(loanId!==undefined&&!uuid(loanId))throw new BankError('Choose a valid credit contract.');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'+(loanId?' WHERE l.id=?':'')+' ORDER BY l.created_at DESC LIMIT 100',loanId?[loanId]:[]);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 pending=await this.db.first("SELECT COALESCE(SUM(amount_minor),0) total FROM pb_credit_actions WHERE loan_id=? AND state='queued'",[loanId]),queued=BigInt(pending.total),maximum=payoff.total>queued?payoff.total-queued:0n;
|
||
const support=await this.db.first('SELECT ticket_id,ticket_number,state FROM pb_credit_support_jobs WHERE loan_id=?',[loanId]);
|
||
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 {supportTicket:support?{state:support.state,number:support.ticket_number||null,url:support.ticket_id?(staff?'https://support.dunerealms.com/scp/tickets.php?id='+support.ticket_id:'https://support.dunerealms.com/tickets.php'):null}:null,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),queuedRepayments:money(queued),maximumRepayment:money(maximum),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_at<? ORDER BY x.created_at,x.id LIMIT 10001",[account.client_number,since.getTime(),monthStart]);
|
||
const months=new Map();if(Number(account.entity_created)<=since.getTime()&&entries.length<=10000)for(let i=0;i<3;i++){const d=new Date(since);d.setUTCMonth(d.getUTCMonth()+i);months.set(d.toISOString().slice(0,7),{income:0n,expenses:0n});}
|
||
for(const row of entries){if(row.counterparty_client===account.client_number||['system','grant','loan','tax','treasury','reserve'].includes(row.mode))continue;const bucket=months.get(new Date(Number(row.created_at)).toISOString().slice(0,7));if(!bucket)continue;const n=BigInt(row.amount_minor);if(n>0n)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,packageKey:a.package_key});if(concession)quote.concession=concession;const collateral=0n;
|
||
return {quote,refinanced,collateral:money(collateral),firstInstalment:quote.firstInstalment,remainingPrincipal:quote.remainingPrincipal,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)throw new BankError('Accept the current credit terms and confirm this application.');
|
||
const applicationProduct=creditProduct(input.productKey),motivation=typeof input.motivation==='string'?input.motivation.trim():'';
|
||
if(input.motivation!==undefined&&typeof input.motivation!=='string'||typeof input.motivation==='string'&&input.motivation.length>4000||applicationProduct.group!=='grants'&&motivation.length<10)throw new BankError(applicationProduct.group==='grants'?'The optional grant note must be plain text of at most 4,000 characters.':'Enter a motivation of 10–4,000 characters.');
|
||
const a=await this.account(user,input.accountId),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 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,first_instalment_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,'0',String(cents(quote.firstInstalment)),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]);
|
||
else await tx.query('INSERT INTO pb_credit_support_jobs(loan_id) VALUES(?)',[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:'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.'};
|
||
});
|
||
}
|
||
}
|

Staff