From de02bc920559c462d78d7e560c1c767bf30ad3ef Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:54:18 +0100 Subject: [PATCH] Set standard settlements to four-hour Brussels windows --- .../alpha-1.0.0.6-imperial-postbank.md | 6 ++-- .../public/cp-v2/cp-v2-postbank-payments.mjs | 4 +-- website/node/postbank-api.mjs | 4 +-- website/node/postbank-payments.mjs | 36 ++++++++++++++----- website/tests/postbank-payments.test.mjs | 4 ++- 5 files changed, 39 insertions(+), 15 deletions(-) diff --git a/docs/releases/alpha-1.0.0.6-imperial-postbank.md b/docs/releases/alpha-1.0.0.6-imperial-postbank.md index 5c6fafa6..3a386a64 100644 --- a/docs/releases/alpha-1.0.0.6-imperial-postbank.md +++ b/docs/releases/alpha-1.0.0.6-imperial-postbank.md @@ -78,8 +78,10 @@ Owner approved 1 DM per month per enabled eligible account. It applies to non-of ## Three-page payment foundation batch Wire Transfer, Transactions & Statements and Payment History now use the independent bank database through the central API. Transfer-options lists currently authorised accounts; debit requires actual operator authority. Beneficiary lookup accepts a literal partial holder name or a full checksum-valid DR account number, returns at most ten active payable matches and is rate limited. Own personal-account transfers omit the additional beneficiary checkbox; managed/external transfers require confirmation. P&O/system accounts, securities, dormant and closed accounts cannot participate. -Amounts are exact decimal strings converted to integer minor units. The transaction locks banking entities in canonical order and both financial rows before checking available funds and revalidating the session/authority. Request IDs and fingerprints prevent a replay from creating another order. Standard instructions reserve funds and are processed in bounded batches of 25 every 60 seconds. The worker reloads actor authority, rejects expired permissions/inactive accounts and releases the hold. Multiple workers lock the same order before posting, so its paired ledger entries and balances commit once. Instant payments post atomically and consume the current package allowance in the Brussels calendar month. No paid instant surcharge, transfer tax, loan, overdraft, game balance link or payroll is enabled by this batch. Fee billing remains explicitly planned. +Amounts are exact decimal strings converted to integer minor units. The transaction locks banking entities in canonical order and both financial rows before checking available funds and revalidating the session/authority. Request IDs and fingerprints prevent a replay from creating another order. Standard instructions reserve funds and are processed in bounded batches of 25 at fixed four-hour Brussels settlement windows (00:00, 04:00, 08:00, 12:00, 16:00, 20:00). The worker reloads actor authority, rejects expired permissions/inactive accounts and releases the hold. Multiple workers lock the same order before posting, so its paired ledger entries and balances commit once. Instant payments post atomically and consume the current package allowance in the Brussels calendar month. No paid instant surcharge, transfer tax, loan, overdraft, game balance link or payroll is enabled by this batch. Fee billing remains explicitly planned. The UI retains the same request on an uncertain response and does not automatically resend. Statements show a wide reference, named counterparties with expandable account numbers, signed direction colours, queued/posted/rejected state, posted balance where applicable and 25-row pagination. Queries cannot select another actor's account. Only the bottom collapsed workspace control reloads the view. -Validation before CI: 36 focused bank/cutover/navigation checks passed; isolated real MySQL checks passed five concurrent reservations, two simultaneous posting workers with exactly five posts, balanced ledger legs, instant quota enforcement, recipient lookup and ten statement records. All temporary QA tables were removed; no real customer funds were used. Worker build and complete-source CI remain required before release. Bank administrative views are the following batch; deferred credit/payroll/tax work stays separate. +Validation before CI: 37 focused bank/cutover/navigation checks passed; isolated real MySQL checks passed five concurrent reservations, two simultaneous posting workers with exactly five posts, balanced ledger legs, instant quota enforcement, recipient lookup and ten statement records. All temporary QA tables were removed; no real customer funds were used. Worker build and complete-source CI remain required before release. Bank administrative views are the following batch; deferred credit/payroll/tax work stays separate. + +Owner timing correction: standard payments wait for the next fixed four-hour cutoff and the worker drains eligible instructions in chunks of 25; newer orders wait for the following window. Restart recovery uses the last cutoff and cannot immediately post newly submitted standard orders. Instant still posts within its request transaction. Calendar calculations use Europe/Brussels including daylight-saving changes. diff --git a/website/control-panel/public/cp-v2/cp-v2-postbank-payments.mjs b/website/control-panel/public/cp-v2/cp-v2-postbank-payments.mjs index 1b029ae6..61b1a919 100644 --- a/website/control-panel/public/cp-v2/cp-v2-postbank-payments.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-postbank-payments.mjs @@ -28,14 +28,14 @@ export function mountPostbankPayments(host,page,{fetcher=fetch}={}){ form.append(grid,balance,searchArea,moneyRow,instantLabel,processing,confirmLabel,el('p',options.fees.message,'pb-muted'),submit);frame.content.append(form);const history=el('a','Open Payment History');history.href='#bank/bank-history';frame.content.append(history);let pending=null,finished=false; 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.instantQuota===0;if(instant.disabled)instant.checked=false;processing.textContent=instant.checked?'Instant payments included in this package: '+source.instantQuota+' per calendar month.':'Standard payments are reserved and processed automatically, usually within one minute.';confirmLabel.hidden=isOwn();confirm.required=!isOwn();} + 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.instantQuota===0;if(instant.disabled)instant.checked=false;processing.textContent=instant.checked?'Instant payments included in this package: '+source.instantQuota+' per calendar month.':options.standard.processing+' Next batch: '+new Date(options.standard.nextAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})+' (Belgian time).';confirmLabel.hidden=isOwn();confirm.required=!isOwn();} from.onchange=()=>{confirm.checked=false;update();};to.onchange=()=>{confirm.checked=false;update();};instant.onchange=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;}}; 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};} busy=true;submit.disabled=true;for(const node of form.querySelectorAll('input,select,textarea,button'))if(node!==submit)node.disabled=true;announce('Sending payment instruction…'); - try{const result=await api.request('/api/bank/transfers',pending);if(!active)return;uncertain=false;finished=true;const receipt=el('section',undefined,'pb-payment-receipt');receipt.append(el('h4',result.state==='posted'?'Payment posted':'Payment reserved'),el('p',result.amount+' DM · '+result.reference),el('p','Status: '+result.state),el('code',result.paymentId));const link=el('a','View Payment History');link.href='#bank/bank-history';receipt.append(link);const next=el('button','New payment');next.type='button';next.onclick=()=>void load();receipt.append(next);form.replaceWith(receipt);frame.status.hidden=true;} + try{const result=await api.request('/api/bank/transfers',pending);if(!active)return;uncertain=false;finished=true;const receipt=el('section',undefined,'pb-payment-receipt');receipt.append(el('h4',result.state==='posted'?'Payment posted':'Payment reserved'),el('p',result.amount+' DM · '+result.reference),el('p','Status: '+result.state+(result.state==='queued'?' · Standard settlement every four hours.':'')),el('code',result.paymentId));const link=el('a','View Payment History');link.href='#bank/bank-history';receipt.append(link);const next=el('button','New payment');next.type='button';next.onclick=()=>void load();receipt.append(next);form.replaceWith(receipt);frame.status.hidden=true;} catch(error){if(!active)return;uncertain=uncertain||!!error.uncertain;announce(uncertain?'The result is not confirmed. Retry below using the SAME payment reference. Do not create another instruction.':error.message);submit.textContent=uncertain?'Check / retry same payment':'Send payment';if(!uncertain){pending=null;for(const node of form.querySelectorAll('input,select,textarea,button'))node.disabled=false;update();}} finally{busy=false;if(active)submit.disabled=false;} };update(); diff --git a/website/node/postbank-api.mjs b/website/node/postbank-api.mjs index 47b2c6a4..bc9247bb 100644 --- a/website/node/postbank-api.mjs +++ b/website/node/postbank-api.mjs @@ -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.until10000)return reply({message:'Recipient lookup is busy. Try shortly.'},429); diff --git a/website/node/postbank-payments.mjs b/website/node/postbank-payments.mjs index 1df95405..752928d6 100644 --- a/website/node/postbank-payments.mjs +++ b/website/node/postbank-payments.mjs @@ -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);}; } diff --git a/website/tests/postbank-payments.test.mjs b/website/tests/postbank-payments.test.mjs index e2fbe537..243bb1a8 100644 --- a/website/tests/postbank-payments.test.mjs +++ b/website/tests/postbank-payments.test.mjs @@ -1,5 +1,5 @@ import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; -import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankPayments} from '../node/postbank-payments.mjs';import {createPostbankApi} from '../node/postbank-api.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs'; +import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankPayments,standardCycle} from '../node/postbank-payments.mjs';import {createPostbankApi} from '../node/postbank-api.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs'; async function setup(){ const db=new BankFixture(),users=[0,1,2].map((n)=>({id:randomUUID(),username:'citizen_'+n})),entities=users.map((u)=>({id:randomUUID(),kind:'person',key:u.id,name:u.username}));let revoked=false; const authority=async u=>({entities:entities.map(e=>({...e,canView:e.key===u.id,canActivate:e.key===u.id,canPay:e.key===u.id&&!revoked})),readAdmin:false,manageAdmin:false}); @@ -21,3 +21,5 @@ test('planned, dormant and system accounts cannot be payment sources or benefici test('bank transfer routes reject wrong origin, identity overrides and fractional JSON numbers',async()=>{const f=await setup();try{const api=createPostbankApi(null,f.db,{}, {authenticate:async()=>f.users[0],authority:f.authority}),base='https://cp.dunerealms.com';const request=(body,origin=base)=>new Request(base+'/api/bank/transfers',{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal((await api(request(f.input(),'https://other.invalid'))).status,403);assert.equal((await api(request(f.input({amount:10.1})))).status,400);assert.equal((await api(new Request(base+'/api/bank/activity?actor=other'))).status,400);assert.equal((await api(new Request(base+'/api/bank/transfer-options'))).status,200);}finally{f.db.close();}}); test('one failed queued posting retains its hold without blocking another instruction',async()=>{const f=await setup();try{const bad=f.input(),good=f.input();await f.service.transfer(f.users[0],bad);await f.service.transfer(f.users[0],good);f.db.sqlite.exec("CREATE TRIGGER fail_one_entry BEFORE INSERT ON pb_entries WHEN NEW.order_id='"+bad.requestId+"' BEGIN SELECT RAISE(ABORT,'isolated ledger fault'); END;");const result=await f.service.processQueue();assert.equal(result.failed,1);assert.equal(result.posted,1);const a=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id]);assert.equal(a.balance_minor,9000);assert.equal(a.reserved_minor,1000);assert.equal((await f.db.first('SELECT * FROM pb_orders WHERE id=?',[bad.requestId])).state,'queued');f.db.sqlite.exec('DROP TRIGGER fail_one_entry');assert.equal((await f.service.processQueue()).posted,1);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,0);}finally{f.db.close();}}); + +test('standard settlement uses four-hour Brussels windows and leaves newer instructions reserved',async()=>{assert.deepEqual(standardCycle(Date.parse('2026-11-13T20:30:00Z')),{cutoff:Date.parse('2026-11-13T19:00:00Z'),nextAt:Date.parse('2026-11-13T23:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-10-25T02:30:00Z')),{cutoff:Date.parse('2026-10-24T22:00:00Z'),nextAt:Date.parse('2026-10-25T03:00:00Z')});assert.deepEqual(standardCycle(Date.parse('2026-03-29T01:30:00Z')),{cutoff:Date.parse('2026-03-28T23:00:00Z'),nextAt:Date.parse('2026-03-29T02:00:00Z')});const f=await setup();try{await f.service.transfer(f.users[0],f.input());const tooEarly=await f.service.processQueue({cutoff:Date.parse('2026-11-13T19:00:00Z')});assert.equal(tooEarly.attempted,0);assert.equal((await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[f.current(0).id])).reserved_minor,1000);assert.equal((await f.service.processQueue({cutoff:Date.parse('2026-11-13T23:00:00Z')})).posted,1);}finally{f.db.close();}});