Scope wire-transfer picker and paginate all permitted beneficiary matches

This commit is contained in:
unimatrixgit 2026-11-15 20:30:17 +01:00
commit f2ab25aab9
6 changed files with 109 additions and 21 deletions

View file

@ -15,13 +15,14 @@ export function mountPostbankPayments(host,page,{fetcher=fetch,accountId=null}={
const beforeUnload=event=>{if(uncertain){event.preventDefault();event.returnValue='';}};window.addEventListener('beforeunload',beforeUnload);
async function load(){if(busy)return;if(uncertain){announce('A payment result is still uncertain. Retry the same payment reference or check Transactions before starting another instruction.');return;}busy=true;frame.reloadButton.disabled=true;announce('Loading authorised bank accounts…');try{options=await api.request('/api/bank/transfer-options');if(!active)return;frame.content.replaceChildren();if(transfer)renderTransfer();else await renderActivity();if(active){frame.status.hidden=true;frame.diagnostics.textContent='Central API · Authorised account records · '+new Date().toLocaleString('en-GB');}}catch(error){if(active)announce(error.message);}finally{busy=false;if(active)frame.reloadButton.disabled=false;}}
function renderTransfer(){
const sources=options.accounts.filter(a=>a.canDebit),targets=options.accounts.filter(a=>a.canReceive),form=el('form',undefined,'pb-remittance');form.append(bankIdentity());
const sources=options.accounts.filter(a=>a.canDebit),targets=options.accounts.filter(a=>a.canReceive&&a.canView),form=el('form',undefined,'pb-remittance');form.append(bankIdentity());
if(!sources.length){form.append(el('p','No activated account is currently available for outgoing payments. Activate an eligible package in My Products.'));frame.content.append(form);return;}
const from=el('select'),to=el('select');from.required=true;to.required=true;for(const a of sources)selectOption(from,accountLabel(a),a.id);for(const a of targets)selectOption(to,accountLabel(a),a.number);for(const b of options.beneficiaries||[]){if(b.active&&!targets.some(a=>a.number===b.number)){targets.push({...b,entityId:null});selectOption(to,b.label+' · '+formatNumber(b.number),b.number);}}selectOption(to,'Other beneficiary — search by name or account number','external');
const from=el('select'),to=el('select');from.required=true;to.required=true;for(const a of sources)selectOption(from,accountLabel(a),a.id);for(const a of targets)selectOption(to,accountLabel(a),a.number);selectOption(to,'Search other accounts by name or account number','external');
const grid=el('div',undefined,'pb-remittance-parties'),fromBox=el('section',undefined,'pb-party-card pb-party-from'),toBox=el('section',undefined,'pb-party-card pb-party-to');fromBox.append(field('From · Debit account',from));toBox.append(field('To · Beneficiary account',to));grid.append(fromBox,toBox);
const balance=el('p',undefined,'pb-transfer-available'),searchArea=el('section',undefined,'pb-recipient-search'),query=el('input');query.type='search';query.minLength=3;query.maxLength=80;query.placeholder='Name or full DR account number';
const balance=el('p',undefined,'pb-transfer-available'),searchArea=el('section',undefined,'pb-recipient-search'),query=el('input');query.type='search';query.minLength=3;query.maxLength=80;query.placeholder='Name or account number';
const search=el('button','Find beneficiary');search.type='button';const found=el('select');found.setAttribute('aria-label','Verified beneficiary account');const searchStatus=el('p',undefined,'pb-muted');
searchArea.append(field('Find another beneficiary',query),search,field('Verified beneficiary',found),searchStatus);let external=null,searchVersion=0;
const searchNav=el('nav',undefined,'pb-ledger-pagination'),previous=el('button','Previous matches'),next=el('button','Next matches'),searchPageLabel=el('span');previous.type=next.type='button';previous.disabled=next.disabled=true;searchNav.append(previous,searchPageLabel,next);
searchArea.append(field('Find another beneficiary',query),search,field('Verified beneficiary',found),searchStatus,searchNav);let external=null,searchVersion=0,recipientPage=1;
const amount=el('input');amount.type='text';amount.inputMode='decimal';amount.required=true;amount.pattern='(?:0|[1-9][0-9]{0,16})(?:\\.[0-9]{1,2})?';amount.placeholder='0.00';
const reference=el('textarea');reference.required=true;reference.maxLength=140;reference.rows=2;reference.placeholder='Payment reference';
const standard=el('input'),instant=el('input');standard.type=instant.type='radio';standard.name=instant.name='payment-processing';standard.checked=true;const modes=el('fieldset',undefined,'pb-transfer-modes');modes.append(el('legend','Processing'));const standardLabel=el('label',undefined,'pb-processing-choice'),instantLabel=el('label',undefined,'pb-processing-choice');standardLabel.append(standard,el('strong','Standard'),el('small','Every four hours'));instantLabel.append(instant,el('strong','Instant'),el('small','Within your package allowance'));modes.append(standardLabel,instantLabel);const processing=el('p',undefined,'pb-muted');
@ -32,8 +33,9 @@ export function mountPostbankPayments(host,page,{fetcher=fetch,accountId=null}={
const currentSource=()=>sources.find(a=>a.id===from.value),currentTarget=()=>to.value==='external'?external:targets.find(a=>a.number===to.value);
const isOwn=()=>{const a=currentSource(),b=currentTarget();return !!a?.isPersonalOwner&&a.entityId===b?.entityId;};
function update(){const source=currentSource();balance.textContent='Available: '+source.available+' DM';for(const o of to.options)o.disabled=o.value===source.number;if(to.value===source.number)to.value=[...to.options].find(o=>!o.disabled)?.value||'external';searchArea.hidden=to.value!=='external';query.required=!searchArea.hidden;found.required=!searchArea.hidden;instant.disabled=!source.unlimitedInstant&&source.instantQuota===0;if(instant.disabled){instant.checked=false;standard.checked=true;}processing.textContent=instant.checked?(source.unlimitedInstant?'Unlimited instant payments · No per-transfer fee.':'Instant payments included in this package: '+source.instantQuota+' per calendar month.'):options.standard.processing+(options.standard.nextAt>Date.now()?' Next batch: '+new Date(options.standard.nextAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})+' (Belgian time).':'');recapAmount.textContent=(amount.value||'0.00')+' DM';recapFrom.textContent=currentSource().holder;recapTo.textContent=currentTarget()?.holder||'Select a beneficiary';recapMode.textContent=instant.checked?'Instant':'Standard · Every four hours';const protectedAmount=instant.checked&&options.security?.enabled!==false&&Number(amount.value)>Number(options.security?.threshold||'5000.00');secretField.hidden=!protectedAmount;secretHelp.hidden=!protectedAmount;paymentSecret.required=protectedAmount&&!!options.security?.configured;if(!protectedAmount)paymentSecret.value='';securityLink.textContent=options.security?.configured?'Manage payment security':'Set your payment secret before sending this amount, or choose Standard';submit.disabled=protectedAmount&&!options.security?.configured;confirmLabel.hidden=isOwn();confirm.required=!isOwn();}
from.onchange=()=>{confirm.checked=false;update();};to.onchange=()=>{confirm.checked=false;update();};instant.onchange=standard.onchange=update;amount.oninput=update;query.oninput=()=>{external=null;found.replaceChildren();searchVersion++;confirm.checked=false;};found.onchange=()=>{external=found._results?.find(a=>a.number===found.value)||null;confirm.checked=false;update();};
search.onclick=async()=>{const version=++searchVersion;external=null;found.replaceChildren();search.disabled=true;searchStatus.textContent='Searching…';try{const data=await api.request('/api/bank/recipients?q='+encodeURIComponent(query.value));if(!active||version!==searchVersion)return;found._results=data.recipients;selectOption(found,'Choose a beneficiary','');for(const r of data.recipients)selectOption(found,r.holder+' · '+formatNumber(r.number),r.number);searchStatus.textContent=data.recipients.length?'Select and confirm the matching account.':'No active matching account was found.';}catch(error){if(active&&version===searchVersion)searchStatus.textContent=error.message;}finally{if(active)search.disabled=false;}};
from.onchange=()=>{confirm.checked=false;update();};to.onchange=()=>{confirm.checked=false;update();};instant.onchange=standard.onchange=update;amount.oninput=update;query.oninput=()=>{external=null;found.replaceChildren();searchVersion++;recipientPage=1;previous.disabled=next.disabled=true;searchPageLabel.textContent='';searchStatus.textContent='';confirm.checked=false;update();};found.onchange=()=>{external=found._results?.find(a=>a.number===found.value)||null;confirm.checked=false;update();};
async function findRecipients(page=1){const version=++searchVersion;external=null;found.replaceChildren();confirm.checked=false;search.disabled=true;previous.disabled=next.disabled=true;searchStatus.textContent='Searching…';update();try{const data=await api.request('/api/bank/recipients?'+new URLSearchParams({q:query.value,page:String(page)}));if(!active||version!==searchVersion)return;recipientPage=data.page;found._results=data.recipients;selectOption(found,'Choose a beneficiary','');for(const r of data.recipients)selectOption(found,accountLabel(r),r.number);searchStatus.textContent=data.recipients.length?'Select and confirm the matching account.':'No active matching account was found.';searchPageLabel.textContent='Page '+recipientPage;previous.disabled=recipientPage<=1;next.disabled=!data.hasMore;}catch(error){if(active&&version===searchVersion)searchStatus.textContent=error.message;}finally{if(active)search.disabled=false;}}
search.onclick=()=>findRecipients(1);previous.onclick=()=>findRecipients(recipientPage-1);next.onclick=()=>findRecipients(recipientPage+1);
form.onsubmit=async event=>{
event.preventDefault();if(busy||finished)return;
if(!pending){if(!form.reportValidity())return;const target=currentTarget();if(!target){announce('Find and select a verified beneficiary.');return;}pending={requestId:crypto.randomUUID(),sourceAccount:from.value,targetNumber:target.number,amount:amount.value,reference:reference.value,mode:instant.checked?'instant':'standard',confirmed:confirm.checked,...(instant.checked?{paymentSecret:paymentSecret.value}:{})};}

View file

@ -22,3 +22,15 @@ The secret is excluded from the payment idempotency fingerprint.
Staff treasury and tax postings use their existing authorised posting paths and
do not acquire a user payment-secret prompt. A staff member using the ordinary
user transfer form follows the same personal security settings as any user.
The wire-transfer beneficiary dropdown contains only active receivable accounts
covered by the user's ownership or account-specific viewing mandate, plus the
search option. Broad bank-inspection rights do not populate that dropdown with
other clients' accounts. Outgoing accounts still require debit authority.
Beneficiary search includes every account the caller may pay, including the
Big Four's permitted treasury/system targets, while P&O remains excluded.
Search matches holder names, account names, partial/formatted account numbers
and the caller's own saved-beneficiary labels. Results are paged in groups of
25; eligibility is applied before pagination, and no balances or client IDs
are returned. Choosing a search result never grants debit rights.

View file

@ -219,10 +219,11 @@ export function createPostbankApi(central,bank,settings={},deps={}){
try{
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),beneficiaries:(await beneficiaries.list(user)).beneficiaries,actorId:user.id,security:await transferSecurity.settings(user),standard:{state:'active',processing:'Standard payments are processed in batches every four hours: 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00 Europe/Brussels.',nextAt:standardCycle().nextAt},fees:{state:'planned',message:'Transfer fees are not currently being charged.'}});
if(path==='/api/bank/recipients'){
if([...url.searchParams.keys()].some(k=>k!=='q')||url.searchParams.getAll('q').length!==1)return reply({message:'Use only the recipient name or account search field.'},400);
if([...url.searchParams.keys()].some(k=>!['q','page'].includes(k))||url.searchParams.getAll('q').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Use the recipient search and page fields.'},400);
const now=Date.now();for(const [key,value]of lookups)if(value.until<now)lookups.delete(key);if(lookups.size>10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429);
const value=lookups.get(user.id)||{until:now+60000,count:0};value.count++;lookups.set(user.id,value);if(value.count>20)return reply({message:'Too many recipient searches. Try again in one minute.'},429);
return reply({recipients:await payments.recipients(user,url.searchParams.get('q'))});
const rawPage=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(rawPage))return reply({message:'Choose a valid beneficiary page.'},400);
const result=await payments.recipientPage(user,url.searchParams.get('q'),{page:Number(rawPage)}),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Search again.'},403);return reply(result);
}
if([...url.searchParams.keys()].some(k=>!['accountId','page','q','state','from','to'].includes(k))||url.searchParams.getAll('accountId').length>1||['page','q','state','from','to'].some(k=>url.searchParams.getAll(k).length>1))return reply({message:'Invalid statement filter.'},400);
const raw=url.searchParams.get('page')||'1';if(!/^[1-9]\d{0,3}$/.test(raw))return reply({message:'Choose a valid statement page.'},400);

View file

@ -23,20 +23,17 @@ export class PostbankPayments{
async accounts(user){
const context=await this.authority(user),all=await this.canInspectAll(user),entities=context.entities.filter(e=>e.canView);if(!all&&!entities.length)return [];
const rows=all?await this.db.query(accountSQL+" WHERE a.system_key IS NULL OR a.system_key<>'sys_payroll_po' ORDER BY a.id"):await this.db.query(accountSQL+' WHERE c.entity_id IN ('+entities.map(()=>'?').join(',')+') ORDER BY a.id',entities.map(e=>e.id));
return rows.filter(a=>all||canViewAccount(context,a.entity_id,a.id)).map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,holder:a.holder||a.display_name,entityId:a.entity_id,kind:a.kind,isPersonalOwner:a.kind==='person'&&a.external_key===user.id,state:a.state,type:a.type_code,canReceive:bankRecipientAllowed(a,all),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),canDebit:payable(a)&&canDebitAccount(context,a.entity_id,a.id),unlimitedInstant:PACKAGES.find(p=>p.key===a.package_key)?.unlimitedInstant===true,instantQuota:PACKAGES.find(p=>p.key===a.package_key)?.instant||0}));
return rows.filter(a=>all||canViewAccount(context,a.entity_id,a.id)).map(a=>({id:String(a.id),number:a.account_number,name:a.display_name,holder:a.holder||a.display_name,entityId:a.entity_id,kind:a.kind,isPersonalOwner:a.kind==='person'&&a.external_key===user.id,state:a.state,type:a.type_code,canView:canViewAccount(context,a.entity_id,a.id),canReceive:bankRecipientAllowed(a,all),available:money(BigInt(a.balance_minor)-BigInt(a.reserved_minor)),canDebit:payable(a)&&canDebitAccount(context,a.entity_id,a.id),unlimitedInstant:PACKAGES.find(p=>p.key===a.package_key)?.unlimitedInstant===true,instantQuota:PACKAGES.find(p=>p.key===a.package_key)?.instant||0}));
}
async recipients(user,query){
if(typeof query!=='string'||query.trim().length<3||query.trim().length>80)throw new BankError('Enter at least three characters of a name, or a full account number.');
// Search only active payable accounts; never expose client numbers or UUIDs.
const all=await this.canInspectAll(user),number=query.replace(/\s/g,'').toUpperCase();let rows;
if(number.startsWith('DR')&&/^DR[0-9 ]+$/i.test(query.trim())){
if(!validBankNumber(number))throw new BankError('Enter a complete valid DR account number.');
rows=await this.db.query(accountSQL+" WHERE a.account_number=? AND a.state='active' LIMIT 10",[number]);
}else{
const term='%'+query.trim().replace(/[!%_]/g,c=>'!'+c)+'%';
rows=await this.db.query(accountSQL+" WHERE (e.display_name LIKE ? ESCAPE '!' OR a.display_name LIKE ? ESCAPE '!') AND a.state='active' ORDER BY e.display_name,a.id LIMIT 10",[term,term]);
}
return rows.filter(a=>bankRecipientAllowed(a,all)).map(a=>({number:a.account_number,name:a.display_name,holder:a.holder||a.display_name}));
async recipients(user,query){return (await this.recipientPage(user,query)).recipients;}
async recipientPage(user,query,{page=1}={}){
if(typeof query!=='string'||query.trim().length<3||query.trim().length>80||!Number.isInteger(page)||page<1||page>10000)throw new BankError('Enter at least three characters of a name or account number, and a valid page.');
const all=await this.canInspectAll(user),escape=value=>'%'+value.replace(/[!%_]/g,c=>'!'+c)+'%',term=escape(query.trim()),numberTerm=escape(query.replace(/\s/g,'').toUpperCase());
// Filter before pagination so ineligible matches cannot hide payable accounts.
const eligibility=all?"(a.system_key IS NULL OR a.system_key<>'sys_payroll_po') AND (a.system_key IS NOT NULL OR e.active=1 AND p.state='active')":"a.system_key IS NULL AND a.type_code<>'106' AND e.active=1 AND p.state='active'";
const rows=await this.db.query(accountSQL+" WHERE a.state='active' AND "+eligibility+" AND (e.display_name LIKE ? ESCAPE '!' OR a.display_name LIKE ? ESCAPE '!' OR a.account_number LIKE ? ESCAPE '!' OR EXISTS (SELECT 1 FROM pb_beneficiaries b WHERE b.account_id=a.id AND b.owner_id=? AND b.label LIKE ? ESCAPE '!')) ORDER BY COALESCE(e.display_name,a.display_name),a.id LIMIT 26 OFFSET "+((page-1)*25),[term,term,numberTerm,user.id,term]);
if(all&&!await this.canInspectAll(user))throw new BankError('Your beneficiary search authority changed. Search again.',403);
return {recipients:rows.slice(0,25).filter(a=>bankRecipientAllowed(a,all)).map(a=>({number:a.account_number,name:a.display_name,holder:a.holder||a.display_name})),page,hasMore:rows.length>25};
}
async transfer(user,input,{revalidate=async()=>user}={}){
const allowed=['requestId','sourceAccount','targetNumber','amount','reference','mode','confirmed','paymentSecret'];

View file

@ -0,0 +1,35 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {mountPostbankPayments} from '../control-panel/public/cp-v2/cp-v2-postbank-payments.mjs';
class Node{
constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.attrs={};this._text='';this._value=null;this.disabled=false;this.checked=false;this.hidden=false;}
set textContent(value){this._text=String(value);this.children=[];}get textContent(){return this._text+this.children.map(n=>n.textContent).join('');}
get value(){return this._value??(this.tagName==='SELECT'?this.children[0]?.value||'':'');}set value(value){this._value=String(value);}
get options(){return this.children;}append(...nodes){for(const node of nodes){node.parent=this;this.children.push(node);}}
replaceChildren(...nodes){this.children=[];this._text='';if(this.tagName==='SELECT')this._value=null;this.append(...nodes);}
setAttribute(key,value){this.attrs[key]=String(value);}closest(){return null;}focus(){}reportValidity(){return true;}
querySelectorAll(selector){return all(this).filter(n=>selector.toUpperCase().split(',').includes(n.tagName));}
remove(){if(this.parent)this.parent.children=this.parent.children.filter(n=>n!==this);}
}
const all=node=>node.children.flatMap(child=>[child,...all(child)]),settle=async()=>{for(let i=0;i<5;i++)await new Promise(resolve=>setImmediate(resolve));};
async function fixture(work,{search=async page=>({recipients:[{name:'External Savings',holder:'External',number:'DR22103000000002'}],page,hasMore:page===1})}={}){
const previousDocument=globalThis.document,previousWindow=globalThis.window;globalThis.document={createElement:tag=>new Node(tag)};globalThis.window={addEventListener(){},removeEventListener(){}};
const host=new Node('main'),calls=[],base={holder:'You',entityId:'person',canReceive:true,canView:true,canDebit:true,available:'100.00',instantQuota:5,isPersonalOwner:true};
const accounts=[{...base,id:'1',name:'Your Current',number:'DR25102000000005'},{...base,id:'2',name:'Your Savings',number:'DR50103000000006'},{...base,id:'3',name:'Foreign Account',number:'DR14102000000007',canView:false,canDebit:false},{...base,id:'4',name:'Treasury',number:'DR8297900000007',canView:false,canDebit:false},{...base,id:'5',name:'Delegated Account',number:'DR14102000000008',canDebit:false}];
const dispose=mountPostbankPayments(host,'bank-transfers',{fetcher:async(path,options)=>{calls.push({path,options});if(path.startsWith('/api/bank/recipients?'))return Response.json(await search(Number(new URL(path,'https://cp.dunerealms.com').searchParams.get('page'))));return Response.json({accounts,beneficiaries:[{active:true,label:'Saved External',number:accounts[2].number}],fees:{message:'No fee'},standard:{processing:'Every four hours'},security:{enabled:false}});}});
const nodes=()=>all(host),button=label=>nodes().find(n=>n.tagName==='BUTTON'&&n.textContent===label);
try{await settle();await work({host,calls,nodes,button});}finally{dispose();globalThis.document=previousDocument;globalThis.window=previousWindow;}
}
test('wire dropdown lists owned and delegated accounts plus search; inspection-only and saved external accounts stay out',()=>fixture(async({nodes})=>{
const selects=nodes().filter(n=>n.tagName==='SELECT'),debit=selects[0],credit=selects[1];assert.equal(debit.options.length,2);assert.equal(credit.options.length,4);
assert(credit.textContent.includes('Your Savings'));assert(credit.textContent.includes('Delegated Account'));assert(credit.textContent.includes('Search other accounts'));assert(!credit.textContent.includes('Foreign Account'));assert(!credit.textContent.includes('Treasury'));assert(!credit.textContent.includes('Saved External'));
}));
test('beneficiary search displays account names and allows every result page to be reached',()=>fixture(async({nodes,button,calls})=>{
const credit=nodes().filter(n=>n.tagName==='SELECT')[1];credit.value='external';credit.onchange();const query=nodes().find(n=>n.type==='search');query.value='External';query.oninput();await button('Find beneficiary').onclick();
const found=nodes().find(n=>n.attrs['aria-label']==='Verified beneficiary account');assert(found.textContent.includes('External Savings'));assert.equal(button('Next matches').disabled,false);await button('Next matches').onclick();assert.equal(button('Previous matches').disabled,false);assert.equal(button('Next matches').disabled,true);assert(calls.some(c=>c.path.includes('page=2')));
query.value='New search';query.oninput();assert.equal(found.options.length,0);assert.equal(button('Next matches').disabled,true);await button('Find beneficiary').onclick();assert(calls.at(-1).path.includes('page=1'));
}));
test('changing a search while results are loading discards the stale response',()=>fixture(async({nodes,button})=>{
const credit=nodes().filter(n=>n.tagName==='SELECT')[1];credit.value='external';credit.onchange();const query=nodes().find(n=>n.type==='search');query.value='First';
query.oninput();const pending=button('Find beneficiary').onclick();query.value='Changed';query.oninput();await pending;assert.equal(nodes().find(n=>n.attrs['aria-label']==='Verified beneficiary account').options.length,0);
},{search:async page=>{await new Promise(resolve=>setImmediate(resolve));return {recipients:[{name:'Stale',number:'DR22103000000002'}],page,hasMore:false};}}));

View file

@ -76,3 +76,44 @@ test('P&O stays excluded even for Big Four; privilege revoked before settlement
test('Big Four system beneficiaries can be saved, and become inactive when the mandate ends',async()=>{const f=await setup();try{const {PostbankBeneficiaries}=await import('../node/postbank-beneficiaries.mjs');const reserve=f.current(2);await f.db.query("UPDATE pb_accounts SET client_number=NULL,package_id=NULL,system_key='sys_bank_capital_issuer',display_name='Federal Reserve' WHERE id=?",[reserve.id]);let allowed=true;const book=new PostbankBeneficiaries(f.db,{canInspectAll:async()=>allowed});await book.write(f.users[0],{requestId:randomUUID(),number:reserve.account_number,label:'Federal Reserve'});assert.equal((await book.list(f.users[0])).beneficiaries[0].active,true);allowed=false;assert.equal((await book.list(f.users[0])).beneficiaries[0].active,false);}finally{f.db.close();}});
test('bank-wide mandate follows protected owner/executive identities, not service or ordinary bank permissions',async()=>{const {canInspectAllBankAccounts,bankRecipientAllowed}=await import('../node/postbank-recipient-policy.mjs');for(const kind of ['owner','executive','service','officer',null]){const central={prepare(){return {bind(){return this;},async first(){return kind?{principal_kind:kind}:null;}};}};assert.equal(await canInspectAllBankAccounts(central,{id:'ordinary-identity'}),['owner','executive'].includes(kind));}assert.equal(bankRecipientAllowed({state:'active',system_key:'sys_payroll_po'},true),false);assert.equal(bankRecipientAllowed({state:'active',system_key:'sys_bank_capital_issuer'},true),true);assert.equal(bankRecipientAllowed({state:'dormant',system_key:'sys_tax_treasury'},true),false);});
test('wire picker access stays scoped while permitted external accounts remain searchable',async()=>{
const f=await setup();try{
f.service.canInspectAll=async()=>true;const accounts=await f.service.accounts(f.users[0]);
assert.equal(accounts.find(a=>a.id===String(f.current(0).id)).canView,true);assert.equal(accounts.find(a=>a.id===String(f.current(1).id)).canView,false);
assert.equal((await f.service.recipientPage(f.users[0],'citizen_1')).recipients.length,2);
const formatted=f.current(1).account_number.match(/.{1,4}/g).join(' ');assert.equal((await f.service.recipientPage(f.users[0],formatted)).recipients[0].number,f.current(1).account_number);
assert((await f.service.recipientPage(f.users[0],formatted.slice(0,9))).recipients.some(a=>a.number===f.current(1).account_number));
}finally{f.db.close();}
});
test('recipient pages include every eligible match beyond the former ten-result cap',async()=>{
const f=await setup();try{
const {bankNumber}=await import('../node/postbank-catalogue.mjs'),sample=f.current(1);
for(let i=0;i<38;i++)await f.db.query("INSERT INTO pb_accounts(client_number,package_id,account_number,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,?,'102',?,0,0,'active',0)",[sample.client_number,sample.package_id,bankNumber('102',1000+i),'Search match '+i]);
// Many unavailable matches must not consume a page or hide valid matches.
for(let i=0;i<12;i++)await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE account_number=?",[bankNumber('102',1000+i)]);
const first=await f.service.recipientPage(f.users[0],'Search match'),second=await f.service.recipientPage(f.users[0],'Search match',{page:2});assert.equal(first.recipients.length,25);assert.equal(first.hasMore,true);assert.equal(second.recipients.length,1);assert.equal(second.hasMore,false);assert.equal(new Set([...first.recipients,...second.recipients].map(a=>a.number)).size,26);
for(const account of first.recipients)assert.deepEqual(Object.keys(account).sort(),['holder','name','number']);
await assert.rejects(f.service.recipientPage(f.users[0],'match',{page:0}));assert.deepEqual((await f.service.recipientPage(f.users[0],'Search%')).recipients,[]);
}finally{f.db.close();}
});
test('saved-beneficiary search aliases are private and use current account eligibility',async()=>{
const f=await setup();try{
const {PostbankBeneficiaries}=await import('../node/postbank-beneficiaries.mjs'),book=new PostbankBeneficiaries(f.db);
await book.write(f.users[0],{requestId:randomUUID(),number:f.current(1).account_number,label:'Secret alias example'});
assert.equal((await f.service.recipientPage(f.users[0],'Secret alias')).recipients.length,1);assert.equal((await f.service.recipientPage(f.users[2],'Secret alias')).recipients.length,0);
await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.current(1).id]);assert.equal((await f.service.recipientPage(f.users[0],'Secret alias')).recipients.length,0);
}finally{f.db.close();}
});
test('recipient API validates paging, and rejects identity changes while loading results',async()=>{
const f=await setup();try{
let changed=false;const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>changed?f.users[1]:f.users[0],authority:f.authority}),base='https://cp.dunerealms.com/api/bank/recipients?q=citizen';
for(const suffix of ['&page=0','&page=1.5','&page=1&page=2','&user=other'])assert.equal((await api(new Request(base+suffix))).status,400);
const response=await api(new Request(base+'&page=1'));assert.equal(response.status,200);assert.equal((await response.json()).page,1);
const authority=async user=>{changed=true;return f.authority(user);};let reads=0;
const changedApi=createPostbankApi(null,f.db,{}, {authenticate:async()=>++reads===1?f.users[0]:f.users[1],authority});assert.equal((await changedApi(new Request(base))).status,403);
}finally{f.db.close();}
});