import {createHash,randomUUID} from 'node:crypto';import {BankError} from './postbank-service.mjs';import {PostbankPayments} from './postbank-payments.mjs';import {REGISTRY_ACTOR} from './postbank-registry.mjs';import {minorAmount,money,bankNumber} from './postbank-catalogue.mjs'; export const COMPENSATION_INSTRUCTION='monthly_service_compensation'; const reserve='sys_service_compensation',treasury='sys_web_treasury'; const calendar=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit'}); export const instructionPeriod=now=>{const parts=Object.fromEntries(calendar.formatToParts(new Date(now)).map(p=>[p.type,p.value]));return parts.year+'-'+parts.month;}; function orderId(key){const h=createHash('sha256').update(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 class PostbankStandingInstructions{ constructor(db,authority,{clock=Date.now}={}){this.db=db;this.authority=authority;this.clock=clock;} async access(user,store=this.db){const rights=await this.authority(user,{bank:store});if(!rights.readAdmin||!rights.manageAdmin)throw new BankError('Bank management permission is required.',403);} async overview(user){await this.access(user);const row=await this.db.first('SELECT * FROM pb_standing_instructions WHERE instruction_key=?',[COMPENSATION_INSTRUCTION]);return {instruction:row?{key:row.instruction_key,amount:money(row.amount_minor),enabled:!!Number(row.enabled),version:Number(row.version),source:'Website bank treasury',target:'Service compensation reserve',frequency:'Monthly · unspent funds carry forward'}:null};} async save(user,input,{revalidate=async()=>user}={}){ await this.access(user);if(!input||Object.keys(input).some(k=>!['requestId','amount','enabled','version','reason','confirmed'].includes(k))||! /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(input.requestId||'')||typeof input.enabled!=='boolean'||!Number.isSafeInteger(input.version)||input.version<1||input.confirmed!==true||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.trim().length>140||/[\u0000-\u001f]/.test(input.reason))throw new BankError('Confirm the monthly funding amount, current instruction version and reason.'); let amount;try{amount=minorAmount(input.amount);}catch(e){throw new BankError(e.message);}const fingerprint=JSON.stringify([user.id,String(amount),input.enabled,input.version,input.reason.trim()]); return this.db.transaction(async tx=>{ const current=await tx.first('SELECT * FROM pb_standing_instructions WHERE instruction_key=? FOR UPDATE',[COMPENSATION_INSTRUCTION]); const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);await this.access(fresh,tx); 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!=='standing_instruction_changed'||JSON.parse(prior.details).fingerprint!==fingerprint)throw new BankError('Request reference already used.',409);return {ok:true,replayed:true};} if(!current||Number(current.version)!==input.version)throw new BankError('The instruction changed. Reload before editing.',409); await tx.query('UPDATE pb_standing_instructions SET amount_minor=?,enabled=?,version=version+1,updated_by=?,updated_at=? WHERE instruction_key=?',[String(amount),input.enabled?1:0,user.id,this.clock(),COMPENSATION_INSTRUCTION]); await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[input.requestId,user.id,'standing_instruction_changed',JSON.stringify({fingerprint,amountDM:money(amount),enabled:input.enabled,reason:input.reason.trim()}),this.clock()]);return {ok:true,replayed:false}; }); } async process(){const period=instructionPeriod(this.clock()); try{return await this.db.transaction(async tx=>{ const instruction=await tx.first('SELECT * FROM pb_standing_instructions WHERE instruction_key=? FOR UPDATE',[COMPENSATION_INSTRUCTION]);if(!instruction||!Number(instruction.enabled))return {funded:0,failed:0}; if(instruction.source_key!==treasury||instruction.target_key!==reserve||BigInt(instruction.amount_minor)<=0n)throw Error('Invalid service funding mandate'); const id=orderId('standing:'+COMPENSATION_INSTRUCTION+':'+period),previous=await tx.first('SELECT state FROM pb_orders WHERE id=? FOR UPDATE',[id]);if(previous){if(previous.state!=='posted')throw Error('Funding requires reconciliation');return {funded:0,failed:0};} const accounts=await tx.query('SELECT * FROM pb_accounts WHERE system_key IN (?,?) ORDER BY id FOR UPDATE',[treasury,reserve]),source=accounts.find(a=>a.system_key===treasury),target=accounts.find(a=>a.system_key===reserve),amount=BigInt(instruction.amount_minor); if(!source||!target||source.state!=='active'||target.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor){ const now=clock();await tx.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,'979','Service compensation reserve',0,0,'active',?) ON DUPLICATE KEY UPDATE system_key=VALUES(system_key)",[reserve,now]); const account=await tx.first('SELECT id,account_number FROM pb_accounts WHERE system_key=? FOR UPDATE',[reserve]);if(!account.account_number)await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('979',Number(account.id)),account.id]); const existing=await tx.first('SELECT instruction_key FROM pb_standing_instructions WHERE instruction_key=? FOR UPDATE',[COMPENSATION_INSTRUCTION]); if(!existing){await tx.query('INSERT INTO pb_standing_instructions(instruction_key,source_key,target_key,amount_minor,enabled,version,updated_by,updated_at) VALUES(?,?,?,2500000,1,1,?,?)',[COMPENSATION_INSTRUCTION,treasury,reserve,actorId,now]);await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,NULL,?,?)',[randomUUID(),actorId,'service_reserve_configured',JSON.stringify({accountId:String(account.id),monthlyDM:'25000.00',reason:'Owner approved shared compensation reserve with monthly standing funding and rollover'}),now]);} return {applied:true,created:!existing,accountId:String(account.id)}; }); }