buchhaltungswidget/ust_detail.php
data db82df2234 Stabile 1.0 Version Firmen Statistik Widgets und
Beurteilung der Rechnungsfristen auf der Kundenkarte
2026-01-30 11:41:02 +01:00

342 lines
11 KiB
PHP

<?php
/* Copyright (C) 2026 Eduard Wisch <data@data-it-solution.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*/
/**
* \file htdocs/custom/buchaltungswidget/ust_detail.php
* \ingroup buchaltungswidget
* \brief Detail page for VAT (Umsatzsteuer) with full charts and year selection
*/
// Load Dolibarr environment
$res = 0;
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
}
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
$tmp2 = realpath(__FILE__);
$i = strlen($tmp) - 1;
$j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
$i--;
$j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
}
if (!$res && file_exists("../main.inc.php")) {
$res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
$res = @include "../../main.inc.php";
}
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
die("Include of main fails");
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
// Load translation files
$langs->loadLangs(array("buchaltungswidget@buchaltungswidget", "bills", "compta"));
// Access control
if (!$user->hasRight('facture', 'lire') && !$user->hasRight('fournisseur', 'facture', 'lire')) {
accessforbidden();
}
// Get parameters
$selectedYear = GETPOST('year', 'int');
if (empty($selectedYear)) {
$selectedYear = date('Y');
}
$viewMode = GETPOST('view', 'alpha');
if (empty($viewMode)) {
$viewMode = 'quarterly';
}
$currentYear = date('Y');
$years = range($currentYear - 5, $currentYear + 1);
/*
* Actions
*/
// None for now
/*
* View
*/
$form = new Form($db);
$title = $langs->trans("UStUebersicht");
llxHeader('', $title, '', '', 0, 0, array('/includes/nnnick/chartjs/dist/Chart.min.js'), array('/buchaltungswidget/css/buchaltungswidget.css'));
print load_fiche_titre($title, '', 'accountancy');
// Year selector and view mode
print '<div class="fichecenter">';
print '<form method="GET" action="'.$_SERVER['PHP_SELF'].'">';
print '<div class="buchaltung-filter-bar">';
print '<label for="year">'.$langs->trans("Year").':</label>';
print '<select name="year" id="year" class="flat" onchange="this.form.submit()">';
foreach ($years as $y) {
$selected = ($y == $selectedYear) ? ' selected' : '';
print '<option value="'.$y.'"'.$selected.'>'.$y.'</option>';
}
print '</select>';
print '&nbsp;&nbsp;';
print '<label for="view">'.$langs->trans("View").':</label>';
print '<select name="view" id="view" class="flat" onchange="this.form.submit()">';
print '<option value="quarterly"'.($viewMode == 'quarterly' ? ' selected' : '').'>'.$langs->trans("Quarterly").'</option>';
print '<option value="monthly"'.($viewMode == 'monthly' ? ' selected' : '').'>'.$langs->trans("Monthly").'</option>';
print '</select>';
print '</div>';
print '</form>';
print '</div>';
// Get data
$vatData = getVatData($db, $selectedYear, $viewMode);
$lastYearData = getVatData($db, $selectedYear - 1, $viewMode);
// Main chart
print '<div class="fichecenter">';
print '<div class="buchaltung-detail-chart" style="height: 350px;">';
print '<div style="height: 310px; position: relative;">';
print '<canvas id="vatDetailChart"></canvas>';
print '</div>';
print '</div>';
print '</div>';
print '<div class="clearboth" style="margin-bottom: 20px;"></div>';
// Data table
print '<div class="div-table-responsive">';
print '<table class="noborder centpercent">';
// Header
print '<tr class="liste_titre">';
print '<th>'.$langs->trans("Period").'</th>';
print '<th class="right">'.$langs->trans("VATCollected").'</th>';
print '<th class="right">'.$langs->trans("VATPaid").'</th>';
print '<th class="right">'.$langs->trans("VATBalance").'</th>';
print '<th class="right">'.$selectedYear - 1 .' '.$langs->trans("VATBalance").'</th>';
print '</tr>';
$totalCollected = 0;
$totalPaid = 0;
$totalCollectedLast = 0;
$totalPaidLast = 0;
$labels = array();
$collectedData = array();
$paidData = array();
$balanceData = array();
$balanceColors = array();
$lastBalanceData = array();
foreach ($vatData['periods'] as $period => $data) {
$collected = $data['collected'];
$paid = $data['paid'];
$balance = $collected - $paid;
$lastCollected = isset($lastYearData['periods'][$period]) ? $lastYearData['periods'][$period]['collected'] : 0;
$lastPaid = isset($lastYearData['periods'][$period]) ? $lastYearData['periods'][$period]['paid'] : 0;
$lastBalance = $lastCollected - $lastPaid;
$totalCollected += $collected;
$totalPaid += $paid;
$totalCollectedLast += $lastCollected;
$totalPaidLast += $lastPaid;
$colorClass = $balance > 0 ? 'buchaltung-negative' : ($balance < 0 ? 'buchaltung-positive' : '');
$colorClassLast = $lastBalance > 0 ? 'buchaltung-negative' : ($lastBalance < 0 ? 'buchaltung-positive' : '');
print '<tr class="oddeven">';
print '<td>'.$period.'</td>';
print '<td class="right">'.price($collected, 0, $langs, 1, 2, 2, $conf->currency).'</td>';
print '<td class="right">'.price($paid, 0, $langs, 1, 2, 2, $conf->currency).'</td>';
print '<td class="right '.$colorClass.'"><strong>'.price($balance, 0, $langs, 1, 2, 2, $conf->currency).'</strong></td>';
print '<td class="right buchaltung-lastyear '.$colorClassLast.'">'.price($lastBalance, 0, $langs, 1, 2, 2, $conf->currency).'</td>';
print '</tr>';
// Chart data
$labels[] = $period;
$collectedData[] = round($collected, 2);
$paidData[] = round($paid, 2);
$balanceData[] = round($balance, 2);
$balanceColors[] = $balance > 0 ? 'rgba(220, 53, 69, 0.7)' : 'rgba(40, 167, 69, 0.7)';
$lastBalanceData[] = round($lastBalance, 2);
}
// Total row
$totalBalance = $totalCollected - $totalPaid;
$totalLastBalance = $totalCollectedLast - $totalPaidLast;
$colorClass = $totalBalance > 0 ? 'buchaltung-negative' : 'buchaltung-positive';
$colorClassLast = $totalLastBalance > 0 ? 'buchaltung-negative' : 'buchaltung-positive';
print '<tr class="liste_total">';
print '<td><strong>'.$langs->trans("Total").'</strong></td>';
print '<td class="right"><strong>'.price($totalCollected, 0, $langs, 1, 2, 2, $conf->currency).'</strong></td>';
print '<td class="right"><strong>'.price($totalPaid, 0, $langs, 1, 2, 2, $conf->currency).'</strong></td>';
print '<td class="right '.$colorClass.'"><strong>'.price($totalBalance, 0, $langs, 1, 2, 2, $conf->currency).'</strong></td>';
print '<td class="right buchaltung-lastyear '.$colorClassLast.'"><strong>'.price($totalLastBalance, 0, $langs, 1, 2, 2, $conf->currency).'</strong></td>';
print '</tr>';
print '</table>';
print '</div>';
// Legend
print '<div class="buchaltung-legend">';
print '<span class="buchaltung-negative">'.$langs->trans("VATToPayLegend").'</span>';
print ' | ';
print '<span class="buchaltung-positive">'.$langs->trans("VATRefundLegend").'</span>';
print '</div>';
// Chart JavaScript
print '<script>
document.addEventListener("DOMContentLoaded", function() {
var ctx = document.getElementById("vatDetailChart").getContext("2d");
new Chart(ctx, {
type: "bar",
data: {
labels: '.json_encode($labels).',
datasets: [{
type: "line",
label: "'.$selectedYear.' '.$langs->trans("VATBalance").'",
data: '.json_encode($balanceData).',
borderColor: "rgba(0, 123, 255, 1)",
backgroundColor: "transparent",
borderWidth: 3,
tension: 0.3,
yAxisID: "y"
}, {
type: "line",
label: "'.($selectedYear-1).' '.$langs->trans("VATBalance").'",
data: '.json_encode($lastBalanceData).',
borderColor: "rgba(108, 117, 125, 0.7)",
backgroundColor: "transparent",
borderDash: [5, 5],
borderWidth: 2,
tension: 0.3,
yAxisID: "y"
}, {
label: "'.$langs->trans("VATCollected").'",
data: '.json_encode($collectedData).',
backgroundColor: "rgba(40, 167, 69, 0.5)",
yAxisID: "y"
}, {
label: "'.$langs->trans("VATPaid").'",
data: '.json_encode($paidData).',
backgroundColor: "rgba(220, 53, 69, 0.5)",
yAxisID: "y"
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: true, position: "top" },
tooltip: {
callbacks: {
label: function(context) {
return context.dataset.label + ": " + new Intl.NumberFormat("de-DE", {style: "currency", currency: "EUR"}).format(context.raw);
}
}
}
},
scales: {
y: {
beginAtZero: true,
grid: {
color: function(context) {
return context.tick.value === 0 ? "rgba(0,0,0,0.5)" : "rgba(0,0,0,0.1)";
}
}
}
}
}
});
});
</script>';
llxFooter();
$db->close();
/**
* Get VAT data for a year
*/
function getVatData($db, $year, $mode = 'quarterly')
{
global $conf;
$result = array('periods' => array());
if ($mode == 'monthly') {
$months = array(1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr', 5 => 'Mai', 6 => 'Jun',
7 => 'Jul', 8 => 'Aug', 9 => 'Sep', 10 => 'Okt', 11 => 'Nov', 12 => 'Dez');
foreach ($months as $m => $name) {
$result['periods'][$name] = array('collected' => 0, 'paid' => 0);
}
$groupBy = "MONTH(f.datef)";
$periodField = "month";
} else {
for ($q = 1; $q <= 4; $q++) {
$result['periods']['Q'.$q] = array('collected' => 0, 'paid' => 0);
}
$groupBy = "QUARTER(f.datef)";
$periodField = "quarter";
}
// VAT collected
$sql = "SELECT ".$groupBy." as period, SUM(fd.total_tva) as tva_amount";
$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
$sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as fd ON fd.fk_facture = f.rowid";
$sql .= " WHERE f.fk_statut > 0 AND f.entity = ".((int) $conf->entity);
$sql .= " AND YEAR(f.datef) = ".((int) $year);
$sql .= " GROUP BY ".$groupBy;
$resql = $db->query($sql);
if ($resql) {
while ($obj = $db->fetch_object($resql)) {
$key = ($mode == 'monthly') ? array_keys($result['periods'])[$obj->period - 1] : 'Q'.$obj->period;
if (isset($result['periods'][$key])) {
$result['periods'][$key]['collected'] = (float) $obj->tva_amount;
}
}
$db->free($resql);
}
// VAT paid
$sql = "SELECT ".$groupBy." as period, SUM(fd.total_tva) as tva_amount";
$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
$sql .= " INNER JOIN ".MAIN_DB_PREFIX."facture_fourn_det as fd ON fd.fk_facture_fourn = f.rowid";
$sql .= " WHERE f.fk_statut > 0 AND f.entity = ".((int) $conf->entity);
$sql .= " AND YEAR(f.datef) = ".((int) $year);
$sql .= " GROUP BY ".$groupBy;
$resql = $db->query($sql);
if ($resql) {
while ($obj = $db->fetch_object($resql)) {
$key = ($mode == 'monthly') ? array_keys($result['periods'])[$obj->period - 1] : 'Q'.$obj->period;
if (isset($result['periods'][$key])) {
$result['periods'][$key]['paid'] = (float) $obj->tva_amount;
}
}
$db->free($resql);
}
return $result;
}