Merge pull request 'Alpha 1.0.0.7 — The Great Migration' (#314) from dev/MC:dev/alpha-1.0.0.7-the-great-migration into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 1m25s
All checks were successful
DuneRealms Web CI / web (push) Successful in 1m25s
This commit is contained in:
commit
700b5edf87
15 changed files with 430 additions and 4 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import {renderPayroll} from './cp-v2-postbank-payroll.mjs';
|
||||
import {renderServiceCompensation} from './cp-v2-postbank-compensation.mjs';
|
||||
import {renderClientManagement} from './cp-v2-postbank-client.mjs';
|
||||
const transactionLabel=r=>r.mode==='service'?'SERVICE COMPENSATION':r.state==='rejected'?'REJECTED':r.state==='queued'?'PENDING':r.direction==='credit'?'CREDIT':r.direction==='debit'?'DEBIT':'DEBIT / CREDIT';
|
||||
|
|
@ -14,8 +15,8 @@ export function mountPostbankAdmin(host,id,{fetcher=fetch}={}){
|
|||
const message=text=>{frame.status.hidden=false;frame.status.textContent=text;};
|
||||
async function load(){if(busy)return;busy=true;frame.reloadButton.disabled=true;message('Loading bank administration…');try{
|
||||
const stats=await api.request('/api/bank/admin/overview');if(!active)return;frame.content.replaceChildren();canCompensate=!!stats.permissions.canCompensate;
|
||||
if(id==='bank-dashboard'){const metrics=el('div',undefined,'pb-admin-metrics');for(const [name,value]of [['Clients',stats.clients],['Accounts',stats.accounts],['Customer balances',stats.balances+' DM'],['Pending payments',stats.pendingPayments]]){const card=el('section');card.append(el('small',name),el('strong',String(value)));metrics.append(card);}frame.content.append(metrics);if(stats.permissions.canRunScheduler){const run=el('button','Run Central Scheduler');run.type='button';run.onclick=async()=>{if(busy||!confirm('Run due scheduled tasks now? Future payment settlement times remain unchanged.'))return;busy=true;run.disabled=true;try{const result=await api.request('/api/bank/admin/scheduler/run',{confirmed:true});message('Scheduler finished: '+result.tasks.filter(t=>t.state==='completed').length+' completed · '+result.tasks.filter(t=>t.state==='retry_pending').length+' need attention. Tasks already current or running were skipped.');}catch(e){message(e.message);}finally{busy=false;if(active)run.disabled=false;}};frame.content.append(run);}const nav=el('nav',undefined,'pb-admin-tabs');for(const [key,label]of [['clients','Clients & Accounts'],['pending','Payment Control'],...(canCompensate?[['compensation','Service Compensation']]:[])]){const button=el('button',label);button.type='button';button.setAttribute('aria-pressed',String(mode===key));button.onclick=()=>{mode=key;page=1;query='';kind='';void load();};nav.append(button);}frame.content.append(nav);}
|
||||
if(mode==='compensation'){const pane=el('section');frame.content.append(pane);await renderServiceCompensation(pane,{api,original:selectedPayment,canManage:stats.permissions.canManage,isActive:()=>active&&mode==='compensation'});frame.status.hidden=true;return;}const tools=el('form',undefined,'pb-admin-tools'),search=el('input');search.type='search';search.value=query;search.placeholder=mode==='audit'?'Action or entity name':'Name or client number';search.maxLength=80;const type=el('select');selectOption(type,'All entity types','');for(const value of mode==='corporate'?['clan','company']:['person','clan','company','house','office','staff'])selectOption(type,human(value),value);type.value=kind;const apply=el('button','Search');apply.type='submit';
|
||||
if(id==='bank-dashboard'){const metrics=el('div',undefined,'pb-admin-metrics');for(const [name,value]of [['Clients',stats.clients],['Accounts',stats.accounts],['Customer balances',stats.balances+' DM'],['Pending payments',stats.pendingPayments]]){const card=el('section');card.append(el('small',name),el('strong',String(value)));metrics.append(card);}frame.content.append(metrics);if(stats.permissions.canRunScheduler){const run=el('button','Run Central Scheduler');run.type='button';run.onclick=async()=>{if(busy||!confirm('Run due scheduled tasks now? Future payment settlement times remain unchanged.'))return;busy=true;run.disabled=true;try{const result=await api.request('/api/bank/admin/scheduler/run',{confirmed:true});message('Scheduler finished: '+result.tasks.filter(t=>t.state==='completed').length+' completed · '+result.tasks.filter(t=>t.state==='retry_pending').length+' need attention. Tasks already current or running were skipped.');}catch(e){message(e.message);}finally{busy=false;if(active)run.disabled=false;}};frame.content.append(run);}const nav=el('nav',undefined,'pb-admin-tabs');for(const [key,label]of [['clients','Clients & Accounts'],['pending','Payment Control'],...(stats.permissions.canRunScheduler?[['payroll','P&O Payroll']]:[]),...(canCompensate?[['compensation','Service Compensation']]:[])]){const button=el('button',label);button.type='button';button.setAttribute('aria-pressed',String(mode===key));button.onclick=()=>{mode=key;page=1;query='';kind='';void load();};nav.append(button);}frame.content.append(nav);}
|
||||
if(mode==='payroll'){const pane=el('section');frame.content.append(pane);await renderPayroll(pane,{api,isActive:()=>active&&mode==='payroll'});frame.status.hidden=true;return;}if(mode==='compensation'){const pane=el('section');frame.content.append(pane);await renderServiceCompensation(pane,{api,original:selectedPayment,canManage:stats.permissions.canManage,isActive:()=>active&&mode==='compensation'});frame.status.hidden=true;return;}const tools=el('form',undefined,'pb-admin-tools'),search=el('input');search.type='search';search.value=query;search.placeholder=mode==='audit'?'Action or entity name':'Name or client number';search.maxLength=80;const type=el('select');selectOption(type,'All entity types','');for(const value of mode==='corporate'?['clan','company']:['person','clan','company','house','office','staff'])selectOption(type,human(value),value);type.value=kind;const apply=el('button','Search');apply.type='submit';
|
||||
if(mode!=='pending'){tools.append(field('Search',search));if(!['audit','treasuries'].includes(mode))tools.append(field('Entity type',type));tools.append(apply);tools.onsubmit=e=>{e.preventDefault();query=search.value;kind=type.value;page=1;void load();};frame.content.append(tools);}
|
||||
const endpoint=mode==='treasuries'?'treasuries':mode==='pending'?'pending':mode==='audit'?'audit':mode==='corporate'?'corporate':'entities',data=await api.request('/api/bank/admin/'+endpoint+'?page='+page+(query?'&q='+encodeURIComponent(query):'')+(kind?'&kind='+encodeURIComponent(kind):''));if(!active)return;
|
||||
if(!data.records.length)frame.content.append(el('p',mode==='pending'?'No standard payments are awaiting settlement.':mode==='corporate'?'No matching business entities. Companies appear only after registration; no example companies are created.':'No matching bank records.'));
|
||||
|
|
@ -26,10 +27,10 @@ export function mountPostbankAdmin(host,id,{fetcher=fetch}={}){
|
|||
if(canManage){const allocations=el('a','Tax Treasury Payments');allocations.href='#bureau/tax-treasury';allocations.className='pb-primary-link';frame.content.append(allocations);}
|
||||
const managed=data.records.filter(a=>!a.system||a.canTransfer),automated=data.records.filter(a=>a.system&&!a.canTransfer),priority=a=>a.name==='Website Bank Treasury'?0:a.name==='In-game Bank Treasury'?1:a.name==='I.D. Taxes'?2:3;
|
||||
managed.sort((a,b)=>priority(a)-priority(b)||a.name.localeCompare(b.name));automated.sort((a,b)=>a.name.localeCompare(b.name));
|
||||
for(const [title,records,type,description]of [['Managed Accounts',managed,'managed','Bank reserves, the combined web/game tax treasury and staff accounts. Manual treasury transfers are limited to the website bank, in-game reserve and tax treasury.'],['System Accounts',automated,'system','Automated service accounts. Federal Imperial Reserve records capital issuance; P&O is a fictitious payroll issuer. Neither can make manual payments here.']]){
|
||||
for(const [title,records,type,description]of [['Managed Accounts',managed,'managed','Bank reserves, the combined web/game tax treasury and staff accounts. Manual treasury transfers are limited to the website bank, in-game reserve and tax treasury.'],['System Accounts',automated,'system','Automated service accounts. Federal Imperial Reserve records capital issuance; P&O receives employer funding and distributes salaries and tax deductions. Neither can make manual payments here.']]){
|
||||
const section=el('section',undefined,'pb-treasury-group');section.dataset.group=type;section.append(el('h2',title),el('p',description,'pb-muted'));
|
||||
const {wrap,body}=table(['Account','Holder','Balance · DM','Reserved · DM','Status','Transactions']);
|
||||
for(const a of records){const row=el('tr'),name=el('td');row.dataset.treasury=a.payroll?'payroll':a.name==='Federal Imperial Reserve'?'reserve':a.name==='I.D. Taxes'?'tax':a.gameLinked===false?'game':a.canTransfer?'web':'staff';name.append(el('strong',a.name),el('code',number(a.number)));const action=el('td'),button=el('button','View transactions');button.type='button';action.append(button);row.append(name,el('td',a.holder),el('td',a.payroll?'Fictitious':a.balance),el('td',a.payroll?'—':a.reserved),el('td',human(a.state)+(a.gameLinked===false?' · Game not linked':a.payroll?' · Payroll inactive':a.system?' · System':'')),action);body.append(row);const detail=el('tr'),cell=el('td');cell.colSpan=6;detail.hidden=true;detail.append(cell);body.append(detail);button.onclick=()=>{detail.hidden=!detail.hidden;if(!detail.hidden)void accountActivity(a.id,cell,1);};}
|
||||
for(const a of records){const row=el('tr'),name=el('td');row.dataset.treasury=a.payroll?'payroll':a.name==='Federal Imperial Reserve'?'reserve':a.name==='I.D. Taxes'?'tax':a.gameLinked===false?'game':a.canTransfer?'web':'staff';name.append(el('strong',a.name),el('code',number(a.number)));const action=el('td'),button=el('button','View transactions');button.type='button';action.append(button);row.append(name,el('td',a.holder),el('td',a.balance),el('td',a.reserved),el('td',human(a.state)+(a.gameLinked===false?' · Game not linked':a.payroll?' · Automated payroll':a.system?' · System':'')),action);body.append(row);const detail=el('tr'),cell=el('td');cell.colSpan=6;detail.hidden=true;detail.append(cell);body.append(detail);button.onclick=()=>{detail.hidden=!detail.hidden;if(!detail.hidden)void accountActivity(a.id,cell,1);};}
|
||||
section.append(wrap);if(!records.length)section.append(el('p','No matching accounts.'));frame.content.append(section);
|
||||
}
|
||||
if(canManage)renderTreasuryTransfer(data.records.filter(a=>a.canTransfer));
|
||||
|
|
|
|||
|
|
@ -0,0 +1,29 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
const labels={officer:'Officer',branch_lead:'Branch Lead',department_head:'Department Head',executive:'Executive',owner_ceo:'Owner & CEO'};
|
||||
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 form=el('form',undefined,'pb-transfer-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;
|
||||
reason.required=true;reason.minLength=5;reason.maxLength=200;
|
||||
const field=(label,input)=>{const box=el('label',undefined,'pb-transfer-field');box.append(el('span',label),input);return box;};
|
||||
form.append(field('Automatic monthly payroll',enabled),field('Payment day of the month',day));
|
||||
const wrap=el('div',undefined,'pb-ledger-scroll'),table=el('table',undefined,'pb-ledger'),head=el('thead'),header=el('tr'),body=el('tbody'),inputs=new Map();
|
||||
for(const title of ['Rank','Net salary · DM','Gross · DM','Employee social · DM','Income tax · DM','Employer social · DM','Employer cost · DM'])header.append(el('th',title));head.append(header);
|
||||
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;
|
||||
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});}
|
||||
catch(error){status.textContent=error.message;save.textContent='Reload before retrying';}
|
||||
};
|
||||
host.append(el('h3','Recent payroll records'));
|
||||
if(!data.records.length){host.append(el('p','No payroll has been posted yet.'));return;}
|
||||
const history=el('table',undefined,'pb-ledger'),historyHead=el('thead'),historyHeader=el('tr'),historyBody=el('tbody');
|
||||
for(const label of ['Period','Staff member','Net salary · DM','State','Current account'])historyHeader.append(el('th',label));historyHead.append(historyHeader);
|
||||
for(const record of data.records){const row=el('tr');for(const value of [record.period,record.actor_name,money(record.amount_minor),record.state,record.account_number||'Created when payment posts'])row.append(el('td',String(value)));historyBody.append(row);}
|
||||
history.append(historyHead,historyBody);const scroll=el('div',undefined,'pb-ledger-scroll');scroll.append(history);host.append(scroll);
|
||||
}
|
||||
36
website/docs/postbank-payroll.md
Normal file
36
website/docs/postbank-payroll.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# P&O payroll
|
||||
|
||||
The central scheduler processes one monthly salary per verified staff identity.
|
||||
The highest valid active rank sets the wage; departments do not stack. Official
|
||||
accounts, deployment identities and duplicate linked Minecraft identities are
|
||||
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.
|
||||
|
||||
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
|
||||
or claim that the employee accepted terms. A blocked or closed personal current
|
||||
account requires review rather than a replacement account.
|
||||
|
||||
Each period freezes rank, policy version, tax parameters and payslip amounts
|
||||
before posting. An employee payment atomically moves employer cost from Website
|
||||
bank treasury to P&O, net salary to the personal account, and social contributions
|
||||
plus income tax to I.D. Taxes. P&O retains no generated money. All three legs
|
||||
share the transaction with account provisioning and the paid marker. Insufficient
|
||||
funds roll everything back. Unpaid recipients are rechecked against current
|
||||
appointments and identity before posting.
|
||||
|
||||
The model is fictional DM payroll using selected Belgian-inspired 2026 parameters,
|
||||
not a real Belgian payroll calculation. Defaults are net DM per month:
|
||||
Officer 2,800; Branch Lead 3,360; Department Head 4,200; Executive 5,040;
|
||||
Owner & CEO 5,600. The payroll policy can be changed centrally.
|
||||
|
||||
`scripts/rollout-postbank-payroll.mjs --actor=UUID` previews eligibility without
|
||||
creating accounts. `--apply` enables the current policy and runs the initial
|
||||
current-period payroll once. Repeating it cannot pay the same period/person
|
||||
again. Use the physical release path when invoking the script.
|
||||
|
||||
Validation includes concurrent-run idempotency, account 108 provisioning,
|
||||
salary/tax conservation and rollback on insufficient funds. The same concurrent
|
||||
rollout was verified in isolated MySQL tables without production payments.
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {PostbankPayroll} from './postbank-payroll.mjs';
|
||||
import {PostbankFinancialPolicies} from './postbank-financial-policy.mjs';
|
||||
import {PostbankClientManagement} from './postbank-client-management.mjs';
|
||||
import {PostbankCompensation} from './postbank-compensation.mjs';
|
||||
import {PostbankStandingInstructions} from './postbank-standing-instructions.mjs';
|
||||
|
|
@ -26,6 +28,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
const credit=bank?new PostbankCredit(bank,authority,{...deps,central}):null;
|
||||
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 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;
|
||||
|
|
@ -121,6 +124,19 @@ 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'){
|
||||
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!=='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);}
|
||||
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);}
|
||||
}
|
||||
if(['/api/bank/admin/scheduler','/api/bank/admin/scheduler/run'].includes(path)){
|
||||
try{
|
||||
if(url.search)return reply({message:'Scheduler overrides are not accepted.'},400);
|
||||
|
|
|
|||
49
website/node/postbank-financial-policy.mjs
Normal file
49
website/node/postbank-financial-policy.mjs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import {randomUUID} from 'node:crypto';import {BankError} from './postbank-service.mjs';import {PACKAGES} from './postbank-catalogue.mjs';import {CREDIT_PRODUCTS} from './postbank-credit-model.mjs';import {canRunScheduler} from './scheduler-authority.mjs';
|
||||
import {DEFAULT_PAYROLL_POLICY,DEFAULT_PAYROLL_TAX,validatePayrollPolicy,validatePayrollTax} from './postbank-payroll-model.mjs';
|
||||
export const DEFAULT_TAXES=Object.freeze({vatBps:2100,bankFeeVatBps:0,monthlyAccountTaxMinor:0});
|
||||
export function defaultBankRates(){return {billingEnabled:false,packages:Object.fromEntries(PACKAGES.map(p=>[p.key,{monthlyMinor:p.monthly,extraMinor:p.extraFee}])),creditAnnualBps:Object.fromEntries(CREDIT_PRODUCTS.map(p=>[p.key,p.annualBps]))};}
|
||||
export const POLICY_KEYS=['payroll','payroll_tax','bank_rates','taxes'];
|
||||
export function defaultFinancialPolicy(key){if(key==='payroll')return structuredClone(DEFAULT_PAYROLL_POLICY);if(key==='payroll_tax')return structuredClone(DEFAULT_PAYROLL_TAX);if(key==='taxes')return structuredClone(DEFAULT_TAXES);if(key==='bank_rates')return defaultBankRates();throw new BankError('Unknown financial policy.');}
|
||||
const integer=(n,max)=>Number.isSafeInteger(n)&&n>=0&&n<=max;
|
||||
export function validateFinancialPolicy(key,value){
|
||||
if(key==='payroll')return validatePayrollPolicy(value);if(key==='payroll_tax')return validatePayrollTax(value);
|
||||
if(key==='taxes'){if(!value||Object.keys(value).length!==3||!integer(value.vatBps,10000)||!integer(value.bankFeeVatBps,10000)||!integer(value.monthlyAccountTaxMinor,100000000))throw new BankError('Choose valid game tax rates and a monthly account tax.');return structuredClone(value);}
|
||||
if(key==='bank_rates'){
|
||||
const baseline=defaultBankRates();if(!value||Object.keys(value).length!==3||typeof value.billingEnabled!=='boolean'||!value.packages||!value.creditAnnualBps||Object.keys(value.packages).length!==PACKAGES.length||Object.keys(value.creditAnnualBps).length!==CREDIT_PRODUCTS.length)throw new BankError('Complete every package and credit rate.');
|
||||
for(const p of PACKAGES){const v=value.packages[p.key];if(!v||Object.keys(v).length!==2||!integer(v.monthlyMinor,100000000)||!integer(v.extraMinor,100000000)||['pb_start','pb_civic','pb_public'].includes(p.key)&&(v.monthlyMinor!==0||v.extraMinor!==0))throw new BankError('Start, Civic and Public remain free; other package prices must use whole DM cents.');}
|
||||
for(const p of CREDIT_PRODUCTS)if(!integer(value.creditAnnualBps[p.key],10000)||p.group==='grants'&&value.creditAnnualBps[p.key]!==0)throw new BankError('Credit rates must be 0–100%; launch grants remain interest-free.');
|
||||
return structuredClone(value);
|
||||
}
|
||||
throw new BankError('Unknown financial policy.');
|
||||
}
|
||||
export async function readFinancialPolicy(db,key){
|
||||
const fallback=defaultFinancialPolicy(key),row=await db.first('SELECT policy_json,version,updated_at FROM pb_financial_policies WHERE policy_key=?',[key]);
|
||||
return {key,value:row?validateFinancialPolicy(key,JSON.parse(row.policy_json)):fallback,version:Number(row?.version||0),updatedAt:Number(row?.updated_at||0)};
|
||||
}
|
||||
export async function makePublicRatesSnapshot(tx,{id=randomUUID(),now=Date.now()}={}){
|
||||
const bank=await readFinancialPolicy(tx,'bank_rates'),tax=await readFinancialPolicy(tx,'taxes'),payroll=await readFinancialPolicy(tx,'payroll_tax');
|
||||
return {version:id,publishedAt:now,policyVersions:{bank:bank.version,taxes:tax.version,payrollTax:payroll.version},packages:PACKAGES.map(p=>({key:p.key,name:p.name,...bank.value.packages[p.key]})),credit:CREDIT_PRODUCTS.map(p=>({key:p.key,name:p.name,annualBps:bank.value.creditAnnualBps[p.key],availability:p.automatic?'Automatic launch grant':p.revolving?'Planned credit line':'Subject to credit review'})),taxes:tax.value,payrollTax:payroll.value,serviceNotices:[bank.value.billingEnabled?'Monthly package charges are processed automatically.':'Monthly package billing is not enabled.', 'Standard transfers settle every four hours in Europe/Brussels. Instant transfers post immediately.', 'Balance Guard is a configured option; protection and billing remain inactive until that service is enabled.', 'Service compensation posts immediately. Statements are free for every package.']};
|
||||
}
|
||||
export async function queueRatesPublication(tx,actorId,now=Date.now()){
|
||||
const data=await makePublicRatesSnapshot(tx,{now});await tx.query("INSERT INTO pb_rate_publications(id,data_json,state,created_by,created_at) VALUES(?,?,'pending',?,?)",[data.version,JSON.stringify(data),actorId,now]);return data.version;
|
||||
}
|
||||
export class PostbankFinancialPolicies{
|
||||
constructor(bank,central,authority,{clock=Date.now}={}){this.db=bank;this.central=central;this.authority=authority;this.clock=clock;}
|
||||
async access(user,key){if(!POLICY_KEYS.includes(key))throw new BankError('Unknown financial policy.');const control=await canRunScheduler(this.central,user);if(key!=='bank_rates'&&!control)throw new BankError('Tax and P&O policy management is reserved for the Big Four.',403);if(key==='bank_rates'&&!control){const rights=await this.authority(user);if(!rights.readAdmin||!rights.manageAdmin)throw new BankError('Bank management permission is required.',403);}}
|
||||
async get(user,key){await this.access(user,key);return readFinancialPolicy(this.db,key);}
|
||||
async save(user,key,input,{revalidate=async()=>user}={}){
|
||||
await this.access(user,key);if(!input||Object.keys(input).some(k=>!['requestId','version','value','reason','confirmed'].includes(k))||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||'')||!Number.isSafeInteger(input.version)||input.version<0||input.confirmed!==true||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 policy version, settings and reason.');
|
||||
let value;try{value=validateFinancialPolicy(key,input.value);}catch(e){throw new BankError(e.message);}const fingerprint=JSON.stringify([user.id,key,input.version,value,input.reason.trim()]);
|
||||
return this.db.transaction(async tx=>{
|
||||
// One existing guard row serialises publication snapshots across policy keys.
|
||||
await tx.query("INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES('publication_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='publication_guard' FOR UPDATE");
|
||||
const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.access(fresh,key);
|
||||
const prior=await tx.first('SELECT actor_id,action,details FROM pb_audit WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.action!=='financial_policy_changed'||JSON.parse(prior.details).fingerprint!==fingerprint)throw new BankError('Request reference already used.',409);return {ok:true,replayed:true};}
|
||||
const current=await tx.first('SELECT version FROM pb_financial_policies WHERE policy_key=? FOR UPDATE',[key]);if(Number(current?.version||0)!==input.version)throw new BankError('The policy changed. Reload before editing.',409);
|
||||
await tx.query('INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE policy_json=VALUES(policy_json),version=VALUES(version),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[key,JSON.stringify(value),input.version+1,user.id,this.clock()]);
|
||||
const publication=key==='payroll'?null:await queueRatesPublication(tx,user.id,this.clock());
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[input.requestId,user.id,'financial_policy_changed',JSON.stringify({key,version:input.version+1,fingerprint,reason:input.reason.trim(),publication}),this.clock()]);return {ok:true,replayed:false,version:input.version+1,publication};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import {CentralScheduler} from './central-scheduler.mjs';
|
||||
import {PostbankPayroll} from './postbank-payroll.mjs';
|
||||
import {PostbankStandingInstructions} from './postbank-standing-instructions.mjs';
|
||||
import {PostbankCreditSupport} from './postbank-credit-support.mjs';
|
||||
import {PostbankTransferSecurity} from './postbank-transfer-security.mjs';
|
||||
|
|
@ -157,6 +158,7 @@ export function createPostbankTasks(central,bank,settings,deps={}){
|
|||
}},
|
||||
{key:'credit_support',slot:now=>Math.floor(now/60000)*60000,run:()=>support.process()},
|
||||
{key:'standing_instructions',slot:now=>Math.floor(now/60000)*60000,run:()=>new PostbankStandingInstructions(bank,deps.authority||createPostbankAuthority(central,{bank}),deps).process()},
|
||||
{key:'staff_payroll',slot:now=>Math.floor(now/60000)*60000,run:()=>new PostbankPayroll(central,bank,deps).process()},
|
||||
{key:'statement_index',slot:now=>Math.floor(now/3600000)*3600000,run:()=>archives.seed()},
|
||||
{key:'statement_archives',slot:now=>Math.floor(now/60000)*60000,run:()=>archives.process()}
|
||||
];
|
||||
|
|
|
|||
37
website/node/postbank-payroll-accounts.mjs
Normal file
37
website/node/postbank-payroll-accounts.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {randomUUID} from 'node:crypto';
|
||||
import {entityId} from './postbank-authority.mjs';
|
||||
import {bankNumber,clientCandidate} from './postbank-catalogue.mjs';
|
||||
import {REGISTRY_ACTOR} from './postbank-registry.mjs';
|
||||
|
||||
// Internal payroll operation. The caller supplies a freshly verified staff
|
||||
// recipient and runs this inside the payroll transaction, never a public route.
|
||||
export async function ensurePayrollCurrentAccount(tx,recipient,{now=Date.now(),makeId=randomUUID}={}){
|
||||
if(!recipient?.id||!recipient.username)throw Error('A verified payroll recipient is required.');
|
||||
const id=entityId('person',recipient.id);
|
||||
await tx.query("INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,'person',?,?,1,?) ON DUPLICATE KEY UPDATE id=id",[id,recipient.id,recipient.username,now]);
|
||||
const entity=await tx.first('SELECT id,kind,active FROM pb_entities WHERE id=? FOR UPDATE',[id]);
|
||||
if(!entity||entity.kind!=='person'||Number(entity.active)!==1)throw Error('Personal banking identity needs review.');
|
||||
let client=await tx.first('SELECT client_number FROM pb_clients WHERE entity_id=? FOR UPDATE',[id]);
|
||||
if(client){
|
||||
const accounts=await tx.query('SELECT id,type_code,state,system_key FROM pb_accounts WHERE client_number=? ORDER BY id FOR UPDATE',[client.client_number]);
|
||||
const suitable=accounts.find(a=>!a.system_key&&a.state==='active'&&['102','108'].includes(a.type_code));
|
||||
if(suitable)return {accountId:String(suitable.id),created:false,entityId:id};
|
||||
// Do not evade an account restriction by opening another salary account.
|
||||
if(accounts.some(a=>['102','108'].includes(a.type_code)))throw Error('Existing personal current account needs review.');
|
||||
}else{
|
||||
for(let attempt=0;attempt<32;attempt++){
|
||||
const number=clientCandidate('person',recipient.id,attempt);
|
||||
try{await tx.query('INSERT INTO pb_clients(client_number,entity_id,created_at) VALUES(?,?,?)',[number,id,now]);client={client_number:number};break;}
|
||||
catch(error){if(error.code!=='ER_DUP_ENTRY')throw error;}
|
||||
}
|
||||
if(!client)throw Error('Personal client number could not be allocated.');
|
||||
}
|
||||
const packageId=makeId();
|
||||
await tx.query("INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,'pb_start',0,'payroll-provisioned-basic-v1',?,?,'active')",[packageId,client.client_number,REGISTRY_ACTOR,now]);
|
||||
const result=await tx.query("INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,'108',?,0,0,'active',?)",[client.client_number,packageId,recipient.username+' · Current',now]);
|
||||
const accountId=String(result.insertId);
|
||||
await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('108',Number(accountId)),accountId]);
|
||||
await tx.query('INSERT INTO pb_activations(entity_id,package_id) VALUES(?,?) ON DUPLICATE KEY UPDATE entity_id=entity_id',[id,packageId]);
|
||||
await tx.query("INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,'payroll_account_provisioned',?,?,?)",[makeId(),REGISTRY_ACTOR,id,JSON.stringify({recipientId:recipient.id,accountId,packageKey:'pb_start',typeCode:'108',openingBalanceMinor:0}),now]);
|
||||
return {accountId,created:true,entityId:id};
|
||||
}
|
||||
29
website/node/postbank-payroll-model.mjs
Normal file
29
website/node/postbank-payroll-model.mjs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
// Fictional DM payroll, inspired by published Belgian 2026 parameters. It is
|
||||
// deliberately not a real Belgian payslip calculator (no household deductions).
|
||||
export const DEFAULT_PAYROLL_POLICY=Object.freeze({enabled:false,payDay:28,netMinor:{officer:280000,branch_lead:336000,department_head:420000,executive:504000,owner_ceo:560000}});
|
||||
export const DEFAULT_PAYROLL_TAX=Object.freeze({employeeSocialBps:1307,employerSocialBps:2500,annualAllowanceMinor:1155000,bands:[{upToMinor:1672000,bps:2500},{upToMinor:2951000,bps:4000},{upToMinor:5107000,bps:4500},{upToMinor:null,bps:5000}],basisYear:2026,sources:['https://fin.belgium.be/en/private-individuals/tax-return/income/tax-rates','https://www.socialsecurity.be/site_nl/employer/infos/employers_nsso/which-contributions.htm']});
|
||||
export const PAYROLL_ROLE_WEIGHTS=Object.freeze({officer:1,branch_lead:2,department_head:3,executive:4,owner_ceo:5});
|
||||
const integer=(n,min,max)=>Number.isSafeInteger(n)&&n>=min&&n<=max;
|
||||
export function validatePayrollPolicy(p){
|
||||
if(!p||Object.keys(p).some(k=>!['enabled','payDay','netMinor'].includes(k))||typeof p.enabled!=='boolean'||!integer(p.payDay,1,28)||!p.netMinor||Object.keys(p.netMinor).length!==5)throw Error('Choose a payroll day of 1–28 and a net monthly wage for each function rank.');
|
||||
let previous=0;for(const role of Object.keys(PAYROLL_ROLE_WEIGHTS)){const amount=p.netMinor[role];if(!integer(amount,100,100000000)||amount<previous)throw Error('Net rank wages must increase with responsibility and use whole DM cents.');previous=amount;}
|
||||
return structuredClone(p);
|
||||
}
|
||||
export function validatePayrollTax(t){
|
||||
if(!t||Object.keys(t).some(k=>!['employeeSocialBps','employerSocialBps','annualAllowanceMinor','bands','basisYear','sources'].includes(k))||!integer(t.employeeSocialBps,0,4000)||!integer(t.employerSocialBps,0,10000)||!integer(t.annualAllowanceMinor,0,100000000)||!Array.isArray(t.bands)||t.bands.length!==4||!integer(t.basisYear,2020,2100))throw Error('Choose valid payroll tax parameters.');
|
||||
let last=0,rate=0;for(let i=0;i<t.bands.length;i++){const b=t.bands[i];if(!b||Object.keys(b).some(k=>!['upToMinor','bps'].includes(k))||!integer(b.bps,rate,7500)||i===3&&b.upToMinor!==null||i!==3&&!integer(b.upToMinor,last+1,10000000000))throw Error('Choose four ascending annual tax bands with an open final band.');last=b.upToMinor;rate=b.bps;}
|
||||
return {...structuredClone(t),sources:[...DEFAULT_PAYROLL_TAX.sources]};
|
||||
}
|
||||
const round=(n,d)=>(n+d/2n)/d;
|
||||
function annualTax(income,tax){let remaining=income,from=0n,total=0n;for(const band of tax.bands){const width=band.upToMinor===null?remaining:BigInt(band.upToMinor)-from,part=remaining<width?remaining:width;if(part>0n)total+=round(part*BigInt(band.bps),10000n);remaining-=part;if(remaining<=0n)break;from=BigInt(band.upToMinor);}return total;}
|
||||
export function payslipForGross(gross,tax=DEFAULT_PAYROLL_TAX){
|
||||
gross=BigInt(gross);if(gross<0n||gross>1000000000n)throw Error('Gross salary is outside the supported range.');
|
||||
const employeeSocial=round(gross*BigInt(tax.employeeSocialBps),10000n),taxable=gross-employeeSocial,credit=annualTax(BigInt(tax.annualAllowanceMinor),tax),annual=annualTax(taxable*12n,tax),incomeTax=round(annual>credit?annual-credit:0n,12n),employerSocial=round(gross*BigInt(tax.employerSocialBps),10000n),net=gross-employeeSocial-incomeTax;
|
||||
return {gross,employeeSocial,incomeTax,employerSocial,net,employerCost:gross+employerSocial,government:employeeSocial+incomeTax+employerSocial};
|
||||
}
|
||||
export function payslipForNet(target,tax=DEFAULT_PAYROLL_TAX){
|
||||
target=BigInt(target);if(target<100n||target>100000000n)throw Error('Choose a supported net salary.');let low=target,high=1000000000n;
|
||||
if(payslipForGross(high,tax).net<target)throw Error('The tax model cannot produce this net salary.');
|
||||
while(low<high){const mid=(low+high)/2n;if(payslipForGross(mid,tax).net<target)low=mid+1n;else high=mid;}
|
||||
const result=payslipForGross(low,tax);if(result.net!==target)throw Error('Exact net salary could not be represented.');return result;
|
||||
}
|
||||
84
website/node/postbank-payroll.mjs
Normal file
84
website/node/postbank-payroll.mjs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {validStaffRole} from './organisation-model.mjs';
|
||||
import {PAYROLL_ROLE_WEIGHTS,payslipForNet} from './postbank-payroll-model.mjs';
|
||||
import {readFinancialPolicy} from './postbank-financial-policy.mjs';
|
||||
import {ensurePayrollCurrentAccount} from './postbank-payroll-accounts.mjs';
|
||||
import {PostbankPayments} from './postbank-payments.mjs';
|
||||
import {REGISTRY_ACTOR} from './postbank-registry.mjs';
|
||||
export function payrollRecipients(rows){
|
||||
const people=new Map();
|
||||
for(const row of rows){
|
||||
if(row.role==='official_account'||Number(row.game_link_exempt)||!row.minecraft_uuid||!validStaffRole(row.scope_type,row.scope_key,row.role_key))continue;
|
||||
const previous=people.get(row.id);
|
||||
if(!previous||PAYROLL_ROLE_WEIGHTS[row.role_key]>PAYROLL_ROLE_WEIGHTS[previous.role_key])people.set(row.id,row);
|
||||
}
|
||||
const uuids=new Set();
|
||||
return [...people.values()].sort((a,b)=>PAYROLL_ROLE_WEIGHTS[b.role_key]-PAYROLL_ROLE_WEIGHTS[a.role_key]||a.id.localeCompare(b.id)).filter(row=>{
|
||||
const uuid=row.minecraft_uuid.toLowerCase();if(uuids.has(uuid))return false;uuids.add(uuid);return true;
|
||||
});
|
||||
}
|
||||
export async function readPayrollRecipients(central,now){
|
||||
return central.readSnapshot(async reader=>payrollRecipients(await reader.query("SELECT a.id,a.username,a.role,f.scope_type,f.scope_key,f.role_key,g.minecraft_uuid,pol.game_link_exempt FROM site_accounts a JOIN org_assignments f ON f.user_id=a.id JOIN site_game_links g ON g.user_id=a.id LEFT JOIN site_account_policies pol ON pol.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND a.role<>'official_account' AND f.status='active' AND f.starts_at<=? AND (f.ends_at IS NULL OR f.ends_at>?) ORDER BY a.id",[now,now])));
|
||||
}
|
||||
const calendar=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit',day:'2-digit'});
|
||||
export function payrollCalendar(now){const p=Object.fromEntries(calendar.formatToParts(new Date(now)).map(x=>[x.type,x.value]));return {period:p.year+'-'+p.month,day:Number(p.day)};}
|
||||
const stableId=key=>{const h=createHash('sha256').update('payroll:'+key).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);};
|
||||
const serialise=value=>JSON.stringify(value,(_,v)=>typeof v==='bigint'?String(v):v);
|
||||
export class PostbankPayroll{
|
||||
constructor(central,bank,{clock=Date.now}={}){this.central=central;this.bank=bank;this.clock=clock;}
|
||||
async overview(){
|
||||
const policy=await readFinancialPolicy(this.bank,'payroll'),tax=await readFinancialPolicy(this.bank,'payroll_tax'),recipients=await readPayrollRecipients(this.central,this.clock());
|
||||
const ranks=Object.keys(PAYROLL_ROLE_WEIGHTS).map(role=>({role,...JSON.parse(serialise(payslipForNet(policy.value.netMinor[role],tax.value)))}));
|
||||
const records=await this.bank.query('SELECT i.period,i.actor_name,i.amount_minor,i.state,a.account_number FROM pb_payroll_items i LEFT JOIN pb_accounts a ON a.id=i.account_id ORDER BY i.period DESC,i.actor_name LIMIT 100');
|
||||
return {policy,taxVersion:tax.version,ranks,eligibleCount:recipients.length,records};
|
||||
}
|
||||
async process({rollout=false}={}){
|
||||
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 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;
|
||||
for(const person of recipients){
|
||||
const slip=payslipForNet(policy.value.netMinor[person.role_key],tax.value);
|
||||
await tx.query("INSERT INTO pb_payroll_items(period,actor_id,actor_name,account_id,order_id,amount_minor,state,created_at) VALUES(?,?,?,NULL,NULL,?,'pending',?)",[period,person.id,person.username,String(slip.net),now]);
|
||||
await tx.query('INSERT INTO pb_payroll_payslips(period,actor_id,details_json) VALUES(?,?,?)',[period,person.id,serialise({recipient:person,role:person.role_key,policyVersion:policy.version,taxVersion:tax.version,tax:tax.value,...slip})]);
|
||||
}
|
||||
await tx.query("UPDATE pb_payroll_runs SET state='running' WHERE period=?",[period]);
|
||||
});
|
||||
const items=await this.bank.query("SELECT actor_id FROM pb_payroll_items WHERE period=? AND state='pending' ORDER BY actor_id",[period]);
|
||||
let paid=0,failed=0;
|
||||
for(const item of items){try{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};
|
||||
}
|
||||
async pay(period,actorId){
|
||||
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;
|
||||
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());
|
||||
if(!eligible.some(p=>p.id===actorId&&PAYROLL_ROLE_WEIGHTS[p.role_key]>=PAYROLL_ROLE_WEIGHTS[slip.role]&&p.minecraft_uuid.toLowerCase()===slip.recipient.minecraft_uuid.toLowerCase()))throw Error('Payroll recipient requires review.');
|
||||
const destination=await ensurePayrollCurrentAccount(tx,slip.recipient,{now:this.clock()});
|
||||
const accounts=await tx.query("SELECT * FROM pb_accounts WHERE system_key IN ('sys_web_treasury','sys_payroll_po','sys_tax_treasury') OR id=? ORDER BY id FOR UPDATE",[destination.accountId]);
|
||||
const source=accounts.find(a=>a.system_key==='sys_web_treasury'),po=accounts.find(a=>a.system_key==='sys_payroll_po'),tax=accounts.find(a=>a.system_key==='sys_tax_treasury'),target=accounts.find(a=>String(a.id)===destination.accountId);
|
||||
if(!source||!po||!tax||!target||accounts.some(a=>a.state!=='active')||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<BigInt(slip.employerCost))throw Error('Payroll funds or accounts require attention.');
|
||||
const payments=new PostbankPayments(this.bank,async()=>{throw Error('Internal payroll only');},{clock:this.clock});
|
||||
const move=async(from,to,amount,leg)=>{
|
||||
amount=BigInt(amount);if(!amount)return;
|
||||
const id=stableId(period+':'+actorId+':'+leg),fingerprint=createHash('sha256').update(serialise([period,actorId,leg,String(amount)])).digest('hex');
|
||||
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'payroll','queued',?)",[id,REGISTRY_ACTOR,from.id,to.id,fingerprint,String(amount),'P&O '+period+' · '+leg,this.clock()]);
|
||||
await payments.post(tx,{id,actor_id:REGISTRY_ACTOR,amount_minor:String(amount)},{...from,entity_id:null},to,false);
|
||||
from.balance_minor=String(BigInt(from.balance_minor)-amount);to.balance_minor=String(BigInt(to.balance_minor)+amount);return id;
|
||||
};
|
||||
await move(source,po,slip.employerCost,'employer funding');
|
||||
const orderId=await move(po,target,slip.net,'net salary');
|
||||
await move(po,tax,slip.government,'social and income tax');
|
||||
await tx.query("UPDATE pb_payroll_items SET state='paid',account_id=?,order_id=? WHERE period=? AND actor_id=?",[destination.accountId,orderId,period,actorId]);return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -189,3 +189,17 @@ CREATE TABLE IF NOT EXISTS pb_standing_instructions (
|
|||
enabled INT NOT NULL DEFAULT 0, version INT NOT NULL DEFAULT 1,
|
||||
updated_by CHAR(36) NOT NULL, updated_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_financial_policies (
|
||||
policy_key VARCHAR(40) PRIMARY KEY, policy_json TEXT NOT NULL,
|
||||
version INT NOT NULL DEFAULT 1, updated_by CHAR(36) NOT NULL, updated_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_rate_publications (
|
||||
id CHAR(36) PRIMARY KEY, data_json TEXT NOT NULL, pdf_blob MEDIUMBLOB NULL,
|
||||
state VARCHAR(16) NOT NULL DEFAULT 'pending', lease_token CHAR(36) NOT NULL DEFAULT '',
|
||||
lease_until BIGINT NOT NULL DEFAULT 0, retry_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_by CHAR(36) NOT NULL, created_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_payroll_payslips (
|
||||
period CHAR(7) NOT NULL, actor_id CHAR(36) NOT NULL, details_json TEXT NOT NULL,
|
||||
PRIMARY KEY(period,actor_id), FOREIGN KEY(period) REFERENCES pb_payroll_runs(period)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
|
|
|||
18
website/scripts/rollout-postbank-payroll.mjs
Normal file
18
website/scripts/rollout-postbank-payroll.mjs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import {fileURLToPath} from 'node:url';import {resolve} from 'node:path';
|
||||
import {openDatabase} from '../node/mysql.mjs';import {openPostbankDatabase} from '../node/postbank-db.mjs';
|
||||
import {canRunScheduler} from '../node/scheduler-authority.mjs';import {PostbankPayroll} from '../node/postbank-payroll.mjs';
|
||||
import {PostbankFinancialPolicies} from '../node/postbank-financial-policy.mjs';import {createPostbankAuthority} from '../node/postbank-authority.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){
|
||||
const central=await openDatabase(process.env),bank=await openPostbankDatabase(process.env);
|
||||
try{
|
||||
const user={id:process.argv.find(a=>a.startsWith('--actor='))?.slice(8)};
|
||||
if(!bank||!await canRunScheduler(central,user))throw Error('Current Big Four or deployment service control is required.');
|
||||
const payroll=new PostbankPayroll(central,bank),preview=await payroll.overview();
|
||||
if(!process.argv.includes('--apply'))console.log(JSON.stringify({plan:true,eligibleStaff:preview.eligibleCount,enabled:preview.policy.value.enabled,payDay:preview.policy.value.payDay,missingAccountPackage:'pb_start',missingAccountType:'108'}));
|
||||
else{
|
||||
if(!preview.policy.value.enabled)await new PostbankFinancialPolicies(bank,central,createPostbankAuthority(central,{bank})).save(user,'payroll',{requestId:randomUUID(),version:preview.policy.version,value:{...preview.policy.value,enabled:true},reason:'Owner-authorised P&O rollout and initial payroll tick',confirmed:true});
|
||||
console.log(JSON.stringify(await payroll.process({rollout:true})));
|
||||
}
|
||||
}finally{await bank?.close();await central.close();}
|
||||
}
|
||||
36
website/tests/postbank-payroll-accounts.test.mjs
Normal file
36
website/tests/postbank-payroll-accounts.test.mjs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {ensurePayrollCurrentAccount} from '../node/postbank-payroll-accounts.mjs';
|
||||
const recipient={id:'f3ffda37-01e4-41ea-b89d-fbeda82e453e',username:'unimatrix999'};
|
||||
function fixture(accounts=[],hasClient=true){
|
||||
const writes=[];return {writes,
|
||||
async first(sql){return sql.includes('FROM pb_entities')?{id:'personal',kind:'person',active:1}:hasClient?{client_number:'123456789012'}:null;},
|
||||
async query(sql,args){if(sql.startsWith('SELECT'))return accounts;writes.push({sql,args});return {insertId:77};}
|
||||
};
|
||||
}
|
||||
test('payroll reuses an existing personal current account without opening a package',async()=>{
|
||||
const tx=fixture([{id:19,type_code:'102',state:'active',system_key:null}]);
|
||||
const result=await ensurePayrollCurrentAccount(tx,recipient);
|
||||
assert.equal(result.accountId,'19');assert.equal(result.created,false);
|
||||
assert.equal(tx.writes.some(w=>w.sql.includes('INSERT INTO pb_packages')),false);
|
||||
});
|
||||
test('a missing personal account receives free Start 108 with zero opening funds',async()=>{
|
||||
const tx=fixture([],false),result=await ensurePayrollCurrentAccount(tx,recipient);
|
||||
assert.equal(result.created,true);
|
||||
const pkg=tx.writes.find(w=>w.sql.includes('INSERT INTO pb_packages'));
|
||||
assert.match(pkg.sql,/'pb_start',0/);assert.match(pkg.sql,/payroll-provisioned-basic/);
|
||||
const account=tx.writes.find(w=>w.sql.includes('INSERT INTO pb_accounts'));
|
||||
assert.match(account.sql,/'108'/);assert.match(account.sql,/,0,0,'active'/);
|
||||
assert.equal(tx.writes.some(w=>w.sql.includes('pb_entries')||w.sql.includes('pb_orders')),false);
|
||||
assert.equal(tx.writes.some(w=>w.sql.includes('979')),false);
|
||||
});
|
||||
test('blocked personal accounts require review rather than a replacement',async()=>{
|
||||
const tx=fixture([{id:19,type_code:'108',state:'blocked',system_key:null}]);
|
||||
await assert.rejects(ensurePayrollCurrentAccount(tx,recipient),/needs review/);
|
||||
assert.equal(tx.writes.some(w=>w.sql.includes('INSERT INTO pb_packages')),false);
|
||||
});
|
||||
test('an official account is not selected as the personal salary destination',async()=>{
|
||||
const tx=fixture([{id:19,type_code:'979',state:'active',system_key:null}]);
|
||||
const result=await ensurePayrollCurrentAccount(tx,recipient);
|
||||
assert.equal(result.created,true);assert.equal(result.accountId,'77');
|
||||
});
|
||||
23
website/tests/postbank-payroll-api.test.mjs
Normal file
23
website/tests/postbank-payroll-api.test.mjs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import {test} from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {BankFixture} from './postbank-fixture.mjs';import {createPostbankApi} from '../node/postbank-api.mjs';import {DEFAULT_PAYROLL_POLICY} from '../node/postbank-payroll-model.mjs';
|
||||
function fixture(principal='owner'){
|
||||
const bank=new BankFixture(),user={id:randomUUID(),username:'QA'};
|
||||
const central={prepare(sql){return {bind(){return this;},async first(){return sql.includes('org_control_principals')?{principal_kind:principal}:null;},async all(){return {results:[]};}};},readSnapshot:async work=>work({query:async()=>[]})};
|
||||
const api=createPostbankApi(central,bank,{}, {authenticate:async()=>user,authority:async()=>({entities:[],readAdmin:true,manageAdmin:true})});
|
||||
const origin='https://cp.dunerealms.com',send=(body,from=origin)=>api(new Request(origin+'/api/bank/admin/payroll',body?{method:'POST',headers:{origin:from,'Content-Type':'application/json'},body:JSON.stringify(body)}:{}));
|
||||
return {bank,send};
|
||||
}
|
||||
test('general bank management cannot read or edit private P&O payroll',async()=>{
|
||||
const f=fixture('department_head');try{assert.equal((await f.send()).status,403);assert.equal((await f.send({confirmed:true})).status,403);}finally{f.bank.close();}
|
||||
});
|
||||
test('Big Four payroll edits enforce origin, policy version and idempotency',async()=>{
|
||||
const f=fixture();try{
|
||||
const initial=await (await f.send()).json();assert.equal(initial.policy.value.enabled,false);
|
||||
const payload={requestId:randomUUID(),version:0,value:{...DEFAULT_PAYROLL_POLICY,enabled:true},reason:'P&O rollout policy test',confirmed:true};
|
||||
assert.equal((await f.send(payload,'https://evil.invalid')).status,403);
|
||||
assert.equal((await f.send(payload)).status,200);assert.equal((await f.send(payload)).status,200);
|
||||
assert.equal((await f.send({...payload,requestId:randomUUID()})).status,409);
|
||||
assert.equal((await f.bank.first("SELECT COUNT(*) n FROM pb_audit WHERE action='financial_policy_changed'")).n,1);
|
||||
assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
|
||||
}finally{f.bank.close();}
|
||||
});
|
||||
4
website/tests/postbank-payroll-model.test.mjs
Normal file
4
website/tests/postbank-payroll-model.test.mjs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {DEFAULT_PAYROLL_POLICY,DEFAULT_PAYROLL_TAX,validatePayrollPolicy,validatePayrollTax,payslipForGross,payslipForNet} from '../node/postbank-payroll-model.mjs';
|
||||
test('every configured rank has an exact net salary and conserved employer cost',()=>{for(const net of Object.values(DEFAULT_PAYROLL_POLICY.netMinor)){const p=payslipForNet(net);assert.equal(p.net,BigInt(net));assert.equal(p.employerCost,p.net+p.government);assert.ok(p.gross>p.net);assert.ok(p.employeeSocial>0n&&p.incomeTax>0n&&p.employerSocial>0n);}});
|
||||
test('tax band and contribution rounding never creates a negative salary step',()=>{for(const center of [1672000,2951000,5107000]){const gross=Number(payslipForNet(Math.round(center/12)).gross);let previous=payslipForGross(gross-100).net;for(let n=gross-99;n<gross+100;n++){const next=payslipForGross(n).net;assert.ok(next>=previous);assert.ok(next-previous<=1n);previous=next;}}});
|
||||
test('zero rates produce exact gross/net equality while invalid policies are rejected',()=>{const tax=validatePayrollTax({...DEFAULT_PAYROLL_TAX,employeeSocialBps:0,employerSocialBps:0,bands:DEFAULT_PAYROLL_TAX.bands.map(b=>({...b,bps:0}))});assert.equal(payslipForNet(280000,tax).gross,280000n);assert.throws(()=>validatePayrollPolicy({...DEFAULT_PAYROLL_POLICY,payDay:31}));assert.throws(()=>validatePayrollPolicy({...DEFAULT_PAYROLL_POLICY,netMinor:{...DEFAULT_PAYROLL_POLICY.netMinor,owner_ceo:10}}));assert.throws(()=>validatePayrollTax({...DEFAULT_PAYROLL_TAX,bands:[{upToMinor:null,bps:11000}]}));});
|
||||
48
website/tests/postbank-payroll.test.mjs
Normal file
48
website/tests/postbank-payroll.test.mjs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import {test} from 'node:test';import assert from 'node:assert/strict';
|
||||
import {payrollRecipients,payrollCalendar,PostbankPayroll} from '../node/postbank-payroll.mjs';
|
||||
import {BankFixture} from './postbank-fixture.mjs';
|
||||
import {DEFAULT_PAYROLL_POLICY} from '../node/postbank-payroll-model.mjs';
|
||||
const officer=(id,uuid)=>({id,username:id,role:'user',minecraft_uuid:uuid,scope_type:'branch',scope_key:'customer_support',role_key:'officer',game_link_exempt:0});
|
||||
test('department count never stacks wages and the highest valid rank wins',()=>{
|
||||
const rows=[officer('one','abc'),{...officer('one','abc'),scope_type:'department',scope_key:'community_operations',role_key:'department_head'},officer('two','def')];
|
||||
const recipients=payrollRecipients(rows);assert.equal(recipients.length,2);assert.equal(recipients[0].role_key,'department_head');
|
||||
});
|
||||
test('official, exempt, unlinked and invalid appointments cannot receive payroll',()=>{
|
||||
const rows=[{...officer('official','a'),role:'official_account'},{...officer('dev','b'),game_link_exempt:1},{...officer('unlinked',''),minecraft_uuid:null},{...officer('invalid','c'),scope_key:'nonexistent'}];
|
||||
assert.deepEqual(payrollRecipients(rows),[]);
|
||||
});
|
||||
test('duplicate linked game identities receive only one highest-rank salary',()=>{
|
||||
const rows=[officer('one','ABC'),{...officer('two','abc'),scope_type:'department',scope_key:'community_operations',role_key:'department_head'}];
|
||||
assert.deepEqual(payrollRecipients(rows).map(p=>p.id),['two']);
|
||||
});
|
||||
test('payroll period follows Brussels calendar across UTC month boundaries',()=>{
|
||||
assert.deepEqual(payrollCalendar(Date.parse('2026-11-30T23:30:00Z')),{period:'2026-12',day:1});
|
||||
});
|
||||
async function payrollFixture(balance=10000000){
|
||||
const bank=new BankFixture(),person=officer('f3ffda37-01e4-41ea-b89d-fbeda82e453e','abc');
|
||||
const central={readSnapshot:async work=>work({query:async()=>[person]})};
|
||||
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}),person.id]);
|
||||
for(const [key,amount] of [['sys_web_treasury',balance],['sys_payroll_po',0],['sys_tax_treasury',0]])await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,'979',?,?,0,'active',0)",[key,key,amount]);
|
||||
return {bank,service:new PostbankPayroll(central,bank,{clock:()=>Date.parse('2026-11-15T12:00:00Z')})};
|
||||
}
|
||||
test('rollout creates basic personal account, pays once, and conserves all bank funds',async()=>{
|
||||
const {bank,service}=await payrollFixture();try{
|
||||
assert.equal((await service.process()).notDue,true);
|
||||
const results=await Promise.all([service.process({rollout:true}),service.process({rollout:true})]);
|
||||
assert.equal(results.reduce((n,r)=>n+r.paid,0),1);
|
||||
assert.equal((await bank.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='108'")).n,1);
|
||||
assert.equal((await bank.first("SELECT balance_minor FROM pb_accounts WHERE type_code='108'")).balance_minor,280000);
|
||||
assert.equal((await bank.first('SELECT SUM(balance_minor) n FROM pb_accounts')).n,10000000);
|
||||
assert.equal((await bank.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_payroll_po'")).balance_minor,0);
|
||||
assert.equal((await bank.first('SELECT COUNT(*) n FROM pb_orders')).n,3);
|
||||
assert.equal((await service.process({rollout:true})).paid,0);
|
||||
}finally{bank.close();}
|
||||
});
|
||||
test('insufficient employer funds roll back account creation and every payment leg',async()=>{
|
||||
const {bank,service}=await payrollFixture(100);try{
|
||||
assert.equal((await service.process({rollout:true})).failed,1);
|
||||
assert.equal((await bank.first("SELECT COUNT(*) n FROM pb_accounts WHERE type_code='108'")).n,0);
|
||||
assert.equal((await bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
|
||||
assert.equal((await bank.first('SELECT SUM(balance_minor) n FROM pb_accounts')).n,100);
|
||||
}finally{bank.close();}
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff