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,{firstFraction=1}={}){ 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);if(!Number.isFinite(firstFraction)||firstFraction<0||firstFraction>1)throw new BankError('Invalid accrual period.');const discounted=Array.from({length:months},(_,i)=>1/((1+rate*firstFraction)*Math.pow(1+rate,i))).reduce((a,b)=>a+b,0),payment=monthly??(firstFraction!==1?BigInt(Math.ceil(Number(principal)/discounted)):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*(i===1?firstFraction:1)));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&&debitMath.floor(Number(time)/86400000); export async function currentPayoff(tx,loan,now){ const rows=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,now]); const future=await tx.first("SELECT * FROM pb_credit_instalments WHERE loan_id=? AND due_at>? AND state='pending' ORDER BY sequence_no LIMIT 1",[loan.id,now]);let accrued=0n,current=null; if(future){const anchor=Number(future.accrual_at??dueMonth(Number(loan.accepted_at),Number(future.sequence_no)-1)),end=Number(future.due_at),remaining=BigInt(future.accrual_remaining_minor??(BigInt(future.interest_minor)-BigInt(future.paid_interest))),span=Math.max(1,valueDay(end)-valueDay(anchor)),elapsed=Math.max(0,Math.min(span,valueDay(now)-valueDay(anchor))),earned=(remaining*BigInt(elapsed)+BigInt(Math.floor(span/2)))/BigInt(span);accrued=BigInt(future.accrued_interest_minor||0)+earned;current={...future,newlyEarned:earned,unearned:remaining-earned};} const interest=rows.reduce((sum,r)=>sum+BigInt(r.interest_minor)-BigInt(r.paid_interest),0n)+accrued;return {principal:BigInt(loan.outstanding_minor),interest,total:BigInt(loan.outstanding_minor)+interest,rows,current,accrued}; } 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)}));