Compare commits

...

12 Commits

8 changed files with 1174 additions and 161 deletions
@@ -120,4 +120,76 @@ class VisualLimsApiClient
return $data;
}
public function post($endpoint, $payload)
{
$token = $this->getToken();
$url = "{$this->baseUrl}/api/odata/{$endpoint}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$token}",
"Content-Type: application/json",
"Accept: application/json"
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($response === false) {
throw new Exception("Errore nella richiesta POST: {$curl_error}");
}
if ($http_code < 200 || $http_code >= 300) {
throw new Exception("POST fallito: HTTP {$http_code}, Risposta: " . substr($response, 0, 1000));
}
return json_decode($response, true);
}
public function patch($endpoint, $payload)
{
$token = $this->getToken();
$url = "{$this->baseUrl}/api/odata/{$endpoint}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$token}",
"Content-Type: application/json",
"Accept: application/json"
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($response === false) {
throw new Exception("Errore nella richiesta PATCH: {$curl_error}");
}
if ($http_code < 200 || $http_code >= 300) {
throw new Exception("PATCH fallito: HTTP {$http_code}, Risposta: " . substr($response, 0, 1000));
}
return json_decode($response, true);
}
public function getBaseUrl()
{
return $this->baseUrl;
}
}
+1 -1
View File
@@ -31,6 +31,6 @@ Content-Length: 51
< strict-transport-security: max-age=2592000
< x-powered-by: ASP.NET
< x-content-type-options: nosniff
< date: Thu, 04 Sep 2025 12:59:20 GMT
< date: Sat, 06 Sep 2025 10:24:00 GMT
<
* Connection #0 to host 93.43.5.102 left intact
+3 -3
View File
@@ -15,11 +15,11 @@
* [HTTP/2] [1] [:scheme: https]
* [HTTP/2] [1] [:authority: 93.43.5.102]
* [HTTP/2] [1] [:path: /limsapi/api/odata/CustomField(1083)?$expand=CustomFieldsValues]
* [HTTP/2] [1] [authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1Njk5Nzk2MCwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.zHug3m3GFz-uMMbRXi70DlHNfw0Islrxyy5vdJ7RKtA]
* [HTTP/2] [1] [authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1NzE2MTQ0MCwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.UgVN5wzjtR8MRU2xLDFWRHIAYLJTmxF3x7kWeVU11YU]
* [HTTP/2] [1] [accept: application/json]
> GET /limsapi/api/odata/CustomField(1083)?$expand=CustomFieldsValues HTTP/2
Host: 93.43.5.102
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1Njk5Nzk2MCwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.zHug3m3GFz-uMMbRXi70DlHNfw0Islrxyy5vdJ7RKtA
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1NzE2MTQ0MCwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.UgVN5wzjtR8MRU2xLDFWRHIAYLJTmxF3x7kWeVU11YU
Accept: application/json
< HTTP/2 200
@@ -30,6 +30,6 @@ Accept: application/json
< odata-version: 4.0
< x-powered-by: ASP.NET
< x-content-type-options: nosniff
< date: Thu, 04 Sep 2025 12:59:23 GMT
< date: Sat, 06 Sep 2025 10:24:02 GMT
<
* Connection #0 to host 93.43.5.102 left intact
+172
View File
@@ -0,0 +1,172 @@
<?php
require_once "class/VisualLimsApiClient.class.php";
include('include/headscript.php');
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
header("Content-Type: application/json");
try {
$iddatadb = $_POST['iddatadb'] ?? null;
if (!$iddatadb) {
throw new Exception("Missing iddatadb");
}
// 🔹 STEP 1+2: Fetch Cliente ID + Schema ID
$stmt = $pdo->prepare("
SELECT et.idclient AS clienteId, et.idschema AS schemaId
FROM datadb as d
INNER JOIN excel_templates as et ON d.templateid = et.id
WHERE d.iddatadb = :iddatadb
LIMIT 1
");
$stmt->execute(['iddatadb' => $iddatadb]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$result) {
throw new Exception("No Cliente/Schema found for iddatadb {$iddatadb}");
}
$clienteId = (int) $result['clienteId'];
$schemaId = (int) $result['schemaId'];
// 🔹 STEP 3: Fetch Parts (including idmatrice)
$stmt = $pdo->prepare("
SELECT part_number, part_description, material, color, mix, idmatrice
FROM identification_parts
WHERE iddatadb = :iddatadb
");
$stmt->execute(['iddatadb' => $iddatadb]);
$parts = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 🔹 STEP 4: Fetch Field Values with Labels
$stmt = $pdo->prepare("
SELECT
idd.field_value,
m.field_label,
m.schema_id,
m.field_id
FROM
import_data_details as idd
JOIN template_mapping m ON idd.mapping_id = m.id
WHERE idd.id = :iddatadb
");
$stmt->execute(['iddatadb' => $iddatadb]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$fieldValues = [];
foreach ($rows as $row) {
$fieldValues[] = [
"IdCommesseCustomFields" => (int) $row['field_id'],
"Valore" => $row['field_value']
];
}
// 🔹 Initialize API client
$api = VisualLimsApiClient::getInstance();
// 🔹 STEP 5: Create CommessaWeb (NOT WebOrder)
$commessaWebPayload = [
"Cliente" => $clienteId,
"SchemaCustomField" => $schemaId,
"Richiedente" => "Test Web Import",
"Descrizione" => "TEST CommessaWeb",
];
$commessaWeb = $api->post("CommessaWeb", $commessaWebPayload);
$commessaId = $commessaWeb["IdCommessa"];
// Estraiamo il numero della commessa usando CodiceCommessa
$commessaWebCode = substr($commessaWeb["CodiceCommessa"] ?? "TEST CommessaWeb", 0, 30); // Limite a 30 caratteri
// 🔹 STEP 6: Create Campioni (Samples) for each part
$campioni = [];
foreach ($parts as $index => $part) {
$matriceId = (int) ($part["idmatrice"] ?? 0);
if ($matriceId <= 0) {
throw new Exception("Invalid or missing idmatrice for part: " . ($part["part_number"] ?? "Unknown"));
}
$campionePayload = [
"Commessa" => $commessaId,
"Matrice" => $matriceId,
"SottoMatrice" => null,
"SchemaCustomField" => $schemaId,
"NoteWeb" => $part["part_description"] ?? ""
];
$campione = $api->post("Campione", $campionePayload);
$campione["PartNumber"] = $part["part_number"] ?? "";
$campione["Material"] = $part["material"] ?? "";
$campione["Color"] = $part["color"] ?? "";
$campione["Mix"] = $part["mix"] ?? "";
$campioni[] = $campione;
}
// 🔹 STEP 7: Update Custom Fields for CommessaWeb
if (!empty($fieldValues)) {
$commessaWithFields = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=CommesseCustomFields");
$commessaCustomFields = [];
foreach ($commessaWithFields["CommesseCustomFields"] as $customField) {
foreach ($fieldValues as $fieldValue) {
if ($customField["IdCommesseCustomFields"] == $fieldValue["IdCommesseCustomFields"]) {
$commessaCustomFields[] = [
"IdCommesseCustomFields" => $customField["IdCommesseCustomFields"],
"Valore" => $fieldValue["Valore"]
];
break;
}
}
}
if (!empty($commessaCustomFields)) {
$updatePayload = ["CommesseCustomFields" => $commessaCustomFields];
$api->patch("CommessaWeb({$commessaId})", $updatePayload);
}
}
// 🔹 STEP 8: Update datadb with idcommessaweb, commessaweb, and status
$stmt = $pdo->prepare("
UPDATE datadb
SET idcommessaweb = :idcommessaweb, commessaweb = :commessaweb, status = 'l'
WHERE iddatadb = :iddatadb
");
$stmt->execute([
'idcommessaweb' => $commessaId,
'commessaweb' => $commessaWebCode,
'iddatadb' => $iddatadb
]);
// 🔹 STEP 9: Send CommessaWeb to laboratory
$sendResult = $api->post("CommessaWeb({$commessaId})/InviaCommessa", []);
// 🔹 STEP 10: Prepare final response
$finalCommessa = [
"Cliente" => $clienteId,
"SchemaCustomField" => $schemaId,
"Richiedente" => $commessaWeb["Richiedente"] ?? "Web Import",
"Descrizione" => $commessaWeb["Descrizione"] ?? "",
"CommesseCustomFields" => $fieldValues,
"Campioni" => $campioni,
"Inviata" => 1
];
echo json_encode([
"success" => true,
"commessaWeb" => $finalCommessa,
"commessaWebApiResponse" => $commessaWeb, // Incluso per debug
"totalCampioni" => count($campioni),
"totalCustomFields" => count($fieldValues),
"message" => "Export successful"
]);
} catch (Exception $e) {
error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
echo json_encode([
"success" => false,
"message" => "Export failed: " . $e->getMessage()
]);
}
File diff suppressed because one or more lines are too long
+262 -151
View File
@@ -21,8 +21,8 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['template_id']) || !i
$template_id = intval($_POST['template_id']) ?? $_SESSION['template_id'];
$selected_rows = $_POST['selected_rows'] ?? $_SESSION['selected_rows'];
$columns = json_decode($_POST['columns'], true) ?? $_SESSION['columns']; // Header dell'XLS
$rows = json_decode($_POST['rows'], true) ?? $_SESSION['rows']; // Dati dell'XLS
$columns = json_decode($_POST['columns'], true) ?? $_SESSION['columns'];
$rows = json_decode($_POST['rows'], true) ?? $_SESSION['rows'];
$newFilename = htmlspecialchars($_POST['filename']) ?? $_SESSION['filename'];
// Log dei dati ricevuti
@@ -31,7 +31,7 @@ error_log("Columns: " . json_encode($columns));
error_log("Rows: " . json_encode($rows));
// Recupera l'ID dell'utente loggato
$user_id = $iduserlogin ?? 1; // Default a 1 se non definito
$user_id = $iduserlogin ?? 1;
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
@@ -98,26 +98,26 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<?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>
/* Colori pastello per input/select */
.cell-changed {
background-color: #fff3b0 !important;
transition: background-color 0.3s ease;
}
input.auto-input,
select.auto-input {
background-color: #d4edda;
/* Verde pastello */
}
input.manual-input,
select.manual-input {
background-color: #fff3cd;
/* Giallino pastello */
}
input.required-input,
select.required-input {
background-color: #f8d7da;
/* Rossino chiaro */
}
/* Stili base per input/select */
input,
select {
width: 100%;
@@ -128,14 +128,11 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
font-size: 14px;
}
/* Mantieni leggibilità del testo */
input,
select {
color: #333;
/* Colore scuro per contrasto */
}
/* Stili per i badge di stato */
.status-badge {
display: inline-block;
padding: 2px 8px;
@@ -161,7 +158,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
color: white;
}
/* Stili esistenti rimangono invariati */
.grid-container {
overflow-x: auto;
max-width: 100%;
@@ -254,6 +250,11 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
align-items: center;
}
.grid-top .save-all-cell {
flex: 0 0 210px;
align-items: flex-start;
}
.propagate-btn {
background: none;
border: none;
@@ -370,7 +371,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}
/* Stile per l'header dei pulsanti combinati */
.grid-cell.button-cell,
.grid-header.button-header {
min-width: 210px !important;
@@ -391,6 +391,20 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
background-color: #d4edda !important;
transition: background-color 0.3s ease;
}
.save-all-btn {
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
padding: 8px 16px;
cursor: pointer;
font-size: 14px;
}
.save-all-btn:hover {
background-color: #218838;
}
</style>
<title>Edit Imported Data - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
</head>
@@ -413,6 +427,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<h6 class="mb-0">Modifica Dati Importati</h6>
<div id="unsavedChanges" style="display:none; color: red; font-weight: bold; margin:10px 0;">
⚠️ Unsaved changes detected! Please save before leaving this page.
<ul id="changedFields" style="margin-top:5px; font-weight:normal; color:darkred;"></ul>
</div>
</div>
</div>
@@ -420,9 +435,10 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<div class="card-body">
<form id="editForm">
<div class="grid-container">
<!-- Riga superiore per gli input dei campi manuali -->
<div class="grid-top">
<div class="grid-cell button-cell" style="flex: 0 0 210px;"></div> <!-- Actions -->
<div class="grid-cell save-all-cell">
<button type="button" class="save-all-btn" title="Save All Rows"><i class="fas fa-save"></i> Save All</button>
</div>
<?php if ($mainFieldMapping): ?>
<div class="grid-cell" style="flex: 0 0 150px;">
<?php
@@ -450,9 +466,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
?>
</div>
<?php endif; ?>
<div class="grid-cell" style="flex: 0 0 150px;"></div> <!-- status -->
<div class="grid-cell" style="flex: 0 0 150px;"></div>
<?php
// Campi automatici (is_manual = 0) escluso main_field
$autoIndex = 0;
foreach ($allMappings as $mapping) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1) {
@@ -471,7 +486,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$autoIndex++;
}
}
// Campi manuali (is_manual = 1) escluso main_field
$manualIndex = 0;
foreach ($allMappings as $mapping) {
if ($mapping['is_manual'] && $mapping['main_field'] != 1) {
@@ -483,7 +497,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
if ($mapping['is_required']) $inputClass .= ' required-input';
echo "<div class='grid-cell' style='flex: 0 0 150px;'>";
if ($mapping['data_type'] === 'SceltaMultipla') {
echo "<select class='custom-field dropdown-select $inputClass' data-column='manual_$manualIndex' data-field-id='{$mapping['field_id']}' data-selected-value='" . htmlspecialchars($fieldValue) . "' " . ($mapping['is_required'] ? 'required' : '') . ">";
echo "<select class='custom-field dropdown-select $inputClass' data-column='manual_$manualIndex' data-field-id='{$mapping['field_id']}' data-selected-value='" . htmlspecialchars($fieldValue) . "' " . ($mainFieldMapping['is_required'] ? 'required' : '') . ">";
echo "<option value=''>Seleziona...</option>";
echo "</select>";
} elseif ($mapping['data_type'] === 'DATE') {
@@ -498,15 +512,14 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$manualIndex++;
}
}
echo "<div class='grid-cell' style='flex: 0 0 200px;'></div>"; // AWB
echo "<div class='grid-cell' style='flex: 0 0 250px;'></div>"; // Tracking Info
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>"; // importreferencecode
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>"; // filename_import
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>"; // importdate
echo "<div class='grid-cell' style='flex: 0 0 200px;'></div>";
echo "<div class='grid-cell' style='flex: 0 0 250px;'></div>";
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
?>
</div>
<!-- Header della tabella -->
<div class="grid-row">
<div class="grid-header button-header" style="flex: 0 0 210px;">Actions</div>
<?php if ($mainFieldMapping): ?>
@@ -543,11 +556,14 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
?>
</div>
<!-- Righe della tabella -->
<?php foreach ($importedData as $index => $row): ?>
<div class="grid-row" data-id="<?= $row['iddatadb'] ?>">
<div class="grid-cell button-cell" style="flex: 0 0 210px; position: relative;">
<button type="button" class="export-lims-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" title="Export to LIMS" style="background: #eb0b0bff; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-upload"></i></button>
<!-- commented only for admin roles -->
<?php if ((Auth::user()->hasRole('Admin'))) : ?>
<button type="button" class="export-lims-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" title="Export to LIMS" style="background: #eb0b0bff; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-upload"></i></button>
<?php endif; ?>
<button type="button" class="save-btn action-btn" data-row="<?= $index ?>" title="Save" style="background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-save"></i></button>
<button type="button" class="photos-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" title="Photos" style="background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-camera"></i></button>
<button type="button" class="parts-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" title="Parts" style="background: #ffc107; color: white; border: none; border-radius: 5px; cursor: pointer;"><i class="fas fa-puzzle-piece"></i></button>
@@ -697,25 +713,224 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<script src="parts.js"></script>
<script src="tracking.js"></script>
<script>
$(document).on("click", ".export-lims-btn", function() {
let rowId = $(this).data("row");
let idDataDb = $(this).data("iddatadb");
$.ajax({
url: "export_to_lims.php",
method: "POST",
data: {
iddatadb: idDataDb
},
dataType: "json",
beforeSend: function() {
alert("Export started in background for row " + rowId);
},
success: function(response) {
if (response.success) {
alert(response.message);
} else {
alert("❌ Error: " + response.message);
}
},
error: function(xhr, status, error) {
alert("❌ AJAX error: " + error);
}
});
});
document.addEventListener("DOMContentLoaded", function() {
console.log("Page loaded, initializing event listeners");
const inputs = document.querySelectorAll(".cell-input, .dropdown-select, .carrier-select, .awb-input");
const unsavedDiv = document.getElementById("unsavedChanges");
const changedList = document.getElementById("changedFields");
let hasChanges = false;
let changedFields = {};
function renderChangedList() {
console.log("Rendering changed fields list:", changedFields);
changedList.innerHTML = "";
Object.keys(changedFields).forEach(rowIndex => {
const fields = changedFields[rowIndex];
if (fields.length > 0) {
const li = document.createElement("li");
li.textContent = `Row ${parseInt(rowIndex) + 1}: ${fields.join(", ")}`;
changedList.appendChild(li);
}
});
unsavedDiv.style.display = Object.keys(changedFields).length > 0 ? "block" : "none";
}
inputs.forEach(el => {
el.addEventListener("change", () => {
console.log("Input changed:", el.name);
hasChanges = true;
unsavedDiv.style.display = "block";
const gridCell = el.closest(".grid-cell");
const colIndex = gridCell?.dataset.index;
const rowIndex = gridCell?.dataset.row;
let label = "Unknown field";
if (colIndex) {
const header = document.querySelector(`.grid-header[data-index="${colIndex}"]`);
if (header) {
label = header.textContent.replace(":", "").trim();
}
}
if (rowIndex !== undefined) {
if (!changedFields[rowIndex]) {
changedFields[rowIndex] = [];
}
if (!changedFields[rowIndex].includes(label)) {
changedFields[rowIndex].push(label);
}
gridCell.classList.add("cell-changed");
}
renderChangedList();
});
});
document.querySelectorAll(".save-btn").forEach(btn => {
btn.addEventListener("click", () => {
hasChanges = false;
unsavedDiv.style.display = "none";
const rowIndex = btn.dataset.row;
console.log(`Saving row ${rowIndex}`);
const row = btn.closest('.grid-row');
const iddatadb = row.getAttribute('data-id');
const formData = new FormData();
const inputs = row.querySelectorAll(`input[name^="rows[${rowIndex}][details]"], select[name^="rows[${rowIndex}][details]"]`);
inputs.forEach(input => {
const matches = input.name.match(/rows\[\d+\]\[details\]\[(\d+)\]\[field_value\]/);
if (matches) {
const mappingId = matches[1];
formData.append(`details${mappingId}field_value`, input.value);
if (input.tagName === 'SELECT' && input.classList.contains('dropdown-select')) {
input.setAttribute('data-selected-value', input.value);
}
}
});
formData.append('iddatadb', iddatadb);
fetch('save_edited_row.php', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
})
.then(data => {
console.log("Save response:", data);
if (data.success) {
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);
if (changedFields[rowIndex]) {
delete changedFields[rowIndex];
document.querySelectorAll(`.grid-cell[data-row="${rowIndex}"]`)
.forEach(cell => cell.classList.remove("cell-changed"));
renderChangedList();
hasChanges = Object.keys(changedFields).length > 0;
}
alert('Salvataggio riga avvenuto con successo!');
} else {
alert('Errore durante il salvataggio: ' + data.message);
}
})
.catch(error => {
console.error("Save error:", error);
alert('Errore durante il salvataggio: ' + error.message);
});
});
});
document.querySelector('.save-all-btn').addEventListener('click', async () => {
console.log("Saving all rows");
const rows = document.querySelectorAll('.grid-row');
let successCount = 0;
let errorMessages = [];
for (const row of rows) {
const saveBtn = row.querySelector('.save-btn');
if (!saveBtn) {
console.warn(`No save button found in row with data-id: ${row.getAttribute('data-id')}`);
continue;
}
const rowIndex = saveBtn.dataset.row;
const iddatadb = row.getAttribute('data-id');
if (!rowIndex || !iddatadb) {
console.warn(`Missing rowIndex or iddatadb in row:`, row);
continue;
}
console.log(`Processing row ${rowIndex} with iddatadb ${iddatadb}`);
const formData = new FormData();
const inputs = row.querySelectorAll(`input[name^="rows[${rowIndex}][details]"], select[name^="rows[${rowIndex}][details]"]`);
inputs.forEach(input => {
const matches = input.name.match(/rows\[\d+\]\[details\]\[(\d+)\]\[field_value\]/);
if (matches) {
const mappingId = matches[1];
formData.append(`details${mappingId}field_value`, input.value);
if (input.tagName === 'SELECT' && input.classList.contains('dropdown-select')) {
input.setAttribute('data-selected-value', input.value);
}
}
});
formData.append('iddatadb', iddatadb);
try {
const response = await fetch('save_edited_row.php', {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log(`Row ${rowIndex} save response:`, data);
if (data.success) {
successCount++;
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);
if (changedFields[rowIndex]) {
delete changedFields[rowIndex];
document.querySelectorAll(`.grid-cell[data-row="${rowIndex}"]`)
.forEach(cell => cell.classList.remove("cell-changed"));
}
} else {
errorMessages.push(`Riga ${parseInt(rowIndex) + 1}: ${data.message}`);
}
} catch (error) {
console.error(`Row ${rowIndex} save error:`, error);
errorMessages.push(`Riga ${parseInt(rowIndex) + 1}: ${error.message}`);
}
}
renderChangedList();
hasChanges = Object.keys(changedFields).length > 0;
console.log(`Save all completed: ${successCount} successes, ${errorMessages.length} errors`);
if (errorMessages.length === 0) {
alert(`Tutte le ${successCount} righe salvate con successo!`);
} else {
alert(`Salvate ${successCount} righe con successo.\nErrori:\n${errorMessages.join('\n')}`);
}
});
window.addEventListener("beforeunload", function(e) {
if (hasChanges) {
e.preventDefault();
@@ -724,9 +939,9 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
});
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
console.log("Initializing cell expansion and propagation");
const inputs = document.querySelectorAll('.cell-input');
inputs.forEach(input => {
input.addEventListener('focus', function() {
@@ -737,48 +952,10 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
});
});
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();
const inputs = row.querySelectorAll(`input[name^="rows[${rowIndex}]"], select[name^="rows[${rowIndex}]"]`);
inputs.forEach(input => {
const name = input.name.replace(`rows[${rowIndex}]`, '').replace(/\[|\]/g, '');
formData.append(name, input.value);
});
formData.append('iddatadb', iddatadb);
formData.append('mapping', JSON.stringify(<?= json_encode($allMappings) ?>));
fetch('save_edited_row.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
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);
alert('Salvataggio avvenuto con successo!');
} else {
alert('Errore durante il salvataggio: ' + data.message);
}
})
.catch(error => alert('Errore durante il salvataggio: ' + error.message));
});
});
const propagateButtons = document.querySelectorAll('.propagate-btn');
propagateButtons.forEach(button => {
button.addEventListener('click', function() {
console.log("Propagating value for column:", this.getAttribute('data-column'));
const column = this.getAttribute('data-column');
const input = this.previousElementSibling;
const value = input.value;
@@ -797,6 +974,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
if (targetInput) {
targetInput.value = value;
if (targetInput.tagName === 'SELECT') {
targetInput.setAttribute('data-selected-value', value);
const event = new Event('change');
targetInput.dispatchEvent(event);
}
@@ -814,6 +992,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
let columnIndex = 0;
resizers.forEach(resizer => {
resizer.addEventListener('mousedown', function(e) {
console.log("Starting column resize");
currentResizer = resizer;
const header = resizer.parentElement;
columnIndex = header.getAttribute('data-index');
@@ -836,6 +1015,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
function stopResize() {
if (currentResizer) {
console.log("Stopping column resize");
document.removeEventListener('mousemove', resize);
document.removeEventListener('mouseup', stopResize);
currentResizer = null;
@@ -846,11 +1026,15 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
console.log("Initializing dropdown population");
const dropdownData = {};
async function populateDropdowns() {
const dropdowns = document.querySelectorAll('.dropdown-select');
if (dropdowns.length === 0) return;
if (dropdowns.length === 0) {
console.log("No dropdowns found");
return;
}
const uniqueFieldIds = [
...new Set(Array.from(dropdowns).map(d => d.getAttribute('data-field-id')))
@@ -859,31 +1043,34 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
const missingFieldIds = uniqueFieldIds.filter(fieldId => !dropdownData[fieldId]);
if (missingFieldIds.length > 0) {
console.log("Fetching dropdown data for field IDs:", missingFieldIds);
try {
const response = await fetch(
`get_customfield_values.php?field_ids=${missingFieldIds.join(",")}`
);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
if (data.error) {
console.error("Errore fetch multiplo:", data.error);
console.error("Fetch error:", data.error);
} else {
for (const fieldId of Object.keys(data)) {
dropdownData[fieldId] = data[fieldId] || [];
}
}
} catch (error) {
console.error("Errore generale nel fetch multiplo:", error);
console.error("Fetch error:", error);
}
}
dropdowns.forEach(dropdown => {
const fieldId = dropdown.getAttribute('data-field-id');
const selectedValue = dropdown.getAttribute('data-selected-value') || '';
const currentValue = dropdown.value; // Preserva il valore corrente
const currentValue = dropdown.value;
if (!fieldId || !dropdownData[fieldId]) {
dropdown.innerHTML = '<option value="">Errore nel caricamento</option>';
console.warn(`No data for fieldId ${fieldId}`);
return;
}
@@ -892,7 +1079,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
const option = document.createElement('option');
option.value = value.IdCustomFieldsValue;
option.textContent = value.Valore;
// Usa il valore corrente se disponibile, altrimenti usa data-selected-value
if (currentValue && currentValue === String(value.IdCustomFieldsValue)) {
option.selected = true;
} else if (!currentValue && selectedValue === String(value.IdCustomFieldsValue)) {
@@ -903,87 +1089,12 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
if ((currentValue || selectedValue) && dropdown.value !== (currentValue || selectedValue)) {
dropdown.value = '';
console.warn(`Valore ${currentValue || selectedValue} non trovato per fieldId ${fieldId}`);
console.warn(`Value ${currentValue || selectedValue} not found for fieldId ${fieldId}`);
}
});
}
// Chiama populateDropdowns solo al caricamento iniziale
populateDropdowns();
document.querySelectorAll('.save-btn').forEach(btn => {
btn.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();
const inputs = row.querySelectorAll(`input[name^="rows[${rowIndex}]"], select[name^="rows[${rowIndex}]"]`);
inputs.forEach(input => {
const name = input.name.replace(`rows[${rowIndex}]`, '').replace(/\[|\]/g, '');
formData.append(name, input.value);
// Aggiorna data-selected-value per i dropdown
if (input.tagName === 'SELECT' && input.classList.contains('dropdown-select')) {
input.setAttribute('data-selected-value', input.value);
}
});
formData.append('iddatadb', iddatadb);
formData.append('mapping', JSON.stringify(<?= json_encode($allMappings) ?>));
fetch('save_edited_row.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
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);
alert('Salvataggio avvenuto con successo!');
} else {
alert('Errore durante il salvataggio: ' + data.message);
}
})
.catch(error => alert('Errore durante il salvataggio: ' + error.message));
});
});
const propagateButtons = document.querySelectorAll('.propagate-btn');
propagateButtons.forEach(button => {
button.addEventListener('click', function() {
const column = this.getAttribute('data-column');
const input = this.previousElementSibling;
const value = input.value;
const gridTopCells = document.querySelector('.grid-top').querySelectorAll('.grid-cell');
const targetTopIndex = Array.from(gridTopCells).findIndex(cell =>
cell.querySelector('.propagate-btn[data-column="' + column + '"]')
);
if (targetTopIndex !== -1) {
const rows = document.querySelectorAll('.grid-row');
rows.forEach(row => {
const cells = row.querySelectorAll('.grid-cell');
if (cells.length > targetTopIndex) {
const targetInput = cells[targetTopIndex].querySelector('select.dropdown-select, input');
if (targetInput) {
targetInput.value = value;
if (targetInput.tagName === 'SELECT') {
targetInput.setAttribute('data-selected-value', value); // Aggiorna anche qui
const event = new Event('change');
targetInput.dispatchEvent(event);
}
}
}
});
}
});
});
});
</script>
</body>
+23 -6
View File
@@ -488,8 +488,13 @@ $(document).ready(function () {
mix: part.partDescription.startsWith("Mix") ? "Y" : "N",
}));
console.log(
"Dati inviati a renumber_parts.php:",
JSON.stringify({ iddatadb: iddatadb, parts: partsToSave }),
);
$.ajax({
url: "save_parts.php",
url: "renumber_parts.php",
method: "POST",
data: JSON.stringify({
iddatadb: iddatadb,
@@ -497,12 +502,17 @@ $(document).ready(function () {
}),
contentType: "application/json",
success: function (response) {
console.log("Risposta da renumber_parts.php:", response);
if (response.success) {
$rows.each(function (index) {
const $row = $(this);
if (response.part_ids && response.part_ids[index]) {
$row.attr("data-part-id", response.part_ids[index]);
$row.data("part-id", response.part_ids[index]);
const newPartId =
response.part_ids && response.part_ids[index]
? response.part_ids[index]
: $row.data("part-id");
if (newPartId) {
$row.attr("data-part-id", newPartId);
$row.data("part-id", newPartId);
}
const $saveStatus = $row.find(".save-status");
const $saveLoading = $row.find(".save-loading");
@@ -515,14 +525,21 @@ $(document).ready(function () {
updateDescriptions();
markUnsaved();
} else {
console.error("Errore dal server:", response.message);
alert(
"Errore nel salvataggio delle parti: " +
"Errore nella rinumerazione delle parti: " +
response.message,
);
}
},
error: function (xhr, status, error) {
alert("Errore nel salvataggio delle parti: " + error);
console.error("Errore AJAX:", status, error, xhr.responseText);
alert(
"Errore nella rinumerazione delle parti: " +
error +
" - " +
xhr.responseText,
);
},
});
}
+63
View File
@@ -0,0 +1,63 @@
<?php
header('Content-Type: application/json');
include('include/headscript.php');
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
$data = json_decode(file_get_contents('php://input'), true);
$iddatadb = $data['iddatadb'] ?? null;
$parts = $data['parts'] ?? [];
if (!$iddatadb || empty($parts)) {
echo json_encode(['success' => false, 'message' => 'Dati mancanti']);
exit;
}
try {
$pdo->beginTransaction();
// Elimina tutte le parti esistenti per l'iddatadb per evitare conflitti di unicità
$stmt = $pdo->prepare("DELETE FROM identification_parts WHERE iddatadb = :iddatadb");
$stmt->execute([':iddatadb' => $iddatadb]);
// Prepara l'inserimento delle nuove parti
$stmt = $pdo->prepare("
INSERT INTO identification_parts
(iddatadb, part_number, part_description, mix, created_at, updated_at)
VALUES (:iddatadb, :part_number, :part_description, :mix, NOW(), NOW())
");
$part_ids = [];
foreach ($parts as $part) {
$partNumber = $part['part_number'] ?? null;
$partDescription = $part['part_description'] ?? '';
$mix = $part['mix'] ?? 'N';
if (!$partNumber || !$partDescription) {
throw new PDOException("Numero parte o descrizione mancante per parte: " . json_encode($part));
}
$stmt->execute([
':iddatadb' => $iddatadb,
':part_number' => $partNumber,
':part_description' => $partDescription,
':mix' => $mix
]);
$part_ids[] = $pdo->lastInsertId();
}
$pdo->commit();
echo json_encode([
'success' => true,
'part_ids' => $part_ids,
'message' => 'Parti rinumerate con successo'
]);
} catch (PDOException $e) {
$pdo->rollBack();
echo json_encode([
'success' => false,
'message' => 'Errore nel salvataggio: ' . $e->getMessage()
]);
}