Files
zibo-dashboard/public/userarea/production_stats.php
T
2026-09-07 15:02:36 +02:00

929 lines
34 KiB
PHP

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
include('include/headscript.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
/* 2=produzione, 3=qualità(fine ok), 7=pausa, 8=problema. "Concluse"=3,8 */
$STATI_CONCLUSI = [3, 8];
$linee = $pdo->query("SELECT id, name, color, max_hours_per_day FROM production_lines ORDER BY line_number")->fetchAll();
$matrici = $pdo->query("SELECT id, nome FROM matrice ORDER BY nome")->fetchAll();
$mescole = $pdo->query("SELECT id, nome FROM mescole ORDER BY nome")->fetchAll();
if (!empty($_GET['ajax'])) {
header('Content-Type: application/json');
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';
// linee multiple (bottoni): CSV di id. Vuoto = tutte.
$lineRaw = $_GET['lines'] ?? '';
$lineArr = $lineRaw !== '' ? array_values(array_filter(array_map('intval', explode(',', $lineRaw)))) : [];
$matId = isset($_GET['matrice_id']) && $_GET['matrice_id'] !== '' ? (int)$_GET['matrice_id'] : null;
$mescId = isset($_GET['mescola_id']) && $_GET['mescola_id'] !== '' ? (int)$_GET['mescola_id'] : null;
$granul = ($_GET['granularity'] ?? 'day') === 'month' ? 'month' : 'day';
$where = ["p.id_status IN (" . implode(',', $STATI_CONCLUSI) . ")"];
$params = [];
if ($dateFrom !== '') {
$where[] = "p.Data >= :date_from";
$params['date_from'] = $dateFrom;
}
if ($dateTo !== '') {
$where[] = "p.Data <= :date_to";
$params['date_to'] = $dateTo;
}
if (!empty($lineArr)) {
$where[] = "p.id_linea IN (" . implode(',', $lineArr) . ")";
}
if ($matId !== null) {
$where[] = "p.idmatrice = :mat_id";
$params['mat_id'] = $matId;
}
if ($mescId !== null) {
$where[] = "EXISTS (SELECT 1 FROM productiondata_mescole pm
WHERE pm.id_productiondata = p.id AND pm.id_mescola = :mesc_id)";
$params['mesc_id'] = $mescId;
}
$whereSql = implode(' AND ', $where);
try {
/* ---------- KPI ---------- */
$sqlKpi = "SELECT
COUNT(*) AS n_produzioni,
COALESCE(SUM(p.tempo_totale_produzione),0) AS tot_occupato_s,
COALESCE(SUM(p.seconds_pause),0) AS tot_pause_s,
COALESCE(SUM(p.seconds_produzione),0) AS tot_netto_s,
COALESCE(SUM(p.kgprod),0) AS tot_kg,
COALESCE(SUM(p.mtprod),0) AS tot_mt,
COALESCE(SUM(p.scarto),0) AS tot_scarto
FROM productiondata p WHERE $whereSql";
$stmt = $pdo->prepare($sqlKpi);
$stmt->execute($params);
$kpi = $stmt->fetch(PDO::FETCH_ASSOC);
$effTempo = ($kpi['tot_occupato_s'] > 0) ? round($kpi['tot_netto_s'] / $kpi['tot_occupato_s'] * 100, 1) : 0;
$denomScarto = $kpi['tot_kg'] + $kpi['tot_scarto'];
$scartoPercTot = ($denomScarto > 0) ? round($kpi['tot_scarto'] / $denomScarto * 100, 2) : 0;
/* ---------- SATURAZIONE (uso di max_hours_per_day) ----------
Capacità teorica = somma, per ogni linea nel perimetro,
di max_hours_per_day * numero giorni di calendario del range.
*/
$giorniRange = 1;
if ($dateFrom !== '' && $dateTo !== '') {
$d1 = new DateTime($dateFrom);
$d2 = new DateTime($dateTo);
$giorniRange = max(1, $d1->diff($d2)->days + 1);
}
// Linee da considerare per la capacità: quelle filtrate, o tutte
$capSql = "SELECT COALESCE(SUM(max_hours_per_day),0) AS somma_ore_giorno
FROM production_lines"
. (!empty($lineArr) ? " WHERE id IN (" . implode(',', $lineArr) . ")" : "");
$capOreGiorno = (float)$pdo->query($capSql)->fetchColumn();
$capacitaTeoricaS = $capOreGiorno * 3600 * $giorniRange;
$saturazione = ($capacitaTeoricaS > 0)
? round($kpi['tot_occupato_s'] / $capacitaTeoricaS * 100, 1) : 0;
/* ---------- PER LINEA ---------- */
$sqlLinea = "SELECT l.id, l.name AS linea, l.color, l.max_hours_per_day, COUNT(*) AS n_prod,
COALESCE(SUM(p.tempo_totale_produzione),0) AS occupato_s,
COALESCE(SUM(p.seconds_pause),0) AS pause_s,
COALESCE(SUM(p.seconds_produzione),0) AS netto_s,
COALESCE(SUM(p.kgprod),0) AS kg, COALESCE(SUM(p.scarto),0) AS scarto
FROM productiondata p JOIN production_lines l ON l.id = p.id_linea
WHERE $whereSql GROUP BY l.id ORDER BY l.line_number";
$stmt = $pdo->prepare($sqlLinea);
$stmt->execute($params);
$perLinea = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($perLinea as &$row) {
$row['eff_tempo'] = ($row['occupato_s'] > 0) ? round($row['netto_s'] / $row['occupato_s'] * 100, 1) : 0;
$den = $row['kg'] + $row['scarto'];
$row['scarto_perc'] = ($den > 0) ? round($row['scarto'] / $den * 100, 2) : 0;
// saturazione della singola linea
$capLineaS = (float)$row['max_hours_per_day'] * 3600 * $giorniRange;
$row['saturazione'] = ($capLineaS > 0) ? round($row['occupato_s'] / $capLineaS * 100, 1) : 0;
}
unset($row);
/* ---------- SERIE TEMPORALE (granularità) ---------- */
if ($granul === 'month') {
$periodExpr = "DATE_FORMAT(p.Data, '%Y-%m')";
} else {
$periodExpr = "p.Data";
}
$sqlSerie = "SELECT $periodExpr AS periodo,
COALESCE(SUM(p.tempo_totale_produzione),0) AS occupato_s,
COALESCE(SUM(p.seconds_pause),0) AS pause_s,
COALESCE(SUM(p.seconds_produzione),0) AS netto_s,
COALESCE(SUM(p.kgprod),0) AS kg, COALESCE(SUM(p.scarto),0) AS scarto
FROM productiondata p WHERE $whereSql
GROUP BY periodo ORDER BY periodo";
$stmt = $pdo->prepare($sqlSerie);
$stmt->execute($params);
$serie = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($serie as &$s) {
$s['eff_tempo'] = ($s['occupato_s'] > 0) ? round($s['netto_s'] / $s['occupato_s'] * 100, 1) : 0;
$den = $s['kg'] + $s['scarto'];
$s['scarto_perc'] = ($den > 0) ? round($s['scarto'] / $den * 100, 2) : 0;
}
unset($s);
/* ---------- PAUSE CATEGORIA ---------- */
$sqlCat = "SELECT pr.category AS category,
COALESCE(SUM(TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause)),0) AS durata_s
FROM production_pauses pp
JOIN productiondata p ON p.id = pp.id_production
JOIN pause_reasons pr ON pr.id = pp.reason_id
WHERE pp.end_pause IS NOT NULL AND $whereSql GROUP BY pr.category";
$stmt = $pdo->prepare($sqlCat);
$stmt->execute($params);
$plannedS = 0;
$unplannedS = 0;
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $c) {
if ($c['category'] === 'planned') $plannedS = (int)$c['durata_s'];
else $unplannedS += (int)$c['durata_s'];
}
/* ---------- DETTAGLIO ---------- */
$sqlDett = "SELECT p.id, p.Data, p.conferma_ordine, p.note_extra,
l.name AS linea, m.nome AS matrice, c.nome AS cliente,
p.tempo_totale_produzione AS occupato_s, p.seconds_pause AS pause_s, p.seconds_produzione AS netto_s,
p.kgprod, p.mtprod, p.scarto, p.scarto_perc, p.id_status,
(SELECT GROUP_CONCAT(mes.nome ORDER BY mes.nome SEPARATOR ', ')
FROM productiondata_mescole pm JOIN mescole mes ON mes.id = pm.id_mescola
WHERE pm.id_productiondata = p.id) AS mescole
FROM productiondata p
LEFT JOIN production_lines l ON l.id = p.id_linea
LEFT JOIN matrice m ON m.id = p.idmatrice
LEFT JOIN clients c ON c.id = p.id_cliente
WHERE $whereSql ORDER BY p.Data DESC, p.id DESC LIMIT 500";
$stmt = $pdo->prepare($sqlDett);
$stmt->execute($params);
$dettaglio = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode([
'success' => true,
'granularity' => $granul,
'kpi' => [
'n_produzioni' => (int)$kpi['n_produzioni'],
'tot_occupato_s' => (int)$kpi['tot_occupato_s'],
'tot_pause_s' => (int)$kpi['tot_pause_s'],
'tot_netto_s' => (int)$kpi['tot_netto_s'],
'tot_kg' => (float)$kpi['tot_kg'],
'tot_mt' => (float)$kpi['tot_mt'],
'tot_scarto' => (float)$kpi['tot_scarto'],
'eff_tempo' => $effTempo,
'scarto_perc_tot' => $scartoPercTot,
'planned_s' => $plannedS,
'unplanned_s' => $unplannedS,
'saturazione' => $saturazione,
'giorni_range' => $giorniRange,
],
'per_linea' => $perLinea,
'serie' => $serie,
'dettaglio' => $dettaglio,
]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'msg' => $e->getMessage()]);
}
exit;
}
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Statistiche Produzione</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<?php include('cssinclude.php'); ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
.stats-header {
background: linear-gradient(135deg, #1d4ed8, #3b82f6);
color: #fff;
padding: 1.1rem 1.4rem;
display: flex;
justify-content: space-between;
align-items: center;
border-radius: 1rem;
flex-wrap: wrap;
gap: .8rem;
margin-bottom: 1rem;
}
.stats-header h4 {
margin: 0;
font-weight: 600;
}
.header-actions {
display: flex;
gap: .5rem;
flex-wrap: wrap;
}
.hbtn {
background: rgba(255, 255, 255, .22);
border: 1px solid rgba(255, 255, 255, .4);
color: #fff;
padding: .5rem 1rem;
border-radius: .7rem;
text-decoration: none;
font-weight: 600;
}
.hbtn:hover {
background: rgba(255, 255, 255, .34);
color: #fff;
}
.hbtn.active {
background: #fff;
color: #1d4ed8;
}
.filters-bar {
background: #fff;
padding: 1rem 1.2rem;
border-radius: 1rem;
box-shadow: 0 4px 15px rgba(0, 0, 0, .05);
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: .9rem;
align-items: end;
margin-bottom: 1rem;
}
.filters-bar label {
display: block;
font-weight: 600;
color: #1e40af;
font-size: .8rem;
margin-bottom: .3rem;
}
.filters-bar input,
.filters-bar select {
width: 100%;
padding: .55rem .7rem;
border: 1px solid #cbd5e1;
border-radius: .6rem;
font-size: .95rem;
background: #fff;
}
.line-buttons {
display: flex;
gap: .5rem;
flex-wrap: wrap;
}
.line-btn2 {
flex: 1;
min-width: 70px;
padding: .55rem .3rem;
border: 2px solid transparent;
border-radius: .6rem;
color: #fff;
font-weight: 700;
cursor: pointer;
font-size: .9rem;
opacity: .35;
transition: .15s;
}
.line-btn2.active {
opacity: 1;
box-shadow: 0 2px 8px rgba(0, 0, 0, .15);
}
.gran-toggle {
display: flex;
gap: .3rem;
}
.gran-btn {
flex: 1;
padding: .55rem .3rem;
border: 1px solid #cbd5e1;
background: #fff;
border-radius: .6rem;
cursor: pointer;
font-weight: 600;
font-size: .85rem;
color: #475569;
}
.gran-btn.active {
background: #2563eb;
color: #fff;
border-color: #2563eb;
}
.filters-actions {
display: flex;
gap: .5rem;
}
.btn-apply {
background: #2563eb;
color: #fff;
border: none;
padding: .6rem 1rem;
border-radius: .6rem;
font-weight: 600;
cursor: pointer;
flex: 1;
}
.btn-reset {
background: #e2e8f0;
color: #475569;
border: none;
padding: .6rem 1rem;
border-radius: .6rem;
font-weight: 600;
cursor: pointer;
}
.kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 1rem;
margin-bottom: 1rem;
}
.kpi-card {
background: #fff;
border-radius: 1rem;
padding: 1.1rem 1.2rem;
box-shadow: 0 4px 15px rgba(0, 0, 0, .05);
border-left: 5px solid #3b82f6;
}
.kpi-card .kpi-label {
font-size: .72rem;
text-transform: uppercase;
letter-spacing: .5px;
color: #64748b;
font-weight: 700;
}
.kpi-card .kpi-value {
font-size: 1.7rem;
font-weight: 800;
color: #0f172a;
margin-top: .2rem;
line-height: 1.1;
}
.kpi-card .kpi-sub {
font-size: .8rem;
color: #94a3b8;
margin-top: .2rem;
}
.kpi-card.green {
border-left-color: #10b981;
}
.kpi-card.amber {
border-left-color: #f59e0b;
}
.kpi-card.red {
border-left-color: #ef4444;
}
.kpi-card.violet {
border-left-color: #8b5cf6;
}
.kpi-card.teal {
border-left-color: #14b8a6;
}
.charts-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
gap: 1rem;
margin-bottom: 1rem;
}
.chart-card {
background: #fff;
border-radius: 1rem;
padding: 1.1rem 1.2rem;
box-shadow: 0 4px 15px rgba(0, 0, 0, .05);
}
.chart-card.wide {
grid-column: 1 / -1;
}
.chart-card h6 {
font-weight: 700;
color: #1e293b;
margin: 0 0 .8rem;
font-size: .95rem;
}
.chart-wrap {
position: relative;
height: 300px;
}
.table-card {
background: #fff;
border-radius: 1rem;
padding: 1.1rem 1.2rem;
box-shadow: 0 4px 15px rgba(0, 0, 0, .05);
overflow-x: auto;
margin-bottom: 2rem;
}
.table-card h6 {
font-weight: 700;
color: #1e293b;
margin: 0 0 .8rem;
}
table.stats-table {
width: 100%;
border-collapse: collapse;
font-size: .85rem;
}
table.stats-table th {
background: #e7f1ff;
color: #0b3d91;
text-align: left;
padding: .55rem .6rem;
}
table.stats-table td {
padding: .5rem .6rem;
border-bottom: 1px solid #eef2f7;
color: #334155;
}
table.stats-table tr:hover td {
background: #f8fafc;
}
.pill {
display: inline-block;
padding: .15rem .55rem;
border-radius: 999px;
font-size: .72rem;
font-weight: 700;
}
.pill-ok {
background: #d1fae5;
color: #065f46;
}
.pill-prob {
background: #fee2e2;
color: #991b1b;
}
.muted {
color: #94a3b8;
}
.loading {
text-align: center;
padding: 3rem;
color: #64748b;
}
.empty {
text-align: center;
padding: 3rem;
color: #94a3b8;
}
</style>
</head>
<body>
<div class="wrapper toggled">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="stats-header">
<h4><i class="bi bi-bar-chart-line"></i> Statistiche Produzione</h4>
<div class="header-actions">
<a class="hbtn active" href="production_stats.php"><i class="bi bi-speedometer2"></i> Produzione</a>
<a class="hbtn" href="pause_stats.php"><i class="bi bi-pause-circle"></i> Pause &amp; Fermi</a>
<a class="hbtn" href="production_dashboard.php">Torna</a>
</div>
</div>
<div class="filters-bar">
<div><label>Da (data)</label><input type="date" id="fDateFrom"></div>
<div><label>A (data)</label><input type="date" id="fDateTo"></div>
<div style="grid-column:span 2;">
<label>Linee</label>
<div class="line-buttons" id="lineButtons">
<?php foreach ($linee as $l): ?>
<button type="button" class="line-btn2 active"
data-line="<?= (int)$l['id'] ?>"
style="background:<?= htmlspecialchars($l['color'] ?: '#3b82f6') ?>;">
<?= htmlspecialchars($l['name']) ?>
</button>
<?php endforeach; ?>
</div>
</div>
<div><label>Matrice</label><select id="fMatrice">
<option value="">Tutte</option>
<?php foreach ($matrici as $m): ?><option value="<?= (int)$m['id'] ?>"><?= htmlspecialchars($m['nome']) ?></option><?php endforeach; ?>
</select></div>
<div><label>Mescola</label><select id="fMescola">
<option value="">Tutte</option>
<?php foreach ($mescole as $me): ?><option value="<?= (int)$me['id'] ?>"><?= htmlspecialchars($me['nome']) ?></option><?php endforeach; ?>
</select></div>
<div>
<label>Vista temporale</label>
<div class="gran-toggle">
<button type="button" class="gran-btn active" data-gran="day">Giorno</button>
<button type="button" class="gran-btn" data-gran="month">Mese</button>
</div>
</div>
<div class="filters-actions">
<button class="btn-apply" id="btnApply"><i class="bi bi-funnel"></i> Applica</button>
<button class="btn-reset" id="btnReset">Reset</button>
</div>
</div>
<div class="kpi-grid" id="kpiGrid">
<div class="loading">Caricamento…</div>
</div>
<div class="charts-grid" id="chartsGrid" style="display:none;">
<div class="chart-card wide">
<h6 id="titSerie">Efficienza tempo nel periodo (%)</h6>
<div class="chart-wrap"><canvas id="chartSerie"></canvas></div>
</div>
<div class="chart-card">
<h6>Efficienza tempo per linea (%)</h6>
<div class="chart-wrap"><canvas id="chartEffLinea"></canvas></div>
</div>
<div class="chart-card">
<h6>Saturazione linea (% su capacità)</h6>
<div class="chart-wrap"><canvas id="chartSat"></canvas></div>
</div>
<div class="chart-card">
<h6>Kg prodotti vs scarto per linea</h6>
<div class="chart-wrap"><canvas id="chartKgLinea"></canvas></div>
</div>
<div class="chart-card">
<h6>Scarto % per linea</h6>
<div class="chart-wrap"><canvas id="chartScartoLinea"></canvas></div>
</div>
</div>
<div class="table-card" id="tableCard" style="display:none;">
<h6>Dettaglio produzioni</h6>
<table class="stats-table">
<thead>
<tr>
<th>Data</th>
<th>Linea</th>
<th>Matrice</th>
<th>Cliente</th>
<th>Mescole</th>
<th>Occupato</th>
<th>Pause</th>
<th>Netto</th>
<th>Eff.%</th>
<th>Kg</th>
<th>Mt</th>
<th>Scarto</th>
<th>Scarto%</th>
<th>Esito</th>
</tr>
</thead>
<tbody id="tableBody"></tbody>
</table>
</div>
</div><!-- /.page-content -->
</div><!-- /.page-wrapper -->
</div><!-- /.wrapper -->
<?php include('jsinclude.php'); ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
// il codice sotto usa jQuery (già caricato nel <head>) e Chart.js
function secToHms(s) {
s = Math.max(0, parseInt(s || 0, 10));
const h = String(Math.floor(s / 3600)).padStart(2, '0'),
m = String(Math.floor((s % 3600) / 60)).padStart(2, '0'),
x = String(s % 60).padStart(2, '0');
return `${h}:${m}:${x}`;
}
function fmtDateIt(iso) {
if (!iso) return '-';
const p = iso.split('-');
return p.length === 3 ? `${p[2]}/${p[1]}/${p[0]}` : iso;
}
function fmtMonth(ym) {
if (!ym) return '-';
const p = ym.split('-');
if (p.length < 2) return ym;
const mesi = ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'];
return `${mesi[parseInt(p[1],10)-1]} ${p[0]}`;
}
function num(v, d = 2) {
return Number(v || 0).toLocaleString('it-IT', {
minimumFractionDigits: d,
maximumFractionDigits: d
});
}
let charts = {};
function destroyChart(k) {
if (charts[k]) {
charts[k].destroy();
charts[k] = null;
}
}
let currentGran = 'day';
function renderKpi(k) {
$('#kpiGrid').html(`
<div class="kpi-card"><div class="kpi-label">Produzioni</div><div class="kpi-value">${k.n_produzioni}</div><div class="kpi-sub">record conclusi</div></div>
<div class="kpi-card green"><div class="kpi-label">Efficienza tempo</div><div class="kpi-value">${k.eff_tempo}%</div><div class="kpi-sub">netto / occupato</div></div>
<div class="kpi-card teal"><div class="kpi-label">Saturazione</div><div class="kpi-value">${k.saturazione}%</div><div class="kpi-sub">su ${k.giorni_range} gg di capacità</div></div>
<div class="kpi-card amber"><div class="kpi-label">Tempo in pausa</div><div class="kpi-value" style="font-size:1.25rem;">${secToHms(k.tot_pause_s)}</div><div class="kpi-sub">pian. ${secToHms(k.planned_s)} · non ${secToHms(k.unplanned_s)}</div></div>
<div class="kpi-card violet"><div class="kpi-label">Kg prodotti</div><div class="kpi-value" style="font-size:1.4rem;">${num(k.tot_kg)}</div><div class="kpi-sub">${num(k.tot_mt)} metri</div></div>
<div class="kpi-card red"><div class="kpi-label">Scarto</div><div class="kpi-value" style="font-size:1.4rem;">${k.scarto_perc_tot}%</div><div class="kpi-sub">${num(k.tot_scarto)} kg scartati</div></div>
`);
}
function renderCharts(d) {
const linee = d.per_linea || [],
serie = d.serie || [],
gran = d.granularity;
const labels = serie.map(x => gran === 'month' ? fmtMonth(x.periodo) : fmtDateIt(x.periodo));
$('#titSerie').text(gran === 'month' ? 'Efficienza tempo per mese (%)' : 'Efficienza tempo per giorno (%)');
destroyChart('serie');
charts.serie = new Chart($('#chartSerie'), {
type: 'line',
data: {
labels,
datasets: [{
label: 'Efficienza %',
data: serie.map(x => x.eff_tempo),
borderColor: '#10b981',
backgroundColor: 'rgba(16,185,129,.15)',
fill: true,
tension: .3,
pointRadius: 3
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
max: 100
}
},
plugins: {
legend: {
display: false
}
}
}
});
destroyChart('effLinea');
charts.effLinea = new Chart($('#chartEffLinea'), {
type: 'bar',
data: {
labels: linee.map(x => x.linea),
datasets: [{
label: 'Efficienza %',
data: linee.map(x => x.eff_tempo),
backgroundColor: linee.map(x => x.color || '#3b82f6')
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
max: 100
}
},
plugins: {
legend: {
display: false
}
}
}
});
destroyChart('sat');
charts.sat = new Chart($('#chartSat'), {
type: 'bar',
data: {
labels: linee.map(x => x.linea),
datasets: [{
label: 'Saturazione %',
data: linee.map(x => x.saturazione),
backgroundColor: linee.map(x => x.color || '#14b8a6')
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
max: 100
}
},
plugins: {
legend: {
display: false
}
}
}
});
destroyChart('kgLinea');
charts.kgLinea = new Chart($('#chartKgLinea'), {
type: 'bar',
data: {
labels: linee.map(x => x.linea),
datasets: [{
label: 'Kg prodotti',
data: linee.map(x => x.kg),
backgroundColor: '#8b5cf6'
}, {
label: 'Kg scarto',
data: linee.map(x => x.scarto),
backgroundColor: '#ef4444'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
}
}
});
destroyChart('scartoLinea');
charts.scartoLinea = new Chart($('#chartScartoLinea'), {
type: 'bar',
data: {
labels: linee.map(x => x.linea),
datasets: [{
label: 'Scarto %',
data: linee.map(x => x.scarto_perc),
backgroundColor: '#f59e0b'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
},
plugins: {
legend: {
display: false
}
}
}
});
}
function renderTable(rows) {
if (!rows || !rows.length) {
$('#tableBody').html('<tr><td colspan="14" class="empty">Nessun dato per i filtri selezionati</td></tr>');
return;
}
let html = '';
rows.forEach(r => {
const esito = (String(r.id_status) === '8') ? '<span class="pill pill-prob">Problema</span>' : '<span class="pill pill-ok">Completata</span>';
const eff = (r.occupato_s > 0) ? Math.round(r.netto_s / r.occupato_s * 100) : 0;
html += `<tr><td>${fmtDateIt(r.Data)}</td><td>${r.linea||'-'}</td>
<td>${r.matrice||'-'}${r.note_extra?'<div class="muted" style="font-size:.72rem;">'+r.note_extra+'</div>':''}</td>
<td>${r.cliente||'-'}</td><td>${r.mescole||'<span class="muted">-</span>'}</td>
<td>${secToHms(r.occupato_s)}</td><td>${secToHms(r.pause_s)}</td><td>${secToHms(r.netto_s)}</td>
<td>${eff}%</td><td>${num(r.kgprod)}</td><td>${num(r.mtprod)}</td><td>${num(r.scarto)}</td>
<td>${r.scarto_perc!==null?num(r.scarto_perc)+'%':'-'}</td><td>${esito}</td></tr>`;
});
$('#tableBody').html(html);
}
function selectedLines() {
return $('#lineButtons .line-btn2.active').map(function() {
return $(this).data('line');
}).get().join(',');
}
function loadStats() {
$('#kpiGrid').html('<div class="loading">Caricamento…</div>');
$('#chartsGrid, #tableCard').hide();
$.getJSON('', {
ajax: 1,
date_from: $('#fDateFrom').val(),
date_to: $('#fDateTo').val(),
lines: selectedLines(),
matrice_id: $('#fMatrice').val(),
mescola_id: $('#fMescola').val(),
granularity: currentGran
},
function(r) {
if (!r.success) {
$('#kpiGrid').html('<div class="empty">Errore: ' + (r.msg || '') + '</div>');
return;
}
renderKpi(r.kpi);
if (r.kpi.n_produzioni === 0) {
$('#chartsGrid, #tableCard').hide();
$('#tableBody').html('');
return;
}
$('#chartsGrid, #tableCard').show();
renderCharts(r);
renderTable(r.dettaglio);
}).fail(function() {
$('#kpiGrid').html('<div class="empty">Errore di comunicazione con il server.</div>');
});
}
$(function() {
const today = new Date(),
past = new Date();
past.setDate(today.getDate() - 30);
$('#fDateTo').val(today.toISOString().slice(0, 10));
$('#fDateFrom').val(past.toISOString().slice(0, 10));
// Bottoni linea: toggle, mai zero (se azzeri torni a tutte)
$('#lineButtons').on('click', '.line-btn2', function() {
$(this).toggleClass('active');
if ($('#lineButtons .line-btn2.active').length === 0) {
$('#lineButtons .line-btn2').addClass('active');
}
loadStats();
});
// Granularità
$('.gran-btn').on('click', function() {
$('.gran-btn').removeClass('active');
$(this).addClass('active');
currentGran = $(this).data('gran');
loadStats();
});
$('#btnApply').on('click', loadStats);
$('#btnReset').on('click', function() {
$('#lineButtons .line-btn2').addClass('active');
$('#fMatrice,#fMescola').val('');
$('.gran-btn').removeClass('active');
$('.gran-btn[data-gran="day"]').addClass('active');
currentGran = 'day';
$('#fDateTo').val(today.toISOString().slice(0, 10));
$('#fDateFrom').val(past.toISOString().slice(0, 10));
loadStats();
});
loadStats();
});
</script>
</body>
</html>