forked from unimatrix/web
Add confirmed Run Wage Cycle controls to P&O
This commit is contained in:
parent
4e4d851e21
commit
3ba10fb9a6
5 changed files with 102 additions and 2 deletions
|
|
@ -4,6 +4,16 @@ const money=value=>(Number(value)/100).toFixed(2);
|
|||
export async function renderPayroll(host,{api,isActive=()=>true}={}){
|
||||
const data=await api.request('/api/bank/admin/payroll');if(!isActive())return;
|
||||
host.replaceChildren(el('h2','People & Organisation'),el('p','One monthly salary per person, using the highest active rank. Missing personal current accounts receive free Start banking.'));
|
||||
const cycle=data.cycle,cyclePanel=el('section',undefined,'pb-payroll-cycle'),cycleStatus=el('p'),run=el('button','Run Wage Cycle');
|
||||
cycleStatus.setAttribute('role','status');run.type='button';run.disabled=!cycle?.canRun;
|
||||
cyclePanel.append(el('h3','Manual wage cycle'));
|
||||
if(cycle){
|
||||
cyclePanel.append(el('p',cycle.period+' · '+cycle.state.replaceAll('_',' ')+' · '+cycle.paidCount+' paid · '+cycle.pendingCount+' pending'),el('p','Pending net wages: '+money(cycle.netMinor)+' DM · Tax and social contributions: '+money(cycle.taxMinor)+' DM · Total P&O issue: '+money(cycle.employerCostMinor)+' DM.'),el('p','P&O issuer balance: '+(cycle.issuerBalanceMinor===null?'Unavailable':money(cycle.issuerBalanceMinor)+' DM')+'. P&O issues wages using the existing payroll mechanism; the bank treasury is not charged.','pb-muted'));
|
||||
if(!cycle.enabled)cyclePanel.append(el('p','Enable and save payroll settings before running a wage cycle.'));
|
||||
else if(cycle.state==='completed')cyclePanel.append(el('p','This month’s wage cycle is complete. It cannot be paid again.'));
|
||||
else if(!cycle.pendingCount)cyclePanel.append(el('p','No staff are awaiting payment in this cycle.'));
|
||||
}
|
||||
cyclePanel.append(run,cycleStatus);host.append(cyclePanel);
|
||||
const form=el('form',undefined,'pb-transfer-form pb-payroll-form'),enabled=el('input'),day=el('input'),reason=el('input'),status=el('p'),save=el('button','Save payroll settings');
|
||||
enabled.type='checkbox';enabled.checked=data.policy.value.enabled;
|
||||
day.type='number';day.min='1';day.max='28';day.step='1';day.required=true;day.value=data.policy.value.payDay;
|
||||
|
|
@ -15,6 +25,28 @@ export async function renderPayroll(host,{api,isActive=()=>true}={}){
|
|||
for(const rank of data.ranks){const row=el('tr'),input=el('input');input.type='number';input.min='1';input.max='1000000';input.step='0.01';input.required=true;input.value=money(rank.net);input.setAttribute('aria-label',labels[rank.role]+' net salary in DM');inputs.set(rank.role,input);const edit=el('td');edit.append(input);row.append(el('th',labels[rank.role]),edit);for(const key of ['gross','employeeSocial','incomeTax','employerSocial','employerCost'])row.append(el('td',money(rank[key])));body.append(row);}
|
||||
table.append(head,body);wrap.append(table);form.append(wrap,el('p',data.eligibleCount+' eligible staff · Figures use the current payroll tax model. Save to recalculate edited net wages.','pb-muted'),field('Reason for this change',reason),save,status);host.append(form);
|
||||
save.type='submit';let busy=false;
|
||||
run.onclick=()=>{
|
||||
if(busy||run.disabled||!isActive())return;run.disabled=true;
|
||||
const confirmation=el('form',undefined,'pb-transfer-form'),reason=el('input'),accepted=el('input'),submit=el('button','Confirm wage payment'),cancel=el('button','Cancel');
|
||||
reason.required=true;reason.minLength=5;reason.maxLength=200;accepted.type='checkbox';accepted.required=true;submit.type='submit';cancel.type='button';
|
||||
const recipients=el('ul');for(const person of cycle.recipients)recipients.append(el('li',person.name+' · '+money(person.netMinor)+' DM'));
|
||||
confirmation.append(el('h4','Confirm wage cycle · '+cycle.period),el('p','This pays the current month using saved payroll settings, even before the scheduled payment day. Each person can be paid once per month. Failed items remain pending for review and retry.'),recipients,field('Reason for running this cycle',reason),field('I confirm payment of '+money(cycle.netMinor)+' DM net wages and '+money(cycle.taxMinor)+' DM contributions for '+cycle.pendingCount+' staff.',accepted),submit,cancel);
|
||||
cyclePanel.append(confirmation);reason.focus();
|
||||
cancel.onclick=()=>{if(busy)return;confirmation.remove();run.disabled=false;run.focus();};
|
||||
confirmation.onsubmit=async event=>{
|
||||
event.preventDefault();if(busy||!isActive()||!confirmation.reportValidity()||!accepted.checked||reason.value.trim().length<5)return;
|
||||
busy=true;submit.disabled=true;cancel.disabled=true;save.disabled=true;reason.disabled=true;accepted.disabled=true;cycleStatus.textContent='Running the confirmed wage cycle…';
|
||||
const input={requestId:crypto.randomUUID(),period:cycle.period,previewKey:cycle.previewKey,reason:reason.value.trim(),confirmed:true};
|
||||
try{
|
||||
const result=await api.request('/api/bank/admin/payroll/run',input);if(!isActive())return;
|
||||
const message=result.inProgress?'This request is already in progress. Reload wage status before trying again.':result.state==='failed'?'The previous request failed. Reload wage status and review pending items.':result.paid+' salaries paid · '+result.failed+' failed. '+(result.failed?'Review and confirm the remaining pending salaries to retry.':'This month’s recorded salaries cannot be paid again.');
|
||||
await renderPayroll(host,{api,isActive});if(!isActive())return;const notice=el('p',message,'pb-message');notice.setAttribute('role','status');host.prepend(notice);
|
||||
}catch(error){
|
||||
if(!isActive())return;cycleStatus.textContent=error.message+' Reload wage status to check recorded payments before retrying.';submit.textContent='Reload before retrying';
|
||||
const reload=el('button','Reload wage status');reload.type='button';reload.onclick=async()=>{reload.disabled=true;try{await renderPayroll(host,{api,isActive});}catch(e){cycleStatus.textContent=e.message;reload.disabled=false;}};cyclePanel.append(reload);
|
||||
}
|
||||
};
|
||||
};
|
||||
form.onsubmit=async event=>{event.preventDefault();if(busy||!form.reportValidity())return;busy=true;save.disabled=true;
|
||||
const value={enabled:enabled.checked,payDay:Number(day.value),netMinor:Object.fromEntries([...inputs].map(([role,input])=>[role,Math.round(Number(input.value)*100)]))};
|
||||
try{await api.request('/api/bank/admin/payroll',{requestId:crypto.randomUUID(),version:data.policy.version,value,reason:reason.value.trim(),confirmed:true});if(isActive())await renderPayroll(host,{api,isActive});}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,22 @@ excluded. The default schedule is the 28th in Europe/Brussels and is disabled
|
|||
until rollout. Big Four control identities manage settings in the bank dashboard's
|
||||
P&O Payroll tab.
|
||||
|
||||
The P&O page also provides **Run Wage Cycle** for authorized Big Four identities.
|
||||
It previews the Brussels calendar month, pending staff, exact net/contribution
|
||||
totals and P&O issuer balance. An explicit confirmation and reason are required.
|
||||
It uses saved, enabled payroll settings and may pay before the scheduled day;
|
||||
it cannot select another month or pay a completed month again. P&O is the issuer,
|
||||
so a negative issuer balance does not impose a bank-treasury funding requirement.
|
||||
|
||||
`POST /api/bank/admin/payroll/run` accepts only `requestId`, `period`,
|
||||
`previewKey`, `reason` and `confirmed`. Preview changes require a fresh review.
|
||||
The existing monthly freeze, recipient checks, payment references and item locks
|
||||
protect manual/scheduler concurrency. A durable `payroll_cycle_run` audit saves
|
||||
the actor, reason and reviewed totals before issuing wages, then records the
|
||||
result. Repeating the same request returns its recorded outcome or in-progress
|
||||
status. Failed items can be resumed after reloading and confirming; paid items
|
||||
are never repaid. If a response is uncertain, reload the recorded status first.
|
||||
|
||||
Payroll reuses an active personal current account (102 or 108). If absent, the
|
||||
payroll transaction creates a free personal Start package and current account
|
||||
**108**, with zero opening funds. This does not create a staff/Public 979 account
|
||||
|
|
|
|||
|
|
@ -53,14 +53,15 @@ 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{await beforePay();if(await this.pay(period,item.actor_id))paid++;}catch{failed++;}}
|
||||
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]);
|
||||
return {period,paid,failed};
|
||||
}
|
||||
async pay(period,actorId){
|
||||
async pay(period,actorId,{beforePay=async()=>{}}={}){
|
||||
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]);
|
||||
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);
|
||||
// Revocation stops an unpaid salary; a frozen record alone never grants eligibility.
|
||||
const eligible=await readPayrollRecipients(this.central,this.clock());
|
||||
|
|
|
|||
|
|
@ -87,3 +87,17 @@ test('disabled and empty wage cycles cannot be forced manually',async()=>{
|
|||
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();}
|
||||
});
|
||||
|
||||
test('an audit write failure stops the cycle before any salary or monthly freeze',async()=>{
|
||||
const f=await fixture();try{
|
||||
f.bank.sqlite.exec("CREATE TRIGGER fail_cycle_audit BEFORE INSERT ON pb_audit WHEN NEW.action='payroll_cycle_run' BEGIN SELECT RAISE(ABORT,'audit unavailable'); END;");
|
||||
await assert.rejects(f.cycle.run(f.user,await f.payload()),/audit unavailable/);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_payroll_runs')).n,0);
|
||||
}finally{f.bank.close();}
|
||||
});
|
||||
|
||||
test('payment authorization is checked inside the salary transaction after its item lock',async()=>{
|
||||
const f=await fixture();try{
|
||||
const original=f.cycle.payroll.pay.bind(f.cycle.payroll);f.cycle.payroll.pay=async(...args)=>{f.state.principal='department_head';return original(...args);};
|
||||
const result=await f.cycle.run(f.user,await f.payload());assert.equal(result.paid,0);assert.equal(result.failed,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.bank.first("SELECT COUNT(*) n FROM pb_payroll_items WHERE state='pending'")).n,1);
|
||||
}finally{f.bank.close();}
|
||||
});
|
||||
|
|
|
|||
37
website/tests/postbank-payroll-ui.test.mjs
Normal file
37
website/tests/postbank-payroll-ui.test.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {renderPayroll} from '../control-panel/public/cp-v2/cp-v2-postbank-payroll.mjs';
|
||||
class Node{
|
||||
constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.attrs={};this._text='';this.value='';this.checked=false;this.disabled=false;}
|
||||
set textContent(value){this._text=String(value);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}
|
||||
append(...nodes){for(const node of nodes){node.parent=this;this.children.push(node);}}prepend(...nodes){for(const node of nodes)node.parent=this;this.children.unshift(...nodes);}
|
||||
replaceChildren(...nodes){this._text='';this.children=[];this.append(...nodes);}setAttribute(key,value){this.attrs[key]=String(value);}focus(){}reportValidity(){return true;}
|
||||
remove(){this.parent.children=this.parent.children.filter(n=>n!==this);}
|
||||
}
|
||||
const all=node=>node.children.flatMap(child=>[child,...all(child)]);
|
||||
async function fixture(work,{canRun=true,enabled=true,state='not_started',post=async()=>({paid:1,failed:0}),active=()=>true}={}){
|
||||
const previous=globalThis.document;globalThis.document={createElement:tag=>new Node(tag)};
|
||||
const host=new Node('main'),calls=[],data={policy:{version:1,value:{enabled:true,payDay:28}},ranks:[],eligibleCount:1,records:[],cycle:{period:'2026-11',previewKey:'a'.repeat(64),state,enabled,canRun,pendingCount:1,paidCount:0,netMinor:'280000',taxMinor:'302344',employerCostMinor:'582344',issuerBalanceMinor:'-582344',recipients:[{name:'Officer <QA>',netMinor:'280000'}]}};
|
||||
const api={request:async(path,input)=>{calls.push({path,input});return input?post(input):data;}};
|
||||
const nodes=()=>all(host),button=label=>nodes().find(n=>n.tagName==='BUTTON'&&n.textContent===label);
|
||||
try{await renderPayroll(host,{api,isActive:active});await work({host,calls,nodes,button});}finally{globalThis.document=previous;}
|
||||
}
|
||||
const event={preventDefault(){}};
|
||||
function confirm(nodes){const form=nodes.find(n=>n.tagName==='FORM'&&n.textContent.includes('Confirm wage cycle'));const controls=all(form);controls.find(n=>n.tagName==='INPUT'&&n.type!=='checkbox').value='Run confirmed monthly wages';controls.find(n=>n.type==='checkbox').checked=true;return form;}
|
||||
|
||||
test('P&O exposes Run Wage Cycle and pending totals even when there are no payroll records',()=>fixture(async({host,button,calls})=>{assert(button('Run Wage Cycle'));assert(host.textContent.includes('2800.00 DM'));assert(host.textContent.includes('5823.44 DM'));assert(host.textContent.includes('No payroll has been posted yet.'));assert.equal(calls.length,1);}));
|
||||
test('opening and cancelling confirmation does not post wages',()=>fixture(async({button,host,calls})=>{button('Run Wage Cycle').onclick();assert(host.textContent.includes('Officer <QA>'));button('Cancel').onclick();assert.equal(button('Run Wage Cycle').disabled,false);assert.equal(calls.length,1);}));
|
||||
test('confirmation requires an explicit checkbox and reason, then sends the reviewed period and preview',()=>fixture(async({button,nodes,calls})=>{
|
||||
button('Run Wage Cycle').onclick();const form=nodes().find(n=>n.tagName==='FORM'&&n.textContent.includes('Confirm wage cycle'));await form.onsubmit(event);assert.equal(calls.length,1);
|
||||
confirm(nodes());await form.onsubmit(event);const call=calls.find(c=>c.input);assert.equal(call.path,'/api/bank/admin/payroll/run');assert.equal(call.input.period,'2026-11');assert.equal(call.input.previewKey,'a'.repeat(64));assert.equal(call.input.confirmed,true);assert.match(call.input.requestId,/^[a-f0-9-]{36}$/);assert(nodes().some(n=>n.attrs.role==='status'&&n.textContent.includes('1 salaries paid')));
|
||||
}));
|
||||
test('double submission is disabled while the payment response is pending',()=>fixture(async({button,nodes,calls})=>{
|
||||
button('Run Wage Cycle').onclick();const form=confirm(nodes()),first=form.onsubmit(event);await form.onsubmit(event);assert.equal(calls.filter(c=>c.input).length,1);assert.equal(button('Cancel').disabled,true);await first;
|
||||
},{post:async()=>{await new Promise(resolve=>setImmediate(resolve));return {paid:1,failed:0};}}));
|
||||
test('an uncertain response requires status reload and cannot silently resubmit',()=>fixture(async({button,nodes,calls,host})=>{
|
||||
button('Run Wage Cycle').onclick();const form=confirm(nodes());await form.onsubmit(event);await form.onsubmit(event);assert.equal(calls.filter(c=>c.input).length,1);assert(button('Reload wage status'));assert(host.textContent.includes('check recorded payments'));await button('Reload wage status').onclick();assert.equal(calls.filter(c=>!c.input).length,2);
|
||||
},{post:async()=>{throw Error('Result unavailable.');}}));
|
||||
test('completed and disabled cycles show a disabled Run Wage Cycle button',async()=>{
|
||||
await fixture(async({button,host})=>{assert.equal(button('Run Wage Cycle').disabled,true);assert(host.textContent.includes('cannot be paid again'));},{canRun:false,state:'completed'});
|
||||
await fixture(async({button,host})=>{assert.equal(button('Run Wage Cycle').disabled,true);assert(host.textContent.includes('Enable and save payroll settings'));},{canRun:false,enabled:false});
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff