forked from unimatrix/web
Automatically archive month-end bank statements through the bank ticker
This commit is contained in:
parent
f3596880fa
commit
27c729b36a
7 changed files with 77 additions and 15 deletions
|
|
@ -1,5 +1,4 @@
|
|||
import {PostbankStatements} from './postbank-statements.mjs';
|
||||
import {dirname,join} from 'node:path';
|
||||
import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs';
|
||||
import {PostbankBeneficiaries} from './postbank-beneficiaries.mjs';
|
||||
import {PostbankAdmin} from './postbank-admin.mjs';
|
||||
import {createPostbankPayments,standardCycle} from './postbank-payments.mjs';
|
||||
|
|
@ -12,21 +11,26 @@ export function createPostbankApi(central,bank,settings={},deps={}){
|
|||
const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority});
|
||||
const admin=bank?new PostbankAdmin(bank,central,authority,deps):null;
|
||||
const beneficiaries=bank?new PostbankBeneficiaries(bank,deps):null;
|
||||
const statements=bank?new PostbankStatements(bank,payments,{...deps,cacheDir:settings.POSTBANK_STATEMENT_CACHE||(settings.POSTBANK_DB_CONFIG?join(dirname(settings.POSTBANK_DB_CONFIG),'postbank-statements'):null),python:settings.POSTBANK_PYTHON,logo:settings.POSTBANK_STATEMENT_LOGO}):null;
|
||||
const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null;
|
||||
const lookups=new Map(),transferAttempts=new Map();
|
||||
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
return async request=>{
|
||||
const url=new URL(request.url),path=url.pathname;
|
||||
const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401);
|
||||
if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503);
|
||||
if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
|
||||
if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
|
||||
if(path==='/api/bank/statements/archive'){
|
||||
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
|
||||
if([...url.searchParams.keys()].some(k=>!['accountId','page'].includes(k))||url.searchParams.getAll('accountId').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Select an archive account.'},400);
|
||||
try{const accountId=url.searchParams.get('accountId'),data=await statements.list(user,{accountId,page:url.searchParams.get('page')||1}),fresh=await auth(request);if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed.'},403);return reply(data);}catch(error){return reply({message:error.status?error.message:'The statement archive could not be loaded.'},error.status||503);}
|
||||
}
|
||||
if(path==='/api/bank/statements'){
|
||||
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
|
||||
if([...url.searchParams.keys()].some(k=>!['accountId','month'].includes(k))||['accountId','month'].some(k=>url.searchParams.getAll(k).length!==1))return reply({message:'Choose one account and month.'},400);
|
||||
try{const accountId=url.searchParams.get('accountId'),result=await statements.download(user,{accountId,month:url.searchParams.get('month')}),fresh=await auth(request);
|
||||
if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed. Reload the workspace.'},403);
|
||||
return new Response(result.pdf,{headers:{'Content-Type':'application/pdf','Content-Disposition':'attachment; filename="'+result.filename+'"','Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});
|
||||
}catch(error){return reply({message:error.status?error.message:'Your statement could not be generated. Please retry shortly.'},error.status||503);}
|
||||
}catch(error){return reply({message:error.status?error.message:'Your archived statement could not be downloaded. Please retry shortly.'},error.status||503);}
|
||||
}
|
||||
if(path==='/api/bank/beneficiaries'&&request.method==='GET'){
|
||||
try{const data=await beneficiaries.list(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the workspace.'},403);return reply(data);}catch{return reply({message:'Saved beneficiaries could not be confirmed.'},503);}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
export const POSTBANK_CONTRACTS=Object.freeze({
|
||||
statements:{title:'Monthly account statement archive',state:'active',request:{method:'GET',path:'/api/bank/statements/archive',fields:['accountId','page']},response:{records:'closed months with ready/preparing status and download metadata'},note:'The trusted bank ticker automatically seeds and prepares closed-month PDF statements. Users only list and download already archived files through GET /api/bank/statements?accountId=...&month=.... No user generation endpoint. Brussels month boundaries; ledger history remains preserved. Recoverable worker claims, 25 statements per tick and one-minute continuation while a backlog remains.'},
|
||||
server:{title:'Game server link',state:'not_linked',request:{method:'POST',path:'/api/bank/integrations/game/payments',fields:['requestId','sourceAccount','targetNumber','amount','reference','mode','gameReceipt']},response:{paymentId:'unique payment reference',state:'queued | posted | rejected'},note:'Future trusted server-to-server payment instructions only. The central bank authorises, reserves and posts; Java must not duplicate accounting or own bank balances. Standard instructions follow the same four-hour Brussels windows; instant instructions post immediately within bank limits. requestId is retained on retries and fulfilment waits for a confirmed posted bank result. No game link or request is enabled by this placeholder. Server credentials must never be supplied by a browser.'},
|
||||
mandates:{title:'Account authorisations',state:'planned',request:{method:'POST',path:'/api/bank/authorisations',fields:['accountNumber','clientNumber','permissions','startsAt','expiresAt','confirmed']},response:{authorisationId:'new authorisation reference',state:'active | pending'},note:'Creation, editing and revocation of mandates are deferred. Existing imported authority remains checked by the central API.'},
|
||||
investments:{title:'Securities service',state:'planned',request:{method:'POST',path:'/api/bank/investments/orders',fields:['requestId','securitiesAccount','settlementAccount','instrument','side','quantity','confirmed']},response:{orderId:'unique order reference',state:'accepted | rejected'},note:'No trading request is sent. Civic/Public and all 979 funding or settlement accounts are forbidden. Personal eligibility does not grant access to official money.'},
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export async function openPostbankDatabase(settings){
|
|||
|
||||
// Apply only missing indexes to this independent bank database. Concurrent worker
|
||||
// startup can race CREATE INDEX; a duplicate-name result is safe to ignore.
|
||||
export const POSTBANK_INDEXES=[['pb_orders','pb_orders_source_period','source_id,created_at,id'],['pb_orders','pb_orders_target_period','target_id,created_at,id'],['pb_orders','pb_orders_queue_period','state,mode,created_at,id'],['pb_entries','pb_entries_account_period','account_id,created_at,id']];
|
||||
export const POSTBANK_INDEXES=[['pb_statement_archives','pb_statement_worker_due','state,retry_at,lease_until,month,account_id'],['pb_orders','pb_orders_source_period','source_id,created_at,id'],['pb_orders','pb_orders_target_period','target_id,created_at,id'],['pb_orders','pb_orders_queue_period','state,mode,created_at,id'],['pb_entries','pb_entries_account_period','account_id,created_at,id']];
|
||||
export async function ensurePostbankIndexes(db){
|
||||
for(const [table,name,columns]of POSTBANK_INDEXES){const found=await db.first('SELECT INDEX_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND INDEX_NAME=? LIMIT 1',[table,name]);if(found)continue;try{await db.query(`CREATE INDEX ${name} ON ${table} (${columns})`);}catch(error){if(error.code!=='ER_DUP_KEYNAME'&&error.errno!==1061)throw error;}}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs';
|
||||
import {createHash,randomUUID} from 'node:crypto';
|
||||
import {BankError} from './postbank-service.mjs';
|
||||
import {PACKAGES,minorAmount,money,validBankNumber} from './postbank-catalogue.mjs';
|
||||
|
|
@ -136,12 +137,12 @@ export function standardCycle(now=Date.now()){
|
|||
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();};
|
||||
if(settings.POSTBANK_ENABLED!=='true'||!bank)return ()=>{};const service=createPostbankPayments(central,bank);const archives=new PostbankStatementArchive(bank,null,statementSettings(settings));let timer=null,stopped=false,archiveBacklog=false,lastArchiveSeed=0;
|
||||
const schedule=()=>{if(stopped)return;timer=setTimeout(()=>void run(),Math.max(1000,Math.min(standardCycle().nextAt-Date.now(),archiveBacklog?60000:Infinity)));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();}
|
||||
catch{console.error('Postbank scheduled settlement needs attention.');}finally{try{if(Date.now()-lastArchiveSeed>3600000){await archives.seed();lastArchiveSeed=Date.now();}const result=await archives.process();archiveBacklog=result.attempted===25;if(result.failed)console.error('Postbank automatic statement archive needs attention.');}catch{console.error('Postbank statement ticker failed.');}schedule();}
|
||||
}
|
||||
// Recover only instructions belonging to the most recent settlement cutoff.
|
||||
// New instructions after that cutoff continue waiting for the next four-hour window.
|
||||
|
|
|
|||
|
|
@ -83,3 +83,11 @@ CREATE TABLE IF NOT EXISTS pb_beneficiaries (
|
|||
CREATE TABLE IF NOT EXISTS pb_contact_locks (
|
||||
owner_id CHAR(36) PRIMARY KEY
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS pb_statement_archives (
|
||||
account_id BIGINT UNSIGNED NOT NULL, month CHAR(7) NOT NULL,
|
||||
state VARCHAR(16) NOT NULL DEFAULT 'pending', claim_token CHAR(36) NULL,
|
||||
lease_until BIGINT NOT NULL DEFAULT 0, retry_at BIGINT NOT NULL DEFAULT 0,
|
||||
file_key VARCHAR(80) NULL, file_hash CHAR(64) NULL, file_size BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL, generated_at BIGINT NULL,
|
||||
PRIMARY KEY(account_id,month), FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
|
|
|||
21
website/node/postbank-statement-archive.mjs
Normal file
21
website/node/postbank-statement-archive.mjs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import {readFile} from 'node:fs/promises';
|
||||
import {join,dirname} from 'node:path';
|
||||
import {createHash,randomUUID} from 'node:crypto';
|
||||
import {BankError} from './postbank-service.mjs';
|
||||
import {PostbankStatements,statementMonth} from './postbank-statements.mjs';
|
||||
export const statementSettings=settings=>({cacheDir:settings.POSTBANK_STATEMENT_CACHE||(settings.POSTBANK_DB_CONFIG?join(dirname(settings.POSTBANK_DB_CONFIG),'postbank-statements'):null),python:settings.POSTBANK_PYTHON,logo:settings.POSTBANK_STATEMENT_LOGO});
|
||||
const monthOf=time=>{const p=Object.fromEntries(new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit'}).formatToParts(new Date(time)).filter(p=>p.type!=='literal').map(p=>[p.type,p.value]));return p.year+'-'+p.month;};
|
||||
const nextMonth=month=>{const [y,m]=month.split('-').map(Number),d=new Date(Date.UTC(y,m,1));return d.toISOString().slice(0,7);};
|
||||
export class PostbankStatementArchive{
|
||||
constructor(db,payments,options={}){this.db=db;this.payments=payments;this.clock=options.clock||Date.now;this.cacheDir=options.cacheDir;this.renderer=options.renderer||new PostbankStatements(db,null,options);}
|
||||
async account(user,accountId){if(typeof accountId!=='string'||!/^\d{1,12}$/.test(accountId))throw new BankError('Select an account.');const account=(await this.payments.accounts(user)).find(a=>a.id===accountId);if(!account)throw new BankError('You cannot view this account.',403);return account;}
|
||||
async list(user,{accountId,page=1}){const account=await this.account(user,accountId);page=Number(page);if(!Number.isInteger(page)||page<1||page>999)throw new BankError('Select a valid archive page.');const current=monthOf(this.clock()),rows=await this.db.query('SELECT month,state,generated_at,file_size FROM pb_statement_archives WHERE account_id=? AND month<? ORDER BY month DESC LIMIT 13 OFFSET '+((page-1)*12),[accountId,current]);return {account:{id:account.id,number:account.number,name:account.name},records:rows.slice(0,12).map(r=>({month:r.month,state:r.state==='ready'?'ready':'preparing',generatedAt:r.generated_at?Number(r.generated_at):null,size:Number(r.file_size)})),hasMore:rows.length>12,page,nextClosing:statementMonth(current,this.clock()).end};}
|
||||
// Downloads only read an already archived file. Never render or enqueue here.
|
||||
async download(user,{accountId,month}){const account=await this.account(user,accountId),period=statementMonth(month,this.clock());if(period.provisional)throw new BankError('This month has not closed yet.',409);const row=await this.db.first("SELECT file_key,file_hash,file_size FROM pb_statement_archives WHERE account_id=? AND month=? AND state='ready'",[accountId,month]);if(!row)throw new BankError('This statement is not yet available. The bank prepares statements automatically after month-end.',404);if(!this.cacheDir||!/^[a-f0-9]{64}\.pdf$/.test(row.file_key||''))throw new BankError('Archived statement unavailable. Contact bank administration.',503);let pdf;try{pdf=await readFile(join(this.cacheDir,row.file_key));}catch{throw new BankError('Archived statement unavailable. Contact bank administration.',503);}if(pdf.length!==Number(row.file_size)||createHash('sha256').update(pdf).digest('hex')!==row.file_hash)throw new BankError('Archived statement integrity check failed.',503);return {pdf,filename:'Statement-'+account.number+'-'+month+'.pdf'};}
|
||||
// Trusted bank ticker only: account identity comes solely from the bank database.
|
||||
async seed(){const now=this.clock(),current=monthOf(now),first=await this.db.first('SELECT MIN(created_at) first_at FROM pb_accounts WHERE client_number IS NOT NULL');if(first?.first_at===null||first?.first_at===undefined)return;let month=monthOf(Number(first.first_at));if(month<'2026-01')month='2026-01';for(;month<current;month=nextMonth(month)){const period=statementMonth(month,now);await this.db.query("INSERT INTO pb_statement_archives(account_id,month,state,created_at) SELECT id,?,'pending',? FROM pb_accounts WHERE client_number IS NOT NULL AND created_at<? ON DUPLICATE KEY UPDATE account_id=VALUES(account_id)",[month,now,period.end]);}}
|
||||
async process({limit=25}={}){if(!this.cacheDir)return {attempted:0,completed:0,failed:0};let attempted=0,completed=0,failed=0;while(attempted<limit){const now=this.clock(),claim=await this.db.transaction(async tx=>{const row=await tx.first("SELECT account_id,month FROM pb_statement_archives WHERE ((state IN ('pending','failed') AND retry_at<=?) OR (state='processing' AND lease_until<?)) ORDER BY month,account_id LIMIT 1 FOR UPDATE",[now,now]);if(!row)return null;const token=randomUUID();await tx.query("UPDATE pb_statement_archives SET state='processing',claim_token=?,lease_until=? WHERE account_id=? AND month=?",[token,now+120000,row.account_id,row.month]);return {...row,token};});if(!claim)break;attempted++;
|
||||
try{const result=await this.renderer.prepare(String(claim.account_id),claim.month),hash=createHash('sha256').update(result.pdf).digest('hex');await this.db.query("UPDATE pb_statement_archives SET state='ready',file_key=?,file_hash=?,file_size=?,generated_at=?,claim_token=NULL,lease_until=0 WHERE account_id=? AND month=? AND claim_token=?",[result.fileKey,hash,result.pdf.length,this.clock(),claim.account_id,claim.month,claim.token]);completed++;}
|
||||
catch{await this.db.query("UPDATE pb_statement_archives SET state='failed',retry_at=?,claim_token=NULL,lease_until=0 WHERE account_id=? AND month=? AND claim_token=?",[this.clock()+4*3600000,claim.account_id,claim.month,claim.token]);failed++;}
|
||||
}return {attempted,completed,failed};}
|
||||
}
|
||||
|
|
@ -32,6 +32,15 @@ export class PostbankStatements{
|
|||
async download(user,{accountId,month}){
|
||||
if(typeof accountId!=='string'||!/^\d{1,12}$/.test(accountId))throw new BankError('Choose an account for your statement.');
|
||||
const period=statementMonth(month,this.clock()),accounts=await this.payments.accounts(user),account=accounts.find(a=>a.id===accountId);if(!account)throw new BankError('You cannot view this account.',403);
|
||||
return this.build(account,period);
|
||||
}
|
||||
async prepare(accountId,month){
|
||||
const period=statementMonth(month,this.clock());if(period.provisional)throw new BankError('Only closed months can be archived.',409);
|
||||
const account=await this.db.first('SELECT a.account_number number,a.display_name name,e.display_name holder FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE a.id=?',[accountId]);if(!account)throw new BankError('Account not found.',404);
|
||||
return this.build({...account,id:String(accountId)},period);
|
||||
}
|
||||
async build(account,period){
|
||||
const accountId=account.id,month=period.month;
|
||||
const snapshot=await this.db.transaction(async tx=>{
|
||||
const row=await tx.first('SELECT created_at FROM pb_accounts WHERE id=?',[accountId]);if(!row||Number(row.created_at)>=period.end)throw new BankError('This account did not exist during that month.',404);
|
||||
const opening=await tx.first('SELECT balance_after_minor,id FROM pb_entries WHERE account_id=? AND created_at<? ORDER BY created_at DESC,id DESC LIMIT 1',[accountId,period.start]);
|
||||
|
|
@ -41,7 +50,7 @@ export class PostbankStatements{
|
|||
// Cache fingerprints include ledger endpoints and holder details; no private URL is exposed.
|
||||
const signature=createHash('sha256').update(JSON.stringify(['statement-v1',account.number,account.name,account.holder,period.month,snapshot])).digest('hex');
|
||||
const cached=!period.provisional&&this.cacheDir?join(this.cacheDir,signature+'.pdf'):null;
|
||||
if(cached){try{const pdf=await readFile(cached);if(pdf.subarray(0,5).toString()==='%PDF-')return {pdf,filename:'Statement-'+account.number+'-'+month+'.pdf'};}catch(e){if(e.code!=='ENOENT')throw e;}}
|
||||
if(cached){try{const pdf=await readFile(cached);if(pdf.subarray(0,5).toString()==='%PDF-')return {pdf,fileKey:signature+'.pdf',filename:'Statement-'+account.number+'-'+month+'.pdf'};}catch(e){if(e.code!=='ENOENT')throw e;}}
|
||||
const rows=await this.db.query('SELECT e.id,e.created_at,e.amount_minor,e.balance_after_minor,o.id payment_id,o.memo,s.account_number source_number,t.account_number target_number,COALESCE(es.display_name,s.display_name) source_name,COALESCE(et.display_name,t.display_name) target_name FROM pb_entries e JOIN pb_orders o ON o.id=e.order_id JOIN pb_accounts s ON s.id=o.source_id LEFT JOIN pb_clients cs ON cs.client_number=s.client_number LEFT JOIN pb_entities es ON es.id=cs.entity_id JOIN pb_accounts t ON t.id=o.target_id LEFT JOIN pb_clients ct ON ct.client_number=t.client_number LEFT JOIN pb_entities et ON et.id=ct.entity_id WHERE e.account_id=? AND e.created_at>=? AND e.created_at<? AND e.id<=? ORDER BY e.created_at,e.id LIMIT 10001',[accountId,period.start,period.end,snapshot.lastId]);
|
||||
if(rows.length>10000)throw new BankError('This month exceeds the online statement limit. Contact bank administration for a complete export.',409);
|
||||
const data={account:{holder:account.holder,number:account.number,name:account.name},month,provisional:period.provisional,generatedAt:this.clock(),opening:snapshot.opening,closing:snapshot.closing,entries:rows.map(r=>({id:String(r.id),date:Number(r.created_at),paymentId:r.payment_id,reference:r.memo,from:{name:r.source_name,number:r.source_number},to:{name:r.target_name,number:r.target_number},amount:money(r.amount_minor),balance:money(r.balance_after_minor)}))};
|
||||
|
|
@ -51,6 +60,6 @@ export class PostbankStatements{
|
|||
const cents=value=>BigInt(value.replace('.',''));if(cents(data.opening)+total!==cents(data.closing))throw new BankError('Statement balances need reconciliation. Contact bank administration.',409);
|
||||
const pdf=await this.renderPDF(data);
|
||||
if(cached){await mkdir(this.cacheDir,{recursive:true,mode:0o700});const temp=cached+'.'+randomUUID()+'.tmp';try{await writeFile(temp,pdf,{mode:0o600,flag:'wx'});await rename(temp,cached);}finally{await unlink(temp).catch(()=>{});}}
|
||||
return {pdf,filename:'Statement-'+account.number+'-'+month+'.pdf'};
|
||||
return {pdf,fileKey:signature+'.pdf',filename:'Statement-'+account.number+'-'+month+'.pdf'};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff