upgrade matrice with files

This commit is contained in:
Claudio 2026-03-19 16:16:41 +01:00
parent 245750f057
commit f043b43791
28 changed files with 4028 additions and 358 deletions

View File

@ -0,0 +1,61 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json; charset=utf-8');
$response = [
'success' => false,
'message' => ''
];
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('Metodo non consentito');
}
if (!isset($_POST['id']) || !is_numeric($_POST['id'])) {
throw new Exception('ID allegato non valido');
}
$id = (int)$_POST['id'];
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$stmt = $pdo->prepare("SELECT id, file_path FROM matrice_attachments WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$attachment = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$attachment) {
throw new Exception('Allegato non trovato');
}
$filePathRelative = ltrim((string)$attachment['file_path'], '/\\');
$filePathAbsolute = __DIR__ . '/' . $filePathRelative;
$pdo->beginTransaction();
$deleteStmt = $pdo->prepare("DELETE FROM matrice_attachments WHERE id = :id");
$deleteStmt->execute([':id' => $id]);
if ($deleteStmt->rowCount() <= 0) {
throw new Exception('Impossibile eliminare il record allegato');
}
if (!empty($filePathRelative) && file_exists($filePathAbsolute) && is_file($filePathAbsolute)) {
@unlink($filePathAbsolute);
}
$pdo->commit();
$response['success'] = true;
$response['message'] = 'Allegato eliminato correttamente';
} catch (Throwable $e) {
if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
$pdo->rollBack();
}
$response['message'] = $e->getMessage();
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;

View File

@ -0,0 +1,20 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid id']);
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
$stmt = $pdo->prepare("DELETE FROM packaging_stock_lots WHERE id = ?");
$stmt->execute([$id]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,65 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json; charset=utf-8');
$response = [
'success' => false,
'attachments' => [],
'message' => ''
];
try {
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
throw new Exception('ID matrice non valido');
}
$idmatrice = (int)$_GET['id'];
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$sql = "SELECT
id,
matrice_id,
file_name,
file_path,
file_type,
description,
sort_order,
created_at,
updated_at
FROM matrice_attachments
WHERE matrice_id = :matrice_id
ORDER BY sort_order ASC, id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute([':matrice_id' => $idmatrice]);
$attachments = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$relativePath = ltrim((string)$row['file_path'], '/\\');
$attachments[] = [
'id' => (int)$row['id'],
'matrice_id' => (int)$row['matrice_id'],
'file_name' => $row['file_name'],
'file_path' => $relativePath,
'file_url' => $relativePath,
'file_type' => $row['file_type'],
'description' => $row['description'] ?? '',
'sort_order' => (int)($row['sort_order'] ?? 0),
'created_at' => !empty($row['created_at']) ? date('d/m/Y H:i', strtotime($row['created_at'])) : '',
'updated_at' => !empty($row['updated_at']) ? date('d/m/Y H:i', strtotime($row['updated_at'])) : ''
];
}
$response['success'] = true;
$response['attachments'] = $attachments;
} catch (Throwable $e) {
$response['message'] = $e->getMessage();
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;

View File

@ -0,0 +1,30 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid id']);
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$sql = "SELECT
psl.id,
psl.idsupplier,
s.supplier_name,
psl.lot_code,
psl.expiry_date,
psl.qty
FROM packaging_stock_lots psl
INNER JOIN suppliers s ON s.idsupplier = psl.idsupplier
WHERE psl.idpackaging_item = ?
ORDER BY psl.id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'rows' => $rows]);

File diff suppressed because it is too large Load Diff

View File

@ -121,9 +121,16 @@
max-width: 260px;
}
/* Azioni */
/* Stato */
#tabellaMescole th:nth-child(5),
#tabellaMescole td:nth-child(5) {
width: 140px;
max-width: 140px;
}
/* Azioni */
#tabellaMescole th:nth-child(6),
#tabellaMescole td:nth-child(6) {
width: 330px;
max-width: 330px;
}
@ -147,7 +154,16 @@
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h6 class="fw-semibold mb-0">Elenco Completo</h6>
<div class="d-flex align-items-center gap-3">
<h6 class="fw-semibold mb-0">Elenco Completo</h6>
<select id="filterActive" class="form-select form-select-sm" style="width:220px;">
<option value="all">Tutte</option>
<option value="1" selected>Solo Attive</option>
<option value="0">Solo Inattive</option>
</select>
</div>
<button class="btn btn-add" data-bs-toggle="modal" data-bs-target="#addMescolaModal"> Aggiungi Mescola</button>
</div>
@ -160,19 +176,36 @@
<th>Nome Uscita</th>
<th>Q. Totale</th>
<th>Linee Associate</th>
<th>Stato</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// filtro: all / 1 / 0
$activeFilter = $_GET['active'] ?? '1';
if (!in_array($activeFilter, ['all', '0', '1'], true)) {
$activeFilter = '1';
}
$where = "";
$params = [];
if ($activeFilter !== 'all') {
$where = "WHERE m.is_active = ?";
$params[] = (int)$activeFilter;
}
// QTY IN SUBQUERY per evitare raddoppi dovuti alle linee
$sql = "
SELECT
m.id,
m.nomeuscita,
m.is_active,
IFNULL(q.qty_totale, 0) AS qty_totale,
GROUP_CONCAT(DISTINCT pl.name SEPARATOR ', ') AS linee
FROM mescole m
@ -183,50 +216,67 @@
) q ON q.idmescola = m.id
LEFT JOIN mescole_lines ml ON m.id = ml.idmescola
LEFT JOIN production_lines pl ON ml.idlinea = pl.id
$where
GROUP BY m.id
ORDER BY m.id DESC
";
$stmt = $pdo->query($sql);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
if ($stmt->rowCount() === 0) {
// DataTables-friendly: 5 TD reali
// DataTables-friendly: 6 TD reali
echo "<tr>
<td class='text-muted'>-</td>
<td class='text-muted'>Nessuna mescola presente</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
</tr>";
} else {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$linee = $row['linee'] ? htmlspecialchars($row['linee']) : '<span class="text-muted">Nessuna</span>';
$qtyTot = number_format((float)$row['qty_totale'], 3, ',', '.');
echo "<tr>
<td>{$row['id']}</td>
<td>" . htmlspecialchars($row['nomeuscita']) . "</td>
<td><span class='fw-semibold'>{$qtyTot}</span></td>
<td>{$linee}</td>
<td>
<button class='btn btn-sm btn-outline-dark associa-fornitori'
data-id='{$row['id']}'
data-nomeuscita='" . htmlspecialchars($row['nomeuscita'], ENT_QUOTES) . "'>
🧾 Fornitori/Lotti
</button>
$isActive = (int)$row['is_active'] === 1;
$badge = $isActive
? "<span class='badge bg-success'>Attiva</span>"
: "<span class='badge bg-secondary'>Inattiva</span>";
<button class='btn btn-sm btn-outline-primary associa-linee'
data-id='{$row['id']}'>
⚙️ Linee
</button>
$toggleText = $isActive ? "Disattiva" : "Attiva";
$toggleClass = $isActive ? "btn-outline-warning" : "btn-outline-success";
<button class='btn btn-sm btn-outline-secondary edit-mescola'
data-id='{$row['id']}'
data-nomeuscita='" . htmlspecialchars($row['nomeuscita'], ENT_QUOTES) . "'>
✏️ Modifica
</button>
</td>
</tr>";
echo "<tr data-mescola-id='{$row['id']}'>
<td>{$row['id']}</td>
<td>" . htmlspecialchars($row['nomeuscita']) . "</td>
<td><span class='fw-semibold'>{$qtyTot}</span></td>
<td>{$linee}</td>
<td>{$badge}</td>
<td>
<button class='btn btn-sm btn-outline-dark associa-fornitori'
data-id='{$row['id']}'
data-nomeuscita='" . htmlspecialchars($row['nomeuscita'], ENT_QUOTES) . "'>
🧾 Fornitori
</button>
<button class='btn btn-sm btn-outline-primary associa-linee'
data-id='{$row['id']}'>
⚙️ Linee
</button>
<button class='btn btn-sm {$toggleClass} toggle-active'
data-id='{$row['id']}'>
🔁 {$toggleText}
</button>
<button class='btn btn-sm btn-outline-secondary edit-mescola'
data-id='{$row['id']}'
data-nomeuscita='" . htmlspecialchars($row['nomeuscita'], ENT_QUOTES) . "'>
✏️ Modifica
</button>
</td>
</tr>";
}
}
?>
@ -400,6 +450,12 @@
<script>
/* ----------------- DATATABLE ----------------- */
$(document).ready(function() {
// init dropdown from URL
const urlParams = new URLSearchParams(window.location.search);
const activeParam = urlParams.get('active') || '1';
$('#filterActive').val(activeParam);
// datatable
$('#tabellaMescole').DataTable({
order: [
[0, 'desc']
@ -409,6 +465,39 @@
url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/it-IT.json'
}
});
// filter reload
$('#filterActive').on('change', function() {
const v = $(this).val();
const url = new URL(window.location.href);
url.searchParams.set('active', v);
window.location.href = url.toString();
});
});
/* -------- TOGGLE ACTIVE -------- */
$(document).on('click', '.toggle-active', function() {
const id = $(this).data('id');
fetch('toggle_mescola_active.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `id=${encodeURIComponent(id)}`
})
.then(r => r.json())
.then(data => {
if (data.success) {
location.reload();
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: data.message || "Operazione non riuscita"
});
}
});
});
/* -------- AGGIUNTA MESCOLA -------- */
@ -448,7 +537,6 @@
$(document).on("click", ".edit-mescola", function() {
$("#editIdMescola").val($(this).data("id"));
$("#editNomeUscita").val($(this).data("nomeuscita"));
// nome interno non lo abbiamo in tabella: lo lasciamo vuoto o lo recuperi se vuoi via endpoint
$("#editNomeMescola").val("");
$("#editMescolaModal").modal("show");
});
@ -707,7 +795,6 @@
if (data.success) {
afResetForm();
afLoadRows(idmescola);
// se vuoi aggiornare anche la Q.tà Totale live senza reload: lo facciamo dopo
} else {
Swal.fire({
icon: "error",

View File

@ -0,0 +1,390 @@
<?php include('include/headscript.php'); ?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Dashboard Produzione - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<!-- Bootstrap + jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
background: linear-gradient(135deg, #f3f6f8, #e8eef3);
font-family: 'Segoe UI', sans-serif;
color: #2b3e50;
}
.page-content {
padding: 2rem 1rem;
display: flex;
flex-direction: column;
align-items: center;
}
h3.dashboard-title {
text-align: center;
font-weight: 700;
color: #2b3e50;
margin-bottom: 2rem;
letter-spacing: 0.3px;
}
/* ===== STATISTICHE ===== */
.stats-row {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
margin-bottom: 20px;
width: 100%;
max-width: 900px;
}
.stat-card {
flex: 1 1 250px;
background: #fff;
border-radius: 16px;
padding: 20px 25px;
box-shadow: 0 5px 12px rgba(0, 0, 0, 0.08);
text-align: center;
transition: all 0.2s ease;
}
.stat-card:hover {
transform: translateY(-3px);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.15);
}
.stat-value {
font-size: 2rem;
font-weight: 700;
color: #2b3e50;
}
.stat-label {
font-size: 1rem;
font-weight: 500;
color: #6b7a89;
}
.stat-prod {
background: linear-gradient(135deg, #cde5ff, #dff0ff);
}
.stat-mese {
background: linear-gradient(135deg, #d2f7d9, #e7ffea);
}
.stat-scarti {
background: linear-gradient(135deg, #ffe7cc, #fff3df);
}
/* ===== BOTTONI ===== */
.dashboard-grid {
display: grid;
grid-template-columns: repeat(3, minmax(200px, 1fr));
gap: 25px 35px;
width: 100%;
max-width: 900px;
justify-items: center;
margin-bottom: 20px;
}
.dashboard-grid-bottom {
display: grid;
grid-template-columns: repeat(3, minmax(200px, 1fr));
gap: 15px 35px;
width: 100%;
max-width: 900px;
justify-items: center;
margin-top: 10px;
}
.btn-tools {
background: linear-gradient(135deg, #9f7aea, #b794f4);
}
.dash-btn {
width: 100%;
max-width: 280px;
border: none;
border-radius: 16px;
padding: 24px 10px;
color: #2b3e50;
font-size: 1.3rem;
font-weight: 600;
background: #fff;
transition: all 0.2s ease;
box-shadow: 0 5px 12px rgba(0, 0, 0, 0.08);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.dash-btn:hover {
transform: translateY(-3px);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.15);
cursor: pointer;
}
.dash-icon {
font-size: 3.2rem;
margin-bottom: 10px;
line-height: 1;
}
/* Colori pastello */
.btn-inserisci {
background: linear-gradient(135deg, #a4c2f3ff, #c1d8ffff);
}
.btn-visualizza {
background: linear-gradient(135deg, #82f09eff, #aaecaaff);
}
.btn-statistiche {
background: linear-gradient(135deg, #ffe0a3ff, #fff1c1ff);
}
.btn-mescole {
background: linear-gradient(135deg, #ffc853ff, #fdd98bff);
}
.btn-matrici {
background: linear-gradient(135deg, #ff8585ff, #ff9d9dff);
}
.btn-linee {
background: linear-gradient(135deg, #b9e3ffff, #d7f1ffff);
}
.btn-programmazione {
background: linear-gradient(135deg, #7c7afaff, #7c7afaff);
}
.btn-status {
background: linear-gradient(135deg, #61ce5dff, #61ce5dff);
}
.btn-problem {
background-color: #ef4444 !important;
color: #ffffff !important;
border-radius: 12px;
}
.btn-problem:hover {
background-color: #dc2626 !important;
}
.btn-tools {
background: linear-gradient(135deg, #9f7aea, #b794f4);
}
/* 🔹 Nuovo bottone Employees */
.btn-employees {
background: linear-gradient(135deg, #a5b4fc, #c7d2fe);
}
/* --- Pulsanti grandi (default) --- */
.dash-btn-large {
padding: 18px 10px;
font-size: 1.3rem;
}
/* --- Pulsanti di servizio: più bassi --- */
.dash-btn-small {
padding: 9px 10px !important;
font-size: 1.05rem !important;
min-height: 80px;
}
@media (max-width: 768px) {
.stats-row {
flex-direction: column;
align-items: center;
}
.dashboard-grid,
.dashboard-grid-bottom {
grid-template-columns: 1fr;
gap: 15px;
}
.dash-btn {
font-size: 1.2rem;
padding: 30px 8px;
}
.dash-icon {
font-size: 2.6rem;
}
}
</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">
<h3 class="dashboard-title">Dashboard Produzione</h3>
<!-- ===== STATISTICHE PRINCIPALI ===== -->
<div class="stats-row">
<?php
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Totale odierno
$stmt = $pdo->query("SELECT SUM(kgprod) AS totale_oggi FROM productiondata WHERE DATE(Data) = CURDATE()");
$totOggi = number_format($stmt->fetchColumn() ?? 0, 2, ',', '.');
// Totale mese
$stmt = $pdo->query("SELECT SUM(kgprod) AS totale_mese FROM productiondata WHERE MONTH(Data) = MONTH(CURDATE()) AND YEAR(Data) = YEAR(CURDATE())");
$totMese = number_format($stmt->fetchColumn() ?? 0, 2, ',', '.');
// Scarti medi %
$stmt = $pdo->query("SELECT (SUM(scarto)/NULLIF(SUM(kgprod),0))*100 AS perc_scarto FROM productiondata WHERE MONTH(Data) = MONTH(CURDATE()) AND YEAR(Data) = YEAR(CURDATE())");
$percScarto = number_format($stmt->fetchColumn() ?? 0, 2, ',', '.');
?>
<div class="stat-card stat-prod">
<div class="stat-value"><?= $totOggi ?> kg</div>
<div class="stat-label">Produzione odierna</div>
</div>
<div class="stat-card stat-mese">
<div class="stat-value"><?= $totMese ?> kg</div>
<div class="stat-label">Produzione mese corrente</div>
</div>
<div class="stat-card stat-scarti">
<div class="stat-value"><?= $percScarto ?>%</div>
<div class="stat-label">Scarto medio mensile</div>
</div>
</div>
<!-- ===== PRIMA RIGA ===== -->
<div class="dashboard-grid">
<button class="dash-btn dash-btn-large btn-programmazione" onclick="location.href='produzione_programmazione_drag.php'">
<div class="dash-icon">🗓️</div>
<div>Programmazione</div>
</button>
<button class="dash-btn dash-btn-large btn-status" onclick="location.href='production_line_view2.php'">
<div class="dash-icon">⚙️</div>
<div>Line View</div>
</button>
<button class="dash-btn dash-btn-large btn-statistiche" onclick="location.href='production_stats.php'">
<div class="dash-icon">📈</div>
<div>Statistiche</div>
</button>
<button class="dash-btn dash-btn-large btn-manager" onclick="location.href='manager_produzione.php'">
<div class="dash-icon">👔</div>
<div>Manager</div>
</button>
<button class="dash-btn dash-btn-large btn-manager-stats" onclick="location.href='manager_stats.php'">
<div class="dash-icon">📊</div>
<div>Manager Stats</div>
</button>
<button class="dash-btn dash-btn-large btn-linee" onclick="location.href='warehouse_dashboard.php'">
<div class="dash-icon">📦</div>
<div>Magazzino</div>
</button>
</div>
<!-- ===== SECONDA RIGA ===== -->
<div class="dashboard-grid">
<button class="dash-btn dash-btn-small btn-mescole" onclick="location.href='mescole.php'">
<div class="dash-icon">⚗️</div>
<div>Mescole</div>
</button>
<button class="dash-btn dash-btn-small btn-matrici" onclick="location.href='matrici.php'">
<div class="dash-icon">🧩</div>
<div>Elenco Profili</div>
</button>
<button class="dash-btn dash-btn-small btn-linee" onclick="location.href='linee.php'">
<div class="dash-icon">🏭</div>
<div>Linee di Produzione</div>
</button>
</div>
<!-- ===== TERZA RIGA ===== -->
<div class="dashboard-grid-bottom">
<button class="dash-btn dash-btn-small btn-inserisci btn-inserisci-status" onclick="location.href='production_status.php'">
<div class="dash-icon">📋</div>
<div>Status</div>
</button>
<button class="dash-btn dash-btn-small btn-problem" onclick="location.href='production_pause_reasons.php'">
<div class="dash-icon">🛑</div>
<div>Cause di Pausa</div>
</button>
<button class="dash-btn dash-btn-small btn-tools" onclick="location.href='production_tools.php'">
<div class="dash-icon">🛠️</div>
<div>Attrezzature</div>
</button>
</div>
<!-- 🔹 QUARTA RIGA: EMPLOYEES -->
<div class="dashboard-grid-bottom" style="margin-top: 20px;">
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='worksheets.php'">
<div class="dash-icon">🛠️</div>
<div>Fogli di lavoro</div>
</button>
<button class="dash-btn dash-btn-small btn-employees" onclick="location.href='employees.php'">
<div class="dash-icon">👥</div>
<div>Employees</div>
</button>
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='skills.php'">
<div class="dash-icon">🛠️</div>
<div>Skills</div>
</button>
</div>
<!-- 🔹 Quinta RIGA: EMPLOYEES -->
<div class="dashboard-grid-bottom" style="margin-top: 20px;">
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='packaging_items.php'">
<div class="dash-icon">🛠️</div>
<div>Imballaggi</div>
</button>
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='suppliers.php'">
<div class="dash-icon">🛠️</div>
<div>Suppliers</div>
</button>
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='lookup_values.php'">
<div class="dash-icon">🛠️</div>
<div>Setup</div>
</button>
</div>
</div>
</div>
<?php include('jsinclude.php'); ?>
<?php include('include/footer.php'); ?>
</div>
</body>
</html>

View File

@ -0,0 +1,689 @@
<?php include('include/headscript.php'); ?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Imballaggi - Anagrafica & Stock - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<!-- jQuery + Bootstrap -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<!-- Select2 -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.full.min.js"></script>
<style>
body {
font-size: 1.05rem;
background: #f8fafc;
}
.card {
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0, 0, 0, .08);
}
.table thead {
background: #cfe3ff;
color: #1f2d3d;
}
.modal-content {
border-radius: 16px;
}
.btn-add {
background-color: #0d6efd;
color: #fff;
border-radius: 8px;
padding: 10px 20px;
font-weight: 500;
}
.btn-add:hover {
background-color: #0b5ed7;
}
#tabPackaging {
table-layout: fixed;
width: 100% !important;
}
#tabPackaging th,
#tabPackaging td {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
/* Column widths */
#tabPackaging th:nth-child(1),
#tabPackaging td:nth-child(1) {
width: 60px;
max-width: 60px;
}
#tabPackaging th:nth-child(2),
#tabPackaging td:nth-child(2) {
width: 170px;
max-width: 170px;
}
#tabPackaging th:nth-child(4),
#tabPackaging td:nth-child(4) {
width: 140px;
max-width: 140px;
}
#tabPackaging th:nth-child(5),
#tabPackaging td:nth-child(5) {
width: 110px;
max-width: 110px;
}
#tabPackaging th:nth-child(6),
#tabPackaging td:nth-child(6) {
width: 120px;
max-width: 120px;
}
#tabPackaging th:nth-child(7),
#tabPackaging td:nth-child(7) {
width: 420px;
max-width: 420px;
}
.back-dashboard {
background-color: #cfe3ff !important;
color: #1f2d3d !important;
border: 1px solid #bcd4f4 !important;
border-radius: 10px;
font-weight: 600;
font-size: 1rem;
padding: 10px 18px;
box-shadow: 0 3px 8px rgba(0, 0, 0, .1);
}
.back-dashboard:hover {
background-color: #b9d3ff !important;
transform: translateY(-2px);
}
.qty-badge {
font-weight: 700;
}
tr.inactive-item {
opacity: 0.65;
}
</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="card p-3">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">Imballaggi - Anagrafica & Stock</h5>
<div class="d-flex gap-2">
<button class="btn back-dashboard" onclick="location.href='warehouse_dashboard.php'">↩️ Torna a Magazzino</button>
<button class="btn btn-add" data-bs-toggle="modal" data-bs-target="#addItemModal"> Nuovo Imballo</button>
</div>
</div>
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<div class="d-flex align-items-center gap-3">
<h6 class="fw-semibold mb-0">Elenco</h6>
<select id="filterActive" class="form-select form-select-sm" style="width:220px;">
<option value="all">Tutti</option>
<option value="1" selected>Solo Attivi</option>
<option value="0">Solo Inattivi</option>
</select>
<select id="filterCategory" class="form-select form-select-sm" style="width:240px;">
<option value="all">Tutte le categorie</option>
<option value="PACKAGING_TYPE">Tipo Confezione</option>
<option value="BOX">Scatole</option>
<option value="PALLET">Pallet</option>
<option value="OTHER">Altro</option>
</select>
</div>
</div>
<?php
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$active = $_GET['active'] ?? '1';
if (!in_array($active, ['all', '0', '1'], true)) $active = '1';
$cat = $_GET['cat'] ?? 'all';
$allowedCats = ['all', 'PACKAGING_TYPE', 'BOX', 'PALLET', 'OTHER'];
if (!in_array($cat, $allowedCats, true)) $cat = 'all';
$where = [];
$params = [];
if ($active !== 'all') {
$where[] = "pi.is_active = ?";
$params[] = (int)$active;
}
if ($cat !== 'all') {
$where[] = "pi.category = ?";
$params[] = $cat;
}
$whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";
// Sum qty in subquery to avoid duplicates
$sql = "
SELECT
pi.id,
pi.category,
pi.item_name,
pi.item_code,
pi.is_active,
IFNULL(q.qty_totale, 0) AS qty_totale
FROM packaging_items pi
LEFT JOIN (
SELECT idpackaging_item, SUM(qty) AS qty_totale
FROM packaging_stock_lots
GROUP BY idpackaging_item
) q ON q.idpackaging_item = pi.id
$whereSql
ORDER BY pi.category ASC, pi.item_name ASC, pi.id DESC
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
function catLabel($c)
{
return match ($c) {
'PACKAGING_TYPE' => 'Tipo Confezione',
'BOX' => 'Scatola',
'PALLET' => 'Pallet',
default => $c
};
}
?>
<div class="table-responsive">
<table id="tabPackaging" class="table table-striped align-middle text-center" style="width:100%;">
<thead>
<tr>
<th>ID</th>
<th>Categoria</th>
<th>Nome</th>
<th>Codice</th>
<th>Q. Tot</th>
<th>Stato</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php
if (!$rows) {
echo "<tr>
<td class='text-muted'>-</td>
<td class='text-muted'>Nessun elemento</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
</tr>";
} else {
foreach ($rows as $r) {
$isActive = ((int)$r['is_active'] === 1);
$badge = $isActive
? "<span class='badge bg-success'>Attivo</span>"
: "<span class='badge bg-secondary'>Inattivo</span>";
$toggleText = $isActive ? "Disattiva" : "Attiva";
$toggleClass = $isActive ? "btn-outline-warning" : "btn-outline-success";
$qtyTot = number_format((float)$r['qty_totale'], 3, ',', '.');
$trClass = $isActive ? "" : " class='inactive-item'";
echo "<tr{$trClass} data-item-id='{$r['id']}'>
<td>{$r['id']}</td>
<td>" . htmlspecialchars(catLabel($r['category'])) . "</td>
<td>" . htmlspecialchars($r['item_name']) . "</td>
<td><span class='fw-semibold'>" . htmlspecialchars($r['item_code']) . "</span></td>
<td><span class='qty-badge'>{$qtyTot}</span></td>
<td>{$badge}</td>
<td>
<button class='btn btn-sm btn-outline-dark manage-stock'
data-id='{$r['id']}'
data-name='" . htmlspecialchars($r['item_name'], ENT_QUOTES) . "'>
📦 Stock
</button>
<button class='btn btn-sm {$toggleClass} toggle-item'
data-id='{$r['id']}'>
🔁 {$toggleText}
</button>
</td>
</tr>";
}
}
?>
</tbody>
</table>
</div>
<div class="text-muted small mt-2">
Q. Tot = somma di tutti i lotti/fornitori collegati allimballo.
</div>
</div>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<!-- MODALE: NUOVO IMBALLO -->
<div class="modal fade" id="addItemModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header" style="background-color:#cfe3ff;">
<h5 class="modal-title">Nuovo Imballo</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form id="addItemForm">
<div class="mb-3">
<label class="form-label fw-semibold">Categoria</label>
<select class="form-select" id="newCategory" required>
<option value="PACKAGING_TYPE">Tipo Confezione</option>
<option value="BOX">Scatola</option>
<option value="PALLET">Pallet</option>
<option value="OTHER">Altro</option>
</select>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Nome</label>
<input type="text" class="form-control" id="newItemName" required>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Codice</label>
<input type="text" class="form-control" id="newItemCode" required>
</div>
<div class="text-center">
<button type="submit" class="btn btn-add">💾 Salva</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- MODALE: STOCK FORNITORI/LOTTI -->
<div class="modal fade" id="stockModal" tabindex="-1">
<div class="modal-dialog modal-xl modal-dialog-centered">
<div class="modal-content">
<div class="modal-header" style="background-color:#cfe3ff;">
<h5 class="modal-title">Stock - <span id="stockItemName"></span></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input type="hidden" id="stockItemId">
<input type="hidden" id="stockEditId">
<div class="row g-2 align-items-end mb-3">
<div class="col-md-3">
<label class="form-label fw-semibold">Fornitore</label>
<select class="form-select" id="stockSupplier" style="width:100%;"></select>
</div>
<div class="col-md-3">
<label class="form-label fw-semibold">Lotto</label>
<input type="text" class="form-control" id="stockLot" placeholder="LOT-...">
</div>
<div class="col-md-2">
<label class="form-label fw-semibold">Scadenza</label>
<input type="date" class="form-control" id="stockExpiry">
</div>
<div class="col-md-2">
<label class="form-label fw-semibold">Q.</label>
<input type="number" step="0.001" class="form-control" id="stockQty" value="0">
</div>
<div class="col-md-2 text-end">
<button class="btn btn-add w-100" id="stockSaveBtn"> Aggiungi</button>
<button class="btn btn-outline-secondary w-100 mt-2" id="stockCancelEdit" type="button" style="display:none;">Annulla</button>
</div>
</div>
<div class="table-responsive">
<table class="table table-striped align-middle text-center" id="stockTable">
<thead class="table-light">
<tr>
<th>ID</th>
<th>Fornitore</th>
<th>Lotto</th>
<th>Scadenza</th>
<th>Q.</th>
<th>Azioni</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="text-muted small">
Suggerimento: per cambiare quantità clicca ✏️, modifica Q. e salva.
</div>
</div>
</div>
</div>
</div>
<?php include('jsinclude.php'); ?>
<script>
let dt;
function refreshUrlParams() {
const url = new URL(window.location.href);
url.searchParams.set('active', $('#filterActive').val());
url.searchParams.set('cat', $('#filterCategory').val());
window.location.href = url.toString();
}
function loadSuppliersSelect($select, dropdownParent) {
return fetch("get_suppliers.php")
.then(r => r.json())
.then(data => {
$select.empty();
$select.append(`<option value="">Seleziona...</option>`);
if (data.success && Array.isArray(data.rows)) {
data.rows.forEach(s => $select.append(`<option value="${s.idsupplier}">${s.supplier_name}</option>`));
}
$select.select2({
theme: "bootstrap-5",
width: "100%",
dropdownParent: dropdownParent
});
});
}
function stockResetForm() {
$("#stockEditId").val("");
$("#stockSupplier").val("").trigger("change");
$("#stockLot").val("");
$("#stockExpiry").val("");
$("#stockQty").val("0");
$("#stockSaveBtn").text(" Aggiungi");
$("#stockCancelEdit").hide();
}
function stockLoadRows(itemId) {
fetch("get_packaging_stock_lots.php?id=" + encodeURIComponent(itemId))
.then(r => r.json())
.then(data => {
const tbody = $("#stockTable tbody");
tbody.empty();
if (!data.success || !Array.isArray(data.rows) || data.rows.length === 0) {
tbody.append(`<tr>
<td class="text-muted">-</td>
<td class="text-muted">Nessuna riga</td>
<td class="text-muted">-</td>
<td class="text-muted">-</td>
<td class="text-muted">-</td>
<td class="text-muted">-</td>
</tr>`);
return;
}
data.rows.forEach(row => {
const exp = row.expiry_date ? row.expiry_date : "";
tbody.append(`
<tr data-row-id="${row.id}">
<td>${row.id}</td>
<td>${row.supplier_name}</td>
<td>${row.lot_code ?? ""}</td>
<td>${exp || "-"}</td>
<td>${row.qty}</td>
<td>
<button class="btn btn-sm btn-outline-secondary stock-edit"
data-id="${row.id}"
data-idsupplier="${row.idsupplier}"
data-lot="${(row.lot_code ?? "").replace(/"/g,'&quot;')}"
data-exp="${exp}"
data-qty="${row.qty}">
✏️
</button>
<button class="btn btn-sm btn-outline-danger stock-del" data-id="${row.id}">🗑️</button>
</td>
</tr>
`);
});
});
}
$(document).ready(function() {
// Init filters from URL
const urlParams = new URLSearchParams(window.location.search);
$('#filterActive').val(urlParams.get('active') || '1');
$('#filterCategory').val(urlParams.get('cat') || 'all');
dt = $('#tabPackaging').DataTable({
order: [
[2, 'asc']
],
pageLength: 50,
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/it-IT.json'
}
});
$('#filterActive, #filterCategory').on('change', refreshUrlParams);
});
// Create new item
$("#addItemForm").on("submit", function(e) {
e.preventDefault();
const category = $("#newCategory").val();
const item_name = $("#newItemName").val().trim();
const item_code = $("#newItemCode").val().trim();
fetch("save_packaging_item.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `category=${encodeURIComponent(category)}&item_name=${encodeURIComponent(item_name)}&item_code=${encodeURIComponent(item_code)}`
})
.then(r => r.json())
.then(data => {
if (data.success) {
Swal.fire({
icon: "success",
title: "Creato!"
}).then(() => location.reload());
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: data.message || "Non salvato"
});
}
});
});
// Toggle item active
$(document).on("click", ".toggle-item", function() {
const id = $(this).data("id");
fetch("toggle_packaging_item_active.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `id=${encodeURIComponent(id)}`
})
.then(r => r.json())
.then(data => {
if (data.success) location.reload();
else Swal.fire({
icon: "error",
title: "Errore",
text: data.message || "Operazione non riuscita"
});
});
});
// Open stock modal
$(document).on("click", ".manage-stock", function() {
const id = $(this).data("id");
const name = $(this).data("name");
$("#stockItemId").val(id);
$("#stockItemName").text(name);
$("#stockModal").modal("show");
stockResetForm();
loadSuppliersSelect($("#stockSupplier"), $("#stockModal")).then(() => stockLoadRows(id));
});
// Click edit stock row
$(document).on("click", ".stock-edit", function() {
$("#stockEditId").val($(this).data("id"));
$("#stockSupplier").val(String($(this).data("idsupplier"))).trigger("change");
$("#stockLot").val($(this).data("lot"));
$("#stockExpiry").val($(this).data("exp"));
$("#stockQty").val($(this).data("qty"));
$("#stockSaveBtn").text("💾 Salva");
$("#stockCancelEdit").show();
});
// Cancel edit
$("#stockCancelEdit").on("click", function() {
stockResetForm();
});
// Save stock (insert/update)
$("#stockSaveBtn").on("click", function(e) {
e.preventDefault();
const itemId = $("#stockItemId").val();
const editId = $("#stockEditId").val();
const idsupplier = $("#stockSupplier").val();
const lot = $("#stockLot").val().trim();
const expiry = $("#stockExpiry").val();
const qty = $("#stockQty").val();
if (!idsupplier) {
Swal.fire({
icon: "warning",
title: "Attenzione",
text: "Seleziona un fornitore"
});
return;
}
const url = editId ? "update_packaging_stock_lot.php" : "save_packaging_stock_lot.php";
const body =
(editId ? `id=${encodeURIComponent(editId)}&` : ``) +
`idpackaging_item=${encodeURIComponent(itemId)}` +
`&idsupplier=${encodeURIComponent(idsupplier)}` +
`&lot_code=${encodeURIComponent(lot)}` +
`&expiry_date=${encodeURIComponent(expiry)}` +
`&qty=${encodeURIComponent(qty)}`;
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body
})
.then(r => r.json())
.then(data => {
if (data.success) {
stockResetForm();
stockLoadRows(itemId);
// Refresh totals by reloading page (simple and safe)
// If you want live update without reload, we can do it.
// location.reload();
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: data.message || "Operazione non riuscita"
});
}
});
});
// Delete stock row
$(document).on("click", ".stock-del", function() {
const id = $(this).data("id");
const itemId = $("#stockItemId").val();
Swal.fire({
title: "Eliminare la riga?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Sì, elimina",
cancelButtonText: "Annulla",
confirmButtonColor: "#d33"
}).then((res) => {
if (!res.isConfirmed) return;
fetch("delete_packaging_stock_lot.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `id=${encodeURIComponent(id)}`
})
.then(r => r.json())
.then(data => {
if (data.success) {
stockLoadRows(itemId);
// location.reload();
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: data.message || "Cancellazione non riuscita"
});
}
});
});
});
</script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 566 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 591 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

View File

@ -12,7 +12,6 @@
<!-- Bootstrap + jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
background: linear-gradient(135deg, #f3f6f8, #e8eef3);
@ -21,7 +20,7 @@
}
.page-content {
padding: 2rem 1rem;
padding: 1.4rem 1rem;
display: flex;
flex-direction: column;
align-items: center;
@ -29,9 +28,9 @@
h3.dashboard-title {
text-align: center;
font-weight: 700;
font-weight: 800;
color: #2b3e50;
margin-bottom: 2rem;
margin-bottom: 1.2rem;
letter-spacing: 0.3px;
}
@ -40,36 +39,37 @@
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
margin-bottom: 20px;
gap: 14px;
margin-bottom: 16px;
width: 100%;
max-width: 900px;
max-width: 980px;
}
.stat-card {
flex: 1 1 250px;
flex: 1 1 240px;
background: #fff;
border-radius: 16px;
padding: 20px 25px;
padding: 18px 20px;
box-shadow: 0 5px 12px rgba(0, 0, 0, 0.08);
text-align: center;
transition: all 0.2s ease;
}
.stat-card:hover {
transform: translateY(-3px);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.15);
transform: translateY(-2px);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.13);
}
.stat-value {
font-size: 2rem;
font-weight: 700;
font-size: 1.8rem;
font-weight: 800;
color: #2b3e50;
line-height: 1.15;
}
.stat-label {
font-size: 1rem;
font-weight: 500;
font-size: 0.98rem;
font-weight: 600;
color: #6b7a89;
}
@ -85,40 +85,91 @@
background: linear-gradient(135deg, #ffe7cc, #fff3df);
}
/* ===== SEZIONI COLLASSABILI ===== */
.sections-wrap {
width: 100%;
max-width: 980px;
}
.section-card {
background: #fff;
border-radius: 16px;
box-shadow: 0 5px 12px rgba(0, 0, 0, 0.08);
margin-bottom: 14px;
overflow: hidden;
}
.section-header {
width: 100%;
border: 0;
background: transparent;
padding: 14px 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
cursor: pointer;
user-select: none;
text-align: left;
}
.section-left {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.section-icon {
font-size: 1.6rem;
line-height: 1;
}
.section-title {
font-weight: 800;
font-size: 1.05rem;
margin: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.section-subtitle {
font-size: 0.9rem;
color: #6b7a89;
margin: 0;
}
.chev {
font-size: 1.25rem;
transition: transform 0.18s ease;
}
.section-header[aria-expanded="true"] .chev {
transform: rotate(180deg);
}
.section-body {
padding: 14px 16px 16px 16px;
border-top: 1px solid rgba(0, 0, 0, 0.06);
}
/* ===== BOTTONI ===== */
.dashboard-grid {
display: grid;
grid-template-columns: repeat(3, minmax(200px, 1fr));
gap: 25px 35px;
gap: 14px 16px;
width: 100%;
max-width: 900px;
justify-items: center;
margin-bottom: 20px;
}
.dashboard-grid-bottom {
display: grid;
grid-template-columns: repeat(3, minmax(200px, 1fr));
gap: 15px 35px;
width: 100%;
max-width: 900px;
justify-items: center;
margin-top: 10px;
}
.btn-tools {
background: linear-gradient(135deg, #9f7aea, #b794f4);
}
.dash-btn {
width: 100%;
max-width: 280px;
border: none;
border-radius: 16px;
padding: 24px 10px;
padding: 16px 10px;
color: #2b3e50;
font-size: 1.3rem;
font-weight: 600;
font-size: 1.15rem;
font-weight: 700;
background: #fff;
transition: all 0.2s ease;
box-shadow: 0 5px 12px rgba(0, 0, 0, 0.08);
@ -126,33 +177,48 @@
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 108px;
}
.dash-btn:hover {
transform: translateY(-3px);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.15);
transform: translateY(-2px);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.13);
cursor: pointer;
}
.dash-icon {
font-size: 3.2rem;
margin-bottom: 10px;
font-size: 2.6rem;
margin-bottom: 6px;
line-height: 1;
}
/* Colori pastello */
.btn-inserisci {
background: linear-gradient(135deg, #a4c2f3ff, #c1d8ffff);
/* Pastel colors */
.btn-programmazione {
background: linear-gradient(135deg, #7c7afaff, #7c7afaff);
color: #fff;
}
.btn-visualizza {
background: linear-gradient(135deg, #82f09eff, #aaecaaff);
.btn-status {
background: linear-gradient(135deg, #61ce5dff, #61ce5dff);
color: #fff;
}
.btn-statistiche {
background: linear-gradient(135deg, #ffe0a3ff, #fff1c1ff);
}
.btn-manager {
background: linear-gradient(135deg, #cde5ff, #dff0ff);
}
.btn-manager-stats {
background: linear-gradient(135deg, #d2f7d9, #e7ffea);
}
.btn-magazzino {
background: linear-gradient(135deg, #b9e3ffff, #d7f1ffff);
}
.btn-mescole {
background: linear-gradient(135deg, #ffc853ff, #fdd98bff);
}
@ -165,18 +231,10 @@
background: linear-gradient(135deg, #b9e3ffff, #d7f1ffff);
}
.btn-programmazione {
background: linear-gradient(135deg, #7c7afaff, #7c7afaff);
}
.btn-status {
background: linear-gradient(135deg, #61ce5dff, #61ce5dff);
}
.btn-problem {
background-color: #ef4444 !important;
color: #ffffff !important;
border-radius: 12px;
border-radius: 16px;
}
.btn-problem:hover {
@ -185,46 +243,41 @@
.btn-tools {
background: linear-gradient(135deg, #9f7aea, #b794f4);
color: #fff;
}
/* 🔹 Nuovo bottone Employees */
.btn-employees {
background: linear-gradient(135deg, #a5b4fc, #c7d2fe);
}
/* --- Pulsanti grandi (default) --- */
.dash-btn-large {
padding: 18px 10px;
font-size: 1.3rem;
.btn-setup {
background: linear-gradient(135deg, #e5e7eb, #f3f4f6);
}
/* --- Pulsanti di servizio: più bassi --- */
.dash-btn-small {
padding: 9px 10px !important;
font-size: 1.05rem !important;
min-height: 80px;
/* Tablet/mobile */
@media (max-width: 992px) {
.dashboard-grid {
grid-template-columns: repeat(2, minmax(180px, 1fr));
}
}
@media (max-width: 768px) {
.stats-row {
flex-direction: column;
align-items: center;
align-items: stretch;
}
.dashboard-grid,
.dashboard-grid-bottom {
.dashboard-grid {
grid-template-columns: 1fr;
gap: 15px;
}
.dash-btn {
font-size: 1.2rem;
padding: 30px 8px;
font-size: 1.12rem;
min-height: 98px;
}
.dash-icon {
font-size: 2.6rem;
font-size: 2.4rem;
}
}
</style>
@ -246,15 +299,12 @@
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Totale odierno
$stmt = $pdo->query("SELECT SUM(kgprod) AS totale_oggi FROM productiondata WHERE DATE(Data) = CURDATE()");
$totOggi = number_format($stmt->fetchColumn() ?? 0, 2, ',', '.');
// Totale mese
$stmt = $pdo->query("SELECT SUM(kgprod) AS totale_mese FROM productiondata WHERE MONTH(Data) = MONTH(CURDATE()) AND YEAR(Data) = YEAR(CURDATE())");
$totMese = number_format($stmt->fetchColumn() ?? 0, 2, ',', '.');
// Scarti medi %
$stmt = $pdo->query("SELECT (SUM(scarto)/NULLIF(SUM(kgprod),0))*100 AS perc_scarto FROM productiondata WHERE MONTH(Data) = MONTH(CURDATE()) AND YEAR(Data) = YEAR(CURDATE())");
$percScarto = number_format($stmt->fetchColumn() ?? 0, 2, ',', '.');
?>
@ -275,99 +325,179 @@
</div>
</div>
<!-- ===== PRIMA RIGA ===== -->
<div class="dashboard-grid">
<button class="dash-btn dash-btn-large btn-programmazione" onclick="location.href='produzione_programmazione_drag.php'">
<div class="dash-icon">🗓️</div>
<div>Programmazione</div>
</button>
<!-- ===== SEZIONI COLLASSABILI ===== -->
<div class="sections-wrap" id="prodAccordion">
<button class="dash-btn dash-btn-large btn-status" onclick="location.href='production_line_view2.php'">
<div class="dash-icon">⚙️</div>
<div>Line View</div>
</button>
<!-- OPERATIVO -->
<div class="section-card">
<button type="button" class="section-header" data-bs-toggle="collapse" data-bs-target="#secOperativo" aria-expanded="true" aria-controls="secOperativo">
<div class="section-left">
<div class="section-icon">🚀</div>
<div style="min-width:0;">
<p class="section-title">Operativo</p>
<p class="section-subtitle">Azioni principali di produzione</p>
</div>
</div>
<div class="chev"></div>
</button>
<button class="dash-btn dash-btn-large btn-statistiche" onclick="location.href='production_stats.php'">
<div class="dash-icon">📈</div>
<div>Statistiche</div>
</button>
<div id="secOperativo" class="collapse show" data-bs-parent="#prodAccordion">
<div class="section-body">
<div class="dashboard-grid">
<button class="dash-btn btn-programmazione" onclick="location.href='produzione_programmazione_drag.php'">
<div class="dash-icon">🗓️</div>
<div>Programmazione</div>
</button>
<button class="dash-btn dash-btn-large btn-manager" onclick="location.href='manager_produzione.php'">
<div class="dash-icon">👔</div>
<div>Manager</div>
</button>
<button class="dash-btn btn-status" onclick="location.href='production_line_view2.php'">
<div class="dash-icon">⚙️</div>
<div>Line View</div>
</button>
<button class="dash-btn dash-btn-large btn-manager-stats" onclick="location.href='manager_stats.php'">
<div class="dash-icon">📊</div>
<div>Manager Stats</div>
</button>
</div>
<button class="dash-btn btn-statistiche" onclick="location.href='production_stats.php'">
<div class="dash-icon">📈</div>
<div>Statistiche</div>
</button>
<!-- ===== SECONDA RIGA ===== -->
<div class="dashboard-grid">
<button class="dash-btn dash-btn-small btn-mescole" onclick="location.href='mescole.php'">
<div class="dash-icon">⚗️</div>
<div>Mescole</div>
</button>
<button class="dash-btn btn-manager" onclick="location.href='manager_produzione.php'">
<div class="dash-icon">👔</div>
<div>Manager</div>
</button>
<button class="dash-btn dash-btn-small btn-matrici" onclick="location.href='matrici.php'">
<div class="dash-icon">🧩</div>
<div>Elenco Profili</div>
</button>
<button class="dash-btn btn-manager-stats" onclick="location.href='manager_stats.php'">
<div class="dash-icon">📊</div>
<div>Manager Stats</div>
</button>
<button class="dash-btn dash-btn-small btn-linee" onclick="location.href='linee.php'">
<div class="dash-icon">🏭</div>
<div>Linee di Produzione</div>
</button>
</div>
<button class="dash-btn btn-magazzino" onclick="location.href='warehouse_dashboard.php'">
<div class="dash-icon">📦</div>
<div>Magazzino</div>
</button>
</div>
</div>
</div>
</div>
<!-- ===== TERZA RIGA ===== -->
<div class="dashboard-grid-bottom">
<button class="dash-btn dash-btn-small btn-inserisci btn-inserisci-status" onclick="location.href='production_status.php'">
<div class="dash-icon">📋</div>
<div>Status</div>
</button>
<!-- ANAGRAFICHE -->
<div class="section-card">
<button type="button" class="section-header" data-bs-toggle="collapse" data-bs-target="#secAnagrafiche" aria-expanded="false" aria-controls="secAnagrafiche">
<div class="section-left">
<div class="section-icon">🗂️</div>
<div style="min-width:0;">
<p class="section-title">Anagrafiche</p>
<p class="section-subtitle">Dati di base e setup di produzione</p>
</div>
</div>
<div class="chev"></div>
</button>
<div id="secAnagrafiche" class="collapse" data-bs-parent="#prodAccordion">
<div class="section-body">
<div class="dashboard-grid">
<button class="dash-btn btn-mescole" onclick="location.href='mescole.php'">
<div class="dash-icon">⚗️</div>
<div>Mescole</div>
</button>
<button class="dash-btn dash-btn-small btn-problem" onclick="location.href='production_pause_reasons.php'">
<div class="dash-icon">🛑</div>
<div>Cause di Pausa</div>
</button>
<button class="dash-btn btn-matrici" onclick="location.href='matrici.php'">
<div class="dash-icon">🧩</div>
<div>Elenco Profili</div>
</button>
<button class="dash-btn dash-btn-small btn-tools" onclick="location.href='production_tools.php'">
<div class="dash-icon">🛠️</div>
<div>Attrezzature</div>
</button>
</div>
<button class="dash-btn btn-linee" onclick="location.href='linee.php'">
<div class="dash-icon">🏭</div>
<div>Linee Produzione</div>
</button>
<!-- 🔹 QUARTA RIGA: EMPLOYEES -->
<div class="dashboard-grid-bottom" style="margin-top: 20px;">
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='worksheets.php'">
<div class="dash-icon">🛠️</div>
<div>Fogli di lavoro</div>
</button>
<button class="dash-btn dash-btn-small btn-employees" onclick="location.href='employees.php'">
<div class="dash-icon">👥</div>
<div>Employees</div>
</button>
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='skills.php'">
<div class="dash-icon">🛠️</div>
<div>Skills</div>
</button>
</div>
<button class="dash-btn btn-setup" onclick="location.href='packaging_items.php'">
<div class="dash-icon">📦</div>
<div>Imballaggi</div>
</button>
<!-- 🔹 Quinta RIGA: EMPLOYEES -->
<div class="dashboard-grid-bottom" style="margin-top: 20px;">
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='suppliers.php'">
<div class="dash-icon">🛠️</div>
<div>Suppliers</div>
</button>
<button class="dash-btn dash-btn-small btn-skills" onclick="location.href='lookup_values.php'">
<div class="dash-icon">🛠️</div>
<div>Setup</div>
</button>
<button class="dash-btn btn-setup" onclick="location.href='suppliers.php'">
<div class="dash-icon">🏷️</div>
<div>Suppliers</div>
</button>
</div>
<button class="dash-btn btn-setup" onclick="location.href='lookup_values.php'">
<div class="dash-icon">⚙️</div>
<div>Setup</div>
</button>
</div>
</div>
</div>
</div>
<!-- QUALITÀ / SERVIZI -->
<div class="section-card">
<button type="button" class="section-header" data-bs-toggle="collapse" data-bs-target="#secServizi" aria-expanded="false" aria-controls="secServizi">
<div class="section-left">
<div class="section-icon">🧰</div>
<div style="min-width:0;">
<p class="section-title">Servizi</p>
<p class="section-subtitle">Status, cause pausa, attrezzature</p>
</div>
</div>
<div class="chev"></div>
</button>
<div id="secServizi" class="collapse" data-bs-parent="#prodAccordion">
<div class="section-body">
<div class="dashboard-grid">
<button class="dash-btn btn-setup" onclick="location.href='production_status.php'">
<div class="dash-icon">📋</div>
<div>Status</div>
</button>
<button class="dash-btn btn-problem" onclick="location.href='production_pause_reasons.php'">
<div class="dash-icon">🛑</div>
<div>Cause di Pausa</div>
</button>
<button class="dash-btn btn-tools" onclick="location.href='production_tools.php'">
<div class="dash-icon">🛠️</div>
<div>Attrezzature</div>
</button>
</div>
</div>
</div>
</div>
<!-- PERSONALE -->
<div class="section-card">
<button type="button" class="section-header" data-bs-toggle="collapse" data-bs-target="#secPersonale" aria-expanded="false" aria-controls="secPersonale">
<div class="section-left">
<div class="section-icon">👥</div>
<div style="min-width:0;">
<p class="section-title">Personale</p>
<p class="section-subtitle">Fogli di lavoro, dipendenti, skill</p>
</div>
</div>
<div class="chev"></div>
</button>
<div id="secPersonale" class="collapse" data-bs-parent="#prodAccordion">
<div class="section-body">
<div class="dashboard-grid">
<button class="dash-btn btn-setup" onclick="location.href='worksheets.php'">
<div class="dash-icon">🗒️</div>
<div>Fogli di lavoro</div>
</button>
<button class="dash-btn btn-employees" onclick="location.href='employees.php'">
<div class="dash-icon">👥</div>
<div>Employees</div>
</button>
<button class="dash-btn btn-setup" onclick="location.href='skills.php'">
<div class="dash-icon">🧠</div>
<div>Skills</div>
</button>
</div>
</div>
</div>
</div>
</div> <!-- /sections-wrap -->
</div>
</div>
@ -375,6 +505,7 @@
<?php include('jsinclude.php'); ?>
<?php include('include/footer.php'); ?>
</div>
</body>
</html>

View File

@ -268,6 +268,7 @@ if (!empty($_GET['ajax'])) {
// --- RECORD IN PRODUZIONE (2,7,8)
$sql = "SELECT
p.*,
m.id AS matrice_id,
m.nome AS matrice,
m.photo AS matrice_photo,
(
@ -329,6 +330,7 @@ if (!empty($_GET['ajax'])) {
// --- RECORD IN STATO 6 ORDINATI PER PRIORITY
$sql2 = "SELECT
p.*,
m.id AS matrice_id,
m.nome AS matrice,
m.photo AS matrice_photo,
(
@ -930,6 +932,10 @@ if (!empty($_GET['ajax'])) {
margin-left: auto;
/* la porta tutta a destra */
}
.show-matrice-files i {
font-size: 1.5rem;
}
</style>
</head>
@ -1277,8 +1283,219 @@ if (!empty($_GET['ajax'])) {
loadRecords();
});
function escapeHtml(str) {
return String(str || '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function getFileExt(filename) {
const parts = String(filename || '').split('.');
return parts.length > 1 ? parts.pop().toLowerCase() : '';
}
function isImageExt(ext) {
return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'heif'].includes(ext);
}
function getFileIcon(ext) {
if (isImageExt(ext)) return '🖼️';
if (ext === 'pdf') return '📕';
if (['doc', 'docx'].includes(ext)) return '📘';
return '📎';
}
function getFileBadge(ext) {
if (isImageExt(ext)) return '<span style="background:#cff4fc;color:#055160;padding:3px 8px;border-radius:999px;font-size:0.78rem;font-weight:700;">Immagine</span>';
if (ext === 'pdf') return '<span style="background:#f8d7da;color:#842029;padding:3px 8px;border-radius:999px;font-size:0.78rem;font-weight:700;">PDF</span>';
if (['doc', 'docx'].includes(ext)) return '<span style="background:#cfe2ff;color:#084298;padding:3px 8px;border-radius:999px;font-size:0.78rem;font-weight:700;">DOC</span>';
return '<span style="background:#e2e3e5;color:#41464b;padding:3px 8px;border-radius:999px;font-size:0.78rem;font-weight:700;">File</span>';
}
function openFilePreview(filePath, fileName) {
const ext = getFileExt(fileName);
$("#filePreviewTitle").text(fileName || 'Anteprima file');
let html = '';
if (isImageExt(ext)) {
html = `
<div style="width:100%; height:100%; min-height:82vh; display:flex; justify-content:center; align-items:center;">
<img src="${escapeHtml(filePath)}"
alt="${escapeHtml(fileName)}"
style="max-width:100%; max-height:82vh; border-radius:10px;">
</div>
`;
} else if (ext === 'pdf') {
html = `
<iframe src="${escapeHtml(filePath)}#zoom=page-width"
style="display:block; width:100%; height:calc(92vh - 64px); border:none; background:#fff;">
</iframe>
`;
} else {
html = `
<div style="text-align:center; padding:40px 20px;">
<div style="font-size:3rem; margin-bottom:12px;">${getFileIcon(ext)}</div>
<div style="color:#475569; margin-bottom:16px;">Anteprima non disponibile per questo formato</div>
<a href="${escapeHtml(filePath)}" target="_blank"
style="display:inline-block; padding:10px 18px; border-radius:10px; text-decoration:none; background:#0d6efd; color:#fff; font-weight:600;">
Apri file
</a>
</div>
`;
}
$("#filePreviewContainer").html(html);
$("#filePreviewModal").addClass("active");
}
function loadMatriceAttachments(matriceId, matriceNome) {
$("#mf_matrice_name").text(matriceNome || '');
$("#matriceFilesList").html('<div style="color:#64748b;">Caricamento file...</div>');
$.getJSON("get_matrice_attachments.php", {
id: matriceId
}, function(r) {
if (!r.success) {
$("#matriceFilesList").html('<div style="color:#b91c1c;">Errore nel caricamento degli allegati.</div>');
return;
}
const files = r.attachments || [];
if (!files.length) {
$("#matriceFilesList").html('<div style="color:#64748b;">Nessun allegato disponibile per questa matrice.</div>');
return;
}
let html = '';
files.forEach(f => {
const fileName = f.file_name || '';
const filePath = f.file_url || f.file_path || '';
const desc = f.description || '';
const createdAt = f.created_at || '';
const ext = getFileExt(fileName);
const icon = getFileIcon(ext);
const badge = getFileBadge(ext);
let actionHtml = '';
if (isImageExt(ext) || ext === 'pdf') {
actionHtml = `
<button type="button"
class="open-matrice-file-preview"
data-file="${escapeHtml(filePath)}"
data-name="${escapeHtml(fileName)}"
style="padding:8px 14px; border-radius:10px; border:none; background:#0d6efd; color:#fff; font-weight:600; cursor:pointer;">
Apri
</button>
`;
} else {
actionHtml = `
<a href="${escapeHtml(filePath)}" target="_blank"
style="display:inline-block; padding:8px 14px; border-radius:10px; text-decoration:none; background:#0d6efd; color:#fff; font-weight:600;">
Apri
</a>
`;
}
let previewHtml = '';
if (isImageExt(ext)) {
previewHtml = `
<img src="${escapeHtml(filePath)}"
alt="${escapeHtml(fileName)}"
style="width:70px; height:70px; object-fit:cover; border-radius:10px; border:1px solid #dbe2ea;">
`;
} else {
previewHtml = `
<div style="width:70px; height:70px; border-radius:10px; background:#f1f5f9; display:flex; align-items:center; justify-content:center; font-size:1.8rem; border:1px solid #dbe2ea;">
${icon}
</div>
`;
}
html += `
<div style="border:1px solid #e2e8f0; border-radius:14px; padding:12px; background:#fff;">
<div style="display:flex; gap:14px; align-items:flex-start;">
<div>${previewHtml}</div>
<div style="flex:1;">
<div style="display:flex; justify-content:space-between; align-items:flex-start; gap:12px;">
<div>
<div style="font-weight:700; color:#1f2d3d;">${escapeHtml(fileName)}</div>
<div style="margin-top:4px;">${badge}</div>
${createdAt ? `<div style="margin-top:6px; color:#64748b; font-size:0.88rem;">${escapeHtml(createdAt)}</div>` : ''}
</div>
<div>${actionHtml}</div>
</div>
<div style="margin-top:10px; color:#475569; white-space:normal;">
${desc ? escapeHtml(desc) : '<em style="color:#94a3b8;">Nessuna descrizione</em>'}
</div>
</div>
</div>
</div>
`;
});
$("#matriceFilesList").html(html);
}).fail(function() {
$("#matriceFilesList").html('<div style="color:#b91c1c;">Errore di comunicazione col server.</div>');
});
}
$(document).on("click", ".show-matrice-files", function(e) {
e.stopPropagation();
const matriceId = $(this).data("matrice-id");
const matriceNome = $(this).data("matrice-nome") || "";
if (!matriceId) {
alert("Nessuna matrice associata a questo record.");
return;
}
loadMatriceAttachments(matriceId, matriceNome);
$("#matriceFilesModal").addClass("active");
});
$(document).on("click", "#closeMatriceFilesModal", function() {
$("#matriceFilesModal").removeClass("active");
});
$(document).on("click", "#matriceFilesModal", function(e) {
if ($(e.target).is("#matriceFilesModal")) {
$("#matriceFilesModal").removeClass("active");
}
});
$(document).on("click", ".open-matrice-file-preview", function(e) {
e.stopPropagation();
const file = $(this).data("file") || "";
const name = $(this).data("name") || "Anteprima file";
openFilePreview(file, name);
});
$(document).on("click", "#closeFilePreviewModal", function() {
$("#filePreviewModal").removeClass("active");
$("#filePreviewContainer").html("");
});
$(document).on("click", "#filePreviewModal", function(e) {
if ($(e.target).is("#filePreviewModal")) {
$("#filePreviewModal").removeClass("active");
$("#filePreviewContainer").html("");
}
});
$(document).on("click", "#filePreviewModal .modal-content", function(e) {
e.stopPropagation();
});
// --- CARICA RECORD ---
function loadRecords() {
@ -1879,12 +2096,45 @@ if (!empty($_GET['ajax'])) {
});
</script>
<!-- MODALE ALLEGATI MATRICE (SOLO LETTURA) -->
<div id="matriceFilesModal" class="modal">
<div class="modal-content" style="width:95%; max-width:1100px; max-height:88vh; overflow:hidden; padding:0; border-radius:16px;">
</body>
<div style="background:#b9ebc7; padding:1rem 1.4rem; display:flex; justify-content:space-between; align-items:center;">
<div>
<h3 style="margin:0; color:#1f2d3d;">File correlati matrice</h3>
<div id="mf_matrice_name" style="font-size:0.95rem; color:#475569; margin-top:4px;"></div>
</div>
</html>
<button type="button" id="closeMatriceFilesModal"
style="font-size:1.9rem; line-height:1; background:none; border:none; cursor:pointer; color:#1f2d3d;">
&times;
</button>
</div>
<div style="padding:1.2rem 1.4rem; overflow-y:auto;">
<div id="matriceFilesList" style="display:flex; flex-direction:column; gap:12px;">
<div style="color:#64748b;">Caricamento file...</div>
</div>
</div>
</div>
</div>
<!-- MODALE PREVIEW FILE -->
<div id="filePreviewModal" class="modal">
<div class="modal-content" style="background:#fff; max-width:1400px; width:98%; height:92vh; padding:0; overflow:hidden; text-align:left;">
<div style="background:#b9ebc7; padding:0.9rem 1.2rem; display:flex; justify-content:space-between; align-items:center;">
<div id="filePreviewTitle" style="font-weight:700; color:#1f2d3d;">Anteprima file</div>
<button type="button" id="closeFilePreviewModal"
style="font-size:1.9rem; line-height:1; background:none; border:none; cursor:pointer; color:#1f2d3d;">
&times;
</button>
</div>
<div id="filePreviewContainer"
style="padding:0; background:#f8fafc; height:calc(92vh - 64px); overflow:hidden;">
</div>
</div>
</div>
</body>
</html>

View File

@ -205,18 +205,27 @@ if ($matricePhoto) {
<?php include __DIR__ . "/components/photo_buttons.php"; ?>
</div>
<!-- 📎 FILE CORRELATI MATRICE -->
<button type="button"
class="qc-btn show-matrice-files"
data-matrice-id="<?= (int)($r['matrice_id'] ?? 0) ?>"
data-matrice-nome="<?= htmlspecialchars($r['matrice'] ?? '', ENT_QUOTES) ?>"
title="File matrice">
<i class="bi bi-paperclip"></i>
</button>
<!-- 🎯 UN BADGE PER OGNI STRUMENTO, SUBITO DOPO LE FOTO -->
<?php foreach ($toolsArray as $toolName): ?>
<span class="badge tools-badge"
style="
background:#0d6efd;
color:#ffffff;
font-size:0.78rem;
font-weight:600;
border-radius:999px;
padding:0.30rem 0.85rem;
white-space:nowrap;
">
background:#0d6efd;
color:#ffffff;
font-size:0.78rem;
font-weight:600;
border-radius:999px;
padding:0.30rem 0.85rem;
white-space:nowrap;
">
<?= htmlspecialchars($toolName) ?>
</span>
<?php endforeach; ?>

View File

@ -0,0 +1,24 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$category = trim($_POST['category'] ?? '');
$item_name = trim($_POST['item_name'] ?? '');
$item_code = trim($_POST['item_code'] ?? '');
$allowed = ['PACKAGING_TYPE', 'BOX', 'PALLET', 'OTHER'];
if (!in_array($category, $allowed, true) || $item_name === '' || $item_code === '') {
echo json_encode(['success' => false, 'message' => 'Invalid input']);
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
$stmt = $pdo->prepare("INSERT INTO packaging_items (category, item_name, item_code) VALUES (?,?,?)");
$stmt->execute([$category, $item_name, $item_code]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,40 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$idpackaging_item = isset($_POST['idpackaging_item']) ? (int)$_POST['idpackaging_item'] : 0;
$idsupplier = isset($_POST['idsupplier']) ? (int)$_POST['idsupplier'] : 0;
$lot_code = trim($_POST['lot_code'] ?? '');
$expiry_date = trim($_POST['expiry_date'] ?? '');
$qty = isset($_POST['qty']) ? (float)$_POST['qty'] : 0;
if ($idpackaging_item <= 0 || $idsupplier <= 0) {
echo json_encode(['success' => false, 'message' => 'Missing required fields']);
exit;
}
if ($qty < 0) {
echo json_encode(['success' => false, 'message' => 'Quantity cannot be negative']);
exit;
}
if ($expiry_date === '') $expiry_date = null;
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
$stmt = $pdo->prepare("INSERT INTO packaging_stock_lots
(idpackaging_item, idsupplier, lot_code, expiry_date, qty)
VALUES (?,?,?,?,?)");
$stmt->execute([
$idpackaging_item,
$idsupplier,
($lot_code !== '' ? $lot_code : null),
$expiry_date,
$qty
]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,28 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid id']);
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
// flip 1 <-> 0
$stmt = $pdo->prepare("UPDATE mescole SET is_active = IF(is_active=1,0,1) WHERE id = ?");
$stmt->execute([$id]);
// verifica righe aggiornate
if ($stmt->rowCount() === 0) {
echo json_encode(['success' => false, 'message' => 'No rows updated (id not found?)']);
exit;
}
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,24 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid id']);
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
$stmt = $pdo->prepare("UPDATE packaging_items SET is_active = IF(is_active=1,0,1) WHERE id = ?");
$stmt->execute([$id]);
if ($stmt->rowCount() === 0) {
echo json_encode(['success' => false, 'message' => 'No rows updated']);
exit;
}
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,33 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$qty = isset($_POST['qty']) ? (float)$_POST['qty'] : null;
if ($id <= 0 || $qty === null) {
echo json_encode(['success' => false, 'message' => 'Invalid input']);
exit;
}
if ($qty < 0) {
echo json_encode(['success' => false, 'message' => 'Quantity cannot be negative']);
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
$stmt = $pdo->prepare("UPDATE mescole_supplier_lots SET qty = ? WHERE id = ?");
$stmt->execute([$qty, $id]);
if ($stmt->rowCount() === 0) {
echo json_encode(['success' => false, 'message' => 'No rows updated (id not found?)']);
exit;
}
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,42 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$idpackaging_item = isset($_POST['idpackaging_item']) ? (int)$_POST['idpackaging_item'] : 0;
$idsupplier = isset($_POST['idsupplier']) ? (int)$_POST['idsupplier'] : 0;
$lot_code = trim($_POST['lot_code'] ?? '');
$expiry_date = trim($_POST['expiry_date'] ?? '');
$qty = isset($_POST['qty']) ? (float)$_POST['qty'] : 0;
if ($id <= 0 || $idpackaging_item <= 0 || $idsupplier <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid input']);
exit;
}
if ($qty < 0) {
echo json_encode(['success' => false, 'message' => 'Quantity cannot be negative']);
exit;
}
if ($expiry_date === '') $expiry_date = null;
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
$stmt = $pdo->prepare("UPDATE packaging_stock_lots
SET idsupplier=?, lot_code=?, expiry_date=?, qty=?
WHERE id=? AND idpackaging_item=?");
$stmt->execute([
$idsupplier,
($lot_code !== '' ? $lot_code : null),
$expiry_date,
$qty,
$id,
$idpackaging_item
]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,33 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$qty = isset($_POST['qty']) ? (float)$_POST['qty'] : null;
if ($id <= 0 || $qty === null) {
echo json_encode(['success' => false, 'message' => 'Invalid input']);
exit;
}
if ($qty < 0) {
echo json_encode(['success' => false, 'message' => 'Quantity cannot be negative']);
exit;
}
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
try {
$stmt = $pdo->prepare("UPDATE packaging_stock_lots SET qty = ? WHERE id = ?");
$stmt->execute([$qty, $id]);
if ($stmt->rowCount() === 0) {
echo json_encode(['success' => false, 'message' => 'No rows updated (id not found?)']);
exit;
}
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

View File

@ -0,0 +1,189 @@
<?php
include('include/headscript.php');
header('Content-Type: application/json; charset=utf-8');
$response = [
'success' => false,
'message' => '',
'uploaded' => [],
'errors' => []
];
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('Metodo non consentito');
}
if (!isset($_POST['idmatrice']) || !is_numeric($_POST['idmatrice'])) {
throw new Exception('ID matrice non valido');
}
if (!isset($_FILES['files'])) {
throw new Exception('Nessun file ricevuto');
}
$idmatrice = (int)$_POST['idmatrice'];
$descriptions = isset($_POST['descriptions']) && is_array($_POST['descriptions']) ? $_POST['descriptions'] : [];
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Verifica esistenza matrice
$checkStmt = $pdo->prepare("SELECT id FROM matrice WHERE id = :id LIMIT 1");
$checkStmt->execute([':id' => $idmatrice]);
if (!$checkStmt->fetchColumn()) {
throw new Exception('Matrice non trovata');
}
$uploadDirRelative = 'photos/matrici/allegati/';
$uploadDirAbsolute = __DIR__ . '/' . $uploadDirRelative;
if (!is_dir($uploadDirAbsolute)) {
if (!mkdir($uploadDirAbsolute, 0775, true) && !is_dir($uploadDirAbsolute)) {
throw new Exception('Impossibile creare la cartella di upload');
}
}
$allowedExtensions = [
'pdf',
'jpg',
'jpeg',
'png',
'gif',
'bmp',
'webp',
'heic',
'heif',
'doc',
'docx'
];
$imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'heif'];
$fileNames = $_FILES['files']['name'] ?? [];
$tmpNames = $_FILES['files']['tmp_name'] ?? [];
$errors = $_FILES['files']['error'] ?? [];
$sizes = $_FILES['files']['size'] ?? [];
if (!is_array($fileNames) || count($fileNames) === 0) {
throw new Exception('Nessun file valido ricevuto');
}
$maxFileSize = 20 * 1024 * 1024; // 20 MB per file
$pdo->beginTransaction();
$sortStmt = $pdo->prepare("SELECT COALESCE(MAX(sort_order), 0) FROM matrice_attachments WHERE matrice_id = :matrice_id");
$sortStmt->execute([':matrice_id' => $idmatrice]);
$nextSort = (int)$sortStmt->fetchColumn();
$insertSql = "INSERT INTO matrice_attachments
(matrice_id, file_name, file_path, file_type, description, sort_order, created_at, updated_at)
VALUES
(:matrice_id, :file_name, :file_path, :file_type, :description, :sort_order, NOW(), NOW())";
$insertStmt = $pdo->prepare($insertSql);
foreach ($fileNames as $index => $originalName) {
$originalName = trim((string)$originalName);
$tmpName = $tmpNames[$index] ?? '';
$errorCode = $errors[$index] ?? UPLOAD_ERR_NO_FILE;
$size = (int)($sizes[$index] ?? 0);
$description = isset($descriptions[$index]) ? trim((string)$descriptions[$index]) : '';
if ($errorCode === UPLOAD_ERR_NO_FILE) {
continue;
}
if ($errorCode !== UPLOAD_ERR_OK) {
$response['errors'][] = "Errore upload file: {$originalName}";
continue;
}
if (!is_uploaded_file($tmpName)) {
$response['errors'][] = "File non valido: {$originalName}";
continue;
}
if ($size <= 0) {
$response['errors'][] = "File vuoto: {$originalName}";
continue;
}
if ($size > $maxFileSize) {
$response['errors'][] = "File troppo grande (max 20 MB): {$originalName}";
continue;
}
$safeOriginalName = preg_replace('/[^\w.\- ]+/u', '_', $originalName);
$extension = strtolower(pathinfo($safeOriginalName, PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions, true)) {
$response['errors'][] = "Formato non ammesso: {$originalName}";
continue;
}
if (in_array($extension, $imageExtensions, true)) {
$fileType = 'image';
} elseif ($extension === 'pdf') {
$fileType = 'pdf';
} elseif (in_array($extension, ['doc', 'docx'], true)) {
$fileType = 'doc';
} else {
$fileType = 'other';
}
$uniqueName = 'matrice_' . $idmatrice . '_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $extension;
$destinationAbsolute = $uploadDirAbsolute . $uniqueName;
$destinationRelative = $uploadDirRelative . $uniqueName;
if (!move_uploaded_file($tmpName, $destinationAbsolute)) {
$response['errors'][] = "Impossibile salvare il file: {$originalName}";
continue;
}
$nextSort++;
$insertStmt->execute([
':matrice_id' => $idmatrice,
':file_name' => $safeOriginalName,
':file_path' => $destinationRelative,
':file_type' => $fileType,
':description' => $description,
':sort_order' => $nextSort
]);
$response['uploaded'][] = [
'id' => (int)$pdo->lastInsertId(),
'file_name' => $safeOriginalName,
'file_path' => $destinationRelative,
'file_type' => $fileType,
'description' => $description
];
}
if (empty($response['uploaded']) && !empty($response['errors'])) {
$pdo->rollBack();
$response['message'] = 'Nessun file caricato';
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
}
$pdo->commit();
$response['success'] = true;
if (!empty($response['errors'])) {
$response['message'] = 'Upload completato con alcuni avvisi';
} else {
$response['message'] = 'File caricati correttamente';
}
} catch (Throwable $e) {
if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
$pdo->rollBack();
}
$response['message'] = $e->getMessage();
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;

View File

@ -0,0 +1,191 @@
<?php include('include/headscript.php'); ?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Dashboard Magazzino - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<!-- Bootstrap + jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
background: linear-gradient(135deg, #f3f6f8, #e8eef3);
font-family: 'Segoe UI', sans-serif;
color: #2b3e50;
}
.page-content {
padding: 2rem 1rem;
display: flex;
flex-direction: column;
align-items: center;
}
h3.dashboard-title {
text-align: center;
font-weight: 700;
color: #2b3e50;
margin-bottom: 1.5rem;
letter-spacing: 0.3px;
}
.section-title {
width: 100%;
max-width: 900px;
margin-top: 20px;
margin-bottom: 10px;
font-weight: 700;
color: #2b3e50;
font-size: 1.1rem;
}
.dashboard-grid {
display: grid;
grid-template-columns: repeat(3, minmax(200px, 1fr));
gap: 18px 30px;
width: 100%;
max-width: 900px;
justify-items: center;
margin-bottom: 10px;
}
.dash-btn {
width: 100%;
max-width: 280px;
border: none;
border-radius: 16px;
padding: 18px 10px;
color: #2b3e50;
font-size: 1.15rem;
font-weight: 600;
background: #fff;
transition: all 0.2s ease;
box-shadow: 0 5px 12px rgba(0, 0, 0, 0.08);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 110px;
}
.dash-btn:hover {
transform: translateY(-3px);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.15);
cursor: pointer;
}
.dash-icon {
font-size: 2.8rem;
margin-bottom: 8px;
line-height: 1;
}
/* Colori */
.btn-mescole {
background: linear-gradient(135deg, #ffc853ff, #fdd98bff);
}
.btn-imballaggi {
background: linear-gradient(135deg, #b9e3ffff, #d7f1ffff);
}
.btn-materieprime {
background: linear-gradient(135deg, #82f09eff, #aaecaaff);
}
.btn-tools {
background: linear-gradient(135deg, #9f7aea, #b794f4);
}
.back-dashboard {
background-color: #cfe3ff !important;
color: #1f2d3d !important;
border: 1px solid #bcd4f4 !important;
border-radius: 10px;
font-weight: 600;
font-size: 1rem;
padding: 10px 18px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease-in-out;
margin-bottom: 10px;
}
.back-dashboard:hover {
background-color: #b9d3ff !important;
transform: translateY(-2px);
}
@media (max-width: 768px) {
.dashboard-grid {
grid-template-columns: 1fr;
gap: 15px;
}
.dash-btn {
font-size: 1.1rem;
min-height: 95px;
}
.dash-icon {
font-size: 2.4rem;
}
}
</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">
<h3 class="dashboard-title">Magazzino</h3>
<button type="button" class="btn back-dashboard" onclick="location.href='production_dashboard.php'">
↩️ Torna alla Dashboard Produzione
</button>
<!-- ===== SEZIONE: MATERIALI ===== -->
<div class="section-title">Materiali</div>
<div class="dashboard-grid">
<button class="dash-btn btn-mescole" onclick="location.href='warehouse_mescole.php'">
<div class="dash-icon">⚗️</div>
<div>Mescole</div>
</button>
<button class="dash-btn btn-materieprime" onclick="location.href='warehouse_materieprime.php'">
<div class="dash-icon">🧪</div>
<div>Materie Prime</div>
</button>
<button class="dash-btn btn-imballaggi" onclick="location.href='warehouse_imballaggi.php'">
<div class="dash-icon">📦</div>
<div>Imballaggi</div>
</button>
</div>
<!-- ===== SEZIONE: SETUP (FUTURO) ===== -->
<div class="section-title">Setup (in espansione)</div>
<div class="dashboard-grid">
<button class="dash-btn btn-tools" onclick="location.href='warehouse_settings.php'">
<div class="dash-icon">🛠️</div>
<div>Impostazioni</div>
</button>
</div>
</div>
</div>
<?php include('jsinclude.php'); ?>
<?php include('include/footer.php'); ?>
</div>
</body>
</html>

View File

@ -0,0 +1,409 @@
<?php include('include/headscript.php'); ?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Magazzino Imballaggi - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<!-- jQuery e Bootstrap -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<style>
body {
font-size: 1.05rem;
background: #f8fafc;
}
.card {
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.back-dashboard {
background-color: #cfe3ff !important;
color: #1f2d3d !important;
border: 1px solid #bcd4f4 !important;
border-radius: 10px;
font-weight: 600;
font-size: 1rem;
padding: 10px 18px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease-in-out;
}
.back-dashboard:hover {
background-color: #b9d3ff !important;
transform: translateY(-2px);
}
.table thead {
background-color: #cfe3ff;
color: #1f2d3d;
}
#tabWarehousePack {
table-layout: fixed;
width: 100% !important;
}
#tabWarehousePack th,
#tabWarehousePack td {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
/* ID */
#tabWarehousePack th:nth-child(1),
#tabWarehousePack td:nth-child(1) {
width: 60px;
max-width: 60px;
}
/* Codice */
#tabWarehousePack th:nth-child(4),
#tabWarehousePack td:nth-child(4) {
width: 120px;
max-width: 120px;
}
/* Scadenza */
#tabWarehousePack th:nth-child(7),
#tabWarehousePack td:nth-child(7) {
width: 120px;
max-width: 120px;
}
/* QTY */
#tabWarehousePack th:nth-child(8),
#tabWarehousePack td:nth-child(8) {
width: 120px;
max-width: 120px;
}
/* Salva */
#tabWarehousePack th:nth-child(9),
#tabWarehousePack td:nth-child(9) {
width: 90px;
max-width: 90px;
}
.qty-input {
width: 95px;
text-align: right;
font-weight: 700;
}
tr.expired {
background: #ffe5e5 !important;
}
tr.inactive-item {
opacity: 0.65;
}
</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="card p-3">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">Magazzino - Imballaggi</h5>
<button type="button" class="btn back-dashboard" onclick="location.href='warehouse_dashboard.php'">
↩️ Torna a Magazzino
</button>
</div>
<div class="card-body">
<!-- FILTRI RAPIDI -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
<div class="d-flex flex-wrap align-items-center gap-2">
<label class="fw-semibold mb-0">Categoria:</label>
<select id="filterCategory" class="form-select form-select-sm" style="width:240px;">
<option value="all">Tutte</option>
<option value="PACKAGING_TYPE">Tipo Confezione</option>
<option value="BOX">Scatole</option>
<option value="PALLET">Pallet</option>
<option value="OTHER">Altro</option>
</select>
<label class="fw-semibold mb-0 ms-2">Stato:</label>
<select id="filterActive" class="form-select form-select-sm" style="width:220px;">
<option value="all">Tutti</option>
<option value="1" selected>Solo Attivi</option>
<option value="0">Solo Inattivi</option>
</select>
<div class="form-check ms-2">
<input class="form-check-input" type="checkbox" id="onlyExpired">
<label class="form-check-label" for="onlyExpired">Solo scaduti</label>
</div>
</div>
<div class="text-muted small">
Cerca per codice, nome, fornitore o lotto
</div>
</div>
<?php
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$cat = $_GET['cat'] ?? 'all';
$allowedCats = ['all', 'PACKAGING_TYPE', 'BOX', 'PALLET', 'OTHER'];
if (!in_array($cat, $allowedCats, true)) $cat = 'all';
$active = $_GET['active'] ?? '1';
if (!in_array($active, ['all', '0', '1'], true)) $active = '1';
$where = [];
$params = [];
if ($cat !== 'all') {
$where[] = "pi.category = ?";
$params[] = $cat;
}
if ($active !== 'all') {
$where[] = "pi.is_active = ?";
$params[] = (int)$active;
}
$whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";
$sql = "
SELECT
psl.id AS stock_id,
pi.id AS item_id,
pi.category,
pi.item_name,
pi.item_code,
pi.is_active,
s.supplier_name,
psl.lot_code,
psl.expiry_date,
psl.qty
FROM packaging_stock_lots psl
INNER JOIN packaging_items pi ON pi.id = psl.idpackaging_item
INNER JOIN suppliers s ON s.idsupplier = psl.idsupplier
$whereSql
ORDER BY pi.category ASC, pi.item_name ASC, s.supplier_name ASC, psl.lot_code ASC, psl.id DESC
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$today = date('Y-m-d');
function catLabel($c)
{
return match ($c) {
'PACKAGING_TYPE' => 'Tipo Confezione',
'BOX' => 'Scatola',
'PALLET' => 'Pallet',
default => $c
};
}
?>
<div class="table-responsive">
<table id="tabWarehousePack" class="table table-striped align-middle text-center" style="width:100%;">
<thead>
<tr>
<th>ID</th>
<th>Categoria</th>
<th>Nome</th>
<th>Codice</th>
<th>Fornitore</th>
<th>Lotto</th>
<th>Scadenza</th>
<th>Q.</th>
<th>Salva</th>
</tr>
</thead>
<tbody>
<?php
if (!$rows) {
echo "<tr>
<td class='text-muted'>-</td>
<td class='text-muted'>Nessuna riga presente</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
</tr>";
} else {
foreach ($rows as $r) {
$expiry = $r['expiry_date'] ?? '';
$isExpired = ($expiry !== '' && $expiry < $today);
$isActiveItem = ((int)$r['is_active'] === 1);
$trClass = [];
if ($isExpired) $trClass[] = 'expired';
if (!$isActiveItem) $trClass[] = 'inactive-item';
$trClassStr = $trClass ? " class='" . implode(' ', $trClass) . "'" : "";
$qtyVal = number_format((float)$r['qty'], 3, '.', '');
$expiryShow = $expiry ? htmlspecialchars($expiry) : '<span class="text-muted">-</span>';
$lotShow = htmlspecialchars($r['lot_code'] ?? '');
echo "<tr{$trClassStr} data-stock-id='{$r['stock_id']}' data-expired='" . ($isExpired ? "1" : "0") . "'>
<td>{$r['stock_id']}</td>
<td>" . htmlspecialchars(catLabel($r['category'])) . "</td>
<td>" . htmlspecialchars($r['item_name']) . "</td>
<td><span class='fw-semibold'>" . htmlspecialchars($r['item_code']) . "</span></td>
<td>" . htmlspecialchars($r['supplier_name']) . "</td>
<td>{$lotShow}</td>
<td>{$expiryShow}</td>
<td>
<input type='number' step='0.001' class='form-control form-control-sm qty-input qty-field' value='{$qtyVal}' />
</td>
<td>
<button class='btn btn-sm btn-outline-primary save-qty'>💾</button>
</td>
</tr>";
}
}
?>
</tbody>
</table>
</div>
<div class="text-muted small mt-2">
* Riga rossa = scaduta. * Riga opaca = item disattivo (ma stock ancora presente).
</div>
</div>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script>
let dt;
$(document).ready(function() {
const urlParams = new URLSearchParams(window.location.search);
const cat = urlParams.get('cat') || 'all';
const active = urlParams.get('active') || '1';
$('#filterCategory').val(cat);
$('#filterActive').val(active);
dt = $('#tabWarehousePack').DataTable({
order: [
[2, 'asc']
],
pageLength: 50,
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/it-IT.json'
}
});
$('#filterCategory, #filterActive').on('change', function() {
const url = new URL(window.location.href);
url.searchParams.set('cat', $('#filterCategory').val());
url.searchParams.set('active', $('#filterActive').val());
window.location.href = url.toString();
});
$('#onlyExpired').on('change', function() {
const only = $(this).is(':checked');
if (!only) {
dt.rows().every(function() {
$(this.node()).show();
});
return;
}
dt.rows().every(function() {
const node = $(this.node());
const expired = node.attr('data-expired') === '1';
if (expired) node.show();
else node.hide();
});
});
});
$(document).on('click', '.save-qty', function() {
const tr = $(this).closest('tr');
const stockId = tr.data('stock-id');
const qty = tr.find('.qty-field').val();
fetch('update_packaging_stock_qty.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `id=${encodeURIComponent(stockId)}&qty=${encodeURIComponent(qty)}`
})
.then(async (r) => {
const text = await r.text();
try {
return JSON.parse(text);
} catch (e) {
throw new Error("Risposta non JSON:\n" + text);
}
})
.then(data => {
if (data.success) {
Swal.fire({
icon: "success",
title: "Salvato",
timer: 900,
showConfirmButton: false
});
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: data.message || "Salvataggio non riuscito"
});
}
})
.catch(err => {
Swal.fire({
icon: "error",
title: "Errore (fetch)",
text: err.message
});
});
});
$(document).on('keypress', '.qty-field', function(e) {
if (e.which === 13) {
e.preventDefault();
$(this).closest('tr').find('.save-qty').click();
}
});
</script>
</body>
</html>

View File

@ -0,0 +1,378 @@
<?php include('include/headscript.php'); ?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Magazzino Mescole - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<!-- jQuery e Bootstrap -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<style>
body {
font-size: 1.05rem;
background: #f8fafc;
}
.card {
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.back-dashboard {
background-color: #cfe3ff !important;
color: #1f2d3d !important;
border: 1px solid #bcd4f4 !important;
border-radius: 10px;
font-weight: 600;
font-size: 1rem;
padding: 10px 18px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease-in-out;
}
.back-dashboard:hover {
background-color: #b9d3ff !important;
transform: translateY(-2px);
}
.table thead {
background-color: #cfe3ff;
color: #1f2d3d;
}
/* Tabella leggibile e colonne fisse */
#tabWarehouseMescole {
table-layout: fixed;
width: 100% !important;
}
#tabWarehouseMescole th,
#tabWarehouseMescole td {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
/* Colonne: stringiamo ID e quantità */
#tabWarehouseMescole th:nth-child(1),
#tabWarehouseMescole td:nth-child(1) {
width: 60px;
max-width: 60px;
}
#tabWarehouseMescole th:nth-child(6),
#tabWarehouseMescole td:nth-child(6) {
width: 120px;
max-width: 120px;
}
#tabWarehouseMescole th:nth-child(7),
#tabWarehouseMescole td:nth-child(7) {
width: 120px;
max-width: 120px;
}
#tabWarehouseMescole th:nth-child(8),
#tabWarehouseMescole td:nth-child(8) {
width: 110px;
max-width: 110px;
}
/* QTY input compatto */
.qty-input {
width: 95px;
text-align: right;
font-weight: 700;
}
/* Riga scaduta */
tr.expired {
background: #ffe5e5 !important;
}
/* Riga inattiva (mescola disattiva) */
tr.inactive-mix {
opacity: 0.65;
}
</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="card p-3">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">Magazzino - Mescole</h5>
<div class="d-flex gap-2">
<button type="button" class="btn back-dashboard" onclick="location.href='warehouse_dashboard.php'">
↩️ Torna a Magazzino
</button>
</div>
</div>
<div class="card-body">
<!-- FILTRI RAPIDI -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
<div class="d-flex align-items-center gap-2">
<label class="fw-semibold mb-0">Filtro mescole:</label>
<select id="filterActive" class="form-select form-select-sm" style="width:220px;">
<option value="all">Tutte (attive + inattive)</option>
<option value="1" selected>Solo attive</option>
<option value="0">Solo inattive</option>
</select>
<div class="form-check ms-2">
<input class="form-check-input" type="checkbox" id="onlyExpired">
<label class="form-check-label" for="onlyExpired">Solo scadute</label>
</div>
</div>
<div class="text-muted small">
Suggerimento: usa la ricerca tabella per trovare lotto/fornitore
</div>
</div>
<?php
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// filtro mescole attive/inattive
$activeFilter = $_GET['active'] ?? '1';
if (!in_array($activeFilter, ['all', '0', '1'], true)) {
$activeFilter = '1';
}
$where = "";
$params = [];
if ($activeFilter !== 'all') {
$where = "WHERE m.is_active = ?";
$params[] = (int)$activeFilter;
}
// Query: tutte le righe lotto-fornitore con nome uscita
$sql = "
SELECT
msl.id AS lot_id,
m.id AS idmescola,
m.nomeuscita,
m.is_active,
s.supplier_name,
msl.supplier_mix_name,
msl.lot_code,
msl.expiry_date,
msl.qty
FROM mescole_supplier_lots msl
INNER JOIN mescole m ON m.id = msl.idmescola
INNER JOIN suppliers s ON s.idsupplier = msl.idsupplier
$where
ORDER BY m.nomeuscita ASC, s.supplier_name ASC, msl.lot_code ASC, msl.id DESC
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$today = date('Y-m-d');
?>
<div class="table-responsive">
<table id="tabWarehouseMescole" class="table table-striped align-middle text-center" style="width:100%;">
<thead>
<tr>
<th>ID</th>
<th>Nome Uscita</th>
<th>Fornitore</th>
<th>Nome Fornitore</th>
<th>Lotto</th>
<th>Scadenza</th>
<th>Q.</th>
<th>Salva</th>
</tr>
</thead>
<tbody>
<?php
if (!$rows) {
echo "<tr>
<td class='text-muted'>-</td>
<td class='text-muted'>Nessuna riga presente</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
<td class='text-muted'>-</td>
</tr>";
} else {
foreach ($rows as $r) {
$expiry = $r['expiry_date'] ?? '';
$isExpired = ($expiry !== '' && $expiry < $today);
$isActiveMix = ((int)$r['is_active'] === 1);
$trClass = [];
if ($isExpired) $trClass[] = 'expired';
if (!$isActiveMix) $trClass[] = 'inactive-mix';
$trClassStr = $trClass ? " class='" . implode(' ', $trClass) . "'" : "";
$qtyVal = number_format((float)$r['qty'], 3, '.', '');
$expiryShow = $expiry ? htmlspecialchars($expiry) : '<span class="text-muted">-</span>';
echo "<tr{$trClassStr}
data-lot-id='{$r['lot_id']}'
data-expired='" . ($isExpired ? "1" : "0") . "'>
<td>{$r['lot_id']}</td>
<td>" . htmlspecialchars($r['nomeuscita']) . "</td>
<td>" . htmlspecialchars($r['supplier_name']) . "</td>
<td>" . htmlspecialchars($r['supplier_mix_name']) . "</td>
<td>" . htmlspecialchars($r['lot_code'] ?? '') . "</td>
<td>{$expiryShow}</td>
<td>
<input type='number' step='0.001' class='form-control form-control-sm qty-input qty-field'
value='{$qtyVal}' />
</td>
<td>
<button class='btn btn-sm btn-outline-primary save-qty'>💾</button>
</td>
</tr>";
}
}
?>
</tbody>
</table>
</div>
<div class="text-muted small mt-2">
* Riga rossa = scaduta. * Riga opaca = mescola disattiva (ma lotto ancora presente).
</div>
</div>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script>
let dt;
$(document).ready(function() {
// init dropdown from URL
const urlParams = new URLSearchParams(window.location.search);
const activeParam = urlParams.get('active') || '1';
$('#filterActive').val(activeParam);
dt = $('#tabWarehouseMescole').DataTable({
order: [
[1, 'asc']
],
pageLength: 50,
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.6/i18n/it-IT.json'
}
});
// filtro attive/inattive: reload server-side semplice
$('#filterActive').on('change', function() {
const v = $(this).val();
const url = new URL(window.location.href);
url.searchParams.set('active', v);
window.location.href = url.toString();
});
// filtro "solo scadute" client-side
$('#onlyExpired').on('change', function() {
const only = $(this).is(':checked');
if (!only) {
dt.rows().every(function() {
$(this.node()).show();
});
return;
}
dt.rows().every(function() {
const node = $(this.node());
const expired = node.attr('data-expired') === '1';
if (expired) node.show();
else node.hide();
});
});
});
// SALVA QTY (per riga)
$(document).on('click', '.save-qty', function() {
const tr = $(this).closest('tr');
const lotId = tr.data('lot-id');
const qty = tr.find('.qty-field').val();
fetch('update_mescola_lot_qty.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `id=${encodeURIComponent(lotId)}&qty=${encodeURIComponent(qty)}`
})
.then(async (r) => {
const text = await r.text();
try {
return JSON.parse(text);
} catch (e) {
throw new Error("Risposta non JSON:\n" + text);
}
})
.then(data => {
if (data.success) {
Swal.fire({
icon: "success",
title: "Salvato",
timer: 900,
showConfirmButton: false
});
} else {
Swal.fire({
icon: "error",
title: "Errore",
text: data.message || "Salvataggio non riuscito"
});
}
})
.catch(err => {
Swal.fire({
icon: "error",
title: "Errore (fetch)",
text: err.message
});
});
});
// SALVA con Enter dentro il campo qty
$(document).on('keypress', '.qty-field', function(e) {
if (e.which === 13) {
e.preventDefault();
$(this).closest('tr').find('.save-qty').click();
}
});
</script>
</body>
</html>