Merge pull request 'P&O wage-cycle controls and wire-transfer account search' (#323) from dev/MC:dev/alpha-1.0.0.7-the-great-migration into main

This commit is contained in:
Dev 2026-11-15 20:37:29 +01:00
commit d8899de8b2
12 changed files with 362 additions and 26 deletions

View file

@ -15,13 +15,14 @@ export function mountPostbankPayments(host,page,{fetcher=fetch,accountId=null}={
const beforeUnload=event=>{if(uncertain){event.preventDefault();event.returnValue='';}};window.addEventListener('beforeunload',beforeUnload);
async function load(){if(busy)return;if(uncertain){announce('A payment result is still uncertain. Retry the same payment reference or check Transactions before starting another instruction.');return;}busy=true;frame.reloadButton.disabled=true;announce('Loading authorised bank accounts…');try{options=await api.request('/api/bank/transfer-options');if(!active)return;frame.content.replaceChildren();if(transfer)renderTransfer();else await renderActivity();if(active){frame.status.hidden=true;frame.diagnostics.textContent='Central API · Authorised account records · '+new Date().toLocaleString('en-GB');}}catch(error){if(active)announce(error.message);}finally{busy=false;if(active)frame.reloadButton.disabled=false;}}
function renderTransfer(){
const sources=options.accounts.filter(a=>a.canDebit),targets=options.accounts.filter(a=>a.canReceive),form=el('form',undefined,'pb-remittance');form.append(bankIdentity());
const sources=options.accounts.filter(a=>a.canDebit),targets=options.accounts.filter(a=>a.canReceive&&a.canView),form=el('form',undefined,'pb-remittance');form.append(bankIdentity());
if(!sources.length){form.append(el('p','No activated account is currently available for outgoing payments. Activate an eligible package in My Products.'));frame.content.append(form);return;}
const from=el('select'),to=el('select');from.required=true;to.required=true;for(const a of sources)selectOption(from,accountLabel(a),a.id);for(const a of targets)selectOption(to,accountLabel(a),a.number);for(const b of options.beneficiaries||[]){if(b.active&&!targets.some(a=>a.number===b.number)){targets.push({...b,entityId:null});selectOption(to,b.label+' · '+formatNumber(b.number),b.number);}}selectOption(to,'Other beneficiary — search by name or account number','external');
const from=el('select'),to=el('select');from.required=true;to.required=true;for(const a of sources)selectOption(from,accountLabel(a),a.id);for(const a of targets)selectOption(to,accountLabel(a),a.number);selectOption(to,'Search other accounts by name or account number','external');
const grid=el('div',undefined,'pb-remittance-parties'),fromBox=el('section',undefined,'pb-party-card pb-party-from'),toBox=el('section',undefined,'pb-party-card pb-party-to');fromBox.append(field('From · Debit account',from));toBox.append(field('To · Beneficiary account',to));grid.append(fromBox,toBox);
const balance=el('p',undefined,'pb-transfer-available'),searchArea=el('section',undefined,'pb-recipient-search'),query=el('input');query.type='search';query.minLength=3;query.maxLength=80;query.placeholder='Name or full DR account number';
const balance=el('p',undefined,'pb-transfer-available'),searchArea=el('section',undefined,'pb-recipient-search'),query=el('input');query.type='search';query.minLength=3;query.maxLength=80;query.placeholder='Name or account number';
const search=el('button','Find beneficiary');search.type='button';const found=el('select');found.setAttribute('aria-label','Verified beneficiary account');const searchStatus=el('p',undefined,'pb-muted');
searchArea.append(field('Find another beneficiary',query),search,field('Verified beneficiary',found),searchStatus);let external=null,searchVersion=0;
const searchNav=el('nav',undefined,'pb-ledger-pagination'),previous=el('button','Previous matches'),next=el('button','Next matches'),searchPageLabel=el('span');previous.type=next.type='button';previous.disabled=next.disabled=true;searchNav.append(previous,searchPageLabel,next);
searchArea.append(field('Find another beneficiary',query),search,field('Verified beneficiary',found),searchStatus,searchNav);let external=null,searchVersion=0,recipientPage=1;
const amount=el('input');amount.type='text';amount.inputMode='decimal';amount.required=true;amount.pattern='(?:0|[1-9][0-9]{0,16})(?:\\.[0-9]{1,2})?';amount.placeholder='0.00';
const reference=el('textarea');reference.required=true;reference.maxLength=140;reference.rows=2;reference.placeholder='Payment reference';
const standard=el('input'),instant=el('input');standard.type=instant.type='radio';standard.name=instant.name='payment-processing';standard.checked=true;const modes=el('fieldset',undefined,'pb-transfer-modes');modes.append(el('legend','Processing'));const standardLabel=el('label',undefined,'pb-processing-choice'),instantLabel=el('label',undefined,'pb-processing-choice');standardLabel.append(standard,el('strong','Standard'),el('small','Every four hours'));instantLabel.append(instant,el('strong','Instant'),el('small','Within your package allowance'));modes.append(standardLabel,instantLabel);const processing=el('p',undefined,'pb-muted');
@ -32,8 +33,9 @@ export function mountPostbankPayments(host,page,{fetcher=fetch,accountId=null}={
const currentSource=()=>sources.find(a=>a.id===from.value),currentTarget=()=>to.value==='external'?external:targets.find(a=>a.number===to.value);
const isOwn=()=>{const a=currentSource(),b=currentTarget();return !!a?.isPersonalOwner&&a.entityId===b?.entityId;};
function update(){const source=currentSource();balance.textContent='Available: '+source.available+' DM';for(const o of to.options)o.disabled=o.value===source.number;if(to.value===source.number)to.value=[...to.options].find(o=>!o.disabled)?.value||'external';searchArea.hidden=to.value!=='external';query.required=!searchArea.hidden;found.required=!searchArea.hidden;instant.disabled=!source.unlimitedInstant&&source.instantQuota===0;if(instant.disabled){instant.checked=false;standard.checked=true;}processing.textContent=instant.checked?(source.unlimitedInstant?'Unlimited instant payments · No per-transfer fee.':'Instant payments included in this package: '+source.instantQuota+' per calendar month.'):options.standard.processing+(options.standard.nextAt>Date.now()?' Next batch: '+new Date(options.standard.nextAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})+' (Belgian time).':'');recapAmount.textContent=(amount.value||'0.00')+' DM';recapFrom.textContent=currentSource().holder;recapTo.textContent=currentTarget()?.holder||'Select a beneficiary';recapMode.textContent=instant.checked?'Instant':'Standard · Every four hours';const protectedAmount=instant.checked&&options.security?.enabled!==false&&Number(amount.value)>Number(options.security?.threshold||'5000.00');secretField.hidden=!protectedAmount;secretHelp.hidden=!protectedAmount;paymentSecret.required=protectedAmount&&!!options.security?.configured;if(!protectedAmount)paymentSecret.value='';securityLink.textContent=options.security?.configured?'Manage payment security':'Set your payment secret before sending this amount, or choose Standard';submit.disabled=protectedAmount&&!options.security?.configured;confirmLabel.hidden=isOwn();confirm.required=!isOwn();}
from.onchange=()=>{confirm.checked=false;update();};to.onchange=()=>{confirm.checked=false;update();};instant.onchange=standard.onchange=update;amount.oninput=update;query.oninput=()=>{external=null;found.replaceChildren();searchVersion++;confirm.checked=false;};found.onchange=()=>{external=found._results?.find(a=>a.number===found.value)||null;confirm.checked=false;update();};
search.onclick=async()=>{const version=++searchVersion;external=null;found.replaceChildren();search.disabled=true;searchStatus.textContent='Searching…';try{const data=await api.request('/api/bank/recipients?q='+encodeURIComponent(query.value));if(!active||version!==searchVersion)return;found._results=data.recipients;selectOption(found,'Choose a beneficiary','');for(const r of data.recipients)selectOption(found,r.holder+' · '+formatNumber(r.number),r.number);searchStatus.textContent=data.recipients.length?'Select and confirm the matching account.':'No active matching account was found.';}catch(error){if(active&&version===searchVersion)searchStatus.textContent=error.message;}finally{if(active)search.disabled=false;}};
from.onchange=()=>{confirm.checked=false;update();};to.onchange=()=>{confirm.checked=false;update();};instant.onchange=standard.onchange=update;amount.oninput=update;query.oninput=()=>{external=null;found.replaceChildren();searchVersion++;recipientPage=1;previous.disabled=next.disabled=true;searchPageLabel.textContent='';searchStatus.textContent='';confirm.checked=false;update();};found.onchange=()=>{external=found._results?.find(a=>a.number===found.value)||null;confirm.checked=false;update();};
async function findRecipients(page=1){const version=++searchVersion;external=null;found.replaceChildren();confirm.checked=false;search.disabled=true;previous.disabled=next.disabled=true;searchStatus.textContent='Searching…';update();try{const data=await api.request('/api/bank/recipients?'+new URLSearchParams({q:query.value,page:String(page)}));if(!active||version!==searchVersion)return;recipientPage=data.page;found._results=data.recipients;selectOption(found,'Choose a beneficiary','');for(const r of data.recipients)selectOption(found,accountLabel(r),r.number);searchStatus.textContent=data.recipients.length?'Select and confirm the matching account.':'No active matching account was found.';searchPageLabel.textContent='Page '+recipientPage;previous.disabled=recipientPage<=1;next.disabled=!data.hasMore;}catch(error){if(active&&version===searchVersion)searchStatus.textContent=error.message;}finally{if(active)search.disabled=false;}}
search.onclick=()=>findRecipients(1);previous.onclick=()=>findRecipients(recipientPage-1);next.onclick=()=>findRecipients(recipientPage+1);
form.onsubmit=async event=>{
event.preventDefault();if(busy||finished)return;
if(!pending){if(!form.reportValidity())return;const target=currentTarget();if(!target){announce('Find and select a verified beneficiary.');return;}pending={requestId:crypto.randomUUID(),sourceAccount:from.value,targetNumber:target.number,amount:amount.value,reference:reference.value,mode:instant.checked?'instant':'standard',confirmed:confirm.checked,...(instant.checked?{paymentSecret:paymentSecret.value}:{})};}

View file

@ -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});}

View file

@ -22,3 +22,15 @@ The secret is excluded from the payment idempotency fingerprint.
Staff treasury and tax postings use their existing authorised posting paths and
do not acquire a user payment-secret prompt. A staff member using the ordinary
user transfer form follows the same personal security settings as any user.
The wire-transfer beneficiary dropdown contains only active receivable accounts
covered by the user's ownership or account-specific viewing mandate, plus the
search option. Broad bank-inspection rights do not populate that dropdown with
other clients' accounts. Outgoing accounts still require debit authority.
Beneficiary search includes every account the caller may pay, including the
Big Four's permitted treasury/system targets, while P&O remains excluded.
Search matches holder names, account names, partial/formatted account numbers
and the caller's own saved-beneficiary labels. Results are paged in groups of
25; eligibility is applied before pagination, and no balances or client IDs
are returned. Choosing a search result never grants debit rights.

View file

@ -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

View file

@ -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);}
}
@ -216,10 +219,11 @@ export function createPostbankApi(central,bank,settings={},deps={}){
try{
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,actorId:user.id,security:await transferSecurity.settings(user),standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}});
if(path==='/api/bank/recipients'){
if([...url.searchParams.keys()].some(k=>k!=='q')||url.searchParams.getAll('q').length!==1)return reply({message:'Use only the recipient name or account search field.'},400);
if([...url.searchParams.keys()].some(k=>!['q','page'].includes(k))||url.searchParams.getAll('q').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Use the recipient search and page fields.'},400);
const now=Date.now();for(const [key,value]of lookups)if(value.until<now)lookups.delete(key);if(lookups.size>10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429);
const value=lookups.get(user.id)||{until:now+60000,count:0};value.count++;lookups.set(user.id,value);if(value.count>20)return reply({message:'Too many recipient searches. Try again in one minute.'},429);
return reply({recipients:await payments.recipients(user,url.searchParams.get('q'))});
const rawPage=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(rawPage))return reply({message:'Choose a valid beneficiary page.'},400);
const result=await payments.recipientPage(user,url.searchParams.get('q'),{page:Number(rawPage)}),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Search again.'},403);return reply(result);
}
if([...url.searchParams.keys()].some(k=>!['accountId','page','q','state','from','to'].includes(k))||url.searchParams.getAll('accountId').length>1||['page','q','state','from','to'].some(k=>url.searchParams.getAll(k).length>1))return reply({message:'Invalid statement filter.'},400);
const raw=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(raw))return reply({message:'Choose a valid statement page.'},400);

View file

@ -23,20 +23,17 @@ export class PostbankPayments{
async accounts(user){
const context=await this.authority(user),all=await this.canInspectAll(user),entities=context.entities.filter(e=>e.canView);if(!all&&!entities.length)return [];
const rows=all?await this.db.query(accountSQL+" WHERE a.system_key IS NULL OR a.system_key<>'sys_payroll_po' ORDER BY a.id"):await this.db.query(accountSQL+' WHERE c.entity_id IN ('+entities.map(()=>'?').join(',')+') ORDER BY a.id',entities.map(e=>e.id));
return rows.filter(a=>all||canViewAccount(context,a.entity_id,a.id)).map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,holder:a.holder||a.display_name,entityId:a.entity_id,kind:a.kind,isPersonalOwner:a.kind==='person'&&a.external_key===user.id,state:a.state,type:a.type_code,canReceive:bankRecipientAllowed(a,all),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),canDebit:payable(a)&&canDebitAccount(context,a.entity_id,a.id),unlimitedInstant:PACKAGES.find(p=>p.key===a.package_key)?.unlimitedInstant===true,instantQuota:PACKAGES.find(p=>p.key===a.package_key)?.instant||0}));
return rows.filter(a=>all||canViewAccount(context,a.entity_id,a.id)).map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,holder:a.holder||a.display_name,entityId:a.entity_id,kind:a.kind,isPersonalOwner:a.kind==='person'&&a.external_key===user.id,state:a.state,type:a.type_code,canView:canViewAccount(context,a.entity_id,a.id),canReceive:bankRecipientAllowed(a,all),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),canDebit:payable(a)&&canDebitAccount(context,a.entity_id,a.id),unlimitedInstant:PACKAGES.find(p=>p.key===a.package_key)?.unlimitedInstant===true,instantQuota:PACKAGES.find(p=>p.key===a.package_key)?.instant||0}));
}
async recipients(user,query){
if(typeof query!=='string'||query.trim().length<3||query.trim().length>80)throw new BankError('Enter at least three characters of a name, or a full account number.');
// Search only active payable accounts; never expose client numbers or UUIDs.
const all=await this.canInspectAll(user),number=query.replace(/\s/g,'').toUpperCase();let rows;
if(number.startsWith('DR')&&/^DR[0-9 ]+$/i.test(query.trim())){
if(!validBankNumber(number))throw new BankError('Enter a complete valid DR account number.');
rows=await this.db.query(accountSQL+" WHERE a.account_number=? AND a.state='active' LIMIT 10",[number]);
}else{
const term='%'+query.trim().replace(/[!%_]/g,c=>'!'+c)+'%';
rows=await this.db.query(accountSQL+" WHERE (e.display_name LIKE ? ESCAPE '!' OR a.display_name LIKE ? ESCAPE '!') AND a.state='active' ORDER BY e.display_name,a.id LIMIT 10",[term,term]);
}
return rows.filter(a=>bankRecipientAllowed(a,all)).map(a=>({number:a.account_number,name:a.display_name,holder:a.holder||a.display_name}));
async recipients(user,query){return (await this.recipientPage(user,query)).recipients;}
async recipientPage(user,query,{page=1}={}){
if(typeof query!=='string'||query.trim().length<3||query.trim().length>80||!Number.isInteger(page)||page<1||page>10000)throw new BankError('Enter at least three characters of a name or account number, and a valid page.');
const all=await this.canInspectAll(user),escape=value=>'%'+value.replace(/[!%_]/g,c=>'!'+c)+'%',term=escape(query.trim()),numberTerm=escape(query.replace(/\s/g,'').toUpperCase());
// Filter before pagination so ineligible matches cannot hide payable accounts.
const eligibility=all?"(a.system_key IS NULL OR a.system_key<>'sys_payroll_po') AND (a.system_key IS NOT NULL OR e.active=1 AND p.state='active')":"a.system_key IS NULL AND a.type_code<>'106' AND e.active=1 AND p.state='active'";
const rows=await this.db.query(accountSQL+" WHERE a.state='active' AND "+eligibility+" AND (e.display_name LIKE ? ESCAPE '!' OR a.display_name LIKE ? ESCAPE '!' OR a.account_number LIKE ? ESCAPE '!' OR EXISTS (SELECT 1 FROM pb_beneficiaries b WHERE b.account_id=a.id AND b.owner_id=? AND b.label LIKE ? ESCAPE '!')) ORDER BY COALESCE(e.display_name,a.display_name),a.id LIMIT 26 OFFSET "+((page-1)*25),[term,term,numberTerm,user.id,term]);
if(all&&!await this.canInspectAll(user))throw new BankError('Your beneficiary search authority changed. Search again.',403);
return {recipients:rows.slice(0,25).filter(a=>bankRecipientAllowed(a,all)).map(a=>({number:a.account_number,name:a.display_name,holder:a.holder||a.display_name})),page,hasMore:rows.length>25};
}
async transfer(user,input,{revalidate=async()=>user}={}){
const allowed=['requestId','sourceAccount','targetNumber','amount','reference','mode','confirmed','paymentSecret'];

View file

@ -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;}
}
}

View file

@ -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<policy.value.payDay)return {paid:0,failed:0,notDue:true};
const tax=await readFinancialPolicy(this.bank,'payroll_tax'),recipients=await readPayrollRecipients(this.central,now);
// 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(run.state!=='prepared')return;
@ -52,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{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());

View file

@ -0,0 +1,35 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {mountPostbankPayments} from '../control-panel/public/cp-v2/cp-v2-postbank-payments.mjs';
class Node{
constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.attrs={};this._text='';this._value=null;this.disabled=false;this.checked=false;this.hidden=false;}
set textContent(value){this._text=String(value);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}
get value(){return this._value??(this.tagName==='SELECT'?this.children[0]?.value||'':'');}set value(value){this._value=String(value);}
get options(){return this.children;}append(...nodes){for(const node of nodes){node.parent=this;this.children.push(node);}}
replaceChildren(...nodes){this.children=[];this._text='';if(this.tagName==='SELECT')this._value=null;this.append(...nodes);}
setAttribute(key,value){this.attrs[key]=String(value);}closest(){return null;}focus(){}reportValidity(){return true;}
querySelectorAll(selector){return all(this).filter(n=>selector.toUpperCase().split(',').includes(n.tagName));}
remove(){if(this.parent)this.parent.children=this.parent.children.filter(n=>n!==this);}
}
const all=node=>node.children.flatMap(child=>[child,...all(child)]),settle=async()=>{for(let i=0;i<5;i++)await new Promise(resolve=>setImmediate(resolve));};
async function fixture(work,{search=async page=>({recipients:[{name:'External Savings',holder:'External',number:'DR22103000000002'}],page,hasMore:page===1})}={}){
const previousDocument=globalThis.document,previousWindow=globalThis.window;globalThis.document={createElement:tag=>new Node(tag)};globalThis.window={addEventListener(){},removeEventListener(){}};
const host=new Node('main'),calls=[],base={holder:'You',entityId:'person',canReceive:true,canView:true,canDebit:true,available:'100.00',instantQuota:5,isPersonalOwner:true};
const accounts=[{...base,id:'1',name:'Your Current',number:'DR25102000000005'},{...base,id:'2',name:'Your Savings',number:'DR50103000000006'},{...base,id:'3',name:'Foreign Account',number:'DR14102000000007',canView:false,canDebit:false},{...base,id:'4',name:'Treasury',number:'DR8297900000007',canView:false,canDebit:false},{...base,id:'5',name:'Delegated Account',number:'DR14102000000008',canDebit:false}];
const dispose=mountPostbankPayments(host,'bank-transfers',{fetcher:async(path,options)=>{calls.push({path,options});if(path.startsWith('/api/bank/recipients?'))return Response.json(await search(Number(new URL(path,'https://cp.dunerealms.com').searchParams.get('page'))));return Response.json({accounts,beneficiaries:[{active:true,label:'Saved External',number:accounts[2].number}],fees:{message:'No fee'},standard:{processing:'Every four hours'},security:{enabled:false}});}});
const nodes=()=>all(host),button=label=>nodes().find(n=>n.tagName==='BUTTON'&&n.textContent===label);
try{await settle();await work({host,calls,nodes,button});}finally{dispose();globalThis.document=previousDocument;globalThis.window=previousWindow;}
}
test('wire dropdown lists owned and delegated accounts plus search; inspection-only and saved external accounts stay out',()=>fixture(async({nodes})=>{
const selects=nodes().filter(n=>n.tagName==='SELECT'),debit=selects[0],credit=selects[1];assert.equal(debit.options.length,2);assert.equal(credit.options.length,4);
assert(credit.textContent.includes('Your Savings'));assert(credit.textContent.includes('Delegated Account'));assert(credit.textContent.includes('Search other accounts'));assert(!credit.textContent.includes('Foreign Account'));assert(!credit.textContent.includes('Treasury'));assert(!credit.textContent.includes('Saved External'));
}));
test('beneficiary search displays account names and allows every result page to be reached',()=>fixture(async({nodes,button,calls})=>{
const credit=nodes().filter(n=>n.tagName==='SELECT')[1];credit.value='external';credit.onchange();const query=nodes().find(n=>n.type==='search');query.value='External';query.oninput();await button('Find beneficiary').onclick();
const found=nodes().find(n=>n.attrs['aria-label']==='Verified beneficiary account');assert(found.textContent.includes('External Savings'));assert.equal(button('Next matches').disabled,false);await button('Next matches').onclick();assert.equal(button('Previous matches').disabled,false);assert.equal(button('Next matches').disabled,true);assert(calls.some(c=>c.path.includes('page=2')));
query.value='New search';query.oninput();assert.equal(found.options.length,0);assert.equal(button('Next matches').disabled,true);await button('Find beneficiary').onclick();assert(calls.at(-1).path.includes('page=1'));
}));
test('changing a search while results are loading discards the stale response',()=>fixture(async({nodes,button})=>{
const credit=nodes().filter(n=>n.tagName==='SELECT')[1];credit.value='external';credit.onchange();const query=nodes().find(n=>n.type==='search');query.value='First';
query.oninput();const pending=button('Find beneficiary').onclick();query.value='Changed';query.oninput();await pending;assert.equal(nodes().find(n=>n.attrs['aria-label']==='Verified beneficiary account').options.length,0);
},{search:async page=>{await new Promise(resolve=>setImmediate(resolve));return {recipients:[{name:'Stale',number:'DR22103000000002'}],page,hasMore:false};}}));

View file

@ -76,3 +76,44 @@ test('P&O stays excluded even for Big Four; privilege revoked before settlement
test('Big Four system beneficiaries can be saved, and become inactive when the mandate ends',async()=>{const f=await setup();try{const {PostbankBeneficiaries}=await import('../node/postbank-beneficiaries.mjs');const reserve=f.current(2);await f.db.query("UPDATE pb_accounts SET client_number=NULL,package_id=NULL,system_key='sys_bank_capital_issuer',display_name='Federal Reserve' WHERE id=?",[reserve.id]);let allowed=true;const book=new PostbankBeneficiaries(f.db,{canInspectAll:async()=>allowed});await book.write(f.users[0],{requestId:randomUUID(),number:reserve.account_number,label:'Federal Reserve'});assert.equal((await book.list(f.users[0])).beneficiaries[0].active,true);allowed=false;assert.equal((await book.list(f.users[0])).beneficiaries[0].active,false);}finally{f.db.close();}});
test('bank-wide mandate follows protected owner/executive identities, not service or ordinary bank permissions',async()=>{const {canInspectAllBankAccounts,bankRecipientAllowed}=await import('../node/postbank-recipient-policy.mjs');for(const kind of ['owner','executive','service','officer',null]){const central={prepare(){return {bind(){return this;},async first(){return kind?{principal_kind:kind}:null;}};}};assert.equal(await canInspectAllBankAccounts(central,{id:'ordinary-identity'}),['owner','executive'].includes(kind));}assert.equal(bankRecipientAllowed({state:'active',system_key:'sys_payroll_po'},true),false);assert.equal(bankRecipientAllowed({state:'active',system_key:'sys_bank_capital_issuer'},true),true);assert.equal(bankRecipientAllowed({state:'dormant',system_key:'sys_tax_treasury'},true),false);});
test('wire picker access stays scoped while permitted external accounts remain searchable',async()=>{
const f=await setup();try{
f.service.canInspectAll=async()=>true;const accounts=await f.service.accounts(f.users[0]);
assert.equal(accounts.find(a=>a.id===String(f.current(0).id)).canView,true);assert.equal(accounts.find(a=>a.id===String(f.current(1).id)).canView,false);
assert.equal((await f.service.recipientPage(f.users[0],'citizen_1')).recipients.length,2);
const formatted=f.current(1).account_number.match(/.{1,4}/g).join(' ');assert.equal((await f.service.recipientPage(f.users[0],formatted)).recipients[0].number,f.current(1).account_number);
assert((await f.service.recipientPage(f.users[0],formatted.slice(0,9))).recipients.some(a=>a.number===f.current(1).account_number));
}finally{f.db.close();}
});
test('recipient pages include every eligible match beyond the former ten-result cap',async()=>{
const f=await setup();try{
const {bankNumber}=await import('../node/postbank-catalogue.mjs'),sample=f.current(1);
for(let i=0;i<38;i++)await f.db.query("INSERT INTO pb_accounts(client_number,package_id,account_number,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,?,'102',?,0,0,'active',0)",[sample.client_number,sample.package_id,bankNumber('102',1000+i),'Search match '+i]);
// Many unavailable matches must not consume a page or hide valid matches.
for(let i=0;i<12;i++)await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE account_number=?",[bankNumber('102',1000+i)]);
const first=await f.service.recipientPage(f.users[0],'Search match'),second=await f.service.recipientPage(f.users[0],'Search match',{page:2});assert.equal(first.recipients.length,25);assert.equal(first.hasMore,true);assert.equal(second.recipients.length,1);assert.equal(second.hasMore,false);assert.equal(new Set([...first.recipients,...second.recipients].map(a=>a.number)).size,26);
for(const account of first.recipients)assert.deepEqual(Object.keys(account).sort(),['holder','name','number']);
await assert.rejects(f.service.recipientPage(f.users[0],'match',{page:0}));assert.deepEqual((await f.service.recipientPage(f.users[0],'Search%')).recipients,[]);
}finally{f.db.close();}
});
test('saved-beneficiary search aliases are private and use current account eligibility',async()=>{
const f=await setup();try{
const {PostbankBeneficiaries}=await import('../node/postbank-beneficiaries.mjs'),book=new PostbankBeneficiaries(f.db);
await book.write(f.users[0],{requestId:randomUUID(),number:f.current(1).account_number,label:'Secret alias example'});
assert.equal((await f.service.recipientPage(f.users[0],'Secret alias')).recipients.length,1);assert.equal((await f.service.recipientPage(f.users[2],'Secret alias')).recipients.length,0);
await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.current(1).id]);assert.equal((await f.service.recipientPage(f.users[0],'Secret alias')).recipients.length,0);
}finally{f.db.close();}
});
test('recipient API validates paging, and rejects identity changes while loading results',async()=>{
const f=await setup();try{
let changed=false;const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>changed?f.users[1]:f.users[0],authority:f.authority}),base='https://cp.dunerealms.com/api/bank/recipients?q=citizen';
for(const suffix of ['&page=0','&page=1.5','&page=1&page=2','&user=other'])assert.equal((await api(new Request(base+suffix))).status,400);
const response=await api(new Request(base+'&page=1'));assert.equal(response.status,200);assert.equal((await response.json()).page,1);
const authority=async user=>{changed=true;return f.authority(user);};let reads=0;
const changedApi=createPostbankApi(null,f.db,{}, {authenticate:async()=>++reads===1?f.users[0]:f.users[1],authority});assert.equal((await changedApi(new Request(base))).status,403);
}finally{f.db.close();}
});

View file

@ -0,0 +1,103 @@
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();}
});
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();}
});

View 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});
});