159 lines
24 KiB
JavaScript
159 lines
24 KiB
JavaScript
import express from 'express';
|
|
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import crypto from 'node:crypto';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { createExcelReport, createPdfReport } from './reports.js';
|
|
|
|
const __filename=fileURLToPath(import.meta.url); const __dirname=path.dirname(__filename); const app=express();
|
|
const port=Number(process.env.PORT||3000); const dataFile=process.env.DATA_FILE||'/app/data/finance.json'; const dataDir=path.dirname(dataFile); const backupFile=`${dataFile}.bak`;
|
|
const pushoverFile=process.env.PUSHOVER_FILE||path.join(dataDir,'pushover.json'); const pushoverStateFile=process.env.PUSHOVER_STATE_FILE||path.join(dataDir,'pushover-state.json');
|
|
const reminderHour=Math.min(23,Math.max(0,Number(process.env.PUSHOVER_REMINDER_HOUR||8))); const PUSHOVER_ENDPOINT='https://api.pushover.net/1/messages.json';
|
|
const validIntervals=new Set(['monthly','quarterly','semiannual','yearly','once']);
|
|
const validScenarioTypes=new Set(['income','expense','transfer']);
|
|
const validAccountOwnerships=new Set(['personal','shared','unassigned']);
|
|
const validAccountFunctions=new Set(['giro','reserve','investment','building','other']);
|
|
const emptyData=()=>({version:11,settings:{includePeriodicInBalance:true},accounts:[],categories:[],persons:[],incomes:[],expenses:[],transfers:[],scenarios:[]});
|
|
const isFiniteNumber=value=>typeof value==='number'&&Number.isFinite(value);
|
|
|
|
function normalizeMovement(item={}) { const interval=validIntervals.has(item.interval)?item.interval:'monthly'; return { ...item, interval, dueMonth: interval!=='monthly'&&interval!=='once'&&Number.isInteger(Number(item.dueMonth)) ? Number(item.dueMonth) : null, oneTimeDate: interval==='once'&&typeof item.oneTimeDate==='string'&&item.oneTimeDate ? item.oneTimeDate : null, endDate: interval!=='once'&&typeof item.endDate==='string'&&item.endDate ? item.endDate : null }; }
|
|
function normalizeAmountChanges(changes){return Array.isArray(changes)?changes.map(c=>({id:typeof c.id==='string'&&c.id?c.id:crypto.randomUUID(),effectiveFrom:typeof c.effectiveFrom==='string'?c.effectiveFrom:'',amount:Number(c.amount||0)})).sort((a,b)=>a.effectiveFrom.localeCompare(b.effectiveFrom)):[];}
|
|
function normalizePersonIds(item={}) {
|
|
const raw=Array.isArray(item.personIds)?item.personIds:(typeof item.personId==='string'&&item.personId?[item.personId]:[]);
|
|
return [...new Set(raw.filter(id=>typeof id==='string'&&id))];
|
|
}
|
|
function normalizeOwnerPersonIds(item={}){const raw=Array.isArray(item.ownerPersonIds)?item.ownerPersonIds:[];return [...new Set(raw.filter(id=>typeof id==='string'&&id))];}
|
|
function normalizeAccount(item={}){
|
|
const ownership=validAccountOwnerships.has(item.ownership)?item.ownership:'unassigned';
|
|
const ownerPersonIds=ownership==='unassigned'?[]:normalizeOwnerPersonIds(item);
|
|
return {id:item.id,name:item.name,ownership,ownerPersonIds,accountFunction:validAccountFunctions.has(item.accountFunction)?item.accountFunction:'other'};
|
|
}
|
|
function normalizeCategorizedMovement(item={}) {
|
|
const normalized=normalizeMovement(item);
|
|
delete normalized.personId;
|
|
return { ...normalized, categoryId: typeof item.categoryId==='string' && item.categoryId ? item.categoryId : null, personIds: normalizePersonIds(item) };
|
|
}
|
|
function normalizeIncome(item={}) { return { ...normalizeCategorizedMovement(item), amountChanges: normalizeAmountChanges(item.amountChanges) }; }
|
|
function normalizeExpense(item={}) { return { ...normalizeCategorizedMovement(item), amountChanges: normalizeAmountChanges(item.amountChanges), pushoverReminder: item.pushoverReminder===true }; }
|
|
function normalizeScenarioAdjustment(item={}) {
|
|
const type=validScenarioTypes.has(item.type)?item.type:'expense';
|
|
const base={id:item.id,name:item.name,type,amount:Number(item.amount||0),personIds:normalizePersonIds(item)};
|
|
if(type==='transfer') return {...base,fromAccountId:item.fromAccountId,toAccountId:item.toAccountId};
|
|
return {...base,accountId:item.accountId};
|
|
}
|
|
function normalizeScenario(item={}) { return {id:item.id,name:item.name,createdAt:typeof item.createdAt==='string'?item.createdAt:null,adjustments:Array.isArray(item.adjustments)?item.adjustments.map(normalizeScenarioAdjustment):[]}; }
|
|
function normalizeData(input){
|
|
if(!input||typeof input!=='object')return input;
|
|
return {
|
|
version:11,
|
|
settings:{includePeriodicInBalance:input.settings?.includePeriodicInBalance!==false},
|
|
accounts:Array.isArray(input.accounts)?input.accounts.map(normalizeAccount):input.accounts,
|
|
categories:Array.isArray(input.categories)?input.categories.map(({id,name})=>({id,name})):[],
|
|
persons:Array.isArray(input.persons)?input.persons.map(({id,name})=>({id,name})):[],
|
|
incomes:Array.isArray(input.incomes)?input.incomes.map(normalizeIncome):input.incomes,
|
|
expenses:Array.isArray(input.expenses)?input.expenses.map(normalizeExpense):input.expenses,
|
|
transfers:Array.isArray(input.transfers)?input.transfers.map(normalizeCategorizedMovement):input.transfers,
|
|
scenarios:Array.isArray(input.scenarios)?input.scenarios.map(normalizeScenario):[],
|
|
};
|
|
}
|
|
function isValidDateString(value){if(typeof value!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(value))return false;const d=new Date(`${value}T00:00:00Z`);return !Number.isNaN(d.getTime())&&d.toISOString().slice(0,10)===value;}
|
|
function validateMovement(item){if(!item.id||typeof item.id!=='string')throw new Error('Eintrag ohne gültige ID.');if(!item.name||typeof item.name!=='string')throw new Error('Eintrag ohne Namen.');if(!isFiniteNumber(item.amount)||item.amount<0)throw new Error(`Ungültiger Betrag bei '${item.name}'.`);if(!validIntervals.has(item.interval))throw new Error(`Ungültiges Intervall bei '${item.name}'.`);if(item.interval==='once'&&(!item.oneTimeDate||!isValidDateString(item.oneTimeDate)))throw new Error(`Bitte ein gültiges Datum für die einmalige Position '${item.name}' setzen.`);if(item.dueMonth!==null&&item.dueMonth!==undefined&&(!Number.isInteger(item.dueMonth)||item.dueMonth<1||item.dueMonth>12))throw new Error(`Ungültiger Monat bei '${item.name}'.`);if(item.endDate!==null&&item.endDate!==undefined&&!isValidDateString(item.endDate))throw new Error(`Ungültiges Enddatum bei '${item.name}'.`);}
|
|
function validateAmountChanges(item){if(!Array.isArray(item.amountChanges))throw new Error(`Ungültige Betragsänderungen bei '${item.name}'.`);const dates=new Set();for(const change of item.amountChanges){if(!change.id||typeof change.id!=='string')throw new Error(`Betragsänderung ohne ID bei '${item.name}'.`);if(!isValidDateString(change.effectiveFrom))throw new Error(`Ungültiges Änderungsdatum bei '${item.name}'.`);if(!isFiniteNumber(change.amount)||change.amount<0)throw new Error(`Ungültiger Änderungsbetrag bei '${item.name}'.`);if(item.endDate&&change.effectiveFrom.slice(0,7)>item.endDate.slice(0,7))throw new Error(`Betragsänderung bei '${item.name}' liegt nach dem Enddatum.`);if(dates.has(change.effectiveFrom))throw new Error(`Für '${item.name}' existieren zwei Änderungen am selben Datum.`);dates.add(change.effectiveFrom);}}
|
|
function validatePersonAssignments(item,personIds,label='Eintrag'){
|
|
if(!Array.isArray(item.personIds))throw new Error(`Ungültige Personenzuordnung bei '${item.name||label}'.`);
|
|
const seen=new Set();
|
|
for(const id of item.personIds){
|
|
if(typeof id!=='string'||!id)throw new Error(`Ungültige Personenzuordnung bei '${item.name||label}'.`);
|
|
if(seen.has(id))throw new Error(`Person bei '${item.name||label}' doppelt zugeordnet.`);
|
|
if(!personIds.has(id))throw new Error(`Unbekannte Person bei '${item.name||label}'.`);
|
|
seen.add(id);
|
|
}
|
|
}
|
|
function validateData(input){
|
|
if(!input||typeof input!=='object')throw new Error('Ungültiges JSON.');
|
|
for(const key of ['accounts','categories','persons','incomes','expenses','transfers','scenarios'])if(!Array.isArray(input[key]))throw new Error(`Feld '${key}' muss ein Array sein.`);
|
|
const accountIds=new Set();
|
|
for(const a of input.accounts){if(!a.id||typeof a.id!=='string')throw new Error('Konto ohne gültige ID.');if(!a.name||typeof a.name!=='string'||!a.name.trim())throw new Error('Konto ohne Namen.');if(accountIds.has(a.id))throw new Error('Doppelte Konto-ID.');accountIds.add(a.id);}
|
|
const categoryIds=new Set(); const categoryNames=new Set();
|
|
for(const c of input.categories){if(!c.id||typeof c.id!=='string')throw new Error('Kategorie ohne gültige ID.');if(!c.name||typeof c.name!=='string'||!c.name.trim())throw new Error('Kategorie ohne Namen.');if(categoryIds.has(c.id))throw new Error('Doppelte Kategorie-ID.');const normalizedName=c.name.trim().toLocaleLowerCase('de-DE');if(categoryNames.has(normalizedName))throw new Error(`Kategorie '${c.name}' existiert bereits.`);categoryIds.add(c.id);categoryNames.add(normalizedName);}
|
|
const personIds=new Set(); const personNames=new Set();
|
|
for(const p of input.persons){if(!p.id||typeof p.id!=='string')throw new Error('Person ohne gültige ID.');if(!p.name||typeof p.name!=='string'||!p.name.trim())throw new Error('Person ohne Namen.');if(personIds.has(p.id))throw new Error('Doppelte Personen-ID.');const normalizedName=p.name.trim().toLocaleLowerCase('de-DE');if(personNames.has(normalizedName))throw new Error(`Person '${p.name}' existiert bereits.`);personIds.add(p.id);personNames.add(normalizedName);}
|
|
for(const a of input.accounts){
|
|
if(!validAccountOwnerships.has(a.ownership))throw new Error(`Ungültige Eigentumsart bei Konto '${a.name}'.`);
|
|
if(!validAccountFunctions.has(a.accountFunction))throw new Error(`Ungültige Kontofunktion bei '${a.name}'.`);
|
|
if(!Array.isArray(a.ownerPersonIds))throw new Error(`Ungültige Eigentümerzuordnung bei '${a.name}'.`);
|
|
const seen=new Set();for(const id of a.ownerPersonIds){if(typeof id!=='string'||!id||seen.has(id)||!personIds.has(id))throw new Error(`Ungültige Eigentümerzuordnung bei '${a.name}'.`);seen.add(id);}
|
|
if(a.ownership==='personal'&&a.ownerPersonIds.length!==1)throw new Error(`Persönliches Konto '${a.name}' braucht genau einen Eigentümer.`);
|
|
if(a.ownership==='shared'&&a.ownerPersonIds.length<2)throw new Error(`Gemeinschaftskonto '${a.name}' braucht mindestens zwei Eigentümer.`);
|
|
if(a.ownership==='unassigned'&&a.ownerPersonIds.length)throw new Error(`Nicht zugeordnetes Konto '${a.name}' darf keine Eigentümer enthalten.`);
|
|
}
|
|
for(const collection of ['incomes','expenses'])for(const item of input[collection]){validateMovement(item);validateAmountChanges(item);if(!accountIds.has(item.accountId))throw new Error(`Unbekanntes Konto bei '${item.name}'.`);if(item.categoryId!==null&&item.categoryId!==undefined&&!categoryIds.has(item.categoryId))throw new Error(`Unbekannte Kategorie bei '${item.name}'.`);validatePersonAssignments(item,personIds);if(collection==='expenses'&&typeof item.pushoverReminder!=='boolean')throw new Error(`Ungültige Reminder-Einstellung bei '${item.name}'.`);if(collection==='expenses'&&item.pushoverReminder&&item.interval!=='monthly'&&item.interval!=='once'&&(item.dueMonth===null||item.dueMonth===undefined))throw new Error(`Für den Pushover-Reminder von '${item.name}' muss ein Fälligkeitsmonat gesetzt sein.`);if(collection==='expenses'&&item.pushoverReminder&&item.interval==='once'&&!item.oneTimeDate)throw new Error(`Für den Pushover-Reminder von '${item.name}' muss ein Datum gesetzt sein.`);}
|
|
for(const t of input.transfers){validateMovement(t);if(!accountIds.has(t.fromAccountId)||!accountIds.has(t.toAccountId))throw new Error(`Unbekanntes Konto beim Transfer '${t.name}'.`);if(t.fromAccountId===t.toAccountId)throw new Error('Quell- und Zielkonto müssen verschieden sein.');if(t.categoryId!==null&&t.categoryId!==undefined&&!categoryIds.has(t.categoryId))throw new Error(`Unbekannte Kategorie beim Transfer '${t.name}'.`);validatePersonAssignments(t,personIds,'Transfer');}
|
|
const scenarioIds=new Set();
|
|
for(const s of input.scenarios){
|
|
if(!s.id||typeof s.id!=='string')throw new Error('Szenario ohne gültige ID.');
|
|
if(!s.name||typeof s.name!=='string'||!s.name.trim())throw new Error('Szenario ohne Namen.');
|
|
if(scenarioIds.has(s.id))throw new Error('Doppelte Szenario-ID.'); scenarioIds.add(s.id);
|
|
if(!Array.isArray(s.adjustments))throw new Error(`Szenario '${s.name}' hat ungültige Anpassungen.`);
|
|
const adjustmentIds=new Set();
|
|
for(const a of s.adjustments){
|
|
if(!a.id||typeof a.id!=='string'||adjustmentIds.has(a.id))throw new Error(`Ungültige Anpassungs-ID in '${s.name}'.`); adjustmentIds.add(a.id);
|
|
if(!a.name||typeof a.name!=='string'||!a.name.trim())throw new Error(`Anpassung ohne Namen in '${s.name}'.`);
|
|
if(!validScenarioTypes.has(a.type))throw new Error(`Ungültige Anpassungsart in '${s.name}'.`);
|
|
if(!isFiniteNumber(a.amount)||a.amount<0)throw new Error(`Ungültiger Szenario-Betrag bei '${a.name}'.`);
|
|
validatePersonAssignments(a,personIds,'Szenario-Anpassung');
|
|
if(a.type==='transfer') { if(!accountIds.has(a.fromAccountId)||!accountIds.has(a.toAccountId))throw new Error(`Unbekanntes Konto bei Szenario-Transfer '${a.name}'.`); if(a.fromAccountId===a.toAccountId)throw new Error(`Quell- und Zielkonto bei '${a.name}' müssen verschieden sein.`); }
|
|
else if(!accountIds.has(a.accountId))throw new Error(`Unbekanntes Konto bei Szenario-Anpassung '${a.name}'.`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const pushoverKeyPattern=/^[A-Za-z0-9]{30}$/;
|
|
function maskKey(value=''){return value?`${value.slice(0,4)}••••••${value.slice(-4)}`:'';}
|
|
async function readJsonFile(file,fallback){try{return JSON.parse(await fs.readFile(file,'utf8'));}catch(error){if(error.code==='ENOENT')return fallback;throw error;}}
|
|
async function writePrivateJson(file,value){await fs.mkdir(path.dirname(file),{recursive:true});const tmp=`${file}.${process.pid}.${crypto.randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value,null,2)+'\n',{encoding:'utf8',mode:0o600});await fs.rename(tmp,file);}
|
|
async function readPushoverConfig(){const value=await readJsonFile(pushoverFile,null);if(!value||!pushoverKeyPattern.test(value.token||'')||!pushoverKeyPattern.test(value.user||''))return null;return {token:value.token,user:value.user};}
|
|
async function savePushoverConfig(input){const token=String(input?.token||'').trim();const user=String(input?.user||'').trim();if(!pushoverKeyPattern.test(token))throw new Error('Der Pushover Application API Token muss 30 alphanumerische Zeichen enthalten.');if(!pushoverKeyPattern.test(user))throw new Error('Der Pushover User/Group Key muss 30 alphanumerische Zeichen enthalten.');await writePrivateJson(pushoverFile,{token,user,updatedAt:new Date().toISOString()});return {configured:true,userMasked:maskKey(user)};}
|
|
async function sendPushover(config,{title,message}){
|
|
const body=new URLSearchParams({token:config.token,user:config.user,title,message});
|
|
const response=await fetch(PUSHOVER_ENDPOINT,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','User-Agent':'FixFin/3.24'},body});
|
|
let payload={}; try{payload=await response.json();}catch{}
|
|
if(!response.ok||payload.status!==1)throw new Error(Array.isArray(payload.errors)?payload.errors.join(' '):`Pushover-API Fehler (${response.status})`);
|
|
return payload;
|
|
}
|
|
function monthKey(year,monthIndex){return `${year}-${String(monthIndex+1).padStart(2,'0')}`;}
|
|
function itemActiveInMonth(item,year,monthIndex){if((item?.interval||'monthly')==='once'){return String(item.oneTimeDate||'').slice(0,7)===monthKey(year,monthIndex);}const end=typeof item.endDate==='string'?item.endDate.slice(0,7):'';return !end||monthKey(year,monthIndex)<=end;}
|
|
function amountInMonth(item,year,monthIndex){const key=monthKey(year,monthIndex);let amount=Number(item.amount||0);let best='';for(const change of item.amountChanges||[]){const mk=String(change.effectiveFrom||'').slice(0,7);if(mk&&mk<=key&&mk>=best){best=mk;amount=Number(change.amount||0);}}return amount;}
|
|
function occursInReminderMonth(item,year,monthIndex){
|
|
if((item?.interval||'monthly')==='once')return String(item.oneTimeDate||'').slice(0,7)===monthKey(year,monthIndex);
|
|
if(!itemActiveInMonth(item,year,monthIndex))return false;
|
|
const interval=item.interval||'monthly'; if(interval==='monthly')return true;
|
|
const dueMonth=Number(item.dueMonth); if(!Number.isInteger(dueMonth)||dueMonth<1||dueMonth>12)return false;
|
|
const start=dueMonth-1; const step=interval==='quarterly'?3:interval==='semiannual'?6:12;
|
|
return monthIndex>=start&&(monthIndex-start)%step===0;
|
|
}
|
|
function reminderMessage(data,expense,now){
|
|
const account=data.accounts.find(a=>a.id===expense.accountId)?.name||'Unbekanntes Konto';
|
|
const amount=new Intl.NumberFormat('de-DE',{style:'currency',currency:'EUR'}).format(amountInMonth(expense,now.getFullYear(),now.getMonth()));
|
|
const month=new Intl.DateTimeFormat('de-DE',{month:'long'}).format(now);
|
|
return {title:`FixFin · ${expense.name}`,message:`Ausgabe im ${month}: ${amount}\nKonto: ${account}\nBitte prüfen, ob eine Umbuchung nötig ist.`};
|
|
}
|
|
async function runPushoverReminderCheck(){
|
|
const now=new Date(); if(now.getDate()!==1||now.getHours()<reminderHour)return;
|
|
const config=await readPushoverConfig(); if(!config)return;
|
|
const data=await readData(); const state=await readJsonFile(pushoverStateFile,{sent:{}}); if(!state.sent||typeof state.sent!=='object')state.sent={};
|
|
const monthKey=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`; let changed=false;
|
|
for(const expense of data.expenses.filter(x=>x.pushoverReminder===true&&occursInReminderMonth(x,now.getFullYear(),now.getMonth()))){
|
|
const key=`${monthKey}:${expense.id}`; if(state.sent[key])continue;
|
|
try{await sendPushover(config,reminderMessage(data,expense,now));state.sent[key]=new Date().toISOString();changed=true;console.log(`[Pushover] Reminder gesendet: ${expense.name}`);}catch(error){console.error(`[Pushover] Reminder fehlgeschlagen (${expense.name}):`,error.message);}
|
|
}
|
|
const keepAfter=new Date(now.getFullYear()-2,now.getMonth(),1); for(const key of Object.keys(state.sent)){const ym=key.slice(0,7);const [y,m]=ym.split('-').map(Number);if(Number.isInteger(y)&&Number.isInteger(m)&&new Date(y,m-1,1)<keepAfter){delete state.sent[key];changed=true;}}
|
|
if(changed)await writePrivateJson(pushoverStateFile,state);
|
|
}
|
|
|
|
async function ensureDataFile(){await fs.mkdir(dataDir,{recursive:true});try{await fs.access(dataFile);}catch{await atomicWrite(emptyData(),false);}}
|
|
async function readData(){await ensureDataFile();const raw=await fs.readFile(dataFile,'utf8');const parsed=JSON.parse(raw);const data=normalizeData(parsed);validateData(data);const movements=[...(parsed.incomes||[]),...(parsed.expenses||[]),...(parsed.transfers||[])];const scenarioAdjustments=(parsed.scenarios||[]).flatMap(s=>s.adjustments||[]);if(parsed.version!==11||!parsed.settings||!Array.isArray(parsed.categories)||!Array.isArray(parsed.persons)||!Array.isArray(parsed.scenarios)||movements.some(x=>!x.interval)||movements.some(x=>!Object.hasOwn(x,'categoryId'))||movements.some(x=>!Array.isArray(x.personIds)||Object.hasOwn(x,'personId'))||scenarioAdjustments.some(x=>!Array.isArray(x.personIds)||Object.hasOwn(x,'personId'))||(parsed.incomes||[]).some(x=>!Array.isArray(x.amountChanges))||(parsed.expenses||[]).some(x=>!Array.isArray(x.amountChanges)||!Object.hasOwn(x,'pushoverReminder'))||movements.some(x=>!Object.hasOwn(x,'endDate'))||movements.some(x=>x.interval==='once'&&!Object.hasOwn(x,'oneTimeDate'))||parsed.accounts?.some(a=>Object.hasOwn(a,'balance')||!Object.hasOwn(a,'ownership')||!Array.isArray(a.ownerPersonIds)||!Object.hasOwn(a,'accountFunction')))await atomicWrite(data,true);return data;}
|
|
async function atomicWrite(input,makeBackup=true){const data=normalizeData(input);validateData(data);await fs.mkdir(dataDir,{recursive:true});const tmp=`${dataFile}.${process.pid}.${crypto.randomUUID()}.tmp`;const payload=JSON.stringify(data,null,2)+'\n';if(makeBackup){try{await fs.copyFile(dataFile,backupFile);}catch(error){if(error.code!=='ENOENT')throw error;}}await fs.writeFile(tmp,payload,{encoding:'utf8',mode:0o600});await fs.rename(tmp,dataFile);}
|
|
app.disable('x-powered-by');app.use(express.json({limit:'1mb'}));app.get('/api/health',(_req,res)=>res.json({ok:true}));app.get('/api/data',async(_req,res,next)=>{try{res.json(await readData());}catch(e){next(e);}});app.put('/api/data',async(req,res,next)=>{try{await atomicWrite(req.body);res.json(await readData());}catch(e){next(e);}});app.get('/api/export',async(_req,res,next)=>{try{const data=await readData();res.setHeader('Content-Disposition','attachment; filename="fixfin-backup.json"');res.type('application/json').send(JSON.stringify(data,null,2)+'\n');}catch(e){next(e);}});app.get('/api/report.xlsx',async(req,res,next)=>{try{const data=await readData();const year=Number(req.query.year)||new Date().getFullYear();const accountId=typeof req.query.account==='string'?req.query.account:'';const personId=typeof req.query.person==='string'&&req.query.person?req.query.person:'all';const includeTransfers=req.query.transfers!=='0';const account=data.accounts.find(a=>a.id===accountId);if(!account)throw new Error('Bitte ein Konto für den Kontoauszug auswählen.');if(personId!=='all'&&!data.persons.some(p=>p.id===personId))throw new Error('Bitte eine gültige Person für den Kontoauszug auswählen.');const buffer=await createExcelReport(data,{year,accountId,personId,includeTransfers});const suffix=account.name.replace(/[^a-zA-Z0-9äöüÄÖÜß_-]+/g,'-');const personSuffix=personId==='all'?'':`-${data.persons.find(p=>p.id===personId)?.name||'Person'}`.replace(/[^a-zA-Z0-9äöüÄÖÜß_-]+/g,'-');res.setHeader('Content-Disposition',`attachment; filename="fixfin-kontoauszug-${year}-${suffix}${personSuffix}.xlsx"`);res.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').send(Buffer.from(buffer));}catch(e){next(e);}});app.get('/api/report.pdf',async(req,res,next)=>{try{const data=await readData();const year=Number(req.query.year)||new Date().getFullYear();const accountId=typeof req.query.account==='string'?req.query.account:'';const personId=typeof req.query.person==='string'&&req.query.person?req.query.person:'all';const includeTransfers=req.query.transfers!=='0';const account=data.accounts.find(a=>a.id===accountId);if(!account)throw new Error('Bitte ein Konto für den Kontoauszug auswählen.');if(personId!=='all'&&!data.persons.some(p=>p.id===personId))throw new Error('Bitte eine gültige Person für den Kontoauszug auswählen.');const buffer=await createPdfReport(data,{year,accountId,personId,includeTransfers});const suffix=account.name.replace(/[^a-zA-Z0-9äöüÄÖÜß_-]+/g,'-');const personSuffix=personId==='all'?'':`-${data.persons.find(p=>p.id===personId)?.name||'Person'}`.replace(/[^a-zA-Z0-9äöüÄÖÜß_-]+/g,'-');res.setHeader('Content-Disposition',`attachment; filename="fixfin-kontoauszug-${year}-${suffix}${personSuffix}.pdf"`);res.type('application/pdf').send(buffer);}catch(e){next(e);}});app.get('/api/pushover/config',async(_req,res,next)=>{try{const config=await readPushoverConfig();res.json(config?{configured:true,userMasked:maskKey(config.user)}:{configured:false,userMasked:''});}catch(e){next(e);}});app.put('/api/pushover/config',async(req,res,next)=>{try{res.json(await savePushoverConfig(req.body));}catch(e){next(e);}});app.delete('/api/pushover/config',async(_req,res,next)=>{try{await fs.rm(pushoverFile,{force:true});res.json({configured:false,userMasked:''});}catch(e){next(e);}});app.post('/api/pushover/test',async(_req,res,next)=>{try{const config=await readPushoverConfig();if(!config)throw new Error('Pushover ist noch nicht konfiguriert.');await sendPushover(config,{title:'FixFin · Test',message:'Pushover ist erfolgreich mit FixFin verbunden.'});res.json({ok:true});}catch(e){next(e);}});
|
|
const dist=path.resolve(__dirname,'../dist');app.use(express.static(dist));app.use((_req,res)=>res.sendFile(path.join(dist,'index.html')));app.use((error,_req,res,_next)=>{console.error(error);res.status(400).json({error:error.message||'Unbekannter Fehler'});});await ensureDataFile();app.listen(port,'0.0.0.0',()=>{console.log(`FixFin läuft auf Port ${port}`);console.log(`Datendatei: ${dataFile}`);console.log(`Pushover-Reminder: Prüfung am 1. des Monats ab ${String(reminderHour).padStart(2,'0')}:00 Uhr (${process.env.TZ||'System-Zeitzone'})`);});setTimeout(()=>runPushoverReminderCheck().catch(error=>console.error('[Pushover] Reminder-Prüfung fehlgeschlagen:',error)),5000);setInterval(()=>runPushoverReminderCheck().catch(error=>console.error('[Pushover] Reminder-Prüfung fehlgeschlagen:',error)),15*60*1000);
|