import {bankRecipientAllowed} from './postbank-recipient-policy.mjs'; import {createHash,randomUUID} from 'node:crypto';import {BankError} from './postbank-service.mjs';import {validBankNumber} from './postbank-catalogue.mjs'; const uuid=s=>typeof s==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(s); export class PostbankBeneficiaries{ constructor(db,{clock=Date.now,canInspectAll=async()=>false}={}){this.db=db;this.clock=clock;this.canInspectAll=canInspectAll;} async list(user){const all=await this.canInspectAll(user);const rows=await this.db.query('SELECT b.id,b.label,b.created_at,a.account_number,a.display_name,a.state,a.type_code,a.system_key,p.state package_state,e.active entity_active,e.display_name holder FROM pb_beneficiaries b JOIN pb_accounts a ON a.id=b.account_id LEFT JOIN pb_packages p ON p.id=a.package_id LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id WHERE b.owner_id=? ORDER BY b.label,b.id',[user.id]);return {beneficiaries:rows.map(r=>({id:r.id,label:r.label,number:r.account_number,name:r.display_name,holder:r.holder||r.display_name,active:bankRecipientAllowed(r,all),createdAt:Number(r.created_at)}))};} async write(user,input,remove=false,{revalidate=async()=>user}={}){ const allowed=remove?['requestId','beneficiaryId']:['requestId','number','label'];if(!input||Object.keys(input).some(k=>!allowed.includes(k))||!uuid(input.requestId))throw new BankError('Complete the beneficiary details.'); const number=typeof input.number==='string'?input.number.replace(/\s/g,'').toUpperCase():null; if(remove?!uuid(input.beneficiaryId):!validBankNumber(number)||typeof input.label!=='string'||!input.label.trim()||input.label.trim().length>80||/[\u0000-\u001f]/.test(input.label))throw new BankError(remove?'Select a saved beneficiary.':'Use a verified account number and a name of 1–80 characters.'); const fingerprint=createHash('sha256').update(JSON.stringify([user.id,remove?'remove':'save',remove?input.beneficiaryId:number,remove?'':input.label.trim()])).digest('hex'); return this.db.transaction(async tx=>{ // Serialise address-book writes for this actor, including simultaneous replay. await tx.query('INSERT INTO pb_contact_locks(owner_id) VALUES(?) ON DUPLICATE KEY UPDATE owner_id=VALUES(owner_id)',[user.id]);await tx.first('SELECT owner_id FROM pb_contact_locks WHERE owner_id=? FOR UPDATE',[user.id]); const previous=await tx.first('SELECT actor_id,action,details FROM pb_audit WHERE id=?',[input.requestId]);if(previous){let details;try{details=JSON.parse(previous.details);}catch{}if(previous.actor_id!==user.id||previous.action!=='beneficiary_changed'||details?.fingerprint!==fingerprint)throw new BankError('This request number was already used.',409);return {ok:true,replayed:true};} const fresh=await revalidate();if(!fresh||fresh.id!==user.id)throw new BankError('Your session changed. The beneficiary was not modified.',409); let account=null; if(remove)await tx.query('DELETE FROM pb_beneficiaries WHERE id=? AND owner_id=?',[input.beneficiaryId,user.id]); else{ account=await tx.first("SELECT a.id,a.state,a.type_code,a.system_key,p.state package_state,e.active entity_active FROM pb_accounts a LEFT JOIN pb_packages p ON p.id=a.package_id LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id WHERE a.account_number=?",[number]); if(!bankRecipientAllowed(account,await this.canInspectAll(fresh)))throw new BankError('This account is not available as a beneficiary.',409); const count=await tx.first('SELECT COUNT(*) n FROM pb_beneficiaries WHERE owner_id=?',[user.id]),existing=await tx.first('SELECT id FROM pb_beneficiaries WHERE owner_id=? AND account_id=?',[user.id,account.id]);if(Number(count.n)>=100&&!existing)throw new BankError('You can save up to 100 beneficiaries. Remove an old entry first.',409); const now=this.clock();await tx.query('INSERT INTO pb_beneficiaries(id,owner_id,account_id,label,created_at,updated_at) VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE label=VALUES(label),updated_at=VALUES(updated_at)',[randomUUID(),user.id,account.id,input.label.trim(),now,now]); } const final=await revalidate();if(!final||final.id!==user.id||account&&!bankRecipientAllowed(account,await this.canInspectAll(final)))throw new BankError('Your session changed. The beneficiary was not modified.',409); await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[input.requestId,user.id,'beneficiary_changed',null,JSON.stringify({operation:remove?'remove':'save',fingerprint}),this.clock()]);return {ok:true,replayed:false}; }); } }