web/website/node/postbank-statement-archive.mjs
2026-11-27 23:43:05 +00:00

21 lines
5.4 KiB
JavaScript

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};}
}