227 lines
7.9 KiB
PHP
227 lines
7.9 KiB
PHP
|
|
<?php
|
|||
|
|
declare(strict_types=1);
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Jahresexport der Mietverträge.
|
|||
|
|
*
|
|||
|
|
* Der Kunde möchte am Ende des Jahres eine Datei mit allen Mietverträgen und
|
|||
|
|
* den zugehörigen Buchungsdaten lokal ablegen (Aufbewahrung: 8 Jahre, solange
|
|||
|
|
* eine Rechnung geschrieben wurde). Der Export bündelt
|
|||
|
|
*
|
|||
|
|
* mietvertraege/<Buchung> <Kunde>.pdf – alle Mietverträge des Jahres
|
|||
|
|
* buchungen.csv – eine Zeile je Buchung
|
|||
|
|
* README.txt – kurze Erläuterung
|
|||
|
|
*
|
|||
|
|
* in einem Archiv unter storage/exports/. Gebaut wird es auf Zuruf
|
|||
|
|
* (Verwaltung → Sicherungen) und automatisch beim ersten Cron-Lauf im Januar.
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
function year_export_dir(): string
|
|||
|
|
{
|
|||
|
|
$path = rtrim((string) config('app.storage_path', dirname(__DIR__) . '/storage'), '/') . '/exports';
|
|||
|
|
if (!is_dir($path)) {
|
|||
|
|
@mkdir($path, 0775, true);
|
|||
|
|
}
|
|||
|
|
return $path;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** Endung des Archivs: ZIP, wenn PHP es kann, sonst tar.gz über PharData. */
|
|||
|
|
function year_export_extension(): string
|
|||
|
|
{
|
|||
|
|
return class_exists('ZipArchive') ? '.zip' : '.tar.gz';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function year_export_path(int $year): string
|
|||
|
|
{
|
|||
|
|
return year_export_dir() . '/mietvertraege-' . $year . year_export_extension();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function year_export_exists(int $year): bool
|
|||
|
|
{
|
|||
|
|
return is_file(year_export_path($year));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** @return list<array{year: int, name: string, size: int, created_at: string}> */
|
|||
|
|
function year_exports(): array
|
|||
|
|
{
|
|||
|
|
$dir = year_export_dir();
|
|||
|
|
$items = [];
|
|||
|
|
foreach (glob($dir . '/mietvertraege-*') ?: [] as $file) {
|
|||
|
|
if (!is_file($file)) {
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
if (!preg_match('/mietvertraege-(\d{4})/', basename($file), $m)) {
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
$items[] = [
|
|||
|
|
'year' => (int) $m[1],
|
|||
|
|
'name' => basename($file),
|
|||
|
|
'size' => (int) filesize($file),
|
|||
|
|
'created_at' => date('Y-m-d H:i', (int) filemtime($file)),
|
|||
|
|
];
|
|||
|
|
}
|
|||
|
|
usort($items, static fn (array $a, array $b): int => $b['year'] <=> $a['year']);
|
|||
|
|
return $items;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** CSV-Zeile einer Buchung (Semikolon, weil Excel das im deutschen Raum erwartet). */
|
|||
|
|
function year_export_row(array $booking, string $contractFile): array
|
|||
|
|
{
|
|||
|
|
return [
|
|||
|
|
(int) $booking['id'],
|
|||
|
|
(string) $booking['customer_name'],
|
|||
|
|
(string) $booking['street'],
|
|||
|
|
(string) $booking['city'],
|
|||
|
|
(string) $booking['mobile'],
|
|||
|
|
(string) $booking['email'],
|
|||
|
|
(string) $booking['trailer_label'],
|
|||
|
|
booking_kind_label((string) $booking['kind']),
|
|||
|
|
fmt_date((string) $booking['start_date']),
|
|||
|
|
fmt_date((string) $booking['end_date']),
|
|||
|
|
number_format((int) $booking['rent_cents'] / 100, 2, ',', ''),
|
|||
|
|
number_format((int) $booking['delivery_cents'] / 100, 2, ',', ''),
|
|||
|
|
number_format((int) $booking['total_cents'] / 100, 2, ',', ''),
|
|||
|
|
number_format(booking_deposit_amount($booking) / 100, 2, ',', ''),
|
|||
|
|
number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
|
|||
|
|
booking_invoice_label((int) $booking['invoice']),
|
|||
|
|
(string) ($booking['invoice_no'] ?? ''),
|
|||
|
|
str_replace(["\r\n", "\r", "\n"], ' | ', (string) ($booking['agreements'] ?? '')),
|
|||
|
|
str_replace(["\r\n", "\r", "\n"], ' | ', (string) ($booking['note'] ?? '')),
|
|||
|
|
$contractFile,
|
|||
|
|
];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Baut das Jahresarchiv neu (überschreibt ein vorhandenes).
|
|||
|
|
*
|
|||
|
|
* @return array{path: string, name: string, bookings: int, contracts: int}
|
|||
|
|
*/
|
|||
|
|
function year_export_build(int $year): array
|
|||
|
|
{
|
|||
|
|
if ($year < 2000 || $year > (int) date('Y') + 1) {
|
|||
|
|
throw new InvalidArgumentException('Ungültiges Jahr für den Export.');
|
|||
|
|
}
|
|||
|
|
$dir = year_export_dir();
|
|||
|
|
if (!is_dir($dir) || !is_writable($dir)) {
|
|||
|
|
throw new RuntimeException('Der Export-Ordner ist nicht beschreibbar: ' . $dir);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$from = sprintf('%04d-01-01', $year);
|
|||
|
|
$to = sprintf('%04d-12-31', $year);
|
|||
|
|
$bookings = booking_list($from, $to, true);
|
|||
|
|
|
|||
|
|
$rows = [[
|
|||
|
|
'Buchung', 'Kunde', 'Straße', 'Ort', 'Handy', 'E-Mail', 'Mietgegenstand', 'Art',
|
|||
|
|
'Beginn', 'Ende', 'Miete', 'Lieferung', 'Gesamt', 'Kaution', 'Anzahlung',
|
|||
|
|
'Rechnung', 'Rechnungsnummer', 'Zusatzvereinbarungen', 'Bemerkung', 'Mietvertrag',
|
|||
|
|
]];
|
|||
|
|
$files = [];
|
|||
|
|
$used = [];
|
|||
|
|
foreach ($bookings as $booking) {
|
|||
|
|
$contractName = '';
|
|||
|
|
foreach (documents_for_booking((int) $booking['id']) as $doc) {
|
|||
|
|
if ((string) $doc['kind'] !== DOCUMENT_KIND_CONTRACT) {
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
$path = document_path($doc);
|
|||
|
|
if (!is_file($path)) {
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
$name = 'mietvertraege/' . $doc['file_name'];
|
|||
|
|
// Doppelte Dateinamen (gleicher Kunde, gleicher Tag) eindeutig machen.
|
|||
|
|
$base = substr($name, 0, -4);
|
|||
|
|
$suffix = 2;
|
|||
|
|
while (isset($used[$name])) {
|
|||
|
|
$name = $base . ' (' . $suffix . ').pdf';
|
|||
|
|
$suffix++;
|
|||
|
|
}
|
|||
|
|
$used[$name] = true;
|
|||
|
|
$files[$name] = $path;
|
|||
|
|
if ($contractName === '') {
|
|||
|
|
$contractName = $name;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
$rows[] = year_export_row($booking, $contractName);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$handle = fopen('php://temp', 'r+');
|
|||
|
|
if ($handle === false) {
|
|||
|
|
throw new RuntimeException('CSV konnte nicht erzeugt werden.');
|
|||
|
|
}
|
|||
|
|
fwrite($handle, "\xEF\xBB\xBF"); // BOM, damit Excel Umlaute richtig liest
|
|||
|
|
foreach ($rows as $row) {
|
|||
|
|
fputcsv($handle, $row, ';', '"', '');
|
|||
|
|
}
|
|||
|
|
rewind($handle);
|
|||
|
|
$csv = (string) stream_get_contents($handle);
|
|||
|
|
fclose($handle);
|
|||
|
|
|
|||
|
|
$readme = "Jahresexport $year – Drink it cold\n"
|
|||
|
|
. "Erstellt am " . fmt_datetime(utc_now()) . "\n\n"
|
|||
|
|
. "Inhalt:\n"
|
|||
|
|
. "- mietvertraege/ alle Mietverträge des Jahres " . $year . ' (' . count($files) . " Dateien)\n"
|
|||
|
|
. "- buchungen.csv eine Zeile je Buchung (Semikolon-getrennt, UTF-8)\n\n"
|
|||
|
|
. "Aufbewahrung: Mietverträge mit Rechnung 8 Jahre, alle übrigen Unterlagen 30 Tage nach Mietende.\n";
|
|||
|
|
|
|||
|
|
$path = year_export_path($year);
|
|||
|
|
if (class_exists('ZipArchive')) {
|
|||
|
|
$zip = new ZipArchive();
|
|||
|
|
if ($zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
|
|||
|
|
throw new RuntimeException('Das Archiv konnte nicht angelegt werden.');
|
|||
|
|
}
|
|||
|
|
foreach ($files as $name => $file) {
|
|||
|
|
$zip->addFile($file, $name);
|
|||
|
|
}
|
|||
|
|
$zip->addFromString('buchungen.csv', $csv);
|
|||
|
|
$zip->addFromString('README.txt', $readme);
|
|||
|
|
$zip->close();
|
|||
|
|
} else {
|
|||
|
|
// Fallback ohne ZIP-Erweiterung: tar.gz über PharData.
|
|||
|
|
if (!class_exists('PharData')) {
|
|||
|
|
throw new RuntimeException('Weder ZIP noch Phar stehen zur Verfügung – Export nicht möglich.');
|
|||
|
|
}
|
|||
|
|
if (is_file($path)) {
|
|||
|
|
@unlink($path);
|
|||
|
|
}
|
|||
|
|
$phar = new PharData($path);
|
|||
|
|
foreach ($files as $name => $file) {
|
|||
|
|
$phar->addFile($file, $name);
|
|||
|
|
}
|
|||
|
|
$phar->addFromString('buchungen.csv', $csv);
|
|||
|
|
$phar->addFromString('README.txt', $readme);
|
|||
|
|
$phar->compress(Phar::GZ);
|
|||
|
|
@unlink($dir . '/mietvertraege-' . $year . '.tar');
|
|||
|
|
$path = year_export_path($year);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return [
|
|||
|
|
'path' => $path,
|
|||
|
|
'name' => basename($path),
|
|||
|
|
'bookings' => count($bookings),
|
|||
|
|
'contracts' => count($files),
|
|||
|
|
];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Beim ersten Cron-Lauf im Januar den Export des Vorjahres anlegen, falls er
|
|||
|
|
* noch fehlt. Fehler dürfen den Erinnerungslauf nicht stoppen.
|
|||
|
|
*
|
|||
|
|
* @return array{path: string, name: string, bookings: int, contracts: int}|null
|
|||
|
|
*/
|
|||
|
|
function year_export_maybe_run(): ?array
|
|||
|
|
{
|
|||
|
|
if ((int) date('n') !== 1) {
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
$year = (int) date('Y') - 1;
|
|||
|
|
if (year_export_exists($year)) {
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
try {
|
|||
|
|
return year_export_build($year);
|
|||
|
|
} catch (Throwable $error) {
|
|||
|
|
error_log('Jahresexport ' . $year . ' fehlgeschlagen: ' . $error->getMessage());
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
}
|