import {randomUUID,createHash} from 'node:crypto'; import {BankError} from './postbank-service.mjs';import {PostbankPayments} from './postbank-payments.mjs'; import {money,minorAmount} from './postbank-catalogue.mjs'; const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); export const COMPENSATION_RESERVE='sys_service_compensation'; const eligible=a=>a&&!a.system_key&&a.state==='active'&&a.type_code!=='106'&&Number(a.entity_active)===1&&a.package_state==='active'; const accountsSQL='SELECT a.*,c.entity_id,e.kind entity_kind,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id'; export class PostbankCompensation{ constructor(db,authority,{clock=Date.now}={}){this.db=db;this.authority=authority;this.clock=clock;} async access(user,store=this.db){const c=await this.authority(user,{bank:store});if(!c.readAdmin||!c.manageAdmin&&!c.manageClients)throw new BankError('Bank client management permission is required.',403);return c;} async overview(user){await this.access(user);const row=await this.db.first('SELECT account_number,balance_minor,reserved_minor FROM pb_accounts WHERE system_key=?',[COMPENSATION_RESERVE]);return {reserve:row?{number:row.account_number,balance:money(row.balance_minor),available:money(BigInt(row.balance_minor)-BigInt(row.reserved_minor))}:null};} async pay(user,input,{revalidate=async()=>user}={}){ await this.access(user); if(!input||Object.keys(input).some(k=>!['requestId','paymentId','amount','reason','confirmed'].includes(k))||!uuid(input.requestId)||!uuid(input.paymentId)||input.confirmed!==true||typeof input.reason!=='string'||input.reason.trim().length<5||input.reason.trim().length>100||/[\u0000-\u001f]/.test(input.reason))throw new BankError('Confirm the original payment, compensation amount and a reason of 5–100 characters.'); let amount;try{amount=minorAmount(input.amount);}catch(e){throw new BankError(e.message);} const reason=input.reason.trim(),fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.paymentId,String(amount),reason,'service'])).digest('hex'); return this.db.transaction(async tx=>{ const meta=await tx.first('SELECT source_id,target_id FROM pb_orders WHERE id=?',[input.paymentId]);if(!meta)throw new BankError('Original payment not found.',404); const entities=await tx.query('SELECT c.entity_id FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE a.id IN (?,?) ORDER BY c.entity_id',[meta.source_id,meta.target_id]); for(const id of [...new Set(entities.map(e=>e.entity_id))].sort())await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]); const original=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[input.paymentId]); const rows=await tx.query(accountsSQL+' WHERE a.id IN (?,?) OR a.system_key=? ORDER BY a.id FOR UPDATE',[original.source_id,original.target_id,COMPENSATION_RESERVE]); const beneficiary=rows.find(a=>String(a.id)===String(original.source_id)),recovery=rows.find(a=>String(a.id)===String(original.target_id)),reserve=rows.find(a=>a.system_key===COMPENSATION_RESERVE); const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed.',403);const rights=await this.access(fresh,tx); const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint)throw new BankError('This request reference was already used.',409);return {ok:true,replayed:true,paymentId:prior.id,state:prior.state};} if(original.state!=='posted'||!['standard','instant'].includes(original.mode)||String(original.source_id)===String(original.target_id)||!eligible(beneficiary)||!eligible(recovery))throw new BankError('Select a posted customer transfer between available accounts.',409); if(!rights.manageAdmin&&[beneficiary,recovery].some(a=>['house','office','staff'].includes(a.entity_kind)))throw new BankError('Official account compensation requires bank management.',403); // Locking reads must bypass an older MySQL REPEATABLE READ snapshot when // another correction committed while this transaction waited on the payer. const corrections=await tx.query('SELECT amount_minor FROM pb_service_compensations WHERE original_order_id=? FOR UPDATE',[original.id]),used=corrections.reduce((n,row)=>n+BigInt(row.amount_minor),0n); if(amount>BigInt(original.amount_minor)-used)throw new BankError('Compensation exceeds the uncompensated amount of this payment.',409); const recoverable=BigInt(recovery.balance_minor)-BigInt(recovery.reserved_minor)>=amount; const source=recoverable?recovery:reserve,funding=recoverable?'recovery':'reserve'; if(!source||source.state!=='active'||BigInt(source.balance_minor)-BigInt(source.reserved_minor)