diff --git a/website/node/postbank-api.mjs b/website/node/postbank-api.mjs index 0dc6c0a3..48b29fce 100644 --- a/website/node/postbank-api.mjs +++ b/website/node/postbank-api.mjs @@ -1,6 +1,7 @@ import {canInspectAllBankAccounts} from './postbank-recipient-policy.mjs'; import {randomUUID} from 'node:crypto'; import {PostbankPayroll} from './postbank-payroll.mjs'; +import {PostbankPayrollCycle} from './postbank-payroll-cycle.mjs'; import {PostbankFinancialPolicies} from './postbank-financial-policy.mjs'; import {PostbankRatePublications} from './postbank-rate-publications.mjs'; import {PostbankClientManagement} from './postbank-client-management.mjs'; @@ -31,6 +32,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){ const creditEnabled=settings.POSTBANK_CREDIT_ENABLED==='true',creditEngine=bank?new PostbankCreditEngine(bank,central,authority,deps):null; const scheduler=bank?new CentralScheduler(bank,deps.scheduledTasks||createPostbankTasks(central,bank,settings,deps),deps):null; const payroll=bank?new PostbankPayroll(central,bank,deps):null,financialPolicies=bank?new PostbankFinancialPolicies(bank,central,authority,deps):null; + const payrollCycle=bank?new PostbankPayrollCycle(central,bank,deps):null; const creditSupport=bank?new PostbankCreditSupport(bank,central,deps):null; const transferSecurity=bank?new PostbankTransferSecurity(bank,central,deps):null; const admin=bank?new PostbankAdmin(bank,central,authority,deps):null; @@ -128,16 +130,17 @@ export function createPostbankApi(central,bank,settings={},deps={}){ if(request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);if(url.search)return reply({message:'Account overrides are not accepted.'},400);const raw=await request.text();if(raw.length>3000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the authorisation form.'},400);}return reply(await authorisations.write(user,input,staff,{revalidate:()=>auth(request)})); }catch(error){return reply({message:error.status?error.message:'The authorisation change could not be confirmed.'},error.status||503);} } - if(path==='/api/bank/admin/payroll'){ + if(['/api/bank/admin/payroll','/api/bank/admin/payroll/run'].includes(path)){ 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'){const result=await payroll.overview();if(!await canRunScheduler(central,await auth(request)))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()},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); const raw=await request.text();if(raw.length>4000)return reply({message:'Request too large.'},413); let input;try{input=JSON.parse(raw);}catch{return reply({message:'Complete the payroll settings.'},400);} + if(path.endsWith('/run'))return reply(await payrollCycle.run(fresh,input,{revalidate:()=>auth(request)})); return reply(await financialPolicies.save(fresh,'payroll',input,{revalidate:()=>auth(request)})); }catch(error){return reply({message:error.status?error.message:'Payroll could not be confirmed. Reload before retrying.'},error.status||503);} } diff --git a/website/node/postbank-payroll-cycle.mjs b/website/node/postbank-payroll-cycle.mjs new file mode 100644 index 00000000..90fe1c60 --- /dev/null +++ b/website/node/postbank-payroll-cycle.mjs @@ -0,0 +1,55 @@ +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 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 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 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(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}; + }); + 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)=>{ + 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); + // 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; + }catch(error){await finish('failed',{period:input.period,state:'failed'});throw error;} + } +} diff --git a/website/node/postbank-payroll.mjs b/website/node/postbank-payroll.mjs index 13c93d39..12765bb1 100644 --- a/website/node/postbank-payroll.mjs +++ b/website/node/postbank-payroll.mjs @@ -33,13 +33,14 @@ export class PostbankPayroll{ 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}; } - async process({rollout=false}={}){ + async process({rollout=false,beforePrepare=async()=>{},beforePay=async()=>{}}={}){ const now=this.clock(),{period,day}=payrollCalendar(now),policy=await readFinancialPolicy(this.bank,'payroll'); if(!policy.value.enabled||!rollout&&day{ + 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(run.state!=='prepared')return; @@ -52,7 +53,7 @@ export class PostbankPayroll{ }); const items=await this.bank.query("SELECT actor_id FROM pb_payroll_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))paid++;}catch{failed++;}} + for(const item of items){try{await beforePay();if(await this.pay(period,item.actor_id))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]); return {period,paid,failed}; } diff --git a/website/tests/postbank-payroll-cycle.test.mjs b/website/tests/postbank-payroll-cycle.test.mjs new file mode 100644 index 00000000..e54f15f1 --- /dev/null +++ b/website/tests/postbank-payroll-cycle.test.mjs @@ -0,0 +1,89 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs'; +import {PostbankPayrollCycle} from '../node/postbank-payroll-cycle.mjs'; +import {PostbankPayroll} from '../node/postbank-payroll.mjs'; +import {createPostbankApi} from '../node/postbank-api.mjs'; +import {DEFAULT_PAYROLL_POLICY} from '../node/postbank-payroll-model.mjs'; + +async function fixture(){ + const bank=new BankFixture(),user={id:randomUUID(),username:'Payroll QA'},person={id:randomUUID(),username:'Officer QA',role:'user',minecraft_uuid:randomUUID(),scope_type:'branch',scope_key:'customer_support',role_key:'officer',game_link_exempt:0}; + const state={principal:'owner',user,people:[person],now:Date.parse('2026-11-15T12:00:00Z')}; + const central={prepare(sql){return {bind(){return this;},async first(){return sql.includes('org_control_principals')?{principal_kind:state.principal}:null;},async all(){return {results:[]};}};},readSnapshot:async fn=>fn({query:async()=>state.people})}; + const deps={clock:()=>state.now,authenticate:async()=>state.user,authority:async()=>({entities:[],readAdmin:true,manageAdmin:true})}; + await bank.query('INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES(?,?,1,?,0)',['payroll',JSON.stringify({...DEFAULT_PAYROLL_POLICY,enabled:true}),user.id]); + for(const key of ['sys_payroll_po','sys_tax_treasury'])await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,'979',?,0,0,'active',0)",[key,key]); + const cycle=new PostbankPayrollCycle(central,bank,deps),payroll=new PostbankPayroll(central,bank,deps),api=createPostbankApi(central,bank,{},deps); + const payload=async()=>{const preview=await cycle.preview();return {requestId:randomUUID(),period:preview.period,previewKey:preview.previewKey,reason:'Confirmed manual monthly wages',confirmed:true};}; + const send=(body,{method='POST',origin='https://cp.dunerealms.com',type='application/json',query=''}={})=>api(new Request('https://cp.dunerealms.com/api/bank/admin/payroll/run'+query,{method,headers:{origin,'Content-Type':type},...(['GET','HEAD'].includes(method)?{}:{body:typeof body==='string'?body:JSON.stringify(body)})})); + return {bank,user,state,cycle,payroll,payload,send}; +} + +test('manual current-month cycle previews exact amounts and posts through the existing issuer before payday',async()=>{ + const f=await fixture();try{ + const preview=await f.cycle.preview();assert.equal(preview.pendingCount,1);assert.equal(preview.netMinor,'280000');assert.equal(preview.employerCostMinor,'582344');assert.equal(preview.issuerBalanceMinor,'0'); + assert.equal((await f.payroll.process()).notDue,true); + const input=await f.payload(),result=await f.cycle.run(f.user,input);assert.equal(result.paid,1);assert.equal(result.period,'2026-11'); + const audit=await f.bank.first('SELECT actor_id,action,details FROM pb_audit WHERE id=?',[input.requestId]),details=JSON.parse(audit.details); + assert.equal(audit.actor_id,f.user.id);assert.equal(audit.action,'payroll_cycle_run');assert.equal(details.reason,input.reason);assert.equal(details.state,'completed');assert.equal(details.result.paid,1); + assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,2); + assert.equal((await f.bank.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0); + assert.equal((await f.cycle.preview()).canRun,false); + }finally{f.bank.close();} +}); + +test('duplicate requests replay the recorded result; a reused reference with changed intent conflicts',async()=>{ + const f=await fixture();try{const input=await f.payload();await f.cycle.run(f.user,input);assert.equal((await f.cycle.run(f.user,input)).replayed,true);await assert.rejects(f.cycle.run(f.user,{...input,reason:'Different instruction'}),e=>e.status===409);assert.equal((await f.bank.first("SELECT COUNT(*) n FROM pb_audit WHERE action='payroll_cycle_run'")).n,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,2);}finally{f.bank.close();} +}); + +test('concurrent manual submissions cannot duplicate a salary and record intent before issuing it',async()=>{ + const f=await fixture();try{ + const input=await f.payload(),original=f.cycle.payroll.pay.bind(f.cycle.payroll);f.cycle.payroll.pay=async(...args)=>{assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_audit WHERE id=?',[input.requestId])).n,1);return original(...args);}; + const results=await Promise.all([f.cycle.run(f.user,input),f.cycle.run(f.user,input)]);assert(results.some(r=>r.replayed));assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,2); + assert.equal((await f.payroll.process({rollout:true})).paid,0); + }finally{f.bank.close();} +}); + +test('a scheduler racing the manual cycle still pays each frozen recipient once',async()=>{ + const f=await fixture();try{const input=await f.payload();await Promise.allSettled([f.cycle.run(f.user,input),f.payroll.process({rollout:true})]);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,2);assert.equal((await f.bank.first("SELECT COUNT(*) n FROM pb_payroll_items WHERE state='paid'")).n,1);}finally{f.bank.close();} +}); + +test('stale amounts, recipients and calendar periods require a new confirmation',async()=>{ + const f=await fixture();try{ + const input=await f.payload();f.state.people=[];await assert.rejects(f.cycle.run(f.user,input),e=>e.status===409);f.state.people=[{id:randomUUID(),username:'New staff',role:'user',minecraft_uuid:randomUUID(),scope_type:'branch',scope_key:'customer_support',role_key:'officer'}]; + const next=await f.payload();await f.bank.query("UPDATE pb_financial_policies SET version=2 WHERE policy_key='payroll'");await assert.rejects(f.cycle.run(f.user,next),e=>e.status===409); + const month=await f.payload();f.state.now=Date.parse('2026-12-01T12:00:00Z');await assert.rejects(f.cycle.run(f.user,month),e=>e.status===409);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0); + }finally{f.bank.close();} +}); + +test('authorization and confirmation are checked again before payments',async()=>{ + const f=await fixture();try{ + const input=await f.payload();await assert.rejects(f.cycle.run(f.user,{...input,confirmed:false}),e=>e.status===400); + await assert.rejects(f.cycle.run(f.user,input,{revalidate:async()=>({id:randomUUID()})}),e=>e.status===403); + f.state.principal='department_head';await assert.rejects(f.cycle.run(f.user,input),e=>e.status===403);f.state.principal='owner'; + let checks=0;await assert.rejects(f.cycle.run(f.user,input,{revalidate:async()=>{if(++checks===2)f.state.principal='department_head';return f.user;}}),e=>e.status===403); + const audit=await f.bank.first('SELECT details FROM pb_audit WHERE id=?',[input.requestId]);assert.equal(JSON.parse(audit.details).state,'failed');assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0); + }finally{f.bank.close();} +}); + +test('failed payroll items can resume with a fresh confirmation without repaying successful items',async()=>{ + const f=await fixture();try{ + await f.bank.query("UPDATE pb_accounts SET state='blocked' WHERE system_key='sys_tax_treasury'");assert.equal((await f.cycle.run(f.user,await f.payload())).failed,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0); + await f.bank.query("UPDATE pb_accounts SET state='active' WHERE system_key='sys_tax_treasury'");assert.equal((await f.cycle.run(f.user,await f.payload())).paid,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,2); + }finally{f.bank.close();} +}); + +test('run endpoint enforces method, origin, JSON, size, strict fields and fresh authority',async()=>{ + const f=await fixture();try{ + const input=await f.payload();assert.equal((await f.send(input,{method:'GET'})).status,405);assert.equal((await f.send(input,{origin:'https://evil.invalid'})).status,403);assert.equal((await f.send(input,{type:'text/plain'})).status,415);assert.equal((await f.send('x'.repeat(4001))).status,413);assert.equal((await f.send('{')).status,400);assert.equal((await f.send({...input,rollout:true})).status,400);assert.equal((await f.send(input,{query:'?period=2027-01'})).status,400); + f.state.principal='department_head';assert.equal((await f.send(input)).status,403);f.state.principal='owner';assert.equal((await f.send(input)).status,200);assert.equal((await f.send(input)).status,200);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,2); + }finally{f.bank.close();} +}); + +test('disabled and empty wage cycles cannot be forced manually',async()=>{ + const f=await fixture();try{ + f.state.people=[];await assert.rejects(f.cycle.run(f.user,await f.payload()),e=>e.status===409); + await f.bank.query("UPDATE pb_financial_policies SET policy_json=? WHERE policy_key='payroll'",[JSON.stringify(DEFAULT_PAYROLL_POLICY)]);await assert.rejects(f.cycle.run(f.user,await f.payload()),e=>e.status===409);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0); + }finally{f.bank.close();} +});