forked from unimatrix/web
Set standard settlements to four-hour Brussels windows
This commit is contained in:
parent
e713ca2aad
commit
de02bc9205
2 changed files with 38 additions and 14 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import {createPostbankPayments} from './postbank-payments.mjs';
|
||||
import {createPostbankPayments,standardCycle} from './postbank-payments.mjs';
|
||||
import {identity} from './auth.mjs';
|
||||
import {PostbankService} from './postbank-service.mjs';
|
||||
import {createPostbankAuthority} from './postbank-authority.mjs';
|
||||
|
|
@ -18,7 +18,7 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
}
|
||||
if(request.method==='GET'&&['/api/bank/transfer-options','/api/bank/recipients','/api/bank/activity'].includes(path)){
|
||||
try{
|
||||
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),actorId:user.id,standard:{state:'active',processing:'Standard payments are reserved and processed automatically in bounded batches, usually within one minute.'},fees:{state:'planned',message:'Automated transfer fee billing is not active in this foundation batch.'}});
|
||||
if(path==='/api/bank/transfer-options')return reply({accounts:await payments.accounts(user),actorId:user.id,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:'Automated transfer fee billing is not active in this foundation batch.'}});
|
||||
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);
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -74,8 +74,9 @@ export class PostbankPayments{
|
|||
await tx.query("UPDATE pb_orders SET state='posted',posted_at=? WHERE id=?",[now,order.id]);
|
||||
await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[this.makeId(),order.actor_id,'transfer_posted',source.entity_id,JSON.stringify({paymentId:order.id}),now]);
|
||||
}
|
||||
async processQueue(){
|
||||
const orders=await this.db.query("SELECT id,actor_id FROM pb_orders WHERE state='queued' AND mode='standard' ORDER BY created_at,id LIMIT 25");let posted=0,rejected=0,failed=0;
|
||||
async processQueue({cutoff=Number.MAX_SAFE_INTEGER,skip=[]}={}){
|
||||
if(!Number.isSafeInteger(cutoff)||cutoff<0||!Array.isArray(skip)||skip.length>1000||skip.some(id=>!uuid(id)))throw new BankError('Invalid settlement window.');
|
||||
const orders=await this.db.query("SELECT id,actor_id FROM pb_orders WHERE state='queued' AND mode='standard' AND created_at<=?"+(skip.length?' AND id NOT IN ('+skip.map(()=>'?').join(',')+')':'')+' ORDER BY created_at,id LIMIT 25',[cutoff,...skip]);let posted=0,rejected=0,failed=0;const failedIds=[];
|
||||
for(const item of orders){try{
|
||||
// Actor identity and authority are reloaded inside the posting transaction.
|
||||
const outcome=await this.db.transaction(async tx=>{
|
||||
|
|
@ -96,8 +97,8 @@ export class PostbankPayments{
|
|||
await this.post(tx,order,source,target,true);return 'posted';
|
||||
});
|
||||
if(outcome==='posted')posted++;if(outcome==='rejected')rejected++;
|
||||
}catch{failed++;}}
|
||||
return {posted,rejected,failed};
|
||||
}catch{failed++;failedIds.push(item.id);}}
|
||||
return {posted,rejected,failed,failedIds,attempted:orders.length};
|
||||
}
|
||||
async activity(user,{accountId=null,page=1}={}){
|
||||
if(!Number.isInteger(page)||page<1||page>10000||accountId!==null&&!/^\d{1,12}$/.test(accountId))throw new BankError('Select a valid account and page.');
|
||||
|
|
@ -114,8 +115,27 @@ export class PostbankPayments{
|
|||
}
|
||||
}
|
||||
export function createPostbankPayments(central,bank,deps={}){return bank?new PostbankPayments(bank,deps.authority||createPostbankAuthority(central),{...deps,resolveUser:deps.resolveUser||(id=>central.prepare("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(id).first())}):null;}
|
||||
export function startPostbankQueue(central,bank,settings){
|
||||
if(settings.POSTBANK_ENABLED!=='true'||!bank)return ()=>{};const service=createPostbankPayments(central,bank);let running=false,stopped=false;
|
||||
const tick=async()=>{if(running||stopped)return;running=true;try{const result=await service.processQueue();if(result.failed)console.error('Postbank queued payment reconciliation needs attention.');}catch{console.error('Postbank queued payment processing needs attention.');}finally{running=false;}};
|
||||
const timer=setInterval(()=>void tick(),60000);timer.unref();return()=>{stopped=true;clearInterval(timer);};
|
||||
// Fixed four-hour settlement windows in the bank's Brussels calendar, including DST.
|
||||
const calendar=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'});
|
||||
const partsAt=time=>Object.fromEntries(calendar.formatToParts(new Date(time)).filter(p=>p.type!=='literal').map(p=>[p.type,Number(p.value)]));
|
||||
function localTimeUTC(year,month,day,hour){
|
||||
const wanted=Date.UTC(year,month-1,day,hour);let guess=wanted;
|
||||
for(let i=0;i<5;i++){const p=partsAt(guess),actual=Date.UTC(p.year,p.month-1,p.day,p.hour,p.minute,p.second),delta=wanted-actual;if(!delta)return guess;guess+=delta;}
|
||||
throw Error('The bank settlement calendar could not be resolved.');
|
||||
}
|
||||
export function standardCycle(now=Date.now()){
|
||||
const p=partsAt(now),hour=Math.floor(p.hour/4)*4,nextLocal=new Date(Date.UTC(p.year,p.month-1,p.day,hour+4));
|
||||
return {cutoff:localTimeUTC(p.year,p.month,p.day,hour),nextAt:localTimeUTC(nextLocal.getUTCFullYear(),nextLocal.getUTCMonth()+1,nextLocal.getUTCDate(),nextLocal.getUTCHours())};
|
||||
}
|
||||
export function startPostbankQueue(central,bank,settings){
|
||||
if(settings.POSTBANK_ENABLED!=='true'||!bank)return ()=>{};const service=createPostbankPayments(central,bank);let timer=null,stopped=false;
|
||||
const schedule=()=>{if(stopped)return;timer=setTimeout(()=>void run(),Math.max(1000,standardCycle().nextAt-Date.now()));timer.unref();};
|
||||
async function run(){
|
||||
const cutoff=standardCycle().cutoff,skip=[];
|
||||
try{while(!stopped){const result=await service.processQueue({cutoff,skip});if(result.failed){skip.push(...result.failedIds);console.error('Postbank queued payment reconciliation needs attention.');}if(result.attempted<25||skip.length>975)break;await new Promise(resolve=>setTimeout(resolve,1000));}}
|
||||
catch{console.error('Postbank scheduled settlement needs attention.');}finally{schedule();}
|
||||
}
|
||||
// Recover only instructions belonging to the most recent settlement cutoff.
|
||||
// New instructions after that cutoff continue waiting for the next four-hour window.
|
||||
timer=setTimeout(()=>void run(),1000);timer.unref();return()=>{stopped=true;if(timer)clearTimeout(timer);};
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff