const express = require('express'); const sqlite3 = require('sqlite3').verbose(); const path = require('path'); const fs = require('fs'); const multer = require('multer'); // Minimal, dependency-free .env loader: load KEY=VALUE lines from a local // (git-ignored) .env file into process.env without overwriting existing vars. (function loadEnv() { try { const envPath = path.join(__dirname, '.env'); if (!fs.existsSync(envPath)) return; for (const raw of fs.readFileSync(envPath, 'utf8').split('\n')) { const line = raw.trim(); if (!line || line.startsWith('#')) continue; const eq = line.indexOf('='); if (eq === -1) continue; const key = line.slice(0, eq).trim(); let val = line.slice(eq + 1).trim(); if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { val = val.slice(1, -1); } if (key && !(key in process.env)) process.env[key] = val; } } catch (e) { console.warn('Konnte .env nicht laden:', e.message); } })(); const { generateApplicationDocuments } = require('./lib/documents'); const app = express(); const PORT = process.env.PORT || 3000; // Shared option lists (used in multiple views) const ART_OPTIONS = [ 'E-Mail', 'Online-Portal', 'Indeed', 'StepStone', 'Firmenwebsite', 'Post', 'Initiativbewerbung', 'Arbeitsagentur', 'Sonstiges' ]; const STATUS_OPTIONS = [ 'Entwurf', 'Gesendet', 'Eingangsbestätigung', 'Vorstellungsgespräch', 'Absage', 'Einstellung', 'Keine Rückmeldung' ]; // Base document types the user can provide as a foundation for AI tailoring const BASIS_TYP_OPTIONS = ['Anschreiben', 'Lebenslauf', 'Profil/Kurzprofil', 'Sonstiges']; // Middleware app.use(express.json({ limit: '2mb' })); app.use(express.urlencoded({ extended: true, limit: '2mb' })); app.use(express.static(path.join(__dirname, 'public'))); // Allow the browser extension (running on indeed.com) to call the import API. // Kept narrow: only the extension-facing endpoints need cross-origin access. app.use('/api/indeed-import', (req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'POST, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type'); if (req.method === 'OPTIONS') return res.sendStatus(204); next(); }); // Set EJS as template engine app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Ensure data directory exists const dataDir = path.join(__dirname, 'data'); if (!fs.existsSync(dataDir)) { fs.mkdirSync(dataDir, { recursive: true }); } // Directory for generated attachment files (application documents) const anhaengeDir = path.join(dataDir, 'anhaenge'); if (!fs.existsSync(anhaengeDir)) { fs.mkdirSync(anhaengeDir, { recursive: true }); } // Directory for static extra attachments (e.g. Zeugnisse) the user uploads once // and that are sent along with every generated application. const basisAnhaengeDir = path.join(dataDir, 'basis_anhaenge'); if (!fs.existsSync(basisAnhaengeDir)) { fs.mkdirSync(basisAnhaengeDir, { recursive: true }); } // Multipart upload for those static attachments const uploadBasisAnhang = multer({ storage: multer.diskStorage({ destination: (req, file, cb) => cb(null, basisAnhaengeDir), filename: (req, file, cb) => { const safe = String(file.originalname).replace(/[^a-zA-Z0-9._-]/g, '_'); cb(null, `${Date.now()}_${safe}`); }, }), limits: { fileSize: 15 * 1024 * 1024 }, // 15 MB }).single('datei'); // Database setup const dbPath = path.join(dataDir, 'bewerbungen.db'); const db = new sqlite3.Database(dbPath); // Sanitize input to prevent XSS function sanitizeInput(input) { if (typeof input !== 'string') return input; return input .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // Promise wrapper for db operations function dbGet(sql, params = []) { return new Promise((resolve, reject) => { db.get(sql, params, (err, result) => { if (err) reject(err); else resolve(result); }); }); } function dbAll(sql, params = []) { return new Promise((resolve, reject) => { db.all(sql, params, (err, results) => { if (err) reject(err); else resolve(results); }); }); } function dbRun(sql, params = []) { return new Promise((resolve, reject) => { db.run(sql, params, function(err) { if (err) reject(err); else resolve({ lastID: this.lastID, changes: this.changes }); }); }); } // Recompute an application's current status from its latest timeline entry async function syncCurrentStatus(bewerbungId) { const latest = await dbGet( 'SELECT status FROM status_verlauf WHERE bewerbung_id = ? ORDER BY date(datum) DESC, id DESC LIMIT 1', [bewerbungId] ); await dbRun( 'UPDATE bewerbungen SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [latest ? latest.status : '', bewerbungId] ); } // Attach the status timeline to each application (single query, grouped in JS) async function attachVerlauf(applications) { if (!applications.length) return applications; const all = await dbAll('SELECT * FROM status_verlauf ORDER BY date(datum) ASC, id ASC'); const byApp = {}; all.forEach((v) => { (byApp[v.bewerbung_id] = byApp[v.bewerbung_id] || []).push(v); }); applications.forEach((a) => { a.verlauf = byApp[a.id] || []; }); return applications; } // Run the AI document generation for one application (async, fire-and-forget). // Loads the base documents + user settings, asks the LLM to tailor them to the // job, writes the resulting PDFs to disk and links them as attachments. async function runGeneration(bewerbungId) { try { const bewerbung = await dbGet('SELECT * FROM bewerbungen WHERE id = ?', [bewerbungId]); if (!bewerbung) return; const basisDokumente = await dbAll('SELECT * FROM basis_dokumente ORDER BY id ASC'); const basisAnhaenge = await dbAll('SELECT * FROM basis_anhaenge ORDER BY id ASC'); const settings = await dbGet('SELECT * FROM settings WHERE id = 1'); const documents = await generateApplicationDocuments({ job: { firma: bewerbung.firma, stelle: bewerbung.stelle, ort: bewerbung.ort, quelle_url: bewerbung.quelle_url, stellenbeschreibung: bewerbung.stellenbeschreibung, }, basisDokumente, settings, // Names of the static attachments so the cover letter can list them under "Anlagen". zusatzAnlagen: basisAnhaenge.map((a) => a.name || a.dateiname), // Free-text notes (company address, contact person, extra context) for the LLM. llmNotizen: bewerbung.llm_notizen || '', }); let seq = 0; const storeAnhang = async (name, filename, mime, buffer) => { const stored = `${bewerbungId}_${Date.now()}_${seq++}_${filename}`; fs.writeFileSync(path.join(anhaengeDir, stored), buffer); await dbRun( 'INSERT INTO anhaenge (bewerbung_id, name, dateiname, mime, pfad) VALUES (?, ?, ?, ?, ?)', [bewerbungId, name, filename, mime, stored] ); }; // Generated (AI) documents for (const doc of documents) { await storeAnhang(doc.name, doc.filename, doc.mime, doc.buffer); } // Static extra attachments (e.g. Zeugnisse) — copied as-is for (const ba of basisAnhaenge) { const src = path.join(basisAnhaengeDir, ba.pfad); if (!fs.existsSync(src)) continue; await storeAnhang(ba.name || ba.dateiname, ba.dateiname, ba.mime || 'application/octet-stream', fs.readFileSync(src)); } await dbRun( "UPDATE bewerbungen SET generierung_status = 'fertig', generierung_fehler = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?", [bewerbungId] ); console.log(`Bewerbungsunterlagen für #${bewerbungId} generiert (${documents.length} Dokument(e)).`); } catch (error) { console.error(`Generierung für #${bewerbungId} fehlgeschlagen:`, error.message); await dbRun( "UPDATE bewerbungen SET generierung_status = 'fehler', generierung_fehler = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", [String(error.message || 'Unbekannter Fehler'), bewerbungId] ).catch(() => {}); } } // Initialize database - create tables and default settings in one operation function initializeDatabase() { return new Promise((resolve, reject) => { db.serialize(() => { db.run('PRAGMA foreign_keys = ON'); // Create tables db.run(` CREATE TABLE IF NOT EXISTS bewerbungen ( id INTEGER PRIMARY KEY AUTOINCREMENT, datum DATE NOT NULL, firma TEXT NOT NULL, stelle TEXT NOT NULL, art TEXT, status TEXT, notizen TEXT, interne_notizen TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `, (err) => { if (err) return reject(err); // Migration: add columns to pre-existing databases (ignore "duplicate column") db.run('ALTER TABLE bewerbungen ADD COLUMN interne_notizen TEXT', () => { db.run('ALTER TABLE bewerbungen ADD COLUMN ort TEXT', () => { db.run('ALTER TABLE bewerbungen ADD COLUMN stellenbeschreibung TEXT', () => { db.run('ALTER TABLE bewerbungen ADD COLUMN quelle_url TEXT', () => { db.run('ALTER TABLE bewerbungen ADD COLUMN generierung_status TEXT', () => { db.run('ALTER TABLE bewerbungen ADD COLUMN generierung_fehler TEXT', () => { db.run('ALTER TABLE bewerbungen ADD COLUMN llm_notizen TEXT', () => { // Chronological status changes, each with an optional comment db.run(` CREATE TABLE IF NOT EXISTS status_verlauf ( id INTEGER PRIMARY KEY AUTOINCREMENT, bewerbung_id INTEGER NOT NULL, datum DATE NOT NULL, status TEXT NOT NULL, kommentar TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (bewerbung_id) REFERENCES bewerbungen(id) ON DELETE CASCADE ) `, (err) => { if (err) return reject(err); // Base documents (Basis-Unterlagen) — the foundation the AI tailors from db.run(` CREATE TABLE IF NOT EXISTS basis_dokumente ( id INTEGER PRIMARY KEY AUTOINCREMENT, typ TEXT, name TEXT, inhalt TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `, (err) => { if (err) return reject(err); // Static extra attachments (e.g. Zeugnisse) attached to every application db.run(` CREATE TABLE IF NOT EXISTS basis_anhaenge ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, dateiname TEXT NOT NULL, mime TEXT, pfad TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `, (err) => { if (err) return reject(err); // Generated attachment files linked to an application db.run(` CREATE TABLE IF NOT EXISTS anhaenge ( id INTEGER PRIMARY KEY AUTOINCREMENT, bewerbung_id INTEGER NOT NULL, name TEXT, dateiname TEXT NOT NULL, mime TEXT, pfad TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (bewerbung_id) REFERENCES bewerbungen(id) ON DELETE CASCADE ) `, (err) => { if (err) return reject(err); db.run(` CREATE TABLE IF NOT EXISTS settings ( id INTEGER PRIMARY KEY CHECK (id = 1), name TEXT, adresse TEXT, kundennummer TEXT ) `, (err) => { if (err) return reject(err); // Insert default settings if not exists db.get('SELECT COUNT(*) as count FROM settings WHERE id = 1', (err, result) => { if (err) return reject(err); if (result && result.count === 0) { db.run( 'INSERT INTO settings (id, name, adresse, kundennummer) VALUES (1, ?, ?, ?)', ['Max Mustermann', 'Musterstraße 1, 12345 Musterstadt', ''], (err) => { if (err) return reject(err); resolve(); } ); } else { resolve(); } }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); } // Initialize and start server initializeDatabase().then(() => { console.log('Database initialized successfully'); // Routes app.get('/', async (req, res) => { try { const { month, year } = req.query; let query = 'SELECT * FROM bewerbungen ORDER BY datum DESC, created_at DESC'; const params = []; if (month && year) { query = 'SELECT * FROM bewerbungen WHERE strftime("%m", datum) = ? AND strftime("%Y", datum) = ? ORDER BY datum DESC, created_at DESC'; params.push(month.padStart(2, '0'), year); } else if (year) { query = 'SELECT * FROM bewerbungen WHERE strftime("%Y", datum) = ? ORDER BY datum DESC, created_at DESC'; params.push(year); } const applications = await dbAll(query, params); await attachVerlauf(applications); const settings = await dbGet('SELECT * FROM settings WHERE id = 1'); // Get statistics const totalCount = await dbGet('SELECT COUNT(*) as count FROM bewerbungen'); const byArt = await dbAll(` SELECT art, COUNT(*) as count FROM bewerbungen WHERE art IS NOT NULL AND art != '' GROUP BY art ORDER BY count DESC `); const byStatus = await dbAll(` SELECT status, COUNT(*) as count FROM bewerbungen WHERE status IS NOT NULL AND status != '' GROUP BY status ORDER BY count DESC `); // Get available months/years for filter const availableMonths = await dbAll(` SELECT DISTINCT strftime("%Y-%m", datum) as yearmonth, strftime("%m", datum) as month, strftime("%Y", datum) as year FROM bewerbungen ORDER BY datum DESC `); res.render('index', { applications, settings, statistics: { total: totalCount ? totalCount.count : 0, byArt, byStatus }, availableMonths, currentFilter: { month, year }, artOptions: ART_OPTIONS, statusOptions: STATUS_OPTIONS }); } catch (error) { console.error('Error:', error); res.status(500).send('Serverfehler'); } }); // Get single application app.get('/api/bewerbungen/:id', async (req, res) => { try { const { id } = req.params; const application = await dbGet('SELECT * FROM bewerbungen WHERE id = ?', [id]); if (!application) { return res.status(404).json({ error: 'Bewerbung nicht gefunden' }); } res.json(application); } catch (error) { console.error('Error getting application:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // Get settings app.get('/api/settings', async (req, res) => { try { const settings = await dbGet('SELECT * FROM settings WHERE id = 1'); res.json(settings); } catch (error) { console.error('Error getting settings:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // Save settings app.post('/api/settings', async (req, res) => { try { const { name, adresse, kundennummer } = req.body; await dbRun( 'UPDATE settings SET name = ?, adresse = ?, kundennummer = ? WHERE id = 1', [sanitizeInput(name), sanitizeInput(adresse), sanitizeInput(kundennummer)] ); res.json({ success: true }); } catch (error) { console.error('Error saving settings:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // ----- Indeed import (called by the browser extension) ----- app.post('/api/indeed-import', async (req, res) => { try { const { firma, stelle, ort, gehalt, stellenbeschreibung, quelle_url } = req.body || {}; if (!firma || !stelle) { return res.status(400).json({ error: 'Firma und Stelle sind erforderlich.' }); } const datum = new Date().toISOString().split('T')[0]; // Keep the extra details (location, salary, source) visible in the notes too. const notizParts = [ ort ? `Ort: ${ort}` : null, gehalt ? `Gehalt: ${gehalt}` : null, quelle_url ? `Quelle: ${quelle_url}` : null, ].filter(Boolean); const notizen = notizParts.join('\n'); // Stored raw: every view renders these through EJS `<%= %>` (auto-escaped), // so this is XSS-safe — and it keeps the text clean for the AI and the PDFs // (no HTML entities leaking into the generated documents). const result = await dbRun( `INSERT INTO bewerbungen (datum, firma, stelle, art, status, notizen, ort, stellenbeschreibung, quelle_url, generierung_status) VALUES (?, ?, ?, 'Indeed', 'Entwurf', ?, ?, ?, ?, 'nicht_gestartet')`, [datum, firma, stelle, notizen, ort || '', stellenbeschreibung || '', quelle_url || ''] ); // Record the initial "Entwurf" status in the timeline await dbRun( 'INSERT INTO status_verlauf (bewerbung_id, datum, status, kommentar) VALUES (?, ?, ?, ?)', [result.lastID, datum, 'Entwurf', 'Automatisch über Indeed importiert'] ); // Note: generation is NOT started automatically — the user reviews the draft, // adds LLM notes if needed, and triggers generation on the application page. res.json({ success: true, id: result.lastID, url: `/bewerbung/${result.lastID}`, message: 'Bewerbung als Entwurf angelegt. Unterlagen können auf der Bewerbungsseite generiert werden.', }); } catch (error) { console.error('Error importing job:', error); res.status(500).json({ error: 'Serverfehler beim Import.' }); } }); // Poll generation status + current attachments for one application app.get('/api/bewerbungen/:id/generierung', async (req, res) => { try { const { id } = req.params; const bewerbung = await dbGet( 'SELECT id, generierung_status, generierung_fehler FROM bewerbungen WHERE id = ?', [id] ); if (!bewerbung) return res.status(404).json({ error: 'Bewerbung nicht gefunden' }); const anhaenge = await dbAll( 'SELECT id, name, dateiname, mime FROM anhaenge WHERE bewerbung_id = ? ORDER BY id ASC', [id] ); res.json({ status: bewerbung.generierung_status, fehler: bewerbung.generierung_fehler, anhaenge, }); } catch (error) { console.error('Error fetching generation status:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // ----- Base documents (Basis-Unterlagen / Vorlagen) ----- app.get('/api/basis-dokumente', async (req, res) => { try { const docs = await dbAll('SELECT * FROM basis_dokumente ORDER BY id ASC'); res.json(docs); } catch (error) { console.error('Error listing base documents:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // Create application app.post('/api/bewerbungen', async (req, res) => { try { const { datum, firma, stelle, art, status, notizen, interne_notizen, kommentar } = req.body; const result = await dbRun( 'INSERT INTO bewerbungen (datum, firma, stelle, art, status, notizen, interne_notizen) VALUES (?, ?, ?, ?, ?, ?, ?)', [datum, sanitizeInput(firma), sanitizeInput(stelle), sanitizeInput(art), sanitizeInput(status), sanitizeInput(notizen), sanitizeInput(interne_notizen)] ); // Record the initial status as the first timeline entry if (status && status.trim()) { await dbRun( 'INSERT INTO status_verlauf (bewerbung_id, datum, status, kommentar) VALUES (?, ?, ?, ?)', [result.lastID, datum, sanitizeInput(status), sanitizeInput(kommentar || '')] ); } const newApplication = await dbGet('SELECT * FROM bewerbungen WHERE id = ?', [result.lastID]); res.json({ success: true, application: newApplication }); } catch (error) { console.error('Error creating application:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // Update application app.put('/api/bewerbungen/:id', async (req, res) => { try { const { id } = req.params; const { datum, firma, stelle, art, status, notizen } = req.body; await dbRun( 'UPDATE bewerbungen SET datum = ?, firma = ?, stelle = ?, art = ?, status = ?, notizen = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [datum, sanitizeInput(firma), sanitizeInput(stelle), sanitizeInput(art), sanitizeInput(status), sanitizeInput(notizen), id] ); const updatedApplication = await dbGet('SELECT * FROM bewerbungen WHERE id = ?', [id]); res.json({ success: true, application: updatedApplication }); } catch (error) { console.error('Error updating application:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // Delete application app.delete('/api/bewerbungen/:id', async (req, res) => { try { const { id } = req.params; await dbRun('DELETE FROM status_verlauf WHERE bewerbung_id = ?', [id]); await dbRun('DELETE FROM bewerbungen WHERE id = ?', [id]); res.json({ success: true }); } catch (error) { console.error('Error deleting application:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // Applications for PDF export (optionally filtered), including the status timeline app.get('/api/export', async (req, res) => { try { const { month, year } = req.query; let query = 'SELECT * FROM bewerbungen ORDER BY datum DESC'; const params = []; if (month && year) { query = 'SELECT * FROM bewerbungen WHERE strftime("%m", datum) = ? AND strftime("%Y", datum) = ? ORDER BY datum DESC'; params.push(month.padStart(2, '0'), year); } else if (year) { query = 'SELECT * FROM bewerbungen WHERE strftime("%Y", datum) = ? ORDER BY datum DESC'; params.push(year); } const applications = await dbAll(query, params); await attachVerlauf(applications); // Internal notes must never reach the PDF/export applications.forEach((a) => { delete a.interne_notizen; }); res.json(applications); } catch (error) { console.error('Error exporting applications:', error); res.status(500).json({ error: 'Serverfehler' }); } }); // ----- Dedicated edit page + status-timeline management ----- // Edit page for a single application app.get('/bewerbung/:id', async (req, res) => { try { const { id } = req.params; const application = await dbGet('SELECT * FROM bewerbungen WHERE id = ?', [id]); if (!application) return res.status(404).send('Bewerbung nicht gefunden'); const verlauf = await dbAll( 'SELECT * FROM status_verlauf WHERE bewerbung_id = ? ORDER BY date(datum) ASC, id ASC', [id] ); const anhaenge = await dbAll( 'SELECT id, name, dateiname, mime, created_at FROM anhaenge WHERE bewerbung_id = ? ORDER BY id ASC', [id] ); const basisCountRow = await dbGet('SELECT COUNT(*) as count FROM basis_dokumente'); res.render('bewerbung', { application, verlauf, anhaenge, basisCount: basisCountRow ? basisCountRow.count : 0, artOptions: ART_OPTIONS, statusOptions: STATUS_OPTIONS, hideSettings: true }); } catch (error) { console.error('Error loading edit page:', error); res.status(500).send('Serverfehler'); } }); // Update application core data (status is managed via the timeline) app.post('/bewerbung/:id', async (req, res) => { try { const { id } = req.params; const { datum, firma, stelle, art, notizen, interne_notizen } = req.body; await dbRun( 'UPDATE bewerbungen SET datum = ?, firma = ?, stelle = ?, art = ?, notizen = ?, interne_notizen = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', [datum, sanitizeInput(firma), sanitizeInput(stelle), sanitizeInput(art), sanitizeInput(notizen), sanitizeInput(interne_notizen), id] ); res.redirect('/bewerbung/' + id); } catch (error) { console.error('Error updating application:', error); res.status(500).send('Serverfehler'); } }); // Add a timeline entry (status change with date + comment) app.post('/bewerbung/:id/verlauf', async (req, res) => { try { const { id } = req.params; const { datum, status, kommentar } = req.body; if (datum && status && status.trim()) { await dbRun( 'INSERT INTO status_verlauf (bewerbung_id, datum, status, kommentar) VALUES (?, ?, ?, ?)', [id, datum, sanitizeInput(status), sanitizeInput(kommentar || '')] ); await syncCurrentStatus(id); } res.redirect('/bewerbung/' + id); } catch (error) { console.error('Error adding timeline entry:', error); res.status(500).send('Serverfehler'); } }); // Update a timeline entry app.post('/bewerbung/:id/verlauf/:eintragId', async (req, res) => { try { const { id, eintragId } = req.params; const { datum, status, kommentar } = req.body; if (datum && status && status.trim()) { await dbRun( 'UPDATE status_verlauf SET datum = ?, status = ?, kommentar = ? WHERE id = ? AND bewerbung_id = ?', [datum, sanitizeInput(status), sanitizeInput(kommentar || ''), eintragId, id] ); await syncCurrentStatus(id); } res.redirect('/bewerbung/' + id); } catch (error) { console.error('Error updating timeline entry:', error); res.status(500).send('Serverfehler'); } }); // Delete a timeline entry app.post('/bewerbung/:id/verlauf/:eintragId/delete', async (req, res) => { try { const { id, eintragId } = req.params; await dbRun('DELETE FROM status_verlauf WHERE id = ? AND bewerbung_id = ?', [eintragId, id]); await syncCurrentStatus(id); res.redirect('/bewerbung/' + id); } catch (error) { console.error('Error deleting timeline entry:', error); res.status(500).send('Serverfehler'); } }); // ----- Vorlagen (Basis-Unterlagen) management page ----- app.get('/vorlagen', async (req, res) => { try { const basisDokumente = await dbAll('SELECT * FROM basis_dokumente ORDER BY id ASC'); const basisAnhaenge = await dbAll('SELECT * FROM basis_anhaenge ORDER BY id ASC'); res.render('vorlagen', { basisDokumente, basisAnhaenge, basisTypOptions: BASIS_TYP_OPTIONS, hasApiKey: Boolean(process.env.OLLAMA_API_KEY), hideSettings: true, }); } catch (error) { console.error('Error loading vorlagen:', error); res.status(500).send('Serverfehler'); } }); // Add a base document app.post('/vorlagen', async (req, res) => { try { const { typ, name, inhalt } = req.body; if (inhalt && inhalt.trim()) { await dbRun( 'INSERT INTO basis_dokumente (typ, name, inhalt) VALUES (?, ?, ?)', [sanitizeInput(typ || 'Sonstiges'), sanitizeInput(name || ''), inhalt] ); } res.redirect('/vorlagen'); } catch (error) { console.error('Error adding base document:', error); res.status(500).send('Serverfehler'); } }); // Update a base document app.post('/vorlagen/:id', async (req, res) => { try { const { id } = req.params; const { typ, name, inhalt } = req.body; await dbRun( 'UPDATE basis_dokumente SET typ = ?, name = ?, inhalt = ? WHERE id = ?', [sanitizeInput(typ || 'Sonstiges'), sanitizeInput(name || ''), inhalt || '', id] ); res.redirect('/vorlagen'); } catch (error) { console.error('Error updating base document:', error); res.status(500).send('Serverfehler'); } }); // Delete a base document app.post('/vorlagen/:id/delete', async (req, res) => { try { await dbRun('DELETE FROM basis_dokumente WHERE id = ?', [req.params.id]); res.redirect('/vorlagen'); } catch (error) { console.error('Error deleting base document:', error); res.status(500).send('Serverfehler'); } }); // ----- Static extra attachments (Zeugnisse etc.) ----- // Upload an attachment app.post('/anlagen', (req, res) => { uploadBasisAnhang(req, res, async (err) => { try { if (err) { console.error('Upload error:', err.message); return res.redirect('/vorlagen'); } if (req.file) { const original = req.file.originalname || req.file.filename; const name = (req.body.name && req.body.name.trim()) ? sanitizeInput(req.body.name.trim()) : sanitizeInput(original.replace(/\.[^.]+$/, '')); await dbRun( 'INSERT INTO basis_anhaenge (name, dateiname, mime, pfad) VALUES (?, ?, ?, ?)', [name, sanitizeInput(original), req.file.mimetype || 'application/octet-stream', req.file.filename] ); } res.redirect('/vorlagen'); } catch (error) { console.error('Error saving attachment:', error); res.status(500).send('Serverfehler'); } }); }); // Download a static attachment app.get('/anlagen/:id/download', async (req, res) => { try { const a = await dbGet('SELECT * FROM basis_anhaenge WHERE id = ?', [req.params.id]); if (!a) return res.status(404).send('Anlage nicht gefunden'); const filePath = path.join(basisAnhaengeDir, a.pfad); if (!fs.existsSync(filePath)) return res.status(404).send('Datei nicht gefunden'); res.download(filePath, a.dateiname); } catch (error) { console.error('Error downloading attachment:', error); res.status(500).send('Serverfehler'); } }); // Delete a static attachment app.post('/anlagen/:id/delete', async (req, res) => { try { const a = await dbGet('SELECT * FROM basis_anhaenge WHERE id = ?', [req.params.id]); if (a) { fs.promises.unlink(path.join(basisAnhaengeDir, a.pfad)).catch(() => {}); await dbRun('DELETE FROM basis_anhaenge WHERE id = ?', [req.params.id]); } res.redirect('/vorlagen'); } catch (error) { console.error('Error deleting attachment:', error); res.status(500).send('Serverfehler'); } }); // Download a generated attachment app.get('/anhaenge/:id/download', async (req, res) => { try { const anhang = await dbGet('SELECT * FROM anhaenge WHERE id = ?', [req.params.id]); if (!anhang) return res.status(404).send('Anhang nicht gefunden'); const filePath = path.join(anhaengeDir, anhang.pfad); if (!fs.existsSync(filePath)) return res.status(404).send('Datei nicht gefunden'); res.download(filePath, anhang.dateiname); } catch (error) { console.error('Error downloading attachment:', error); res.status(500).send('Serverfehler'); } }); // Delete a generated attachment app.post('/bewerbung/:id/anhaenge/:anhangId/delete', async (req, res) => { try { const { id, anhangId } = req.params; const anhang = await dbGet('SELECT * FROM anhaenge WHERE id = ? AND bewerbung_id = ?', [anhangId, id]); if (anhang) { const filePath = path.join(anhaengeDir, anhang.pfad); fs.promises.unlink(filePath).catch(() => {}); await dbRun('DELETE FROM anhaenge WHERE id = ?', [anhangId]); } res.redirect('/bewerbung/' + id); } catch (error) { console.error('Error deleting attachment:', error); res.status(500).send('Serverfehler'); } }); // Start (or re-run) the AI generation for an application. Saves the LLM notes // first, removes any previously generated attachments, then generates. app.post('/bewerbung/:id/generieren', async (req, res) => { try { const { id } = req.params; const bewerbung = await dbGet('SELECT id FROM bewerbungen WHERE id = ?', [id]); if (!bewerbung) return res.status(404).send('Bewerbung nicht gefunden'); // Persist the LLM notes the user provided (used as context during generation) if (typeof req.body.llm_notizen !== 'undefined') { await dbRun('UPDATE bewerbungen SET llm_notizen = ? WHERE id = ?', [req.body.llm_notizen || '', id]); } const alte = await dbAll('SELECT * FROM anhaenge WHERE bewerbung_id = ?', [id]); for (const a of alte) { fs.promises.unlink(path.join(anhaengeDir, a.pfad)).catch(() => {}); } await dbRun('DELETE FROM anhaenge WHERE bewerbung_id = ?', [id]); await dbRun("UPDATE bewerbungen SET generierung_status = 'ausstehend', generierung_fehler = NULL WHERE id = ?", [id]); runGeneration(id); res.redirect('/bewerbung/' + id); } catch (error) { console.error('Error generating documents:', error); res.status(500).send('Serverfehler'); } }); // Start server app.listen(PORT, () => { console.log(`Server läuft auf http://localhost:${PORT}`); }); // Handle 404 app.use((req, res) => { res.status(404).send('Seite nicht gefunden'); }); }).catch((err) => { console.error('Failed to initialize database:', err); process.exit(1); }); // Close database on exit process.on('SIGINT', () => { db.close(); process.exit(); }); process.on('SIGTERM', () => { db.close(); process.exit(); });