zibo-dashboard/public/userarea/import_edit.php
2025-05-07 17:16:13 +02:00

1006 lines
44 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
include('include/headscript.php');
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['template_id']) || !isset($_POST['selected_rows']) || !isset($_POST['filename'])) {
header("Location: xlstemplates_grid.php?status=error&message=" . urlencode("Richiesta non valida"));
exit;
}
$template_id = intval($_POST['template_id']);
$selected_rows = $_POST['selected_rows'];
$columns = json_decode($_POST['columns'], true);
$rows = json_decode($_POST['rows'], true);
$newFilename = htmlspecialchars($_POST['filename']);
// Recupera l'ID dell'utente loggato (disponibile da headscript.php)
$user_id = $iduserlogin;
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Genera un UUID univoco per importreferencecode
$importReferenceCode = date('YmdHis') . '-' . uniqid();
// Recupera il mapping per il template
$stmt = $pdo->prepare("SELECT excel_column, mysql_column, data_type, is_required, default_value FROM excel_column_mappings WHERE template_id = ?");
$stmt->execute([$template_id]);
$mappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($mappings)) {
header("Location: import_xls.php?id=$template_id&status=error&message=" . urlencode("Nessun mapping trovato per il template"));
exit;
}
// Recupera il client_specific_fields dal template
$stmt = $pdo->prepare("SELECT client_specific_fields FROM excel_templates WHERE id = ?");
$stmt->execute([$template_id]);
$template = $stmt->fetch(PDO::FETCH_ASSOC);
$clientSpecificFields = $template && !empty($template['client_specific_fields']) ? json_decode($template['client_specific_fields'], true) : [];
// Crea un array per il mapping
$columnMapping = [];
foreach ($mappings as $mapping) {
$excelColumnIndex = array_search($mapping['excel_column'], $columns);
if ($excelColumnIndex !== false) {
$columnMapping[$excelColumnIndex] = [
'mysql_column' => $mapping['mysql_column'],
'data_type' => $mapping['data_type'],
'is_required' => $mapping['is_required'],
'default_value' => $mapping['default_value']
];
}
}
// Inserisci le righe selezionate in datadb
$insertedIds = [];
foreach ($selected_rows as $rowIndex) {
$row = $rows[$rowIndex];
$values = [];
$placeholders = [];
$columnsToInsert = [];
foreach ($columnMapping as $excelIndex => $mapping) {
$mysqlColumn = $mapping['mysql_column'];
$value = $row[$excelIndex] ?? $mapping['default_value'];
if ($mapping['is_required'] && (is_null($value) || $value === '')) {
$value = $mapping['default_value'];
if (is_null($value)) {
header("Location: import_xls.php?id=$template_id&status=error&message=" . urlencode("Valore richiesto mancante per la colonna $mysqlColumn"));
exit;
}
}
switch ($mapping['data_type']) {
case 'INT':
$value = is_numeric($value) ? (int)$value : ($mapping['default_value'] ?? null);
break;
case 'DATE':
$value = !empty($value) ? date('Y-m-d', strtotime($value)) : ($mapping['default_value'] ?? null);
break;
case 'CHAR':
$value = !empty($value) ? substr($value, 0, 1) : ($mapping['default_value'] ?? null);
break;
case 'VARCHAR':
default:
$value = !empty($value) ? htmlspecialchars($value) : ($mapping['default_value'] ?? null);
break;
}
if (!is_null($value)) {
$columnsToInsert[] = $mysqlColumn;
$placeholders[] = '?';
$values[] = $value;
}
}
$columnsToInsert[] = 'importreferencecode';
$placeholders[] = '?';
$values[] = $importReferenceCode;
$columnsToInsert[] = 'filename_import';
$placeholders[] = '?';
$values[] = $newFilename;
$columnsToInsert[] = 'status';
$placeholders[] = '?';
$values[] = 'i';
$columnsToInsert[] = 'user_id';
$placeholders[] = '?';
$values[] = $user_id;
$columnsToInsert[] = 'limscode';
$placeholders[] = '?';
$values[] = null;
$columnsToInsert[] = 'importdate';
$placeholders[] = '?';
$values[] = date('Y-m-d');
$sql = "INSERT INTO datadb (" . implode(', ', $columnsToInsert) . ") VALUES (" . implode(', ', $placeholders) . ")";
$stmt = $pdo->prepare($sql);
$stmt->execute($values);
$insertedIds[] = $pdo->lastInsertId();
}
// Recupera i dati appena inseriti con i nomi degli utenti
$stmt = $pdo->prepare("
SELECT d.*, CONCAT(u.first_name, ' ', u.last_name) AS user_name
FROM datadb d
LEFT JOIN auth_users u ON d.user_id = u.id
WHERE d.iddatadb IN (" . implode(',', array_fill(0, count($insertedIds), '?')) . ")
");
$stmt->execute($insertedIds);
$importedData = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Recupera il mapping globale per mostrare gli slug leggibili
$stmt = $pdo->query("SELECT mysql_column_name, user_friendly_slug FROM column_mapping");
$slugMapping = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$slugMapping[$row['mysql_column_name']] = $row['user_friendly_slug'];
}
?>
<!doctype html>
<html lang="en">
<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'); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2Lw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
.grid-container {
overflow-x: auto;
max-width: 100%;
margin-bottom: 20px;
border: 1px solid #dee2e6;
border-radius: 0.25rem;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.grid-row {
display: flex;
align-items: center;
padding: 0;
border-bottom: 1px solid #dee2e6;
}
.grid-row:last-child {
border-bottom: none;
}
.grid-row:nth-child(even) {
background-color: #f8f9fa;
/* Righe alternate (striped) */
}
.grid-row:hover {
background-color: #e9ecef;
/* Effetto hover */
}
.grid-header,
.grid-cell {
flex: 1;
min-width: 100px;
padding: 12px 15px;
border-right: 1px solid #dee2e6;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
transition: max-width 0.3s ease, background-color 0.5s ease;
box-sizing: border-box;
}
.grid-header {
font-weight: 600;
background-color: #e9ecef;
color: #495057;
border-bottom: 2px solid #dee2e6;
position: relative;
}
.grid-header:last-child,
.grid-cell:last-child {
border-right: none;
}
.grid-cell.expanded {
max-width: 500px !important;
white-space: normal !important;
overflow-wrap: break-word !important;
background-color: #e0f7fa !important;
flex: 0 0 500px !important;
/* Forza l'espansione */
}
.grid-cell input,
.grid-cell textarea,
.grid-cell select {
width: 100%;
box-sizing: border-box;
border: 1px solid #ced4da;
border-radius: 4px;
padding: 5px;
font-size: 14px;
}
.grid-cell textarea {
resize: vertical;
}
/* Stile per i campi aggiuntivi */
.grid-cell input.custom-field,
.grid-cell select.custom-field,
.grid-top input.custom-field,
.grid-top select.custom-field {
background-color: #fff3cd;
/* Giallo chiaro */
border-color: #ffca2c;
}
.save-btn,
.photos-btn {
background: none;
border: none;
cursor: pointer;
font-size: 16px;
margin-right: 10px;
}
.save-btn {
color: #28a745;
}
.save-btn:hover {
color: #218838;
}
.photos-btn {
color: #007bff;
}
.photos-btn:hover {
color: #0056b3;
}
.status-display {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
color: white;
font-size: 12px;
margin-right: 10px;
}
.status-i {
background-color: #ffa500;
/* Giallo/arancione per Importato */
}
.status-P {
background-color: #007bff;
/* Blu per Progress */
}
.status-l {
background-color: #28a745;
/* Verde per LIMS */
}
.flash-success {
animation: flash-green 0.5s ease-in-out;
}
@keyframes flash-green {
0%,
100% {
background-color: transparent;
}
50% {
background-color: #d4edda;
/* Verde chiaro per flash */
}
}
/* Trascinatore per ridimensionare colonne */
.resizer {
width: 5px;
height: 100%;
background: #ddd;
cursor: col-resize;
position: absolute;
right: 0;
top: 0;
bottom: 0;
}
.resizer:hover {
background: #999;
}
/* Stile per la riga superiore (input sopra l'header) */
.grid-top {
display: flex;
align-items: flex-start;
background-color: #f1f3f5;
padding: 10px 0;
border-bottom: 1px solid #dee2e6;
}
.grid-top .grid-cell {
padding: 5px 10px;
flex: 0 0 150px;
position: relative;
display: flex;
flex-direction: column;
align-items: center;
}
.propagate-btn {
background: none;
border: none;
cursor: pointer;
color: #666;
font-size: 14px;
margin-top: 5px;
padding: 2px 5px;
border-radius: 3px;
transition: color 0.3s ease;
}
.propagate-btn:hover {
color: #28a745;
}
.grid-cell {
display: flex;
align-items: center;
flex-wrap: nowrap;
overflow: visible !important;
}
.awb-input {
width: 60% !important;
/* Assicurati che l'input non occupi tutto lo spazio */
display: inline-block;
}
.go-btn {
display: inline-block;
width: 30%;
/* Dai al pulsante uno spazio definito */
margin-left: 5px;
}
.go-btn:hover {
background-color: #0056b3;
}
.tracking-info .tracking-result {
font-size: 12px;
color: #495057;
}
.carrier-select {
width: 40% !important;
display: inline-block;
border: 1px solid #ced4da;
border-radius: 4px;
padding: 5px;
font-size: 14px;
margin-right: 5px;
}
.awb-input {
width: 40% !important;
display: inline-block;
margin-right: 5px;
}
.go-btn {
width: 15% !important;
display: inline-block;
}
/* Stile per il popup */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 600px;
border-radius: 8px;
position: relative;
}
.close-btn {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close-btn:hover,
.close-btn:focus {
color: #000;
text-decoration: none;
}
</style>
<title>Edit Imported Data - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<?php include('top_stat_widget.php'); ?>
<div class="card radius-10">
<div class="card-header">
<div class="d-flex align-items-center">
<div>
<h6 class="mb-0">Modifica Dati Importati</h6>
</div>
</div>
</div>
<div class="card-body">
<form id="editForm">
<div class="grid-container">
<!-- Riga superiore per gli input dei campi aggiuntivi -->
<div class="grid-top">
<div class="grid-cell" style="flex: 0 0 100px;"></div>
<div class="grid-cell" style="flex: 0 0 100px;"></div> <!-- Spazio per la colonna Photos -->
<?php
$columns = array_keys($importedData[0]);
$headerIndex = 0;
foreach ($columns as $col) {
$visible = !in_array($col, ['iddatadb', 'importreferencecode', 'limscode', 'user_name']);
if ($visible) {
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
$headerIndex++;
}
}
// Aggiungi gli input per i campi aggiuntivi sopra l'header
foreach ($clientSpecificFields as $fieldName => $fieldDetails) {
$fieldValue = $fieldDetails['default_value'];
if ($fieldDetails['type'] === 'date' && $fieldDetails['default_value'] === 'today') {
$fieldValue = date('Y-m-d');
}
$requiredAttr = $fieldDetails['is_required'] ? 'required' : '';
echo "<div class='grid-cell' style='flex: 0 0 150px;'>";
if ($fieldDetails['type'] === 'date') {
echo "<input type='date' class='custom-field' data-column='$headerIndex' value='" . htmlspecialchars($fieldValue) . "' " . $requiredAttr . ">";
} elseif ($fieldDetails['type'] === 'boolean') {
echo "<select class='custom-field' data-column='$headerIndex' " . $requiredAttr . ">";
echo "<option value='yes' " . ($fieldValue === 'yes' ? 'selected' : '') . ">Yes</option>";
echo "<option value='no' " . ($fieldValue === 'no' ? 'selected' : '') . ">No</option>";
echo "</select>";
} else {
echo "<input type='text' class='custom-field' data-column='$headerIndex' value='" . htmlspecialchars($fieldValue) . "' " . $requiredAttr . ">";
}
echo "<button type='button' class='propagate-btn' data-column='$headerIndex'><i class='fas fa-arrow-down'></i></button>";
echo "</div>";
$headerIndex++;
}
// Spazi vuoti per AWB Number e Tracking Info
echo "<div class='grid-cell' style='flex: 0 0 200px;'></div>";
echo "<div class='grid-cell' style='flex: 0 0 250px;'></div>";
?>
</div>
<!-- Header della tabella -->
<div class="grid-row">
<div class="grid-header" style="flex: 0 0 100px;">Save</div>
<div class="grid-header" style="flex: 0 0 100px;">Photos</div> <!-- Nuova colonna Photos -->
<?php
$headerIndex = 0;
foreach ($columns as $col) {
$displayName = $slugMapping[$col] ?? $col;
$visible = !in_array($col, ['iddatadb', 'importreferencecode', 'limscode', 'user_name']);
if ($visible) {
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>$displayName<div class='resizer'></div></div>";
$headerIndex++;
}
}
// Aggiungi gli header per i campi aggiuntivi
foreach ($clientSpecificFields as $fieldName => $fieldDetails) {
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>$fieldName<div class='resizer'></div></div>";
$headerIndex++;
}
?>
<div class="grid-header" data-index="<?= $headerIndex ?>" style="flex: 0 0 200px; position: relative;">AWB Number<div class="resizer"></div>
</div>
<div class="grid-header" data-index="<?= $headerIndex + 1 ?>" style="flex: 0 0 250px; position: relative;">Tracking Info<div class="resizer"></div>
</div>
</div>
<!-- Righe della tabella -->
<?php foreach ($importedData as $index => $row): ?>
<div class="grid-row" data-id="<?= $row['iddatadb'] ?>">
<div class="grid-cell" style="flex: 0 0 100px; position: relative;">
<button type="button" class="save-btn" data-row="<?= $index ?>"><i class="fas fa-save"></i></button>
</div>
<div class="grid-cell" style="flex: 0 0 100px; position: relative;">
<button type="button" class="photos-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>"><i class="fas fa-camera"></i></button>
</div>
<?php
$cellIndex = 0;
foreach ($row as $col => $value) {
$visible = !in_array($col, ['iddatadb', 'importreferencecode', 'limscode', 'user_name']);
if ($visible) {
?>
<div class="grid-cell editable-cell" data-col="<?= $col ?>" data-row="<?= $index ?>" data-index="<?= $cellIndex ?>" style="flex: 0 0 150px;">
<?php if ($col === 'importdate'): ?>
<span><?= htmlspecialchars($value ?? '') ?></span>
<input type="hidden" name="rows[<?= $index ?>][<?= $col ?>]" value="<?= htmlspecialchars($value ?? '') ?>">
<?php elseif ($col === 'filename_import'): ?>
<a href="imported_trf/<?= htmlspecialchars($value ?? '') ?>" target="_blank">File</a>
<input type="hidden" name="rows[<?= $index ?>][<?= $col ?>]" value="<?= htmlspecialchars($value ?? '') ?>">
<?php elseif ($col === 'status'): ?>
<span class="status-display status-<?= htmlspecialchars($value ?? 'i') ?>">
<?= htmlspecialchars($value === 'i' ? 'Imported' : ($value === 'P' ? 'Progress' : 'LIMS')) ?>
</span>
<input type="hidden" name="rows[<?= $index ?>][<?= $col ?>]" value="<?= htmlspecialchars($value ?? 'i') ?>">
<?php elseif ($col === 'user_id'): ?>
<span><?= htmlspecialchars($row['user_name'] ?? 'Utente Sconosciuto') ?></span>
<input type="hidden" name="rows[<?= $index ?>][<?= $col ?>]" value="<?= htmlspecialchars($value ?? '') ?>">
<?php else: ?>
<input type="text" name="rows[<?= $index ?>][<?= $col ?>]" value="<?= htmlspecialchars($value ?? '') ?>" class="cell-input">
<?php endif; ?>
</div>
<?php
$cellIndex++;
} else {
?>
<input type="hidden" name="rows[<?= $index ?>][<?= $col ?>]" value="<?= htmlspecialchars($value ?? '') ?>">
<?php
}
}
// Aggiungi i campi aggiuntivi
foreach ($clientSpecificFields as $fieldName => $fieldDetails) {
?>
<div class="grid-cell editable-cell" data-col="<?= htmlspecialchars($fieldDetails['export_column_name']) ?>" data-row="<?= $index ?>" data-index="<?= $cellIndex ?>" style="flex: 0 0 150px;">
<?php
$fieldValue = $fieldDetails['default_value'];
if ($fieldDetails['type'] === 'date' && $fieldDetails['default_value'] === 'today') {
$fieldValue = date('Y-m-d');
}
$requiredAttr = $fieldDetails['is_required'] ? 'required' : '';
if ($fieldDetails['type'] === 'date') {
echo "<input type='date' name='rows[$index][custom_fields][" . htmlspecialchars($fieldDetails['export_column_name']) . "]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input custom-field' $requiredAttr>";
} elseif ($fieldDetails['type'] === 'boolean') {
echo "<select name='rows[$index][custom_fields][" . htmlspecialchars($fieldDetails['export_column_name']) . "]' class='cell-input custom-field' $requiredAttr>";
echo "<option value='yes' " . ($fieldValue === 'yes' ? 'selected' : '') . ">Yes</option>";
echo "<option value='no' " . ($fieldValue === 'no' ? 'selected' : '') . ">No</option>";
echo "</select>";
} else {
echo "<input type='text' name='rows[$index][custom_fields][" . htmlspecialchars($fieldDetails['export_column_name']) . "]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input custom-field' $requiredAttr>";
}
?>
</div>
<?php
$cellIndex++;
}
?>
<!-- Colonna AWB con tendina -->
<div class="grid-cell" style="flex: 0 0 200px;">
<select name="rows[<?= $index ?>][carrier]" class="carrier-select" style="width: 40%; display: inline-block;">
<option value="tnt-it">TNT Italy</option>
<option value="dhl">DHL</option>
<option value="gls">GLS</option>
<option value="sda">SDA</option>
<option value="ups">UPS</option>
</select>
<input type="text" name="rows[<?= $index ?>][awb_number]" class="cell-input awb-input" placeholder="Inserisci AWB Number" style="width: 40%; display: inline-block;">
<button type="button" class="go-btn" data-row="<?= $index ?>" style="width: 15%;"><i class="fas fa-play"></i> </button>
</div>
<div class="grid-cell tracking-info" data-row="<?= $index ?>" style="flex: 0 0 250px;">
<span class="tracking-result">Shipment Info</span>
<input type="hidden" name="rows[<?= $index ?>][tracking_info]" class="tracking-hidden">
</div>
</div>
<?php endforeach; ?>
</div>
</form>
<!-- Popup per le foto -->
<div id="photosModal" class="modal">
<div class="modal-content">
<span class="close-btn">×</span>
<div id="popupContent">
<!-- Il contenuto verrà caricato dinamicamente -->
<p>Loading...</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--end page wrapper -->
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<!--end wrapper-->
<?php include('jsinclude.php'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
const inputs = document.querySelectorAll('.cell-input');
// Espansione della cella al focus dell'input
inputs.forEach(input => {
input.addEventListener('focus', function() {
console.log('Focus on input:', this.name);
const cell = this.closest('.grid-cell');
if (cell) {
cell.classList.add('expanded');
console.log('Class "expanded" added to cell:', cell);
} else {
console.error('Cell not found for input:', this.name);
}
});
input.addEventListener('blur', function() {
console.log('Blur on input:', this.name);
const cell = this.closest('.grid-cell');
if (cell) {
cell.classList.remove('expanded');
console.log('Class "expanded" removed from cell:', cell);
}
});
});
// Salvataggio della riga
const saveButtons = document.querySelectorAll('.save-btn');
saveButtons.forEach(button => {
button.addEventListener('click', function() {
const rowIndex = this.getAttribute('data-row');
const row = this.closest('.grid-row');
const iddatadb = row.getAttribute('data-id');
const formData = new FormData();
// Raccogli i dati della riga, includendo i campi aggiuntivi
const inputs = row.querySelectorAll(`input[name^="rows[${rowIndex}]"], select[name^="rows[${rowIndex}]"]`);
inputs.forEach(input => {
const name = input.name.replace(`rows[${rowIndex}]`, '').replace(/\[|\]/g, '');
if (name !== 'user_name') {
formData.append(name, input.value);
}
});
formData.append('iddatadb', iddatadb);
// Invia la richiesta AJAX
fetch('save_edited_row.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Fai flashare le celle della riga di verde
const cells = row.querySelectorAll('.grid-cell');
cells.forEach(cell => {
cell.classList.remove('flash-success');
void cell.offsetWidth;
cell.classList.add('flash-success');
});
setTimeout(() => {
cells.forEach(cell => cell.classList.remove('flash-success'));
}, 500);
} else {
alert('Errore durante il salvataggio: ' + data.message);
}
})
.catch(error => {
alert('Errore durante il salvataggio: ' + error.message);
});
});
});
// Gestione del popup per le foto
// Funzione per caricare il contenuto del popup
async function loadPopupContent(iddatadb) {
const popupContent = document.getElementById('popupContent');
try {
const response = await fetch(`photos_popup.php?iddatadb=${iddatadb}`);
popupContent.innerHTML = await response.text();
// Dopo aver caricato il contenuto, associa gli event listener
attachPhotoEventListeners(iddatadb);
} catch (error) {
popupContent.innerHTML = `<p>Errore durante il caricamento: ${error.message}</p>`;
}
}
// Funzione per associare gli event listener per il drag-and-drop e la rimozione delle foto
function attachPhotoEventListeners(iddatadb) {
const dropArea = document.getElementById('dropArea');
const photoInput = document.getElementById('photoInput');
if (!dropArea || !photoInput) {
console.error('Elementi dropArea o photoInput non trovati nel DOM');
return;
}
console.log('Associando event listener per drag-and-drop'); // Debug
// Gestione drag-and-drop
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, () => {
console.log('Drag enter/over'); // Debug
dropArea.classList.add('highlight');
}, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, () => {
console.log('Drag leave/drop'); // Debug
dropArea.classList.remove('highlight');
}, false);
});
dropArea.addEventListener('drop', (e) => {
console.log('File droppato'); // Debug
const files = e.dataTransfer.files;
handleFiles(files, iddatadb);
}, false);
dropArea.addEventListener('click', () => {
console.log('Click su dropArea'); // Debug
photoInput.click();
}, false);
photoInput.addEventListener('change', () => {
console.log('File selezionato tramite input'); // Debug
handleFiles(photoInput.files, iddatadb);
}, false);
// Gestione della rimozione delle foto
const deleteButtons = document.querySelectorAll('.delete-photo-btn');
deleteButtons.forEach(button => {
button.addEventListener('click', async function() {
const photoId = this.getAttribute('data-photo-id');
if (confirm('Sei sicuro di voler eliminare questa foto?')) {
try {
const response = await fetch('delete_photo.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `photo_id=${photoId}`
});
const result = await response.json();
if (result.success) {
// Ricarica il contenuto del popup
loadPopupContent(iddatadb);
} else {
alert('Errore durante l\'eliminazione: ' + result.message);
}
} catch (error) {
alert('Errore durante l\'eliminazione: ' + error.message);
}
}
});
});
}
// Funzione per gestire i file caricati
async function handleFiles(files, iddatadb) {
for (const file of files) {
if (!file.type.startsWith('image/')) {
alert('Per favore, carica solo immagini!');
continue;
}
const formData = new FormData();
formData.append('photo', file);
formData.append('iddatadb', iddatadb);
try {
const response = await fetch('upload_photo.php', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
// Ricarica il contenuto del popup
loadPopupContent(iddatadb);
} else {
alert('Errore durante il caricamento: ' + result.message);
}
} catch (error) {
alert('Errore durante il caricamento: ' + error.message);
}
}
}
// Gestione del popup per le foto
const photosButtons = document.querySelectorAll('.photos-btn');
const modal = document.getElementById('photosModal');
const closeBtn = document.querySelector('.close-btn');
photosButtons.forEach(button => {
button.addEventListener('click', function() {
const iddatadb = this.getAttribute('data-iddatadb');
loadPopupContent(iddatadb);
modal.style.display = 'block';
});
});
closeBtn.addEventListener('click', function() {
modal.style.display = 'none';
});
window.addEventListener('click', function(event) {
if (event.target === modal) {
modal.style.display = 'none';
}
});
closeBtn.addEventListener('click', function() {
modal.style.display = 'none';
});
window.addEventListener('click', function(event) {
if (event.target === modal) {
modal.style.display = 'none';
}
});
// Ridimensionamento manuale delle colonne dagli header
const resizers = document.querySelectorAll('.resizer');
let currentResizer = null;
let startX = 0;
let startWidth = 0;
let columnIndex = 0;
resizers.forEach(resizer => {
resizer.addEventListener('mousedown', function(e) {
currentResizer = resizer;
const header = resizer.parentElement;
columnIndex = header.getAttribute('data-index');
startX = e.pageX;
startWidth = header.offsetWidth;
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', stopResize);
});
function resize(e) {
if (currentResizer) {
const dx = e.pageX - startX;
const newWidth = startWidth + dx;
const headers = document.querySelectorAll(`.grid-header[data-index="${columnIndex}"]`);
const cells = document.querySelectorAll(`.grid-cell[data-index="${columnIndex}"]`);
headers.forEach(header => header.style.flex = `0 0 ${newWidth}px`);
cells.forEach(cell => cell.style.flex = `0 0 ${newWidth}px`);
}
}
function stopResize() {
if (currentResizer) {
document.removeEventListener('mousemove', resize);
document.removeEventListener('mouseup', stopResize);
currentResizer = null;
}
}
});
// Propagazione del valore dall'input superiore
const propagateButtons = document.querySelectorAll('.propagate-btn');
propagateButtons.forEach(button => {
button.addEventListener('click', function() {
const columnIndex = this.getAttribute('data-column');
const input = this.previousElementSibling;
const value = input.value;
// Seleziona tutti gli input della stessa colonna tra le righe
const cells = document.querySelectorAll(`.grid-cell[data-index="${columnIndex}"]`);
cells.forEach(cell => {
const rowInput = cell.querySelector('input, select');
if (rowInput && rowInput.classList.contains('custom-field')) {
if (rowInput.tagName === 'INPUT' && rowInput.type === 'date') {
rowInput.value = value; // Per input date
} else if (rowInput.tagName === 'SELECT') {
rowInput.value = value; // Per select boolean
} else {
rowInput.value = value; // Per input text
}
}
});
});
});
});
</script>
<script>
document.querySelectorAll('.go-btn').forEach(button => {
button.addEventListener('click', async function() {
const rowIndex = this.getAttribute('data-row');
const awbInput = document.querySelector(`input[name="rows[${rowIndex}][awb_number]"]`);
const carrierSelect = document.querySelector(`select[name="rows[${rowIndex}][carrier]"]`);
const trackingResult = document.querySelector(`.tracking-info[data-row="${rowIndex}"] .tracking-result`);
const trackingHidden = document.querySelector(`input[name="rows[${rowIndex}][tracking_info]"]`);
const trackingNumber = awbInput.value.trim();
const carrierCode = carrierSelect.value;
if (!trackingNumber) {
alert('Inserisci un numero AWB valido!');
return;
}
try {
trackingResult.textContent = 'Caricamento...';
this.disabled = true;
const formData = new FormData();
formData.append('tracking_number', trackingNumber);
formData.append('courier_code', carrierCode);
const response = await fetch('fetch_tracking_info.php', {
method: 'POST',
body: formData
});
const result = await response.json();
if (!result.success) {
throw new Error(result.message);
}
const trackingText = `Date: ${result.deliveryDate}, Signed by: ${result.signedBy}, Courier: ${result.carrierName}`;
trackingResult.textContent = trackingText;
trackingHidden.value = JSON.stringify({
deliveryDate: result.deliveryDate,
signedBy: result.signedBy,
carrierName: result.carrierName
});
} catch (error) {
console.error('Errore:', error);
trackingResult.textContent = 'Errore: ' + error.message;
trackingHidden.value = '';
} finally {
this.disabled = false;
}
});
});
</script>
</body>
</html>