web/website/node/postbank-payroll-cycle.mjs

69 lines
8.7 KiB
JavaScript

import {createHash} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
import {canRunScheduler} from './scheduler-authority.mjs';
import {readFinancialPolicy} from './postbank-financial-policy.mjs';
import {PostbankPayroll,payrollCalendar,readPayrollRecipients} from './postbank-payroll.mjs';
import {payslipForNet} from './postbank-payroll-model.mjs';
// Manual execution uses the same period freeze, item locks and stable payment
// references as the scheduler. Audit is committed before any payment can start.
export class PostbankPayrollCycle{
constructor(central,bank,{clock=Date.now}={}){this.central=central;this.bank=bank;this.clock=clock;this.payroll=new PostbankPayroll(central,bank,{clock});}
async access(user){if(!await canRunScheduler(this.central,user))throw new BankError('P&O wage cycles are reserved for the Big Four.',403);}
async preview(db=this.bank){
const {period}=payrollCalendar(this.clock()),policy=await readFinancialPolicy(db,'payroll'),tax=await readFinancialPolicy(db,'payroll_tax');
const people=await readPayrollRecipients(this.central,this.clock()),run=await db.first('SELECT state FROM pb_payroll_runs WHERE period=?',[period]);
const frozen=await db.query('SELECT i.actor_id,i.actor_name,i.state,p.details_json FROM pb_payroll_items i JOIN pb_payroll_payslips p ON p.period=i.period AND p.actor_id=i.actor_id WHERE i.period=? ORDER BY i.actor_id',[period]);
const entries=run?frozen.map(row=>({...row,slip:JSON.parse(row.details_json)})):people.map(person=>({actor_id:person.id,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 issuer=await db.first("SELECT balance_minor,state FROM pb_accounts WHERE system_key='sys_payroll_po'");
const previewKey=createHash('sha256').update(JSON.stringify({period,policy,tax,people,run,frozen})).digest('hex');
return {period,previewKey,state:run?.state||'not_started',enabled:policy.value.enabled,canRun:policy.value.enabled&&run?.state!=='completed'&&pending.length>0,
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);
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(),...(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!==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);
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,additionalCycleId:claim.details.cycleId,beforePrepare:async(tx,snapshot)=>{
await check();
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);
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;}
}
}