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

300 lines
20 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 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'] ?? '';
$lineId = isset($_GET['line_id']) && $_GET['line_id'] !== '' ? (int)$_GET['line_id'] : null;
$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;
$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 ($lineId !== null) { $where[] = "p.id_linea = :line_id"; $params['line_id'] = $lineId; }
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 {
$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;
$sqlLinea = "SELECT l.id, l.name AS linea, 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;
} unset($row);
$sqlGiorno = "SELECT p.Data AS giorno,
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 p.Data ORDER BY p.Data";
$stmt = $pdo->prepare($sqlGiorno); $stmt->execute($params);
$perGiorno = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($perGiorno as &$g) {
$g['eff_tempo'] = ($g['occupato_s'] > 0) ? round($g['netto_s'] / $g['occupato_s'] * 100, 1) : 0;
$den = $g['kg'] + $g['scarto'];
$g['scarto_perc'] = ($den > 0) ? round($g['scarto'] / $den * 100, 2) : 0;
} unset($g);
$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'];
}
$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,
'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,
],
'per_linea'=>$perLinea,'per_giorno'=>$perGiorno,'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>
<?php include('cssinclude.php'); ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
* { box-sizing: border-box; }
body { background:#f1f5f9; font-family:'Segoe UI',sans-serif; }
.stats-header { background:linear-gradient(135deg,#1d4ed8,#3b82f6); color:#fff; padding:1.2rem 1.5rem;
display:flex; justify-content:space-between; align-items:center; border-radius:0 0 1rem 1rem; flex-wrap:wrap; gap:.8rem; }
.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; margin:1rem; 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; }
.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; }
.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 { margin:0 1rem 1rem; display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap: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; }
.charts-grid { margin:0 1rem 1rem; display:grid; grid-template-columns:repeat(auto-fit,minmax(360px,1fr)); gap: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 h6 { font-weight:700; color:#1e293b; margin:0 0 .8rem; font-size:.95rem; }
.chart-wrap { position:relative; height:280px; }
.table-card { background:#fff; border-radius:1rem; margin:0 1rem 2rem; padding:1.1rem 1.2rem; box-shadow:0 4px 15px rgba(0,0,0,.05); overflow-x:auto; }
.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>
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<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><label>Linea</label><select id="fLine"><option value="">Tutte</option>
<?php foreach ($linee as $l): ?><option value="<?= (int)$l['id'] ?>"><?= htmlspecialchars($l['name']) ?></option><?php endforeach; ?>
</select></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 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"><h6>Efficienza tempo per linea (%)</h6><div class="chart-wrap"><canvas id="chartEffLinea"></canvas></div></div>
<div class="chart-card"><h6>Efficienza tempo giornaliera (%)</h6><div class="chart-wrap"><canvas id="chartEffGiorno"></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>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
(function forceSidebarCollapsed(){
try{
const b=document.body,h=document.documentElement;
b.setAttribute('data-sidebar-size','condensed');
b.setAttribute('data-sidenav-size','condensed');
b.classList.add('sidebar-enable','enlarge-menu','sidebar-collapse','vertical-collapsed');
h.setAttribute('data-sidebar-size','sm');
b.classList.remove('sidebar-open','sidebar-enable-mobile');
}catch(e){}
})();
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 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; } }
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"><div class="kpi-label">Tempo occupato</div><div class="kpi-value" style="font-size:1.25rem;">${secToHms(k.tot_occupato_s)}</div><div class="kpi-sub">linea impegnata</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||[], giorni=d.per_giorno||[];
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:'#3b82f6'}]},options:{responsive:true,maintainAspectRatio:false,scales:{y:{beginAtZero:true,max:100}},plugins:{legend:{display:false}}}});
destroyChart('effGiorno');
charts.effGiorno=new Chart($('#chartEffGiorno'),{type:'line',data:{labels:giorni.map(x=>fmtDateIt(x.giorno)),datasets:[{label:'Efficienza %',data:giorni.map(x=>x.eff_tempo),borderColor:'#10b981',backgroundColor:'rgba(16,185,129,.15)',fill:true,tension:.3}]},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 loadStats(){
$('#kpiGrid').html('<div class="loading">Caricamento…</div>'); $('#chartsGrid, #tableCard').hide();
$.getJSON('',{ajax:1,date_from:$('#fDateFrom').val(),date_to:$('#fDateTo').val(),line_id:$('#fLine').val(),matrice_id:$('#fMatrice').val(),mescola_id:$('#fMescola').val()},
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));
$('#btnApply').on('click',loadStats);
$('#btnReset').on('click',function(){ $('#fLine,#fMatrice,#fMescola').val(''); $('#fDateTo').val(today.toISOString().slice(0,10)); $('#fDateFrom').val(past.toISOString().slice(0,10)); loadStats(); });
loadStats();
});
</script>
</body>
</html>