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 {postPayrollIssue} from './postbank-payroll-issuer.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);}; export const payrollOrderId=(period,actorId,leg)=>stableId(period+':'+actorId+':'+leg); 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'); const extra=await this.bank.query('SELECT r.calendar_period AS period,i.period AS cycleId,i.actor_name,i.amount_minor,i.state,a.account_number FROM pb_payroll_additional_items i JOIN pb_payroll_additional_runs r ON r.period=i.period LEFT JOIN pb_accounts a ON a.id=i.account_id ORDER BY r.created_at DESC,i.actor_name LIMIT 100'); return {policy,taxVersion:tax.version,ranks,eligibleCount:recipients.length,records:[...extra.map(row=>({...row,additional:true})),...records].slice(0,100)}; } async process({rollout=false,additionalCycleId=null,beforePrepare=async()=>{},beforePay=async()=>{}}={}){ const now=this.clock(),calendar=payrollCalendar(now),{day}=calendar,period=additionalCycleId||calendar.period,tables=additionalCycleId?{runs:'pb_payroll_additional_runs',items:'pb_payroll_additional_items',slips:'pb_payroll_additional_payslips'}:{runs:'pb_payroll_runs',items:'pb_payroll_items',slips:'pb_payroll_payslips'},policy=await readFinancialPolicy(this.bank,'payroll'); if(!policy.value.enabled||!rollout&&day{ await beforePrepare(tx,{period,policyVersion:policy.version,taxVersion:tax.version}); if(!additionalCycleId)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 ${tables.runs} WHERE period=? FOR UPDATE`,[period]); if(!run)throw Error('Additional wage cycle was not confirmed.'); 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 ${tables.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 ${tables.slips}(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 ${tables.runs} SET state='running' WHERE period=?`,[period]); }); const items=await this.bank.query(`SELECT actor_id FROM ${tables.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,{beforePay,additional:!!additionalCycleId}))paid++;}catch{failed++;}} if(!failed)await this.bank.query(`UPDATE ${tables.runs} SET state='completed' WHERE period=? AND NOT EXISTS (SELECT 1 FROM ${tables.items} WHERE period=? AND state='pending')`,[period,period]); return {period,paid,failed}; } async pay(period,actorId,{additional=false,beforePay=async()=>{}}={}){ const tables=additional?{items:'pb_payroll_additional_items',slips:'pb_payroll_additional_payslips'}:{items:'pb_payroll_items',slips:'pb_payroll_payslips'}; return this.bank.transaction(async tx=>{ const item=await tx.first(`SELECT * FROM ${tables.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 ${tables.slips} 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_payroll_po','sys_tax_treasury') OR id=? ORDER BY id FOR UPDATE",[destination.accountId]); const 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(!po||!tax||!target||accounts.some(a=>a.state!=='active'))throw Error('Payroll funds or accounts require attention.'); 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 '+(additional?'additional '+period:period)+' ยท '+leg,this.clock()]); await postPayrollIssue(tx,{id,actor_id:REGISTRY_ACTOR,amount_minor:String(amount)},from,to,{now:this.clock()}); from.balance_minor=String(BigInt(from.balance_minor)-amount);to.balance_minor=String(BigInt(to.balance_minor)+amount);return id; }; const orderId=await move(po,target,slip.net,'net salary'); await move(po,tax,slip.government,'social and income tax'); await tx.query(`UPDATE ${tables.items} SET state='paid',account_id=?,order_id=? WHERE period=? AND actor_id=?`,[destination.accountId,orderId,period,actorId]);return true; }); } }