routine scripts

This commit is contained in:
Claudio 2025-09-24 14:18:31 +02:00
parent 33aacfb469
commit 864714d198
4 changed files with 342 additions and 176 deletions

View File

@ -0,0 +1,50 @@
<?php
ob_start();
session_start();
require_once '../../vendor/autoload.php';
$response = ['error' => '', 'rows' => [], 'columns' => [], 'template_id' => 0, 'filename' => '', 'excel_data' => []];
try {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
$template_id = isset($input['template_id']) ? intval($input['template_id']) : 0;
$filename = $input['routine_data']['filename'] ?? '';
$headerrow = $input['routine_data']['headerrow'] ?? 1;
$excelData = $input['excel_data'] ?? [];
$routineData = $input['routine_data'] ?? [];
if (!$filename || empty($excelData)) {
throw new Exception("Dati della routine mancanti.");
}
$routineFile = __DIR__ . '/routines/' . $filename;
if (file_exists($routineFile)) {
include_once $routineFile;
$routineData['xls_headers'] = $_SESSION['headers'] ?? [];
applyRoutine($excelData, $routineData); // Modifica $excelData in place
error_log("Routine {$routineData['name']} applicata (file: {$filename}) per template {$template_id}, header row: {$headerrow}");
} else {
throw new Exception("File della routine non trovato: $routineFile");
}
// Aggiorna la sessione con i dati modificati
$_SESSION['excel_data'] = $excelData;
$response['excel_data'] = $excelData;
$response['rows'] = array_column($excelData, 'data');
$response['columns'] = $_SESSION['headers'];
$response['template_id'] = $template_id;
$response['filename'] = $input['filename'] ?? '';
} else {
$response['error'] = "Richiesta non valida.";
}
} catch (Exception $e) {
$response['error'] = "Errore durante l'applicazione della routine: " . $e->getMessage();
error_log("Exception in apply_routine.php: " . $e->getMessage());
}
ob_end_clean();
header('Content-Type: application/json');
echo json_encode($response);
exit;

View File

@ -17,23 +17,27 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['template_id']) || !i
header("Location: xlstemplates_grid.php?status=error&message=" . urlencode("Richiesta non valida")); header("Location: xlstemplates_grid.php?status=error&message=" . urlencode("Richiesta non valida"));
exit; exit;
} }
$template_id = intval($_POST['template_id']); $template_id = intval($_POST['template_id']);
$selected_rows = $_POST['selected_rows']; $selected_rows = array_map('intval', $_POST['selected_rows']);
$columns = json_decode($_POST['columns'], true); // Header dell'XLS $columns = json_decode($_POST['columns'], true);
$rows = json_decode($_POST['rows'], true); // Dati dell'XLS $rows = json_decode($_POST['rows'], true);
$excelrows = json_decode($_POST['excelrows'], true);
$newFilename = htmlspecialchars($_POST['filename']); $newFilename = htmlspecialchars($_POST['filename']);
$_SESSION['template_id'] = $template_id; $_SESSION['template_id'] = $template_id;
$_SESSION['selected_rows'] = $selected_rows; $_SESSION['selected_rows'] = $selected_rows;
$_SESSION['columns'] = $columns; $_SESSION['columns'] = $columns;
$_SESSION['rows'] = $rows; $_SESSION['rows'] = $rows;
$_SESSION['excelrows'] = $excelrows;
$_SESSION['filename'] = $newFilename; $_SESSION['filename'] = $newFilename;
error_log("Received Data - Template ID: $template_id, Selected Rows: " . json_encode($selected_rows)); error_log("Received Data - Template ID: $template_id, Selected Rows: " . json_encode($selected_rows));
error_log("Columns: " . json_encode($columns)); error_log("Columns: " . json_encode($columns));
error_log("Rows: " . json_encode($rows)); error_log("Rows: " . json_encode($rows));
error_log("Excelrows: " . json_encode($excelrows));
$user_id = $iduserlogin ?? 1; // Default a 1 se non definito $user_id = $iduserlogin ?? 1;
$db = DBHandlerSelect::getInstance(); $db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection(); $pdo = $db->getConnection();
@ -60,30 +64,38 @@ foreach ($allMappings as $mapping) {
} }
} }
// Inserisci le righe selezionate in datadb (solo campi generici con templateid) // Inserisci le righe selezionate in datadb
$insertedIds = []; $insertedIds = [];
foreach ($selected_rows as $rowIndex) { foreach ($selected_rows as $rowIndex) {
$row = $rows[$rowIndex]; $row = $rows[$rowIndex] ?? null;
$excelrow = $excelrows[$rowIndex] ?? null;
if ($row === null || $excelrow === null) {
error_log("Errore: riga o excelrow mancante per rowIndex $rowIndex");
continue;
}
$values = [ $values = [
$template_id, // templateid $template_id,
$importReferenceCode, // importreferencecode $importReferenceCode,
$newFilename, // filename_import $newFilename,
'i', // status 'i',
$user_id, // user_id $user_id,
null, // limscode null,
date('Y-m-d') // importdate date('Y-m-d'),
$excelrow // Aggiunto excelrow per la colonna excelrow
]; ];
$sql = "INSERT INTO datadb (templateid, importreferencecode, filename_import, status, user_id, limscode, importdate) VALUES (?, ?, ?, ?, ?, ?, ?)"; $sql = "INSERT INTO datadb (templateid, importreferencecode, filename_import, status, user_id, limscode, importdate, excelrow) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql); $stmt = $pdo->prepare($sql);
$stmt->execute($values); $stmt->execute($values);
$iddatadb = $pdo->lastInsertId(); $iddatadb = $pdo->lastInsertId();
$insertedIds[] = $iddatadb; $insertedIds[] = $iddatadb;
// Inserisci tutti i campi (automatici e manuali) in import_data_details // Inserisci tutti i campi in import_data_details
foreach ($allMappings as $mapping) { foreach ($allMappings as $mapping) {
$fieldValue = null; $fieldValue = null;
if (!$mapping['is_manual']) { // Campi automatici dall'XLS if (!$mapping['is_manual']) {
$excelColumn = trim($mapping['excel_column']); $excelColumn = trim($mapping['excel_column']);
$excelColumnIndex = array_search($excelColumn, array_map('trim', $columns)); $excelColumnIndex = array_search($excelColumn, array_map('trim', $columns));
if ($excelColumnIndex !== false && isset($row[$excelColumnIndex]) && $row[$excelColumnIndex] !== '') { if ($excelColumnIndex !== false && isset($row[$excelColumnIndex]) && $row[$excelColumnIndex] !== '') {
@ -109,7 +121,7 @@ foreach ($selected_rows as $rowIndex) {
$fieldValue = !empty($fieldValue) ? htmlspecialchars((string)$fieldValue) : ($mapping['manual_default'] ?? ''); $fieldValue = !empty($fieldValue) ? htmlspecialchars((string)$fieldValue) : ($mapping['manual_default'] ?? '');
break; break;
} }
} else { // Campi manuali } else {
$fieldValue = $mapping['manual_default'] ?? ''; $fieldValue = $mapping['manual_default'] ?? '';
if ($mapping['data_type'] === 'DATE' && $mapping['manual_default'] === 'today') { if ($mapping['data_type'] === 'DATE' && $mapping['manual_default'] === 'today') {
$fieldValue = date('Y-m-d'); $fieldValue = date('Y-m-d');
@ -129,29 +141,26 @@ $_SESSION['inserted_ids'] = $insertedIds;
$params = [ $params = [
'template_id' => $template_id, 'template_id' => $template_id,
'filename' => $newFilename, 'filename' => $newFilename,
]; ];
?> ?>
<form id="redirectForm" action="import_edit2.php" method="post"> <form id="redirectForm" action="import_edit2.php" method="post">
<input type="hidden" name="template_id" value="<?= htmlspecialchars($template_id) ?>"> <input type="hidden" name="template_id" value="<?= htmlspecialchars($template_id) ?>">
<input type="hidden" name="filename" value="<?= htmlspecialchars($newFilename) ?>"> <input type="hidden" name="filename" value="<?= htmlspecialchars($newFilename) ?>">
<?php foreach ($selected_rows as $row): ?>
<?php foreach ($selected_rows as $row): ?> <input type="hidden" name="selected_rows[]" value="<?= htmlspecialchars($row) ?>">
<input type="hidden" name="selected_rows[]" value="<?= htmlspecialchars($row) ?>"> <?php endforeach; ?>
<?php endforeach; ?> <?php foreach ($insertedIds as $id): ?>
<input type="hidden" name="inserted_ids[]" value="<?= htmlspecialchars($id) ?>">
<?php foreach ($insertedIds as $id): ?> <?php endforeach; ?>
<input type="hidden" name="inserted_ids[]" value="<?= htmlspecialchars($id) ?>"> <input type="hidden" name="columns" value='<?= json_encode($columns) ?>'>
<?php endforeach; ?> <input type="hidden" name="rows" value='<?= json_encode($rows) ?>'>
<input type="hidden" name="excelrows" value='<?= json_encode($excelrows) ?>'>
<input type="hidden" name="columns" value='<?= json_encode($columns) ?>'> </form>
<input type="hidden" name="rows" value='<?= json_encode($rows) ?>'> <script>
</form> document.getElementById('redirectForm').submit();
<script> </script>
document.getElementById('redirectForm').submit();
</script>
<?php <?php
exit; exit;
?>

View File

@ -21,6 +21,11 @@ if (!$template) {
exit; exit;
} }
// Verifica i mapping
$stmt = $pdo->prepare("SELECT id FROM template_mapping WHERE template_id = ?");
$stmt->execute([$id]);
$hasMappings = $stmt->fetch(PDO::FETCH_ASSOC);
// Debug del template // Debug del template
error_log("Loaded template: " . print_r($template, true)); error_log("Loaded template: " . print_r($template, true));
?> ?>
@ -33,6 +38,7 @@ error_log("Loaded template: " . print_r($template, true));
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" /> <link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?> <?php include('cssinclude.php'); ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style> <style>
.table-container { .table-container {
overflow-x: auto; overflow-x: auto;
@ -140,43 +146,55 @@ error_log("Loaded template: " . print_r($template, true));
</div> </div>
</div> </div>
</div> </div>
<div class="card-body"> <div class="card-body">
<!-- Form per caricare il file --> <?php if (!$hasMappings): ?>
<div class="alert alert-warning" role="alert">
Nessun mapping trovato per questo template. Configura i mapping prima di procedere.
</div>
<?php endif; ?>
<form id="uploadForm" enctype="multipart/form-data" class="mb-4"> <form id="uploadForm" enctype="multipart/form-data" class="mb-4">
<div class="mb-3"> <div class="mb-3">
<label for="excel_file" class="form-label">Upload XLS File</label> <label for="excel_file" class="form-label">Upload XLS File</label>
<input type="file" class="form-control" id="excel_file" name="excel_file" accept=".xls,.xlsx" required> <input type="file" class="form-control" id="excel_file" name="excel_file" accept=".xls,.xlsx" required>
</div> </div>
<button type="submit" class="btn btn-primary">Upload</button> <button type="submit" class="btn btn-primary" <?= !$hasMappings ? 'disabled' : '' ?>>Upload</button>
<div class="loader" id="loader"></div> <div class="loader" id="loader"></div>
</form> </form>
<!-- Contenitore per messaggi di errore -->
<div id="errorContainer" class="alert alert-danger mt-3" style="display: none;"></div> <div id="errorContainer" class="alert alert-danger mt-3" style="display: none;"></div>
<!-- Contenitore per la tabella -->
<div id="tableContainer"></div> <div id="tableContainer"></div>
<div class="modal fade" id="routineConfirmModal" tabindex="-1" aria-labelledby="routineConfirmModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="routineConfirmModalLabel">Conferma Applicazione Routine</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p><strong>Routine:</strong> <span id="routineName"></span></p>
<p><strong>Descrizione:</strong> <span id="routineDescription"></span></p>
<p>Vuoi applicare questa routine al file caricato?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="cancelRoutineBtn">Annulla</button>
<button type="button" class="btn btn-primary" id="confirmRoutineBtn">Applica</button>
</div>
</div>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!--end page wrapper -->
<div class="overlay toggle-icon"></div> <div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?> <?php include('include/footer.php'); ?>
</div> </div>
<!--end wrapper-->
<!-- search modal --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<?php //include('include/searchmodal.php'); <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></script>
?>
<!-- end search modal -->
<!--start switcher-->
<?php //include('include/themeswitcher.php');
?>
<!--end switcher-->
<?php include('jsinclude.php'); ?> <?php include('jsinclude.php'); ?>
<script> <script>
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
@ -184,6 +202,12 @@ error_log("Loaded template: " . print_r($template, true));
const loader = document.getElementById('loader'); const loader = document.getElementById('loader');
const errorContainer = document.getElementById('errorContainer'); const errorContainer = document.getElementById('errorContainer');
const tableContainer = document.getElementById('tableContainer'); const tableContainer = document.getElementById('tableContainer');
const routineModal = new bootstrap.Modal(document.getElementById('routineConfirmModal'));
const confirmRoutineBtn = document.getElementById('confirmRoutineBtn');
const cancelRoutineBtn = document.getElementById('cancelRoutineBtn');
let routineData = null;
let excelData = null;
let responseData = null;
form.addEventListener('submit', function(e) { form.addEventListener('submit', function(e) {
e.preventDefault(); e.preventDefault();
@ -202,133 +226,188 @@ error_log("Loaded template: " . print_r($template, true));
method: 'POST', method: 'POST',
body: formData body: formData
}) })
.then(response => response.json()) .then(response => {
console.log('Stato risposta:', response.status);
return response.json();
})
.then(data => { .then(data => {
console.log('Risposta JSON:', data);
loader.style.display = 'none'; loader.style.display = 'none';
if (data.error) { if (data.error) {
errorContainer.textContent = data.error; errorContainer.textContent = data.error;
errorContainer.style.display = 'block'; errorContainer.style.display = 'block';
} else if (data.apply_routine) {
console.log('Routine rilevata:', data.routine_data);
routineData = data.routine_data;
excelData = data.excel_data;
responseData = data;
document.getElementById('routineName').textContent = routineData.name || 'Sconosciuta';
document.getElementById('routineDescription').textContent = routineData.instruction || 'Nessuna descrizione';
routineModal.show();
} else { } else {
let html = ` console.log('Nessuna routine, procedo con tabella');
<form id="selectRowsForm" action="import_insert.php" method="POST"> showTable(data);
<input type="hidden" name="template_id" value="${data.template_id}">
<input type="hidden" name="columns" value='${JSON.stringify(data.columns)}'>
<input type="hidden" name="rows" value='${JSON.stringify(data.rows)}'>
<input type="hidden" name="filename" value="${data.filename}">
<div class="search-container">
<input type="text" id="searchInput" class="form-control" placeholder="Cerca nelle righe...">
</div>
<div class="table-container">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="selectAll"> Seleziona</th>
${data.columns.map(col => `<th>${col || 'Colonna senza nome'}<div class="resize-handle"></div></th>`).join('')}
</tr>
</thead>
<tbody>
${data.rows.map((row, index) => `
<tr>
<td><input type="checkbox" class="row-checkbox" name="selected_rows[]" value="${index}"></td>
${row.map(cell => `<td>${cell}</td>`).join('')}
</tr>
`).join('')}
</tbody>
</table>
</div>
<button type="submit" class="btn btn-primary mt-3" id="proceedButton" disabled>Prosegui</button>
</form>
`;
tableContainer.innerHTML = html;
// Inizializza le variabili dopo aver inserito la tabella
const proceedButton = document.getElementById('proceedButton');
const selectAllCheckbox = document.getElementById('selectAll');
const checkboxes = document.querySelectorAll('.row-checkbox');
// Funzione per aggiornare lo stato del pulsante Prosegui
function updateProceedButton() {
proceedButton.disabled = !Array.from(checkboxes).some(cb => cb.checked);
}
// Event listener per il checkbox "Seleziona tutto"
selectAllCheckbox.addEventListener('change', function() {
checkboxes.forEach(checkbox => {
checkbox.checked = this.checked;
});
updateProceedButton();
});
// Event listener per i checkbox delle righe
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
console.log('Checkbox changed, checked: ', this.checked); // Debug
// Aggiorna lo stato del checkbox "Seleziona tutto"
selectAllCheckbox.checked = Array.from(checkboxes).every(cb => cb.checked);
updateProceedButton();
});
});
// Aggiungi logica per il ridimensionamento delle colonne
const thElements = document.querySelectorAll('.table th');
thElements.forEach((th, index) => {
if (index === 0) return;
const resizeHandle = th.querySelector('.resize-handle');
if (resizeHandle) {
resizeHandle.addEventListener('mousedown', (e) => {
e.preventDefault();
const startX = e.clientX;
const startWidth = th.offsetWidth;
const onMouseMove = (e) => {
const newWidth = Math.max(50, startWidth + (e.clientX - startX));
th.style.width = `${newWidth}px`;
th.style.minWidth = `${newWidth}px`;
th.style.maxWidth = `${newWidth}px`;
const cells = document.querySelectorAll(`.table td:nth-child(${index + 1})`);
cells.forEach(cell => {
cell.style.width = `${newWidth}px`;
cell.style.minWidth = `${newWidth}px`;
cell.style.maxWidth = `${newWidth}px`;
});
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
}
});
// Aggiungi event listener per la ricerca
const searchInput = document.getElementById('searchInput');
const rows = document.querySelectorAll('.table tbody tr');
searchInput.addEventListener('input', function() {
const searchTerm = this.value.toLowerCase();
rows.forEach(row => {
const text = Array.from(row.cells).slice(1).map(cell => cell.textContent.toLowerCase()).join(' ');
row.style.display = text.includes(searchTerm) ? '' : 'none';
});
});
// Abilita il pulsante se ci sono checkbox selezionate all'inizio
updateProceedButton();
} }
}) })
.catch(error => { .catch(error => {
console.log('Errore fetch:', error);
loader.style.display = 'none'; loader.style.display = 'none';
errorContainer.textContent = 'Errore durante il caricamento del file: ' + error.message; errorContainer.textContent = 'Errore durante il caricamento del file: ' + error.message;
errorContainer.style.display = 'block'; errorContainer.style.display = 'block';
}); });
}); });
confirmRoutineBtn.addEventListener('click', function() {
console.log('Conferma routine:', routineData);
routineModal.hide();
fetch('apply_routine.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
template_id: <?= $id ?>,
filename: routineData.filename,
headerrow: routineData.headerrow,
excel_data: excelData,
routine_data: routineData
})
})
.then(response => {
console.log('Stato apply_routine:', response.status);
return response.json();
})
.then(data => {
console.log('Risposta apply_routine:', data);
if (data.error) {
errorContainer.textContent = data.error;
errorContainer.style.display = 'block';
} else {
showTable(data);
}
})
.catch(error => {
console.log('Errore apply_routine:', error);
errorContainer.textContent = 'Errore durante l\'applicazione della routine: ' + error.message;
errorContainer.style.display = 'block';
});
});
cancelRoutineBtn.addEventListener('click', function() {
console.log('Routine annullata, procedo con tabella');
routineModal.hide();
showTable(responseData);
});
function showTable(data) {
console.log('Mostro tabella con dati:', data);
let html = `
<form id="selectRowsForm" action="import_insert.php" method="POST">
<input type="hidden" name="template_id" value="${data.template_id}">
<input type="hidden" name="columns" value='${JSON.stringify(data.columns)}'>
<input type="hidden" name="rows" value='${JSON.stringify(data.rows)}'>
<input type="hidden" name="excelrows" value='${JSON.stringify(data.excel_data.map(row => row.excelrow))}'>
<input type="hidden" name="filename" value="${data.filename}">
<div class="search-container">
<input type="text" id="searchInput" class="form-control" placeholder="Cerca nelle righe...">
</div>
<div class="table-container">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="selectAll"> Seleziona</th>
${data.columns.map(col => `<th>${col || 'Colonna senza nome'}<div class="resize-handle"></div></th>`).join('')}
</tr>
</thead>
<tbody>
${data.excel_data.map((row, index) => `
<tr>
<td><input type="checkbox" class="row-checkbox" name="selected_rows[]" value="${index}" data-excelrow="${row.excelrow}"></td>
${row.data.map(cell => `<td>${cell}</td>`).join('')}
</tr>
`).join('')}
</tbody>
</table>
</div>
<button type="submit" class="btn btn-primary mt-3" id="proceedButton" disabled>Prosegui</button>
</form>
`;
tableContainer.innerHTML = html;
const proceedButton = document.getElementById('proceedButton');
const selectAllCheckbox = document.getElementById('selectAll');
const checkboxes = document.querySelectorAll('.row-checkbox');
function updateProceedButton() {
proceedButton.disabled = !Array.from(checkboxes).some(cb => cb.checked);
}
selectAllCheckbox.addEventListener('change', function() {
checkboxes.forEach(checkbox => {
checkbox.checked = this.checked;
});
updateProceedButton();
});
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
console.log('Checkbox changed, checked:', this.checked, 'excelrow:', this.dataset.excelrow);
selectAllCheckbox.checked = Array.from(checkboxes).every(cb => cb.checked);
updateProceedButton();
});
});
const thElements = document.querySelectorAll('.table th');
thElements.forEach((th, index) => {
if (index === 0) return;
const resizeHandle = th.querySelector('.resize-handle');
if (resizeHandle) {
resizeHandle.addEventListener('mousedown', (e) => {
e.preventDefault();
const startX = e.clientX;
const startWidth = th.offsetWidth;
const onMouseMove = (e) => {
const newWidth = Math.max(50, startWidth + (e.clientX - startX));
th.style.width = `${newWidth}px`;
th.style.minWidth = `${newWidth}px`;
th.style.maxWidth = `${newWidth}px`;
const cells = document.querySelectorAll(`.table td:nth-child(${index + 1})`);
cells.forEach(cell => {
cell.style.width = `${newWidth}px`;
cell.style.minWidth = `${newWidth}px`;
cell.style.maxWidth = `${newWidth}px`;
});
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
}
});
const searchInput = document.getElementById('searchInput');
const rows = document.querySelectorAll('.table tbody tr');
searchInput.addEventListener('input', function() {
const searchTerm = this.value.toLowerCase();
rows.forEach(row => {
const text = Array.from(row.cells).slice(1).map(cell => cell.textContent.toLowerCase()).join(' ');
row.style.display = text.includes(searchTerm) ? '' : 'none';
});
});
updateProceedButton();
}
}); });
</script> </script>
</body> </body>
</html> </html>

View File

@ -1,7 +1,7 @@
<?php <?php
// Sopprime eventuali output di errori (li logghiamo invece di mostrarli) // Sopprime eventuali output di errori (li logghiamo invece di mostrarli)
ob_start(); ob_start();
ini_set('display_errors', 0); // Disattiva l'output degli errori a schermo ini_set('display_errors', 0);
error_reporting(E_ALL); error_reporting(E_ALL);
// Inizia la sessione // Inizia la sessione
@ -9,9 +9,9 @@ session_start();
// Includi PHPSpreadsheet e la classe DBHandler // Includi PHPSpreadsheet e la classe DBHandler
require_once '../../vendor/autoload.php'; require_once '../../vendor/autoload.php';
require_once __DIR__ . '/class/db-functions.php'; // Assumo che DBHandlerSelect sia qui require_once __DIR__ . '/class/db-functions.php';
$response = ['error' => '', 'rows' => [], 'columns' => [], 'template_id' => 0, 'filename' => '']; $response = ['error' => '', 'rows' => [], 'columns' => [], 'template_id' => 0, 'filename' => '', 'apply_routine' => false];
try { try {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) {
@ -29,7 +29,7 @@ try {
if ($fileError === UPLOAD_ERR_OK) { if ($fileError === UPLOAD_ERR_OK) {
// Recupera l'ID dell'utente loggato // Recupera l'ID dell'utente loggato
if (!isset($iduserlogin)) { if (!isset($iduserlogin)) {
$iduserlogin = 1; // Valore di default $iduserlogin = 1;
error_log("Warning: iduserlogin non definito, usando 1 come default"); error_log("Warning: iduserlogin non definito, usando 1 come default");
} }
@ -69,7 +69,7 @@ try {
$worksheet = $spreadsheet->getActiveSheet(); $worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow(); $highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn(); $highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // Corretto $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
$startRow = max(1, $header_row); $startRow = max(1, $header_row);
$startColumn = max(1, $start_column); $startColumn = max(1, $start_column);
@ -93,7 +93,7 @@ try {
$headerRowData[] = htmlspecialchars($cellValue ?: ''); $headerRowData[] = htmlspecialchars($cellValue ?: '');
} }
// Estrai i dati a partire dalla riga successiva // Estrai i dati a partire dalla riga successiva, includendo excelrow
for ($row = $startRow + 1; $row <= $highestRow; $row++) { for ($row = $startRow + 1; $row <= $highestRow; $row++) {
$rowData = []; $rowData = [];
for ($col = $startColumn; $col <= $highestColumnIndex; $col++) { for ($col = $startColumn; $col <= $highestColumnIndex; $col++) {
@ -103,18 +103,46 @@ try {
$rowData[] = htmlspecialchars($cellValue ?: ''); $rowData[] = htmlspecialchars($cellValue ?: '');
} }
if (!empty(array_filter($rowData))) { if (!empty(array_filter($rowData))) {
$excelData[] = $rowData; $excelData[] = ['data' => $rowData, 'excelrow' => $row];
} }
} }
// Recupera routine dal template
$stmt = $pdo->prepare("SELECT idroutine FROM excel_templates WHERE id = ?");
$stmt->execute([$template_id]);
$template = $stmt->fetch(PDO::FETCH_ASSOC);
if ($template && $template['idroutine']) {
$stmtRoutine = $pdo->prepare("SELECT idroutine, name, filename, headerrow, instruction FROM routine WHERE idroutine = ?");
$stmtRoutine->execute([$template['idroutine']]);
$routineData = $stmtRoutine->fetch(PDO::FETCH_ASSOC);
if ($routineData) {
$response['apply_routine'] = true;
$response['routine_data'] = [
'name' => $routineData['name'] ?? 'Routine Sconosciuta',
'instruction' => $routineData['instruction'] ?? 'Nessuna descrizione disponibile',
'filename' => $routineData['filename'] ?? '',
'headerrow' => $routineData['headerrow'] ?? $header_row
];
error_log("Routine rilevata per template {$template_id}: " . print_r($routineData, true));
} else {
error_log("Errore: Nessuna routine trovata per idroutine {$template['idroutine']}");
}
} else {
error_log("Nessuna routine associata al template {$template_id}");
}
// Salva i dati in sessione // Salva i dati in sessione
$_SESSION['excel_data'] = $excelData; $_SESSION['excel_data'] = $excelData;
$_SESSION['template_id'] = $template_id; $_SESSION['template_id'] = $template_id;
$_SESSION['headers'] = $headerRowData; $_SESSION['headers'] = $headerRowData;
$_SESSION['mappings'] = $mappings; // Salva i mapping per l'importazione $_SESSION['mappings'] = $mappings;
$response['rows'] = $excelData; // Includi excel_data nella risposta JSON in ogni caso
$response['columns'] = $headerRowData; // Usa gli header reali $response['excel_data'] = $excelData;
$response['rows'] = array_column($excelData, 'data');
$response['columns'] = $headerRowData;
$response['template_id'] = $template_id; $response['template_id'] = $template_id;
$response['filename'] = $newFilename; $response['filename'] = $newFilename;
} }