Files
zibo-dashboard/public/userarea/pause_stats.php
T
2026-09-15 15:46:32 +02:00

958 lines
36 KiB
PHP

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
include('include/headscript.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$linee = $pdo->query("SELECT id, name, color 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'] ?? '';
$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;
$where = ["pp.end_pause IS NOT NULL"];
$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 {
$sqlKpi = "SELECT
COUNT(*) AS n_pause, COUNT(DISTINCT pp.id_production) AS n_prod_con_pause,
COALESCE(SUM(TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause)),0) AS tot_s,
COALESCE(AVG(TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause)),0) AS media_s,
COALESCE(MAX(TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause)),0) AS max_s,
COALESCE(SUM(CASE WHEN pr.is_problem=1 THEN 1 ELSE 0 END),0) AS n_problemi,
COALESCE(SUM(CASE WHEN pr.category='planned' THEN TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause) ELSE 0 END),0) AS planned_s,
COALESCE(SUM(CASE WHEN pr.category='unplanned' THEN TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause) ELSE 0 END),0) AS unplanned_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 $whereSql";
$stmt = $pdo->prepare($sqlKpi);
$stmt->execute($params);
$kpi = $stmt->fetch(PDO::FETCH_ASSOC);
$sqlMotivo = "SELECT pr.id, pr.name AS motivo, pr.is_problem, pr.category,
COUNT(pp.id) AS n_pause,
COALESCE(SUM(TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause)),0) AS durata_s,
COALESCE(AVG(TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause)),0) AS media_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 $whereSql GROUP BY pr.id ORDER BY durata_s DESC";
$stmt = $pdo->prepare($sqlMotivo);
$stmt->execute($params);
$perMotivo = $stmt->fetchAll(PDO::FETCH_ASSOC);
$totDurata = array_sum(array_map(fn($x) => (int)$x['durata_s'], $perMotivo));
$cum = 0;
foreach ($perMotivo as &$m) {
$cum += (int)$m['durata_s'];
$m['cum_perc'] = ($totDurata > 0) ? round($cum / $totDurata * 100, 1) : 0;
$m['perc'] = ($totDurata > 0) ? round($m['durata_s'] / $totDurata * 100, 1) : 0;
}
unset($m);
$sqlLinea = "SELECT l.name AS linea, l.color,
COUNT(pp.id) AS n_pause,
COALESCE(SUM(TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause)),0) AS durata_s,
COALESCE(SUM(CASE WHEN pr.is_problem=1 THEN 1 ELSE 0 END),0) AS n_problemi
FROM production_pauses pp
JOIN productiondata p ON p.id = pp.id_production
JOIN production_lines l ON l.id = p.id_linea
JOIN pause_reasons pr ON pr.id = pp.reason_id
WHERE $whereSql GROUP BY l.id ORDER BY durata_s DESC";
$stmt = $pdo->prepare($sqlLinea);
$stmt->execute($params);
$perLinea = $stmt->fetchAll(PDO::FETCH_ASSOC);
$sqlGiorno = "SELECT p.Data AS giorno,
COUNT(pp.id) AS n_pause,
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 $whereSql GROUP BY p.Data ORDER BY p.Data";
$stmt = $pdo->prepare($sqlGiorno);
$stmt->execute($params);
$perGiorno = $stmt->fetchAll(PDO::FETCH_ASSOC);
$sqlDett = "SELECT pp.id, pp.start_pause, pp.end_pause, pp.note,
TIMESTAMPDIFF(SECOND, pp.start_pause, pp.end_pause) AS durata_s,
pr.name AS motivo, pr.is_problem, pr.category,
l.name AS linea, m.nome AS matrice, p.id AS prod_id
FROM production_pauses pp
JOIN productiondata p ON p.id = pp.id_production
LEFT JOIN production_lines l ON l.id = p.id_linea
LEFT JOIN matrice m ON m.id = p.idmatrice
JOIN pause_reasons pr ON pr.id = pp.reason_id
WHERE $whereSql ORDER BY pp.start_pause DESC LIMIT 500";
$stmt = $pdo->prepare($sqlDett);
$stmt->execute($params);
$dettaglio = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode([
'success' => true,
'kpi' => [
'n_pause' => (int)$kpi['n_pause'],
'n_prod_con_pause' => (int)$kpi['n_prod_con_pause'],
'tot_s' => (int)$kpi['tot_s'],
'media_s' => (int)$kpi['media_s'],
'max_s' => (int)$kpi['max_s'],
'n_problemi' => (int)$kpi['n_problemi'],
'planned_s' => (int)$kpi['planned_s'],
'unplanned_s' => (int)$kpi['unplanned_s'],
],
'per_motivo' => $perMotivo,
'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 Pause &amp; Fermi</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, #b91c1c, #ef4444);
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: #b91c1c;
}
.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: #b91c1c;
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);
}
.filters-actions {
display: flex;
gap: .5rem;
}
.btn-apply {
background: #dc2626;
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 {
position: relative;
background: #fff;
border-radius: 1rem;
padding: 1.1rem 1.2rem;
box-shadow: 0 4px 15px rgba(0, 0, 0, .05);
border-left: 5px solid #ef4444;
}
.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.amber {
border-left-color: #f59e0b;
}
.kpi-card.slate {
border-left-color: #64748b;
}
.kpi-card.green {
border-left-color: #10b981;
}
.kpi-card.red {
border-left-color: #ef4444;
}
.charts-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
gap: 1rem;
margin-bottom: 1rem;
}
.chart-card {
position: relative;
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;
padding-right: 1.8rem;
}
.chart-wrap {
position: relative;
height: 300px;
}
.table-card {
position: relative;
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;
padding-right: 1.8rem;
}
table.stats-table {
width: 100%;
border-collapse: collapse;
font-size: .85rem;
}
table.stats-table th {
background: #fee2e2;
color: #991b1b;
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-prob {
background: #fee2e2;
color: #991b1b;
}
.pill-norm {
background: #e0e7ff;
color: #3730a3;
}
.pill-plan {
background: #fef3c7;
color: #92400e;
}
.pill-unplan {
background: #fee2e2;
color: #991b1b;
}
.muted {
color: #94a3b8;
}
.loading {
text-align: center;
padding: 3rem;
color: #64748b;
}
.empty {
text-align: center;
padding: 3rem;
color: #94a3b8;
}
/* --- PULSANTINO "?" INFO --- */
.info-btn {
position: absolute;
top: .6rem;
right: .6rem;
width: 20px;
height: 20px;
border-radius: 50%;
border: none;
cursor: pointer;
background: #e2e8f0;
color: #475569;
font-size: .72rem;
font-weight: 800;
line-height: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
transition: .15s;
z-index: 5;
}
.info-btn:hover {
background: #dc2626;
color: #fff;
}
.info-pop {
position: absolute;
top: 2.1rem;
right: .6rem;
width: 250px;
max-width: 80vw;
background: #0f172a;
color: #f1f5f9;
border-radius: .6rem;
padding: .7rem .8rem;
font-size: .8rem;
line-height: 1.4;
font-weight: 400;
text-transform: none;
letter-spacing: normal;
box-shadow: 0 8px 24px rgba(0, 0, 0, .25);
z-index: 50;
display: none;
}
.info-pop.show {
display: block;
}
.info-pop strong {
color: #fff;
}
.info-pop .info-pop-title {
display: block;
font-weight: 800;
margin-bottom: .25rem;
color: #fff;
}
</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-pause-circle"></i> Statistiche Pause &amp; Fermi</h4>
<div class="header-actions">
<a class="hbtn" href="production_stats.php"><i class="bi bi-speedometer2"></i> Produzione</a>
<a class="hbtn active" 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'] ?: '#ef4444') ?>;">
<?= 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 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">
<button type="button" class="info-btn" data-title="Pareto delle causali" data-info="Il grafico più utile. Le barre sono le ore perse per ogni causa, ordinate dalla peggiore. La linea sale e mostra la somma progressiva in percentuale. Regola pratica: poche cause fanno la maggior parte del tempo perso. Concentrati sulle prime 2-3 barre a sinistra.">?</button>
<h6>Pareto causali — tempo perso e cumulata</h6>
<div class="chart-wrap"><canvas id="chartPareto"></canvas></div>
</div>
<div class="chart-card">
<button type="button" class="info-btn" data-title="Pianificato vs non pianificato" data-info="La fetta di tempo perso previsto (arancione, es. cambio turno, pulizia) contro quello imprevisto (rosso, es. guasti). Una torta sbilanciata verso il rosso significa molte perdite evitabili.">?</button>
<h6>Ripartizione tempo: pianificato vs non pianificato</h6>
<div class="chart-wrap"><canvas id="chartCat"></canvas></div>
</div>
<div class="chart-card">
<button type="button" class="info-btn" data-title="Tempo perso per linea" data-info="Quale linea perde più ore di produzione a causa dei fermi. Individua la linea più problematica su cui concentrare le attenzioni.">?</button>
<h6>Tempo perso per linea (ore)</h6>
<div class="chart-wrap"><canvas id="chartLinea"></canvas></div>
</div>
<div class="chart-card">
<button type="button" class="info-btn" data-title="Numero fermi per causale" data-info="Quante volte si verifica ogni causa (la frequenza, non la durata). Una causa che compare tante volte anche se breve indica un problema ricorrente da eliminare alla radice.">?</button>
<h6>Numero fermi per causale</h6>
<div class="chart-wrap"><canvas id="chartCount"></canvas></div>
</div>
<div class="chart-card">
<button type="button" class="info-btn" data-title="Andamento giornaliero" data-info="Le ore perse giorno per giorno. Individua le giornate nere e cerca cosa è successo (un guasto grave, una fornitura mancata).">?</button>
<h6>Andamento fermi giornaliero (ore)</h6>
<div class="chart-wrap"><canvas id="chartGiorno"></canvas></div>
</div>
</div>
<div class="table-card" id="tableCard" style="display:none;">
<button type="button" class="info-btn" data-title="Dettaglio eventi" data-info="Ogni riga è un singolo fermo: inizio, fine, durata, motivo, tipo (Problema o Normale), categoria (Pianificato o Non pianificato), linea, matrice e la nota dell'operatore. Il massimo dettaglio per ricostruire cosa è successo in un momento preciso.">?</button>
<h6>Dettaglio eventi di pausa</h6>
<table class="stats-table">
<thead>
<tr>
<th>Inizio</th>
<th>Fine</th>
<th>Durata</th>
<th>Motivo</th>
<th>Tipo</th>
<th>Categoria</th>
<th>Linea</th>
<th>Matrice</th>
<th>Prod. #</th>
<th>Nota</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>
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 secToH(s) {
return parseInt(s || 0, 10) / 3600;
}
function fmtDT(iso) {
if (!iso) return '-';
const d = new Date(iso.replace(' ', 'T'));
if (isNaN(d)) return iso;
const p = n => String(n).padStart(2, '0');
return `${p(d.getDate())}/${p(d.getMonth()+1)} ${p(d.getHours())}:${p(d.getMinutes())}`;
}
function fmtDateIt(iso) {
if (!iso) return '-';
const p = iso.split('-');
return p.length === 3 ? `${p[2]}/${p[1]}/${p[0]}` : iso;
}
let charts = {};
function destroyChart(k) {
if (charts[k]) {
charts[k].destroy();
charts[k] = null;
}
}
// Testi spiegazione per i KPI
const KPI_INFO = {
n_pause: {
t: "Fermi totali",
d: "Quante volte le linee si sono fermate in pausa nel periodo. Sotto, quante lavorazioni sono state coinvolte."
},
tot: {
t: "Tempo perso",
d: "Il totale di tutte le pause sommate: il costo in tempo complessivo dei fermi. Confrontalo tra periodi per vedere se migliora."
},
media: {
t: "Durata media",
d: "Quanto dura in media un singolo fermo (accanto, il fermo più lungo). Se il massimo è molto più alto della media, c'è stato un episodio eccezionale da approfondire."
},
problemi: {
t: "Problemi tecnici",
d: "Quanti fermi erano dovuti a un guasto o anomalia vera, e la loro percentuale sul totale. È la spia della salute degli impianti."
},
planned: {
t: "Pianificato",
d: "Il tempo dei fermi previsti (cambio turno, pulizia, manutenzione programmata...). È tempo normale, in parte inevitabile."
},
unplanned: {
t: "Non pianificato",
d: "Il tempo dei fermi imprevisti (guasti, mancanza materiale, qualità...). È QUESTO il tempo da ridurre: sono le perdite evitabili."
},
};
function infoBtn(key) {
const i = KPI_INFO[key];
if (!i) return '';
return `<button type="button" class="info-btn" data-title="${i.t}" data-info="${i.d.replace(/"/g,'&quot;')}">?</button>`;
}
function renderKpi(k) {
const pctProblemi = k.n_pause > 0 ? Math.round(k.n_problemi / k.n_pause * 100) : 0;
$('#kpiGrid').html(`
<div class="kpi-card">${infoBtn('n_pause')}<div class="kpi-label">Fermi totali</div><div class="kpi-value">${k.n_pause}</div><div class="kpi-sub">${k.n_prod_con_pause} produzioni coinvolte</div></div>
<div class="kpi-card">${infoBtn('tot')}<div class="kpi-label">Tempo perso</div><div class="kpi-value" style="font-size:1.25rem;">${secToHms(k.tot_s)}</div><div class="kpi-sub">totale fermi</div></div>
<div class="kpi-card slate">${infoBtn('media')}<div class="kpi-label">Durata media</div><div class="kpi-value" style="font-size:1.25rem;">${secToHms(k.media_s)}</div><div class="kpi-sub">max ${secToHms(k.max_s)}</div></div>
<div class="kpi-card red">${infoBtn('problemi')}<div class="kpi-label">Problemi tecnici</div><div class="kpi-value">${k.n_problemi}</div><div class="kpi-sub">${pctProblemi}% dei fermi</div></div>
<div class="kpi-card green">${infoBtn('planned')}<div class="kpi-label">Pianificato</div><div class="kpi-value" style="font-size:1.25rem;">${secToHms(k.planned_s)}</div><div class="kpi-sub">fermi previsti</div></div>
<div class="kpi-card amber">${infoBtn('unplanned')}<div class="kpi-label">Non pianificato</div><div class="kpi-value" style="font-size:1.25rem;">${secToHms(k.unplanned_s)}</div><div class="kpi-sub">da ridurre</div></div>
`);
}
function renderCharts(d) {
const mot = d.per_motivo || [],
linee = d.per_linea || [],
giorni = d.per_giorno || [],
k = d.kpi;
destroyChart('pareto');
charts.pareto = new Chart($('#chartPareto'), {
data: {
labels: mot.map(x => x.motivo),
datasets: [{
type: 'bar',
label: 'Ore perse',
data: mot.map(x => +secToH(x.durata_s).toFixed(2)),
backgroundColor: mot.map(x => x.category === 'planned' ? '#f59e0b' : '#ef4444'),
yAxisID: 'y'
},
{
type: 'line',
label: 'Cumulata %',
data: mot.map(x => x.cum_perc),
borderColor: '#1e293b',
backgroundColor: '#1e293b',
yAxisID: 'y1',
tension: .2,
pointRadius: 3
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
position: 'left',
title: {
display: true,
text: 'Ore'
}
},
y1: {
beginAtZero: true,
max: 100,
position: 'right',
grid: {
drawOnChartArea: false
},
title: {
display: true,
text: '% cumulata'
}
}
}
}
});
destroyChart('cat');
charts.cat = new Chart($('#chartCat'), {
type: 'doughnut',
data: {
labels: ['Pianificato', 'Non pianificato'],
datasets: [{
data: [+secToH(k.planned_s).toFixed(2), +secToH(k.unplanned_s).toFixed(2)],
backgroundColor: ['#f59e0b', '#ef4444']
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom'
}
}
}
});
destroyChart('linea');
charts.linea = new Chart($('#chartLinea'), {
type: 'bar',
data: {
labels: linee.map(x => x.linea),
datasets: [{
label: 'Ore perse',
data: linee.map(x => +secToH(x.durata_s).toFixed(2)),
backgroundColor: linee.map(x => x.color || '#3b82f6')
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
},
plugins: {
legend: {
display: false
}
}
}
});
destroyChart('count');
charts.count = new Chart($('#chartCount'), {
type: 'bar',
data: {
labels: mot.map(x => x.motivo),
datasets: [{
label: 'N. fermi',
data: mot.map(x => x.n_pause),
backgroundColor: '#64748b'
}]
},
options: {
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
beginAtZero: true
}
},
plugins: {
legend: {
display: false
}
}
}
});
destroyChart('giorno');
charts.giorno = new Chart($('#chartGiorno'), {
type: 'line',
data: {
labels: giorni.map(x => fmtDateIt(x.giorno)),
datasets: [{
label: 'Ore perse',
data: giorni.map(x => +secToH(x.durata_s).toFixed(2)),
borderColor: '#ef4444',
backgroundColor: 'rgba(239,68,68,.15)',
fill: true,
tension: .3
}]
},
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="10" class="empty">Nessun fermo per i filtri selezionati</td></tr>');
return;
}
let html = '';
rows.forEach(r => {
const tipo = (String(r.is_problem) === '1') ? '<span class="pill pill-prob">Problema</span>' : '<span class="pill pill-norm">Normale</span>';
const cat = (r.category === 'planned') ? '<span class="pill pill-plan">Pianificato</span>' : '<span class="pill pill-unplan">Non pian.</span>';
html += `<tr><td>${fmtDT(r.start_pause)}</td><td>${fmtDT(r.end_pause)}</td><td>${secToHms(r.durata_s)}</td>
<td>${r.motivo||'-'}</td><td>${tipo}</td><td>${cat}</td>
<td>${r.linea||'-'}</td><td>${r.matrice||'-'}</td><td>#${r.prod_id}</td>
<td>${r.note?('<span class="muted">'+r.note+'</span>'):'<span class="muted">-</span>'}</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()
},
function(r) {
if (!r.success) {
$('#kpiGrid').html('<div class="empty">Errore: ' + (r.msg || '') + '</div>');
return;
}
renderKpi(r.kpi);
if (r.kpi.n_pause === 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));
$('#lineButtons').on('click', '.line-btn2', function() {
$(this).toggleClass('active');
if ($('#lineButtons .line-btn2.active').length === 0) {
$('#lineButtons .line-btn2').addClass('active');
}
loadStats();
});
$('#btnApply').on('click', loadStats);
$('#btnReset').on('click', function() {
$('#lineButtons .line-btn2').addClass('active');
$('#fMatrice,#fMescola').val('');
$('#fDateTo').val(today.toISOString().slice(0, 10));
$('#fDateFrom').val(past.toISOString().slice(0, 10));
loadStats();
});
// --- POPOVER INFO (delegato: funziona anche sui box creati via JS) ---
$(document).on('click', '.info-btn', function(e) {
e.stopPropagation();
const $btn = $(this);
const alreadyOpen = $btn.next('.info-pop').length && $btn.next('.info-pop').hasClass('show');
$('.info-pop').remove();
if (alreadyOpen) return;
const title = $btn.data('title') || '';
const text = $btn.data('info') || '';
const $pop = $('<div class="info-pop show"></div>');
$pop.html('<span class="info-pop-title">' + title + '</span>' + text);
$btn.after($pop);
});
$(document).on('click', function() {
$('.info-pop').remove();
});
loadStats();
});
</script>
</body>
</html>