Add extra wage cycles, recheck bank tickers and apply first loan instalments

This commit is contained in:
unimatrixgit 2026-11-15 22:13:52 +01:00
commit ff06ac894e
9 changed files with 184 additions and 74 deletions

View file

@ -4,14 +4,14 @@ import {randomUUID} from 'node:crypto';
export class CentralScheduler{
constructor(db,tasks,{clock=Date.now}={}){this.db=db;this.tasks=tasks;this.clock=clock;this.stopped=false;}
async status(){return this.db.query('SELECT task_key,last_slot,succeeded_at,lease_until,last_error FROM pb_scheduler_tasks ORDER BY task_key');}
async runDue(){const results=[];
async runDue({recheck=false,beforeTask=async()=>{}}={}){const results=[];
for(const task of this.tasks){
if(this.stopped)break;const now=this.clock(),slot=task.slot(now);if(slot===null)continue;
if(this.stopped)break;await beforeTask();const now=this.clock(),slot=task.slot(now);if(slot===null)continue;
const token=randomUUID();
const claimed=await this.db.transaction(async tx=>{
await tx.query("INSERT INTO pb_scheduler_tasks(task_key,last_slot,succeeded_at,lease_token,lease_until,last_error) VALUES(?,-1,0,'',0,'') ON DUPLICATE KEY UPDATE task_key=VALUES(task_key)",[task.key]);
const row=await tx.first('SELECT * FROM pb_scheduler_tasks WHERE task_key=? FOR UPDATE',[task.key]);
if(Number(row.last_slot)>=slot||Number(row.lease_until)>now)return false;
if((!recheck&&Number(row.last_slot)>=slot)||Number(row.lease_until)>now)return false;
await tx.query('UPDATE pb_scheduler_tasks SET lease_token=?,lease_until=? WHERE task_key=?',[token,now+300000,task.key]);return true;
});
if(!claimed){results.push({task:task.key,state:'not_due_or_running'});continue;}

View file

@ -134,7 +134,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
try{
if(url.search)return reply({message:'Payroll overrides are not accepted.'},400);
const fresh=await auth(request);if(!fresh||fresh.id!==user.id||!await canRunScheduler(central,fresh))return reply({message:'P&O payroll management is reserved for the Big Four.'},403);
if(request.method==='GET'&&!path.endsWith('/run')){const result={...await payroll.overview(),cycle:await payrollCycle.preview()},current=await auth(request);if(!current||current.id!==user.id||!await canRunScheduler(central,current))return reply({message:'Payroll access changed.'},403);return reply(result);}
if(request.method==='GET'&&!path.endsWith('/run')){const result={...await payroll.overview(),cycle:await payrollCycle.preview(),additionalCycle:await payrollCycle.previewAdditional()},current=await auth(request);if(!current||current.id!==user.id||!await canRunScheduler(central,current))return reply({message:'Payroll access changed.'},403);return reply(result);}
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
@ -154,7 +154,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
const raw=await request.text();if(raw.length>300)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Confirm the scheduler run.'},400);}
if(!input||input.confirmed!==true||Object.keys(input).some(k=>k!=='confirmed'))return reply({message:'Confirm running due tasks. Future dates cannot be forced.'},400);
const result=await scheduler.runDue();await bank.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),fresh.id,'central_scheduler_run',null,JSON.stringify(result),Date.now()]);return reply(result);
const auditId=randomUUID();await bank.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[auditId,fresh.id,'central_scheduler_run',null,JSON.stringify({state:'started',recheckAll:true}),Date.now()]);const result=await scheduler.runDue({recheck:true,beforeTask:async()=>{const current=await auth(request);if(!current||current.id!==fresh.id||!await canRunScheduler(central,current))throw Error('Scheduler access changed');}});await bank.query('UPDATE pb_audit SET details=? WHERE id=?',[JSON.stringify({state:'completed',recheckAll:true,...result}),auditId]);return reply(result);
}
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);return reply({tasks:await scheduler.status()});
}catch{return reply({message:'The scheduler result could not be confirmed. Reload its status before retrying.'},503);}

View file

@ -24,7 +24,7 @@ export class PostbankCreditEngine{
}
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)<required)throw new BankError('The borrower account needs its own 25% DM collateral before this offer can be accepted.',409);if(required)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[String(required),a.current.id]);await tx.query("UPDATE pb_credit_loans SET state='payout_queued',borrower_hold_minor=?,accepted_by=?,accepted_at=?,queued_at=?,updated_at=?,version=version+1 WHERE id=?",[String(required),user.id,this.clock(),this.clock(),this.clock(),loan.id]);await this.event(tx,loan,input.requestId,user.id,'offer_accepted',{collateralReserved:money(required)},fingerprint);return {ok:true,state:'payout_queued'};});
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.first_instalment_minor||0)||(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)<required)throw new BankError('The borrower account needs '+money(required)+' DM of its own funds for the '+(BigInt(loan.first_instalment_minor||0)?'first instalment':'agreed collateral')+' before this offer can be accepted.',409);if(required)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[String(required),a.current.id]);await tx.query("UPDATE pb_credit_loans SET state='payout_queued',borrower_hold_minor=?,accepted_by=?,accepted_at=?,queued_at=?,updated_at=?,version=version+1 WHERE id=?",[String(required),user.id,this.clock(),this.clock(),this.clock(),loan.id]);await this.event(tx,loan,input.requestId,user.id,'offer_accepted',BigInt(loan.first_instalment_minor||0)?{firstInstalmentReserved:money(required)}:{collateralReserved:money(required)},fingerprint);return {ok:true,state:'payout_queued'};});
}
async collateralAccount(tx,loan){if(loan.collateral_account_id)return tx.first('SELECT * FROM pb_accounts WHERE id=?',[loan.collateral_account_id]);let a=await tx.first("SELECT * FROM pb_accounts WHERE client_number=? AND type_code='106' ORDER BY id LIMIT 1 FOR UPDATE",[loan.client_number]);if(!a){const current=await tx.first('SELECT package_id FROM pb_accounts WHERE id=?',[loan.account_id]),insert=await tx.query("INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,state,created_at) VALUES(?,?,'106','Blocked Collateral Account','blocked',?)",[loan.client_number,current.package_id,this.clock()]);await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('106',Number(insert.insertId)),insert.insertId]);a=await tx.first('SELECT * FROM pb_accounts WHERE id=?',[insert.insertId]);}await tx.query('UPDATE pb_credit_loans SET collateral_account_id=? WHERE id=?',[a.id,loan.id]);loan.collateral_account_id=a.id;return a;}
async payout(loanId,cutoff){return this.lock(loanId,async(tx,loan)=>{
@ -32,13 +32,15 @@ export class PostbankCreditEngine{
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});
const firstInstalment=BigInt(loan.first_instalment_minor||0);
if(firstInstalment){if(BigInt(loan.borrower_hold_minor||0)!==firstInstalment)throw new BankError('The first instalment must be reserved before this loan is issued.',409);await creditMovement(tx,{key:loan.id+':first-instalment',actor:actor.id,source:a.current,target:a.bank,amount:firstInstalment,reference:'First loan instalment · '+loan.id,now,held:true});}
else 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,accrual_at,accrual_remaining_minor) VALUES(?,?,?,?,?,'pending',?,?)",[loan.id,row.number,dueMonth(now,row.number),String(row.principal),String(row.interest),dueMonth(now,row.number-1),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;
const schedule=creditSchedule(BigInt(loan.principal_minor)-firstInstalment,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,accrual_at,accrual_remaining_minor) VALUES(?,?,?,?,?,'pending',?,?)",[loan.id,row.number,dueMonth(now,row.number),String(row.principal),String(row.interest),dueMonth(now,row.number-1),String(row.interest)]);
await tx.query("UPDATE pb_credit_loans SET state='active',outstanding_minor=principal_minor-first_instalment_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),firstInstalment:money(firstInstalment),remainingPrincipal:money(BigInt(loan.principal_minor)-firstInstalment),collateral:money(collateral)});await creditNotice(tx,loan,'disbursed','Credit disbursed','Your credit is active. Principal '+money(loan.principal_minor)+' DM; first instalment '+money(firstInstalment)+' DM already paid; remaining principal '+money(BigInt(loan.principal_minor)-firstInstalment)+' 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');

View file

@ -1,6 +1,6 @@
import {BankError} from './postbank-service.mjs';
import {minorAmount,money} from './postbank-catalogue.mjs';
export const CREDIT_VERSION='postbank-credit-2026-11-14';
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'},
@ -22,11 +22,13 @@ export function creditQuote({productKey,amount,months,monthly},{annualBps=null,p
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=BigInt(Math.ceil(Number(principal)*rate/(1-Math.pow(1+rate,-n))));
let remaining=principal,totalInterest=0n,total=0n;const schedule=[];
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),annualRate:(rateBps/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),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=[]}={}){

View file

@ -1,6 +1,6 @@
import {createHash} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
import {currentPayoff} from './postbank-credit-ledger.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';
@ -37,8 +37,8 @@ export class PostbankCredit{
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=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.'};
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.');
@ -52,7 +52,7 @@ export class PostbankCredit{
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)),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]);
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]);

View file

@ -20,7 +20,7 @@ export async function ensurePostbankIndexes(db){
}
// 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 const CREDIT_COLUMNS={first_instalment_minor:'BIGINT NOT NULL DEFAULT 0',accepted_by:'CHAR(36) NULL',queued_at:'BIGINT NULL',offer_expires_at:'BIGINT NULL',borrower_hold_minor:'BIGINT NOT NULL DEFAULT 0'};
export const INSTALMENT_COLUMNS={accrual_at:'BIGINT NULL',accrual_remaining_minor:'BIGINT NULL',accrued_interest_minor:'BIGINT NOT NULL DEFAULT 0'};
export async function ensureCreditColumns(db){
for(const [table,columns] of [['pb_credit_loans',CREDIT_COLUMNS],['pb_credit_instalments',INSTALMENT_COLUMNS]])for(const [column,type] of Object.entries(columns)){

View file

@ -22,34 +22,48 @@ export class PostbankPayrollCycle{
recipients:pending.map(row=>({name:row.actor_name,netMinor:String(row.slip.net)})),pendingCount:pending.length,paidCount:entries.filter(row=>row.state==='paid').length,
netMinor:sum('net'),taxMinor:sum('government'),employerCostMinor:sum('employerCost'),issuerBalanceMinor:issuer?String(issuer.balance_minor):null,issuerState:issuer?.state||'missing',policyVersion:policy.version,taxVersion:tax.version};
}
async previewAdditional(db=this.bank){
const {period}=payrollCalendar(this.clock()),policy=await readFinancialPolicy(db,'payroll'),tax=await readFinancialPolicy(db,'payroll_tax'),people=await readPayrollRecipients(this.central,this.clock());
const run=await db.first("SELECT period,state FROM pb_payroll_additional_runs WHERE calendar_period=? AND state IN ('prepared','running') ORDER BY created_at,period LIMIT 1",[period]);
const count=await db.first('SELECT COUNT(*) n FROM pb_payroll_additional_runs WHERE calendar_period=?',[period]);
const frozen=run?await db.query('SELECT i.actor_id,i.actor_name,i.state,p.details_json FROM pb_payroll_additional_items i JOIN pb_payroll_additional_payslips p ON p.period=i.period AND p.actor_id=i.actor_id WHERE i.period=? ORDER BY i.actor_id',[run.period]):[];
const entries=run&&run.state!=='prepared'?frozen.map(row=>({...row,slip:JSON.parse(row.details_json)})):people.map(person=>({actor_name:person.username,state:'pending',slip:payslipForNet(policy.value.netMinor[person.role_key],tax.value)}));
const pending=entries.filter(row=>row.state==='pending'),sum=key=>pending.reduce((total,row)=>total+BigInt(row.slip[key]),0n).toString();
const previewKey=createHash('sha256').update(JSON.stringify({mode:'additional',period,policy,tax,people,run,frozen,cycleCount:Number(count.n)})).digest('hex');
return {mode:'additional',period,cycleId:run?.period||null,previewKey,state:run?.state||'new_cycle',enabled:policy.value.enabled,canRun:policy.value.enabled&&(pending.length>0||!!run),recipients:pending.map(row=>({name:row.actor_name,netMinor:String(row.slip.net)})),pendingCount:pending.length,paidCount:entries.filter(row=>row.state==='paid').length,netMinor:sum('net'),taxMinor:sum('government'),employerCostMinor:sum('employerCost'),policyVersion:policy.version,taxVersion:tax.version};
}
async run(user,input,{revalidate=async()=>user}={}){
await this.access(user);
if(!input||Object.keys(input).some(k=>!['requestId','period','previewKey','reason','confirmed'].includes(k))||input.confirmed!==true||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||'')||!/^\d{4}-\d{2}$/.test(input.period||'')||! /^[a-f0-9]{64}$/.test(input.previewKey||'')||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.trim().length>200||/[\u0000-\u001f]/.test(input.reason))throw new BankError('Confirm the current wage cycle and provide a reason.');
const additional=input?.mode==='additional',action=additional?'payroll_additional_cycle_run':'payroll_cycle_run';
if(!input||Object.keys(input).some(k=>!['requestId','period','previewKey','reason','confirmed',...(additional?['mode']:[])].includes(k))||input.confirmed!==true||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||'')||!/^\d{4}-\d{2}$/.test(input.period||'')||! /^[a-f0-9]{64}$/.test(input.previewKey||'')||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.trim().length>200||/[\u0000-\u001f]/.test(input.reason))throw new BankError('Confirm the current wage cycle and provide a reason.');
const check=async()=>{const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.access(fresh);};
const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.period,input.previewKey,input.reason.trim()])).digest('hex');
const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.period,input.previewKey,input.reason.trim(),...(additional?['additional']:[])])).digest('hex');
const claim=await this.bank.transaction(async tx=>{
await tx.query("INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES('payroll_manual_guard','{}',0,?,?) ON DUPLICATE KEY UPDATE policy_key=VALUES(policy_key)",[user.id,this.clock()]);
await tx.first("SELECT policy_key FROM pb_financial_policies WHERE policy_key='payroll_manual_guard' FOR UPDATE");await check();
const prior=await tx.first('SELECT actor_id,action,details FROM pb_audit WHERE id=? FOR UPDATE',[input.requestId]);
if(prior){const details=JSON.parse(prior.details);if(prior.actor_id!==user.id||prior.action!=='payroll_cycle_run'||details.fingerprint!==fingerprint)throw new BankError('Request reference already used.',409);return {replayed:true,...(details.result||{period:input.period,inProgress:details.state==='started',state:details.state})};}
const preview=await this.preview(tx);
if(prior){const details=JSON.parse(prior.details);if(prior.actor_id!==user.id||prior.action!==action||details.fingerprint!==fingerprint)throw new BankError('Request reference already used.',409);return {replayed:true,...(details.result||{period:input.period,inProgress:details.state==='started',state:details.state})};}
const preview=additional?await this.previewAdditional(tx):await this.preview(tx);
if(preview.period!==input.period||preview.previewKey!==input.previewKey)throw new BankError('The wage cycle changed. Reload and confirm the current preview.',409);
if(!preview.canRun)throw new BankError('This wage cycle is disabled, completed or has no pending recipients.',409);
const details={fingerprint,period:input.period,reason:input.reason.trim(),state:'started',preview};
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[input.requestId,user.id,'payroll_cycle_run',JSON.stringify(details),this.clock()]);return {details};
let cycleId=null,executionPreviewKey=preview.previewKey;
if(additional){cycleId=preview.cycleId||input.requestId;if(!preview.cycleId)await tx.query("INSERT INTO pb_payroll_additional_runs(period,calendar_period,requested_by,index_value,wage_minor,state,created_at) VALUES(?,?,?,1,0,'prepared',?)",[cycleId,input.period,user.id,this.clock()]);executionPreviewKey=(await this.previewAdditional(tx)).previewKey;}
const details={fingerprint,period:input.period,reason:input.reason.trim(),state:'started',preview,cycleId,executionPreviewKey};
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[input.requestId,user.id,action,JSON.stringify(details),this.clock()]);return {details};
});
if(claim.replayed)return claim;
const finish=async(state,result)=>{await this.bank.query('UPDATE pb_audit SET details=? WHERE id=?',[JSON.stringify({...claim.details,state,result,finishedAt:this.clock()}),input.requestId]);};
try{
const result=await this.payroll.process({rollout:true,beforePrepare:async(tx,snapshot)=>{
const result=await this.payroll.process({rollout:true,additionalCycleId:claim.details.cycleId,beforePrepare:async(tx,snapshot)=>{
await check();
if((await this.preview(tx)).previewKey!==input.previewKey)throw new BankError('The wage cycle changed. Reload before retrying.',409);
if(snapshot.period!==input.period||snapshot.policyVersion!==claim.details.preview.policyVersion||snapshot.taxVersion!==claim.details.preview.taxVersion)throw new BankError('The wage policy changed. Reload before retrying.',409);
if((additional?await this.previewAdditional(tx):await this.preview(tx)).previewKey!==claim.details.executionPreviewKey)throw new BankError('The wage cycle changed. Reload before retrying.',409);
if(snapshot.period!==(claim.details.cycleId||input.period)||snapshot.policyVersion!==claim.details.preview.policyVersion||snapshot.taxVersion!==claim.details.preview.taxVersion)throw new BankError('The wage policy changed. Reload before retrying.',409);
// A scheduler run can finish between confirmation and execution; process()
// safely resumes pending items and never adds recipients to a frozen month.
},beforePay:check});
if(result.notDue)throw new BankError('Payroll was disabled before the cycle started.',409);
await finish(result.failed?'partial':'completed',result);return result;
const output=additional?{...result,period:input.period,cycleId:claim.details.cycleId,additional:true}:result;
await finish(result.failed?'partial':'completed',output);return output;
}catch(error){await finish('failed',{period:input.period,state:'failed'});throw error;}
}
}

View file

@ -31,38 +31,42 @@ export class PostbankPayroll{
const policy=await readFinancialPolicy(this.bank,'payroll'),tax=await readFinancialPolicy(this.bank,'payroll_tax'),recipients=await readPayrollRecipients(this.central,this.clock());
const ranks=Object.keys(PAYROLL_ROLE_WEIGHTS).map(role=>({role,...JSON.parse(serialise(payslipForNet(policy.value.netMinor[role],tax.value)))}));
const records=await this.bank.query('SELECT i.period,i.actor_name,i.amount_minor,i.state,a.account_number FROM pb_payroll_items i LEFT JOIN pb_accounts a ON a.id=i.account_id ORDER BY i.period DESC,i.actor_name LIMIT 100');
return {policy,taxVersion:tax.version,ranks,eligibleCount:recipients.length,records};
const extra=await this.bank.query('SELECT r.calendar_period AS period,i.period AS cycleId,i.actor_name,i.amount_minor,i.state,a.account_number FROM pb_payroll_additional_items i JOIN pb_payroll_additional_runs r ON r.period=i.period LEFT JOIN pb_accounts a ON a.id=i.account_id ORDER BY r.created_at DESC,i.actor_name LIMIT 100');
return {policy,taxVersion:tax.version,ranks,eligibleCount:recipients.length,records:[...extra.map(row=>({...row,additional:true})),...records].slice(0,100)};
}
async process({rollout=false,beforePrepare=async()=>{},beforePay=async()=>{}}={}){
const now=this.clock(),{period,day}=payrollCalendar(now),policy=await readFinancialPolicy(this.bank,'payroll');
async process({rollout=false,additionalCycleId=null,beforePrepare=async()=>{},beforePay=async()=>{}}={}){
const now=this.clock(),calendar=payrollCalendar(now),{day}=calendar,period=additionalCycleId||calendar.period,tables=additionalCycleId?{runs:'pb_payroll_additional_runs',items:'pb_payroll_additional_items',slips:'pb_payroll_additional_payslips'}:{runs:'pb_payroll_runs',items:'pb_payroll_items',slips:'pb_payroll_payslips'},policy=await readFinancialPolicy(this.bank,'payroll');
if(!policy.value.enabled||!rollout&&day<policy.value.payDay)return {paid:0,failed:0,notDue:true};
const tax=await readFinancialPolicy(this.bank,'payroll_tax'),recipients=await readPayrollRecipients(this.central,now);
if(additionalCycleId&&!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(additionalCycleId))throw Error('Invalid additional wage cycle.');
// Freeze the entire period before posting any salary. Every rank is paid once,
// independently of department count and subsequent policy changes.
await this.bank.transaction(async tx=>{
await beforePrepare(tx,{period,policyVersion:policy.version,taxVersion:tax.version});
await tx.query("INSERT INTO pb_payroll_runs(period,index_value,wage_minor,state,created_at) VALUES(?,1,0,'prepared',?) ON DUPLICATE KEY UPDATE period=period",[period,now]);
const run=await tx.first('SELECT state FROM pb_payroll_runs WHERE period=? FOR UPDATE',[period]);
if(!additionalCycleId)await tx.query("INSERT INTO pb_payroll_runs(period,index_value,wage_minor,state,created_at) VALUES(?,1,0,'prepared',?) ON DUPLICATE KEY UPDATE period=period",[period,now]);
const run=await tx.first(`SELECT state FROM ${tables.runs} WHERE period=? FOR UPDATE`,[period]);
if(!run)throw Error('Additional wage cycle was not confirmed.');
if(run.state!=='prepared')return;
for(const person of recipients){
const slip=payslipForNet(policy.value.netMinor[person.role_key],tax.value);
await tx.query("INSERT INTO pb_payroll_items(period,actor_id,actor_name,account_id,order_id,amount_minor,state,created_at) VALUES(?,?,?,NULL,NULL,?,'pending',?)",[period,person.id,person.username,String(slip.net),now]);
await tx.query('INSERT INTO pb_payroll_payslips(period,actor_id,details_json) VALUES(?,?,?)',[period,person.id,serialise({recipient:person,role:person.role_key,policyVersion:policy.version,taxVersion:tax.version,tax:tax.value,...slip})]);
await tx.query(`INSERT INTO ${tables.items}(period,actor_id,actor_name,account_id,order_id,amount_minor,state,created_at) VALUES(?,?,?,NULL,NULL,?,'pending',?)`,[period,person.id,person.username,String(slip.net),now]);
await tx.query(`INSERT INTO ${tables.slips}(period,actor_id,details_json) VALUES(?,?,?)`,[period,person.id,serialise({recipient:person,role:person.role_key,policyVersion:policy.version,taxVersion:tax.version,tax:tax.value,...slip})]);
}
await tx.query("UPDATE pb_payroll_runs SET state='running' WHERE period=?",[period]);
await tx.query(`UPDATE ${tables.runs} SET state='running' WHERE period=?`,[period]);
});
const items=await this.bank.query("SELECT actor_id FROM pb_payroll_items WHERE period=? AND state='pending' ORDER BY actor_id",[period]);
const items=await this.bank.query(`SELECT actor_id FROM ${tables.items} WHERE period=? AND state='pending' ORDER BY actor_id`,[period]);
let paid=0,failed=0;
for(const item of items){try{if(await this.pay(period,item.actor_id,{beforePay}))paid++;}catch{failed++;}}
if(!failed)await this.bank.query("UPDATE pb_payroll_runs SET state='completed' WHERE period=? AND NOT EXISTS (SELECT 1 FROM pb_payroll_items WHERE period=? AND state='pending')",[period,period]);
for(const item of items){try{if(await this.pay(period,item.actor_id,{beforePay,additional:!!additionalCycleId}))paid++;}catch{failed++;}}
if(!failed)await this.bank.query(`UPDATE ${tables.runs} SET state='completed' WHERE period=? AND NOT EXISTS (SELECT 1 FROM ${tables.items} WHERE period=? AND state='pending')`,[period,period]);
return {period,paid,failed};
}
async pay(period,actorId,{beforePay=async()=>{}}={}){
async pay(period,actorId,{additional=false,beforePay=async()=>{}}={}){
const tables=additional?{items:'pb_payroll_additional_items',slips:'pb_payroll_additional_payslips'}:{items:'pb_payroll_items',slips:'pb_payroll_payslips'};
return this.bank.transaction(async tx=>{
const item=await tx.first('SELECT * FROM pb_payroll_items WHERE period=? AND actor_id=? FOR UPDATE',[period,actorId]);
const item=await tx.first(`SELECT * FROM ${tables.items} WHERE period=? AND actor_id=? FOR UPDATE`,[period,actorId]);
if(!item||item.state!=='pending')return false;
await beforePay();
const row=await tx.first('SELECT details_json FROM pb_payroll_payslips WHERE period=? AND actor_id=?',[period,actorId]),slip=JSON.parse(row.details_json);
const row=await tx.first(`SELECT details_json FROM ${tables.slips} WHERE period=? AND actor_id=?`,[period,actorId]),slip=JSON.parse(row.details_json);
// Revocation stops an unpaid salary; a frozen record alone never grants eligibility.
const eligible=await readPayrollRecipients(this.central,this.clock());
if(!eligible.some(p=>p.id===actorId&&PAYROLL_ROLE_WEIGHTS[p.role_key]>=PAYROLL_ROLE_WEIGHTS[slip.role]&&p.minecraft_uuid.toLowerCase()===slip.recipient.minecraft_uuid.toLowerCase()))throw Error('Payroll recipient requires review.');
@ -73,13 +77,13 @@ export class PostbankPayroll{
const move=async(from,to,amount,leg)=>{
amount=BigInt(amount);if(!amount)return;
const id=stableId(period+':'+actorId+':'+leg),fingerprint=createHash('sha256').update(serialise([period,actorId,leg,String(amount)])).digest('hex');
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'payroll','queued',?)",[id,REGISTRY_ACTOR,from.id,to.id,fingerprint,String(amount),'P&O '+period+' · '+leg,this.clock()]);
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'payroll','queued',?)",[id,REGISTRY_ACTOR,from.id,to.id,fingerprint,String(amount),'P&O '+(additional?'additional '+period:period)+' · '+leg,this.clock()]);
await postPayrollIssue(tx,{id,actor_id:REGISTRY_ACTOR,amount_minor:String(amount)},from,to,{now:this.clock()});
from.balance_minor=String(BigInt(from.balance_minor)-amount);to.balance_minor=String(BigInt(to.balance_minor)+amount);return id;
};
const orderId=await move(po,target,slip.net,'net salary');
await move(po,tax,slip.government,'social and income tax');
await tx.query("UPDATE pb_payroll_items SET state='paid',account_id=?,order_id=? WHERE period=? AND actor_id=?",[destination.accountId,orderId,period,actorId]);return true;
await tx.query(`UPDATE ${tables.items} SET state='paid',account_id=?,order_id=? WHERE period=? AND actor_id=?`,[destination.accountId,orderId,period,actorId]);return true;
});
}
}

View file

@ -96,7 +96,7 @@ CREATE TABLE IF NOT EXISTS pb_credit_loans (
account_id BIGINT UNSIGNED NOT NULL, collateral_account_id BIGINT UNSIGNED NULL,
product_key VARCHAR(40) NOT NULL, state VARCHAR(32) NOT NULL, principal_minor BIGINT NOT NULL,
outstanding_minor BIGINT NOT NULL DEFAULT 0, monthly_minor BIGINT NOT NULL,
annual_bps INT NOT NULL, months INT NOT NULL, collateral_minor BIGINT NOT NULL DEFAULT 0,
annual_bps INT NOT NULL, months INT NOT NULL, collateral_minor BIGINT NOT NULL DEFAULT 0, first_instalment_minor BIGINT NOT NULL DEFAULT 0,
treasury_hold_minor BIGINT NOT NULL DEFAULT 0, created_by CHAR(36) NOT NULL,
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,
@ -203,3 +203,18 @@ CREATE TABLE IF NOT EXISTS pb_payroll_payslips (
period CHAR(7) NOT NULL, actor_id CHAR(36) NOT NULL, details_json TEXT NOT NULL,
PRIMARY KEY(period,actor_id), FOREIGN KEY(period) REFERENCES pb_payroll_runs(period)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS pb_payroll_additional_runs (
period CHAR(36) PRIMARY KEY, calendar_period CHAR(7) NOT NULL,
requested_by CHAR(36) NOT NULL, index_value INT NOT NULL, wage_minor BIGINT NOT NULL,
state VARCHAR(16) NOT NULL, created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS pb_payroll_additional_items (
period CHAR(36) NOT NULL, actor_id CHAR(36) NOT NULL, actor_name VARCHAR(80) NOT NULL,
account_id BIGINT UNSIGNED NULL, order_id CHAR(36) NULL, amount_minor BIGINT NOT NULL,
state VARCHAR(24) NOT NULL, created_at BIGINT NOT NULL,
PRIMARY KEY(period,actor_id), FOREIGN KEY(period) REFERENCES pb_payroll_additional_runs(period)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS pb_payroll_additional_payslips (
period CHAR(36) NOT NULL, actor_id CHAR(36) NOT NULL, details_json TEXT NOT NULL,
PRIMARY KEY(period,actor_id), FOREIGN KEY(period) REFERENCES pb_payroll_additional_runs(period)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;