Files
Symcon_Belevo_Energiemanage…/Abrechnung/module.php
2025-11-04 11:01:47 +01:00

185 lines
7.0 KiB
PHP

<?php
declare(strict_types=1);
class Abrechnung extends IPSModule
{
public function Create()
{
parent::Create();
// Eigenschaften
$this->RegisterPropertyString('Users', '[]');
$this->RegisterPropertyString('PowerMeters', '[]');
$this->RegisterPropertyString('WaterMeters', '[]');
$this->RegisterPropertyString('Tariffs', '[]');
// Variablen für Zeitraum und Status
$this->RegisterVariableInteger('FromDate', 'Startdatum', '~UnixTimestamp', 1);
$this->RegisterVariableInteger('ToDate', 'Enddatum', '~UnixTimestamp', 2);
$this->RegisterVariableString('LastResult', 'Letzte Abrechnung', '', 3);
$this->EnableAction('FromDate');
$this->EnableAction('ToDate');
// Abrechnungs-Button
$this->RegisterScript('StartBilling', 'Abrechnung starten', "<?php IPS_RequestAction(" . $this->InstanceID . ", 'StartBilling', ''); ?>");
// 🧾 Media-Objekt für das PDF
$this->RegisterMediaDocument('InvoicePDF', 'Letzte Rechnung', 'pdf');
}
public function ApplyChanges()
{
parent::ApplyChanges();
}
private function RegisterMediaDocument($Ident, $Name, $Extension, $Position = 0)
{
$this->RegisterMedia(5, $Ident, $Name, $Extension, $Position);
}
private function RegisterMedia($Type, $Ident, $Name, $Extension, $Position)
{
$mid = @IPS_GetObjectIDByIdent($Ident, $this->InstanceID);
if ($mid === false) {
$mid = IPS_CreateMedia(5 /* Document */);
IPS_SetParent($mid, $this->InstanceID);
IPS_SetIdent($mid, $Ident);
IPS_SetName($mid, $Name);
IPS_SetPosition($mid, $Position);
IPS_SetMediaFile($mid, 'media/' . $mid . '.' . $Extension, false);
}
}
public function RequestAction($Ident, $Value)
{
IPS_LogMessage('Abrechnung', "RequestAction: $Ident");
switch ($Ident) {
case 'FromDate':
case 'ToDate':
SetValue($this->GetIDForIdent($Ident), $Value);
break;
case 'StartBilling':
IPS_LogMessage('Abrechnung', 'Starte Abrechnung...');
$pdfContent = $this->GenerateInvoices();
if ($pdfContent && strlen($pdfContent) > 100) {
$mediaID = $this->GetIDForIdent('InvoicePDF');
IPS_SetMediaContent($mediaID, base64_encode($pdfContent));
IPS_LogMessage('Abrechnung', '✅ PDF erfolgreich im Media-Objekt gespeichert');
SetValue($this->GetIDForIdent('LastResult'), 'Abrechnung ' . date('Y-m-d H:i'));
echo "✅ Abrechnung erfolgreich erstellt.";
} else {
IPS_LogMessage('Abrechnung', '❌ Fehler bei der PDF-Erstellung oder leeres PDF');
echo "❌ Fehler bei der PDF-Erstellung";
}
break;
}
}
// 🧾 Hauptfunktion: PDF erzeugen (wie SymconReport)
public function GenerateInvoices()
{
$from = GetValue($this->GetIDForIdent('FromDate'));
$to = GetValue($this->GetIDForIdent('ToDate'));
if ($from >= $to) {
IPS_LogMessage('Abrechnung', '❌ Ungültiger Zeitraum');
return false;
}
$users = json_decode($this->ReadPropertyString('Users'), true);
$power = json_decode($this->ReadPropertyString('PowerMeters'), true);
$water = json_decode($this->ReadPropertyString('WaterMeters'), true);
$tariffs = json_decode($this->ReadPropertyString('Tariffs'), true);
IPS_LogMessage('Abrechnung', 'Starte PDF-Erstellung mit TCPDF...');
// TCPDF initialisieren
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('IPSymcon Abrechnung');
$pdf->SetTitle('Zählerabrechnung');
$pdf->SetSubject('Automatische Abrechnung');
$pdf->setPrintHeader(false);
$pdf->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP - 15, PDF_MARGIN_RIGHT);
$pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM);
$pdf->SetFont('dejavusans', '', 10);
// Jede Seite = Benutzer
foreach ($users as $user) {
$pdf->AddPage();
$pdf->writeHTML("<h2>Rechnung für {$user['name']}</h2>", true, false, true, false, '');
$pdf->writeHTML("<p>{$user['address']}<br>{$user['city']}</p>", true, false, true, false, '');
$pdf->writeHTML("<table border=\"1\" cellpadding=\"4\">
<tr style=\"background-color:#eee;\">
<th>Zähler</th><th>Start</th><th>Ende</th><th>Verbrauch</th><th>Kosten (CHF)</th>
</tr>", false, false, false, false, '');
$userMeters = array_merge(
array_filter($power, fn($m) => $m['user_id'] == $user['id']),
array_filter($water, fn($m) => $m['user_id'] == $user['id'])
);
$total = 0.0;
foreach ($userMeters as $m) {
$start = $this->GetValueAt($m['var_consumption'], $from);
$end = $this->GetValueAt($m['var_consumption'], $to);
if ($start === null || $end === null) continue;
$diff = max(0, $end - $start);
$price = $this->GetTariffForMeter($tariffs, $from, $to, $m);
$cost = $diff * $price;
$total += $cost;
$pdf->writeHTML("
<tr>
<td>{$m['name']}</td>
<td>$start</td>
<td>$end</td>
<td>$diff</td>
<td>" . number_format($cost, 2) . "</td>
</tr>", false, false, false, false, '');
}
$pdf->writeHTML("</table><br><h3>Gesamt: " . number_format($total, 2) . " CHF</h3>", true, false, true, false, '');
}
// Rückgabe als String
return $pdf->Output('Abrechnung.pdf', 'S');
}
private function GetValueAt(int $varId, int $timestamp)
{
$archiveID = @IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0];
if (!$archiveID) return GetValue($varId);
$values = AC_GetLoggedValues($archiveID, $varId, $timestamp - 3600, $timestamp + 3600, 1);
if (count($values) > 0) return floatval($values[0]['Value']);
return GetValue($varId);
}
private function GetTariffForMeter(array $tariffs, int $from, int $to, array $meter): float
{
$type = $meter['meter_type'] ?? 'Wärme';
$tariff = 0.0;
foreach ($tariffs as $t) {
$start = strtotime($t['start']);
$end = strtotime($t['end']);
if ($from >= $start && $to <= $end && $t['unit_type'] == $type) {
$tariff = floatval($t['price']) / 100.0;
}
}
return $tariff;
}
}