web/website/node/postbank-statements.mjs
2026-11-14 14:59:32 +01:00

65 lines
7.8 KiB
JavaScript

import {spawn} from 'node:child_process';
import {createHash,randomUUID} from 'node:crypto';
import {readFile,writeFile,mkdir,rename,unlink} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import {join} from 'node:path';
import {BankError} from './postbank-service.mjs';
import {money} from './postbank-catalogue.mjs';
const calendar=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit'});
export function statementMonth(month,now=Date.now()){
if(typeof month!=='string'||!/^\d{4}-(0[1-9]|1[0-2])$/.test(month))throw new BankError('Choose a valid statement month.');
const parts=Object.fromEntries(calendar.formatToParts(new Date(now)).filter(p=>p.type!=='literal').map(p=>[p.type,p.value])),current=parts.year+'-'+parts.month;
if(month>current||month<'2026-01')throw new BankError('Choose a month that has started.');
const [year,m]=month.split('-').map(Number);
const boundary=(y,mo)=>{const wanted=Date.UTC(y,mo-1,1),fmt=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',hourCycle:'h23'});let guess=wanted;for(let i=0;i<4;i++){const p=Object.fromEntries(fmt.formatToParts(new Date(guess)).filter(p=>p.type!=='literal').map(p=>[p.type,Number(p.value)]));const delta=wanted-Date.UTC(p.year,p.month-1,p.day,p.hour);if(!delta)return guess;guess+=delta;}throw Error('Statement calendar unavailable.');};
return {month,start:boundary(year,m),end:boundary(m===12?year+1:year,m===12?1:m+1),provisional:month===current};
}
let renders=0;
export async function renderStatementPDF(data,{python='python3',logo=fileURLToPath(new URL('../web/assets/imperial-postbank-v2.png',import.meta.url))}={}){
if(renders>=2)throw new BankError('Statement generation is busy. Try again shortly.',429);renders++;
try{return await new Promise((resolve,reject)=>{
const child=spawn(python,[fileURLToPath(new URL('./postbank-statement.py',import.meta.url)),logo],{stdio:['pipe','pipe','pipe'],windowsHide:true});let chunks=[],length=0,done=false;
const finish=(error,buffer)=>{if(done)return;done=true;clearTimeout(timer);if(error){child.kill();reject(error);}else resolve(buffer);};
const timer=setTimeout(()=>finish(new Error('Statement rendering timed out.')),30000);timer.unref();
child.on('error',()=>finish(new Error('Statement renderer unavailable.')));child.stdin.on('error',()=>finish(new Error('Statement rendering interrupted.')));child.stderr.resume();
child.stdout.on('data',chunk=>{length+=chunk.length;if(length>12*1024*1024)finish(new Error('Statement exceeds the download limit.'));else chunks.push(chunk);});
child.on('close',code=>{const pdf=Buffer.concat(chunks);finish(code!==0||pdf.subarray(0,5).toString()!=='%PDF-'?new Error('Statement rendering failed.'):null,pdf);});
child.stdin.end(JSON.stringify(data));
});}finally{renders--;}
}
export class PostbankStatements{
constructor(db,payments,{clock=Date.now,renderPDF=renderStatementPDF,cacheDir=null,python,logo}={}){this.db=db;this.payments=payments;this.clock=clock;this.renderPDF=data=>renderPDF(data,{python,logo});this.cacheDir=cacheDir;}
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]);
const closing=await tx.first('SELECT balance_after_minor,id FROM pb_entries WHERE account_id=? AND created_at>=? AND created_at<? ORDER BY created_at DESC,id DESC LIMIT 1',[accountId,period.start,period.end]);
const initial=opening?.balance_after_minor||'0';return {opening:money(initial),closing:money(closing?.balance_after_minor??initial),lastId:String(closing?.id||0),openingId:String(opening?.id||0)};
});
// 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,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,CASE WHEN o.mode=\'grant\' AND s.system_key=\'sys_bank_capital_issuer\' THEN \'Grand Nagus\' ELSE COALESCE(es.display_name,s.display_name) END 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)}))};
// Assert the selected ledger slice closes exactly; never publish a truncated statement.
if(data.entries.length?data.entries.at(-1).balance!==data.closing:snapshot.lastId!=='0')throw new BankError('The statement changed while loading. Please retry.',409);
const total=rows.reduce((sum,r)=>sum+BigInt(r.amount_minor),0n);
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,fileKey:signature+'.pdf',filename:'Statement-'+account.number+'-'+month+'.pdf'};
}
}