const db = require("../db"); const ejs = require("ejs"); const path = require("path"); const fs = require("fs"); const pdf = require("html-pdf-node"); async function createInvoicePdf(req, res) { const patientId = req.params.id; try { // 1️⃣ Patient laden const [[patient]] = await db.promise().query( "SELECT * FROM patients WHERE id = ?", [patientId] ); if (!patient) { return res.status(404).send("Patient nicht gefunden"); } // 2️⃣ Leistungen laden const [rows] = await db.promise().query(` SELECT ps.quantity, COALESCE(ps.price_override, s.price) AS price, CASE WHEN UPPER(TRIM(?)) = 'ES' THEN COALESCE(NULLIF(s.name_es, ''), s.name_de) ELSE s.name_de END AS name FROM patient_services ps JOIN services s ON ps.service_id = s.id WHERE ps.patient_id = ? AND ps.invoice_id IS NULL `, [patient.country, patientId]); if (rows.length === 0) { return res.send("Keine Leistungen vorhanden"); } const services = rows.map(s => ({ quantity: Number(s.quantity), name: s.name, price: Number(s.price), total: Number(s.price) * Number(s.quantity) })); const total = services.reduce((sum, s) => sum + s.total, 0); // 3️⃣ HTML rendern (NOCH OHNE invoiceId) const invoice = { number: "—", date: new Date().toLocaleDateString("de-DE") }; const html = await ejs.renderFile( path.join(__dirname, "../views/invoices/invoice.ejs"), { patient, services, total, invoice } ); // 4️⃣ PDF erzeugen const pdfBuffer = await pdf.generatePdf( { content: html }, { format: "A4" } ); // 5️⃣ Datei speichern const dateStr = new Date().toISOString().split("T")[0]; const fileName = `invoice_${patientId}_${dateStr}.pdf`; const outputPath = path.join(__dirname, "..", "documents", fileName); fs.writeFileSync(outputPath, pdfBuffer); // 6️⃣ Rechnung EINMAL in DB speichern const [invoiceResult] = await db.promise().query(` INSERT INTO invoices (patient_id, invoice_date, total_amount, file_path, created_by, status) VALUES (?, CURDATE(), ?, ?, ?, 'open') `, [ patientId, total, `documents/${fileName}`, req.session.user.id ]); const invoiceId = invoiceResult.insertId; // 7️⃣ Leistungen verknüpfen await db.promise().query(` UPDATE patient_services SET invoice_id = ? WHERE patient_id = ? AND invoice_id IS NULL `, [invoiceId, patientId]); // 8️⃣ PDF anzeigen res.setHeader("Content-Type", "application/pdf"); res.setHeader( "Content-Disposition", `inline; filename="${fileName}"` ); res.send(pdfBuffer); } catch (err) { console.error("❌ PDF ERROR:", err); res.status(500).send("Fehler beim Erstellen der Rechnung"); } } module.exports = { createInvoicePdf };