diff --git a/src/Controllers/InvoiceController.php b/src/Controllers/InvoiceController.php index 7a3f4c8..1eaeec4 100644 --- a/src/Controllers/InvoiceController.php +++ b/src/Controllers/InvoiceController.php @@ -275,12 +275,13 @@ class InvoiceController if (!$invoice) { http_response_code(404); return; } // Gespeicherte PDF aus dem Beleg ausliefern (GoBD: unveränderlicher Stand) + $beleg = null; if (!empty($invoice['beleg_id'])) { $beleg = Beleg::find((int)$invoice['beleg_id']); $absPath = $beleg ? dirname(__DIR__, 2) . '/public/' . $beleg['storage_path'] : ''; - if ($absPath && file_exists($absPath)) { + if ($absPath && is_file($absPath)) { header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="' . $beleg['filename'] . '"'); header('Content-Length: ' . filesize($absPath)); @@ -289,7 +290,7 @@ class InvoiceController } } - // Fallback: PDF on-the-fly generieren (Entwurf oder Beleg noch ohne Datei) + // PDF generieren (Entwurf oder Altrechnung ohne gespeicherte Datei) if (!empty($invoice['storno_of_id'])) { $original = Invoice::find((int)$invoice['storno_of_id']); if ($original) { @@ -302,7 +303,37 @@ class InvoiceController $settings = Setting::get(); $svc = new PdfInvoiceService(); - $svc->render($invoice, $lines, $settings); + $pdf = $svc->renderToString($invoice, $lines, $settings); + + // Finalisierte Altrechnung: PDF nachträglich im Beleg speichern + if ($invoice['status'] !== 'Entwurf' && $beleg !== null) { + if (!empty($beleg['storage_path'])) { + $relPath = $beleg['storage_path']; + $absDir = dirname(dirname(__DIR__, 2) . '/public/' . $relPath); + } else { + $year = date('Y', strtotime($invoice['rechnungs_datum'])); + $relDir = 'static/uploads/' . $year . '/' . $beleg['beleg_nr']; + $relPath = $relDir . '/original.pdf'; + $absDir = dirname(__DIR__, 2) . '/public/' . $relDir; + } + if (!is_dir($absDir)) { + mkdir($absDir, 0755, true); + } + $absFilePath = dirname(__DIR__, 2) . '/public/' . $relPath; + file_put_contents($absFilePath, $pdf); + \Steuerkram\Database::execute( + 'UPDATE belege SET storage_path=?, filename=?, file_hash=?, updated_at=NOW() WHERE id=?', + [$relPath, ($invoice['rechnungs_nr'] ?? 'Rechnung') . '.pdf', hash('sha256', $pdf), (int)$invoice['beleg_id']] + ); + } + + $prefix = !empty($invoice['storno_of_id']) ? 'Stornorechnung-' : 'Rechnung-'; + $filename = $prefix . ($invoice['rechnungs_nr'] ?? 'Entwurf') . '.pdf'; + + header('Content-Type: application/pdf'); + header('Content-Disposition: attachment; filename="' . $filename . '"'); + header('Content-Length: ' . strlen($pdf)); + echo $pdf; } public function book(array $params): void diff --git a/src/version.txt b/src/version.txt index af7d1fa..5814d3d 100644 --- a/src/version.txt +++ b/src/version.txt @@ -1 +1 @@ -1-260505 +1-260506