Compare commits

...

31 Commits

Author SHA1 Message Date
MGrigoryan 6ec0c2062e fix: Include single sample photo in save operation when no photos selected 2025-10-31 11:45:04 +04:00
MGrigoryan 03771e3ca8 feat: Add quotation modal and iddatadb update for quotation parts/images
- Add quotation modal for selecting quotation
- Load quotation parts and photos
- Update iddatadb with quotation parts and photo references
2025-10-31 11:26:11 +04:00
MGrigoryan f6ea17388c fix(partsTable, annotationsModal): correct table height and restore "Torna alle Parti"
- partsTable: reduce excessive height to prevent oversized rendering
- annotationsModal: fix "Torna alle Parti" button behavior to return to parts view
2025-10-30 10:26:46 +04:00
solocla 1c2b4ab7a6 Merge branch 'bugfix/part-creation-matrice-dropdown-fix' 2025-10-29 18:25:26 +01:00
MGrigoryan 31cb23b00e fix(partsTable): skip change handler when setting Select2 value programmatically
Pass skipHandler flag in change event data to prevent handler execution
during programmatic value updates.
2025-10-29 19:18:33 +04:00
MGrigoryan d29563d20d feat(partsTable): add image icon to show/hide photo button
- Add image icon alongside eye icon in show/hide photo button
- Improve visual indication of photo toggle functionality
2025-10-29 18:27:33 +04:00
solocla 82af925ac1 added size to line markers 2025-10-29 13:45:38 +01:00
solocla 5d8360dd87 marker with size 2025-10-29 12:32:09 +01:00
MGrigoryan 683073c244 fix(partsTable): initialize new item matrice as empty and refresh on global filter change
- Default new items' matrice to empty to prevent stale values leaking from prior state
- Force matrice update when the global filter changes to keep items in sync
2025-10-29 14:17:00 +04:00
solocla 8d6fe92481 fixed multiple parts mix and single line 2025-10-28 08:58:39 +01:00
solocla dbc66723a6 fixed color save 2025-10-27 15:53:12 +01:00
solocla 218fc14462 fixed country client and parts column matrice 2025-10-27 14:38:20 +01:00
solocla 29e4b41874 update export to lims 2025-10-11 20:19:43 +02:00
solocla eef9ae8d36 added note to export 2025-10-10 11:31:49 +02:00
solocla 68c867a3f4 change clienti to datadb and fixed column pages 2025-10-09 15:30:44 +02:00
solocla a9827e4e81 added note and date to identification parts 2025-10-08 17:34:21 +02:00
solocla b51936f784 various fixing modal 2025-10-07 20:56:57 +02:00
solocla 15b6f38e8b fixed matrici with db cron 2025-10-07 09:41:29 +02:00
solocla 12c6cc5f95 lazy load modal parts and matrici cron 2025-10-07 09:12:54 +02:00
solocla a0b12463c0 fixed for matrici 2025-10-03 08:52:37 +02:00
solocla 07ddcafd3f fixed nologin 2025-09-27 13:38:26 +02:00
solocla 7843d4b1fc added nologin 2025-09-27 13:37:37 +02:00
solocla 4eae855e23 added headscriptnologin 2025-09-27 13:36:26 +02:00
solocla c709f64a17 remove login smartphone 2025-09-27 13:33:23 +02:00
solocla d5f0690f59 background trasparent annotation 2025-09-27 13:28:21 +02:00
solocla 6bbd3fcae9 fixed get clienti with id, nominativo and country 2025-09-27 09:53:21 +02:00
solocla 9e19e9e1d4 fixed export to lims, fixed multiple upload, added calendar to Data 2025-09-27 09:44:00 +02:00
solocla 7caee9c994 prova 2025-09-26 11:27:33 +02:00
solocla f8320315f7 historical added commessaweb., edit added tested components 2025-09-26 09:28:49 +02:00
solocla 7397d86bc2 fixed template dashboard 2025-09-25 14:26:22 +02:00
solocla 2deb1f101a hide column and fixed edit template 2025-09-25 14:18:09 +02:00
36 changed files with 6353 additions and 280 deletions
File diff suppressed because it is too large Load Diff
+131
View File
@@ -0,0 +1,131 @@
<?php
require_once "class/VisualLimsApiClient.class.php";
include('include/headscript.php');
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
header("Content-Type: application/json");
// 🔹 Configura directory log (creala se non esiste)
$logDir = __DIR__ . '/logs/api/';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// 🔹 Base URL API
$apiBaseUrl = 'https://93.43.5.102/limsapi/api/odata/';
// 🔹 Hardcoded values
$iddatadb = 846;
$commessaId = 533357;
try {
// 🔹 STEP 4: Fetch Field Values with Labels (usa dati reali per iddatadb=845)
$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 = [];
$valueMap = []; // Mappa per field_id -> valore
foreach ($rows as $row) {
$fieldValues[] = [
"IdCommesseCustomFields" => (int) $row['field_id'],
"Valore" => $row['field_value'],
"FieldLabel" => $row['field_label']
];
$valueMap[(int) $row['field_id']] = $row['field_value']; // Mappa per ID definizione
}
// Logga i fieldValues in error_log
$logFieldValues = "FieldValues dal DB (iddatadb={$iddatadb}):\n" . json_encode($fieldValues, JSON_PRETTY_PRINT);
error_log($logFieldValues);
// 🔹 Initialize API client
$api = VisualLimsApiClient::getInstance();
// 🔹 STEP A: GET iniziale per CommesseCustomFields con espansione CustomField
$expand = "CommesseCustomFields(\$expand=CustomField)"; // Espansione come da istruzioni fornitore
$commessaWithFields = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand);
// 🔹 STEP B: Prepara payload PATCH (tutti i campi, sovrascrivi se match su CustomField.IdCustomField == field_id)
$commessaCustomFields = [];
foreach ($commessaWithFields["CommesseCustomFields"] as $customField) {
$definitionId = (int) ($customField["CustomField"]["IdCustomField"] ?? 0); // Usa IdCustomField dal CustomField
$currentValue = $customField["Valore"] ?? '';
$newValue = isset($valueMap[$definitionId]) ? $valueMap[$definitionId] : $currentValue;
$commessaCustomFields[] = [
"IdCommesseCustomFields" => (int) $customField["IdCommesseCustomFields"],
"Valore" => $newValue
];
}
// 🔹 Unico file di log per tutto
$logFile = $logDir . "commessa_{$commessaId}_patch_and_get_" . time() . ".txt";
$logContent = "FieldValues dal DB (iddatadb={$iddatadb}):\n" . json_encode($fieldValues, JSON_PRETTY_PRINT) . "\n\n";
// Log curl-like per GET iniziale
$logContent .= "GET iniziale:\n" .
"curl --location --request GET '{$apiBaseUrl}CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)' \\\n" .
"--header 'Authorization: Bearer ••••••'\n\n" .
"RESPONSE:\n" . json_encode($commessaWithFields, JSON_PRETTY_PRINT) . "\n\n---\n";
if (!empty($commessaCustomFields)) {
$updatePayload = ["CommesseCustomFields" => $commessaCustomFields];
// Log curl-like per PATCH
$jsonPayload = json_encode($updatePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$logContent .= "PATCH:\n" .
"curl --location --request PATCH '{$apiBaseUrl}CommessaWeb({$commessaId})' \\\n" .
"--header 'Content-Type: application/json' \\\n" .
"--header 'Authorization: Bearer ••••••' \\\n" .
"--data '{$jsonPayload}'\n\n";
$patchResponse = $api->patch("CommessaWeb({$commessaId})", $updatePayload);
$logContent .= "PATCH RESPONSE:\n" . json_encode($patchResponse, JSON_PRETTY_PRINT) . "\n\n---\n";
} else {
$logContent .= "PATCH: Nessun campo custom da aggiornare\n\n---\n";
}
// 🔹 STEP C: GET di controllo post-PATCH
$commessaAfterPatch = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand);
// Log curl-like per GET di controllo
$logContent .= "GET di controllo:\n" .
"curl --location --request GET '{$apiBaseUrl}CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)' \\\n" .
"--header 'Authorization: Bearer ••••••'\n\n" .
"RESPONSE:\n" . json_encode($commessaAfterPatch, JSON_PRETTY_PRINT);
// Salva log unico
file_put_contents($logFile, $logContent);
// 🔹 Output a schermo
echo json_encode([
"success" => true,
"message" => "PATCH eseguito su commessa {$commessaId} con dati da iddatadb {$iddatadb}",
"commessaAfterPatch" => $commessaAfterPatch,
"totalCustomFieldsUpdated" => count($commessaCustomFields),
"fieldValues" => $fieldValues,
"logFile" => $logFile
]);
} catch (Exception $e) {
error_log("Patch Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
echo json_encode([
"success" => false,
"message" => "Patch failed: " . $e->getMessage(),
"logFile" => $logFile ?? 'Nessun log generato'
]);
}
@@ -29,7 +29,7 @@ class VisualLimsApiClient
return self::$instance;
}
private function authenticate()
private function authenticate($retryCount = 0, $maxRetries = 3)
{
$ch = curl_init("{$this->baseUrl}/api/authentication/authenticate");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@@ -45,16 +45,22 @@ class VisualLimsApiClient
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$log = fopen(__DIR__ . '/curl_auth_debug.log', 'w') ?: fopen('php://stderr', 'w');
$log = fopen(__DIR__ . '/curl_auth_debug.log', 'a') ?: fopen('php://stderr', 'w');
curl_setopt($ch, CURLOPT_STDERR, $log);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
$log_message = date('Y-m-d H:i:s') . " - Auth attempt {$retryCount}: HTTP {$http_code}, Error: {$curl_error}, Response: " . substr($response, 0, 1000) . "\n";
fwrite($log, $log_message);
fclose($log);
curl_close($ch);
if ($response === false || $http_code != 200) {
if ($http_code === 400 && strpos($response, 'Cannot persist the object') !== false && $retryCount < $maxRetries) {
usleep(500000); // Ritardo di 500ms
return $this->authenticate($retryCount + 1, $maxRetries); // Riprova
}
throw new Exception("Autenticazione fallita: HTTP {$http_code}, Errore cURL: {$curl_error}, Risposta: " . substr($response, 0, 1000));
}
@@ -191,5 +197,4 @@ class VisualLimsApiClient
{
return $this->baseUrl;
}
}
@@ -0,0 +1,103 @@
<?php
require_once dirname(__DIR__, 3) . '/vendor/autoload.php'; // Risale a root/vendor/
require_once dirname(__FILE__) . '/../class/VisualLimsApiClient.class.php'; // In root/public/userarea/class/
use Dotenv\Dotenv;
// Debug: Log the path where we expect the .env file
$envPath = dirname(__DIR__, 3);
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - Expected .env path: ' . $envPath . PHP_EOL, FILE_APPEND);
// Carica il file .env dalla root del progetto
try {
$dotenv = Dotenv::createImmutable($envPath);
$dotenv->load();
} catch (Exception $e) {
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore caricamento .env: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
exit(1);
}
// Recupera le variabili d'ambiente
$dbHost = $_ENV['DB_HOST'];
$dbName = $_ENV['DB_DATABASE'];
$dbUser = $_ENV['DB_USERNAME'];
$dbPass = $_ENV['DB_PASSWORD'];
$dbPrefix = $_ENV['DB_PREFIX'];
// Debug: Log database connection details (excluding password)
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . " - DB Connection: host=$dbHost, dbname=$dbName, user=$dbUser, prefix=$dbPrefix" . PHP_EOL, FILE_APPEND);
// Connessione al database MySQL
try {
$pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore connessione DB: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
exit(1);
}
try {
$api = VisualLimsApiClient::getInstance();
// Endpoint per recuperare le Matrici
$endpoint = 'Matrice';
// (Opzionale) aggiungi parametri
$options = []; // es. ['$top' => 100]
// Debug: salva URL usato
$base_url = 'https://93.43.5.102/limsapi/api/odata/';
$query = http_build_query($options);
$full_url = $base_url . $endpoint . ($query ? '?' . $query : '');
file_put_contents(__DIR__ . '/last_url.txt', $full_url . PHP_EOL, FILE_APPEND);
// Chiamata API
$data = $api->get($endpoint, $options);
// Debug: Log the API response size
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - API response received, value count: ' . (isset($data['value']) ? count($data['value']) : 0) . PHP_EOL, FILE_APPEND);
// Salva il JSON in locale (opzionale, per debug)
file_put_contents(__DIR__ . '/matrici_response.json', json_encode($data, JSON_PRETTY_PRINT));
// Svuota la tabella (dump rapido)
$pdo->exec("TRUNCATE TABLE {$dbPrefix}matrici");
// Debug: Log after truncate
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - Table truncated: ' . $dbPrefix . 'matrici' . PHP_EOL, FILE_APPEND);
// Prepara l'insert
$stmt = $pdo->prepare("
INSERT INTO {$dbPrefix}matrici (
IdMatrice, NomeMatriceTraduzione, DescrizioneTraduzione, MacroMatrice, NomeMatrice, Descrizione
) VALUES (
:IdMatrice, :NomeMatriceTraduzione, :DescrizioneTraduzione, :MacroMatrice, :NomeMatrice, :Descrizione
)
");
// Inserisci i dati
$insertedRows = 0;
if (isset($data['value']) && is_array($data['value'])) {
foreach ($data['value'] as $item) {
$stmt->execute([
':IdMatrice' => $item['IdMatrice'],
':NomeMatriceTraduzione' => $item['NomeMatriceTraduzione'],
':DescrizioneTraduzione' => $item['DescrizioneTraduzione'] ?? null,
':MacroMatrice' => $item['MacroMatrice'] ?? null,
':NomeMatrice' => $item['NomeMatrice'],
':Descrizione' => $item['Descrizione'] ?? null,
]);
$insertedRows++;
// Debug: Log each inserted row
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - Inserted row with IdMatrice: ' . $item['IdMatrice'] . PHP_EOL, FILE_APPEND);
}
}
// Log successo
file_put_contents(__DIR__ . '/success_log.txt', date('Y-m-d H:i:s') . ' - Aggiornamento completato: ' . $insertedRows . ' record inseriti.' . PHP_EOL, FILE_APPEND);
} catch (Exception $e) {
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
exit(1);
}
exit(0); // Esci con successo per cron
File diff suppressed because one or more lines are too long
+25 -1
View File
@@ -48,7 +48,7 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<div class="page-content">
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">UpdateXLS Template</h5>
<h5 class="mb-0">Update XLS Template</h5>
</div>
<div class="card-body">
<p class="mb-2">Edit the following form in order to update the selected import XLS template</p>
@@ -99,6 +99,30 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<input type="text" name="target_table" class="form-control" value="<?php echo htmlspecialchars($template['target_table']); ?>" readonly required>
</div>
<div class="mb-3">
<label class="form-label">Button Size</label>
<select name="button_size" class="form-control">
<option value="small" <?php echo ($template['button_size'] ?? 'medium') === 'small' ? 'selected' : ''; ?>>Small</option>
<option value="medium" <?php echo ($template['button_size'] ?? 'medium') === 'medium' ? 'selected' : ''; ?>>Medium</option>
<option value="large" <?php echo ($template['button_size'] ?? 'medium') === 'large' ? 'selected' : ''; ?>>Large</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Button Background Color</label>
<input type="color" name="button_bg_color" class="form-control" value="<?php echo htmlspecialchars($template['button_bg_color'] ?? '#007bff'); ?>">
</div>
<div class="mb-3">
<label class="form-label">Button Text Color</label>
<input type="color" name="button_text_color" class="form-control" value="<?php echo htmlspecialchars($template['button_text_color'] ?? '#ffffff'); ?>">
</div>
<div class="mb-3">
<label class="form-label">Button Label</label>
<input type="text" name="button_label" class="form-control" value="<?php echo htmlspecialchars($template['button_label'] ?? 'Click Me'); ?>">
</div>
<div class="mb-3">
<label class="form-label">Select Client *</label>
<select name="client_id" id="clientSelect" class="form-control" required>
+140 -21
View File
@@ -7,20 +7,40 @@ $pdo = $dbHandler->getConnection();
header("Content-Type: application/json");
// 🔹 Configura directory log (creala se non esiste)
$logDir = __DIR__ . '/logs/api/';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// 🔹 Base URL API
$apiBaseUrl = 'https://93.43.5.102/limsapi/api/odata/';
// 🔹 Funzione per validare e convertire date
function validateDate($value)
{
// Prova a validare come data (accetta formati comuni)
$date = DateTime::createFromFormat('Y-m-d', $value) ?: DateTime::createFromFormat('Y-m-d H:i:s', $value);
if ($date) {
return $date->format('Y-m-d\TH:i:sP'); // Formato ISO 8601
}
return null; // Imposta null se non è una data valida
}
try {
$iddatadb = $_POST['iddatadb'] ?? null;
if (!$iddatadb) {
throw new Exception("Missing iddatadb");
}
// 🔹 STEP 1+2: Fetch Cliente ID + Schema ID
// 🔹 STEP 1+2: Fetch Cliente ID from datadb and Schema ID from excel_templates
$stmt = $pdo->prepare("
SELECT et.idclient AS clienteId, et.idschema AS schemaId
SELECT d.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);
@@ -56,13 +76,20 @@ try {
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$fieldValues = [];
$valueMap = [];
foreach ($rows as $row) {
$fieldValues[] = [
"IdCommesseCustomFields" => (int) $row['field_id'],
"Valore" => $row['field_value']
"Valore" => $row['field_value'],
"FieldLabel" => $row['field_label']
];
$valueMap[(int) $row['field_id']] = $row['field_value'];
}
// Logga i fieldValues in error_log
$logFieldValues = "FieldValues dal DB (iddatadb={$iddatadb}):\n" . json_encode($fieldValues, JSON_PRETTY_PRINT);
error_log($logFieldValues);
// 🔹 Initialize API client
$api = VisualLimsApiClient::getInstance();
@@ -73,14 +100,29 @@ try {
"Richiedente" => "Test Web Import",
"Descrizione" => "TEST CommessaWeb",
];
// Costruisci log curl-like per STEP 5
$jsonPayload = json_encode($commessaWebPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$logContentStep5 = "curl --location --request POST '{$apiBaseUrl}CommessaWeb' \\\n" .
"--header 'Content-Type: application/json' \\\n" .
"--header 'Authorization: Bearer ••••••' \\\n" .
"--data '{$jsonPayload}'";
$commessaWeb = $api->post("CommessaWeb", $commessaWebPayload);
$logContentStep5 .= "\n\nRESPONSE:\n" . json_encode($commessaWeb, JSON_PRETTY_PRINT);
// Salva log
$logFileStep5 = $logDir . "commessa_create_step5_" . $iddatadb . "_" . time() . ".txt";
file_put_contents($logFileStep5, $logContentStep5);
$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 = [];
$logContentStep6 = "";
foreach ($parts as $index => $part) {
$matriceId = (int) ($part["idmatrice"] ?? 0);
@@ -96,8 +138,18 @@ try {
"NoteWeb" => $part["part_description"] ?? ""
];
// Costruisci curl-like per questo campione
$jsonPayload = json_encode($campionePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$logContentStep6 .= "CAMPIONE #{$index}\n" .
"curl --location --request POST '{$apiBaseUrl}Campione' \\\n" .
"--header 'Content-Type: application/json' \\\n" .
"--header 'Authorization: Bearer ••••••' \\\n" .
"--data '{$jsonPayload}'\n\n";
$campione = $api->post("Campione", $campionePayload);
$logContentStep6 .= "RESPONSE:\n" . json_encode($campione, JSON_PRETTY_PRINT) . "\n\n---\n";
$campione["PartNumber"] = $part["part_number"] ?? "";
$campione["Material"] = $part["material"] ?? "";
$campione["Color"] = $part["color"] ?? "";
@@ -106,25 +158,58 @@ try {
$campioni[] = $campione;
}
// Salva log per STEP 6
$logFileStep6 = $logDir . "commessa_{$commessaId}_campioni_step6_" . time() . ".txt";
file_put_contents($logFileStep6, $logContentStep6);
// 🔹 STEP 7: Update Custom Fields for CommessaWeb
if (!empty($fieldValues)) {
$commessaWithFields = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=CommesseCustomFields");
// GET con espansione per CustomField
$expand = "CommesseCustomFields(\$expand=CustomField)";
$commessaWithFields = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand);
// Logga il GET
$logContentGet = "curl --location --request GET '{$apiBaseUrl}CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)' \\\n" .
"--header 'Authorization: Bearer ••••••'\n\n" .
"RESPONSE:\n" . json_encode($commessaWithFields, JSON_PRETTY_PRINT);
$logFileGet = $logDir . "commessa_{$commessaId}_get_step7_" . time() . ".txt";
file_put_contents($logFileGet, $logContentGet);
// Prepara payload PATCH
$commessaCustomFields = [];
foreach ($commessaWithFields["CommesseCustomFields"] as $customField) {
foreach ($fieldValues as $fieldValue) {
if ($customField["IdCommesseCustomFields"] == $fieldValue["IdCommesseCustomFields"]) {
$definitionId = (int) ($customField["CustomField"]["IdCustomField"] ?? 0);
$fieldId = (int) $customField["IdCommesseCustomFields"];
$currentValue = $customField["Valore"] ?? '';
$fieldType = $customField["CustomField"]["Tipo"] ?? '';
$newValue = isset($valueMap[$definitionId]) ? $valueMap[$definitionId] : $currentValue;
// Valida se il campo è di tipo Data
if ($fieldType === 'Data' && $newValue !== $currentValue) {
$newValue = validateDate($newValue);
}
$commessaCustomFields[] = [
"IdCommesseCustomFields" => $customField["IdCommesseCustomFields"],
"Valore" => $fieldValue["Valore"]
"IdCommesseCustomFields" => $fieldId,
"Valore" => $newValue
];
break;
}
}
}
if (!empty($commessaCustomFields)) {
$updatePayload = ["CommesseCustomFields" => $commessaCustomFields];
$api->patch("CommessaWeb({$commessaId})", $updatePayload);
// Logga payload e response
$jsonPayload = json_encode($updatePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$logContentStep7 = "curl --location --request PATCH '{$apiBaseUrl}CommessaWeb({$commessaId})' \\\n" .
"--header 'Content-Type: application/json' \\\n" .
"--header 'Authorization: Bearer ••••••' \\\n" .
"--data '{$jsonPayload}'";
$patchResponse = $api->patch("CommessaWeb({$commessaId})", $updatePayload);
$logContentStep7 .= "\n\nRESPONSE:\n" . json_encode($patchResponse, JSON_PRETTY_PRINT);
$logFileStep7 = $logDir . "commessa_{$commessaId}_update_step7_" . time() . ".txt";
file_put_contents($logFileStep7, $logContentStep7);
}
}
@@ -140,18 +225,40 @@ try {
'iddatadb' => $iddatadb
]);
// 🔹 STEP 9: Send CommessaWeb to laboratory
// 🔹 STEP 9: Send CommessaWeb to laboratory (commentato come richiesto)
/*
$sendResult = $api->post("CommessaWeb({$commessaId})/InviaCommessa", []);
// 🔹 STEP 10: Prepare final response
// Logga il POST
$logContentStep9 = "curl --location --request POST '{$apiBaseUrl}CommessaWeb({$commessaId})/InviaCommessa' \\\n" .
"--header 'Content-Type: application/json' \\\n" .
"--header 'Authorization: Bearer ••••••' \\\n" .
"--data '{}'\n\n" .
"RESPONSE:\n" . json_encode($sendResult, JSON_PRETTY_PRINT);
$logFileStep9 = $logDir . "commessa_{$commessaId}_send_step9_" . time() . ".txt";
file_put_contents($logFileStep9, $logContentStep9);
*/
// 🔹 STEP 10: GET di controllo post-PATCH
$expand = "CommesseCustomFields(\$expand=CustomField)";
$commessaAfterPatch = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand);
// Logga il GET di controllo
$logContentStep10 = "curl --location --request GET '{$apiBaseUrl}CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)' \\\n" .
"--header 'Authorization: Bearer ••••••'\n\n" .
"RESPONSE:\n" . json_encode($commessaAfterPatch, JSON_PRETTY_PRINT);
$logFileStep10 = $logDir . "commessa_{$commessaId}_get_step10_" . time() . ".txt";
file_put_contents($logFileStep10, $logContentStep10);
// 🔹 STEP 11: Prepare final response
$finalCommessa = [
"Cliente" => $clienteId,
"SchemaCustomField" => $schemaId,
"Richiedente" => $commessaWeb["Richiedente"] ?? "Web Import",
"Descrizione" => $commessaWeb["Descrizione"] ?? "",
"CommesseCustomFields" => $fieldValues,
"CommesseCustomFields" => $commessaAfterPatch["CommesseCustomFields"] ?? [],
"Campioni" => $campioni,
"Inviata" => 1
"Inviata" => 0 // Non inviato, come richiesto
];
echo json_encode([
@@ -159,14 +266,26 @@ try {
"commessaWeb" => $finalCommessa,
"commessaWebApiResponse" => $commessaWeb, // Incluso per debug
"totalCampioni" => count($campioni),
"totalCustomFields" => count($fieldValues),
"message" => "Export successful"
"totalCustomFields" => count($commessaAfterPatch["CommesseCustomFields"] ?? []),
"message" => "Export successful",
"logFiles" => [
"step5_create" => $logFileStep5,
"step6_campioni" => $logFileStep6,
"step7_patch" => $logFileStep7,
"step10_get" => $logFileStep10
]
]);
} catch (Exception $e) {
error_log("LIMS Export Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
echo json_encode([
"success" => false,
"message" => "Export failed: " . $e->getMessage()
"message" => "Export failed: " . $e->getMessage(),
"logFiles" => [
"step5_create" => $logFileStep5 ?? null,
"step6_campioni" => $logFileStep6 ?? null,
"step7_patch" => $logFileStep7 ?? null,
"step10_get" => $logFileStep10 ?? null
]
]);
}
+59 -9
View File
@@ -1,24 +1,74 @@
<?php
require_once dirname(__DIR__, 2) . '/vendor/autoload.php'; // Torna al livello di public per trovare vendor/
require_once dirname(__FILE__) . '/class/VisualLimsApiClient.class.php';
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
require_once __DIR__ . '/class/VisualLimsApiClient.class.php';
header('Content-Type: application/json');
// Disabilita la visualizzazione degli errori PHP per evitare output HTML
// Disable PHP error display
ini_set('display_errors', '0');
error_reporting(E_ALL);
try {
$api = VisualLimsApiClient::getInstance();
$data = $api->get("Cliente"); // Recupera i clienti
// Salva la risposta in un file per debug
file_put_contents(__DIR__ . '/clienti_response.json', json_encode($data));
// Parametri OData
$params = [
'$select' => 'IdCliente,Nominativo,CodiceNazioneFatturazione',
'$orderby' => 'Nominativo asc'
];
// Costruisce query string con encoding corretto
$queryString = http_build_query($params);
// Componi endpoint finale
$endpoint = "Cliente?$queryString";
// Funzione per eseguire la chiamata con retry
function makeApiRequest($api, $endpoint, $maxRetries = 3)
{
for ($retry = 0; $retry < $maxRetries; $retry++) {
try {
// Tenta la chiamata API
$data = $api->get($endpoint);
// Salva risposta per debug
file_put_contents(__DIR__ . '/clienti_response.json', json_encode($data, JSON_PRETTY_PRINT));
return $data;
} catch (Exception $e) {
$errorMessage = $e->getMessage();
// Controlla se l'errore è legato all'autenticazione (HTTP 400 con messaggio specifico)
if (strpos($errorMessage, 'HTTP 400') !== false && strpos($errorMessage, 'Cannot persist the object') !== false) {
// Forza il refresh del token
try {
// Assumi che VisualLimsApiClient abbia un metodo per il refresh del token
$api->refreshToken(); // Da implementare in VisualLimsApiClient se non esiste
error_log("Tentativo $retry: Refresh token eseguito per endpoint $endpoint");
} catch (Exception $refreshEx) {
error_log("Errore durante il refresh del token: " . $refreshEx->getMessage());
throw new Exception("Impossibile eseguire il refresh del token: " . $refreshEx->getMessage());
}
// Ritarda leggermente prima del retry
usleep(500000); // 500ms
continue;
}
// Altri errori non gestiti dal retry
throw $e;
}
}
throw new Exception("Massimo numero di tentativi raggiunto per $endpoint");
}
// Esegui la chiamata con retry
$data = makeApiRequest($api, $endpoint);
echo json_encode($data);
} catch (Exception $e) {
http_response_code(500);
echo json_encode([
'error' => $e->getMessage()
]);
$errorResponse = [
'error' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString()
];
error_log("Errore in get_clienti.php: " . json_encode($errorResponse));
echo json_encode($errorResponse);
}
+59
View File
@@ -0,0 +1,59 @@
<?php
require_once dirname(__DIR__, 2) . '/vendor/autoload.php'; // Risale a root/vendor/
use Dotenv\Dotenv;
// Set JSON header
header('Content-Type: application/json');
// Debug: Log the path where we expect the .env file
$envPath = dirname(__DIR__, 2);
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - Expected .env path: ' . $envPath . PHP_EOL, FILE_APPEND);
// Carica il file .env dalla root del progetto
try {
$dotenv = Dotenv::createImmutable($envPath);
$dotenv->load();
} catch (Exception $e) {
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore caricamento .env: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
echo json_encode(['success' => false, 'message' => 'Errore caricamento configurazione: ' . $e->getMessage()]);
exit(1);
}
// Recupera le variabili d'ambiente
$dbHost = $_ENV['DB_HOST'];
$dbName = $_ENV['DB_DATABASE'];
$dbUser = $_ENV['DB_USERNAME'];
$dbPass = $_ENV['DB_PASSWORD'];
$dbPrefix = $_ENV['DB_PREFIX'];
// Debug: Log database connection details (excluding password)
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . " - DB Connection: host=$dbHost, dbname=$dbName, user=$dbUser, prefix=$dbPrefix" . PHP_EOL, FILE_APPEND);
// Connessione al database MySQL
try {
$pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore connessione DB: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
echo json_encode(['success' => false, 'message' => 'Errore connessione al database: ' . $e->getMessage()]);
exit(1);
}
try {
// Query per recuperare i valori distinti di MacroMatrice, escludendo quelli che iniziano con '*' e ordinandoli
$query = "SELECT DISTINCT MacroMatrice FROM {$dbPrefix}matrici WHERE MacroMatrice IS NOT NULL AND MacroMatrice NOT LIKE '*%' ORDER BY MacroMatrice ASC";
$stmt = $pdo->prepare($query);
$stmt->execute();
$macroMatrici = $stmt->fetchAll(PDO::FETCH_COLUMN);
// Debug: Log del numero di MacroMatrice recuperate
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - Retrieved ' . count($macroMatrici) . ' MacroMatrice from database' . PHP_EOL, FILE_APPEND);
// Restituisci risposta JSON
echo json_encode(['success' => true, 'value' => $macroMatrici]);
} catch (PDOException $e) {
// Log errore e restituisci risposta di errore
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore nel recupero delle MacroMatrice: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
echo json_encode(['success' => false, 'message' => 'Errore nel recupero delle MacroMatrice: ' . $e->getMessage()]);
exit(1);
}
+59
View File
@@ -0,0 +1,59 @@
<?php
require_once dirname(__DIR__, 2) . '/vendor/autoload.php'; // Risale a root/vendor/
use Dotenv\Dotenv;
// Set JSON header
header('Content-Type: application/json');
// Debug: Log the path where we expect the .env file
$envPath = dirname(__DIR__, 2);
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - Expected .env path: ' . $envPath . PHP_EOL, FILE_APPEND);
// Carica il file .env dalla root del progetto
try {
$dotenv = Dotenv::createImmutable($envPath);
$dotenv->load();
} catch (Exception $e) {
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore caricamento .env: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
echo json_encode(['success' => false, 'message' => 'Errore caricamento configurazione: ' . $e->getMessage()]);
exit(1);
}
// Recupera le variabili d'ambiente
$dbHost = $_ENV['DB_HOST'];
$dbName = $_ENV['DB_DATABASE'];
$dbUser = $_ENV['DB_USERNAME'];
$dbPass = $_ENV['DB_PASSWORD'];
$dbPrefix = $_ENV['DB_PREFIX'];
// Debug: Log database connection details (excluding password)
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . " - DB Connection: host=$dbHost, dbname=$dbName, user=$dbUser, prefix=$dbPrefix" . PHP_EOL, FILE_APPEND);
// Connessione al database MySQL
try {
$pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore connessione DB: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
echo json_encode(['success' => false, 'message' => 'Errore connessione al database: ' . $e->getMessage()]);
exit(1);
}
try {
// Query per recuperare le matrici, includendo MacroMatrice, escludendo quelle che iniziano con '*' e ordinandole
$query = "SELECT IdMatrice, NomeMatrice, MacroMatrice FROM {$dbPrefix}matrici WHERE NomeMatrice NOT LIKE '*%' ORDER BY NomeMatrice ASC";
$stmt = $pdo->prepare($query);
$stmt->execute();
$matrici = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Debug: Log del numero di matrici recuperate
file_put_contents(__DIR__ . '/debug_log.txt', date('Y-m-d H:i:s') . ' - Retrieved ' . count($matrici) . ' matrices from database' . PHP_EOL, FILE_APPEND);
// Restituisci risposta JSON
echo json_encode(['success' => true, 'value' => $matrici]);
} catch (PDOException $e) {
// Log errore e restituisci risposta di errore
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - Errore nel recupero delle matrici: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
echo json_encode(['success' => false, 'message' => 'Errore nel recupero delle matrici: ' . $e->getMessage()]);
exit(1);
}
+1 -1
View File
@@ -9,7 +9,7 @@ error_reporting(E_ALL);
try {
$api = VisualLimsApiClient::getInstance();
$rapporto_id = 515081;
$rapporto_id = 533329;
// Costruzione manuale dell'endpoint con espansione annidata
$endpoint = "Rapporto($rapporto_id)?\$expand=CampioniDatiRapporto(\$expand=AnalisiDatiRapporto,CustomFieldsDatiRapporto)";
+34 -29
View File
@@ -662,6 +662,11 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
} else {
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
}
// Status (subito dopo main_field)
$fixedColumnsReduced = ['status'];
foreach ($fixedColumnsReduced as $col) {
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
}
// Campi automatici (escluso main_field)
$autoIndex = ($mainFieldMapping && !$mainFieldMapping['is_manual']) ? 1 : 0;
foreach ($allMappings as $mapping) {
@@ -712,11 +717,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$manualIndex++;
}
}
// Colonne status, Import Reference Code, filename_import
$fixedColumnsReduced = ['status'];
foreach ($fixedColumnsReduced as $col) {
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
}
// Colonne Import Reference Code, filename_import
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>"; // Import Reference Code
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>"; // filename_import
// AWB Number e Tracking Info
@@ -734,6 +735,12 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>" . htmlspecialchars($mainFieldMapping['field_label']) . "<div class='resizer'></div></div>";
$headerIndex++;
}
// Header per status (subito dopo main_field)
foreach ($fixedColumnsReduced as $col) {
$displayName = $slugMapping[$col] ?? $col;
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>$displayName<div class='resizer'></div></div>";
$headerIndex++;
}
// Header per campi automatici (escluso main_field)
foreach ($allMappings as $mapping) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1) {
@@ -748,12 +755,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$headerIndex++;
}
}
// Header per status, Import Reference Code, filename_import
foreach ($fixedColumnsReduced as $col) {
$displayName = $slugMapping[$col] ?? $col;
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>$displayName<div class='resizer'></div></div>";
$headerIndex++;
}
// Header per Import Reference Code, filename_import
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>Import Reference Code<div class='resizer'></div></div>";
$headerIndex++;
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>File<div class='resizer'></div></div>";
@@ -770,13 +772,11 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<div style="display: flex; gap: 5px; justify-content: center;">
<?php if (!$is_readonly): ?>
<button type="button" class="save-btn action-btn" data-row="<?= $index ?>" style="background: #28a745; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: pointer; flex: 1;"><i class="fas fa-save"></i></button>
<button type="button" class="photos-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" style="background: #007bff; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: pointer; flex: 1;"><i class="fas fa-camera"></i></button>
<button type="button" class="parts-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" style="background: #ffc107; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: pointer; flex: 1;"><i class="fas fa-puzzle-piece"></i></button>
<?php else: ?>
<button type="button" class="save-btn action-btn" data-row="<?= $index ?>" style="background: #ccc; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: not-allowed; flex: 1;" disabled><i class="fas fa-save"></i></button>
<button type="button" class="photos-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" style="background: #ccc; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: not-allowed; flex: 1;" disabled><i class="fas fa-camera"></i></button>
<button type="button" class="parts-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" style="background: #ccc; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: not-allowed; flex: 1;" disabled><i class="fas fa-puzzle-piece"></i></button>
<?php endif; ?>
<button type="button" class="photos-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" style="background: #007bff; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: pointer; flex: 1;"><i class="fas fa-camera"></i></button>
<button type="button" class="parts-btn action-btn" data-row="<?= $index ?>" data-iddatadb="<?= $row['iddatadb'] ?>" style="background: #ffc107; color: white; border: none; padding: 8px 12px; border-radius: 5px; cursor: pointer; flex: 1;"><i class="fas fa-puzzle-piece"></i></button>
</div>
</div>
<?php
@@ -806,6 +806,25 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo "</div>";
$cellIndex++;
}
// Status (subito dopo main_field)
$fixedColumnsReduced = ['status'];
foreach ($fixedColumnsReduced as $col) {
$value = $row[$col] ?? '';
echo "<div class='grid-cell editable-cell' data-col='$col' data-row='$index' data-index='$cellIndex' style='flex: 0 0 150px;'>";
if ($col === 'status') {
$badgeClass = $value === 'i' ? 'status-i' : ($value === 'P' ? 'status-P' : 'status-l');
$badgeText = $value === 'i' ? 'Imported' : ($value === 'P' ? 'Progress' : 'LIMS');
// Aggiungi il numero di commessaweb se lo status è 'l'
if ($value === 'l') {
$commessaWeb = isset($row['commessaweb']) ? htmlspecialchars($row['commessaweb']) : '';
$badgeText .= " ($commessaWeb)";
}
echo "<span class='status-badge $badgeClass'>" . htmlspecialchars($badgeText) . "</span>";
echo "<input type='hidden' name='rows[$index][$col]' value='" . htmlspecialchars($value ?? 'i') . "'>";
}
echo "</div>";
$cellIndex++;
}
// Campi automatici (escluso main_field)
$autoIndex = ($mainFieldMapping && !$mainFieldMapping['is_manual']) ? 1 : 0;
foreach ($allMappings as $mapping) {
@@ -863,20 +882,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$manualIndex++;
}
}
// Colonna status
$fixedColumnsReduced = ['status'];
foreach ($fixedColumnsReduced as $col) {
$value = $row[$col] ?? '';
echo "<div class='grid-cell editable-cell' data-col='$col' data-row='$index' data-index='$cellIndex' style='flex: 0 0 150px;'>";
if ($col === 'status') {
$badgeClass = $value === 'i' ? 'status-i' : ($value === 'P' ? 'status-P' : 'status-l');
$badgeText = $value === 'i' ? 'Imported' : ($value === 'P' ? 'Progress' : 'LIMS');
echo "<span class='status-badge $badgeClass'>" . htmlspecialchars($badgeText) . "</span>";
echo "<input type='hidden' name='rows[$index][$col]' value='" . htmlspecialchars($value ?? 'i') . "'>";
}
echo "</div>";
$cellIndex++;
}
// Colonne Import Reference Code e filename_import
echo "<div class='grid-cell' data-col='importreferencecode' data-row='$index' data-index='$cellIndex' style='flex: 0 0 150px;'>";
echo "<span>" . htmlspecialchars($row['importreferencecode']) . "</span>";
+525 -91
View File
@@ -1,17 +1,4 @@
<?php
// Abilita errori per debug
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/import_debug.log');
if (!file_exists(__DIR__ . '/import_debug.log')) {
file_put_contents(__DIR__ . '/import_debug.log', "Inizio importazione alle " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
}
// Log iniziale
error_log("Inizio importazione alle " . date('Y-m-d H:i:s'));
include('include/headscript.php');
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['template_id']) || !isset($_POST['selected_rows']) || !isset($_POST['filename'])) {
@@ -25,11 +12,6 @@ $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
error_log("Received Data - Template ID: $template_id, Selected Rows: " . json_encode($selected_rows));
error_log("Columns: " . json_encode($columns));
error_log("Rows: " . json_encode($rows));
// Recupera l'ID dell'utente loggato
$user_id = $iduserlogin ?? 1;
@@ -39,8 +21,8 @@ $pdo = $db->getConnection();
// Genera un UUID univoco per importreferencecode
$importReferenceCode = date('YmdHis') . '-' . uniqid();
// Recupera tutti i mapping dal template
$stmt = $pdo->prepare("SELECT id, excel_column, data_type, is_required, manual_default, is_manual, field_label, field_id, main_field FROM template_mapping WHERE template_id = ?");
// Recupera tutti i mapping dal template, includendo is_visible_import
$stmt = $pdo->prepare("SELECT id, excel_column, data_type, is_required, manual_default, is_manual, field_label, field_id, main_field, is_visible_import FROM template_mapping WHERE template_id = ?");
$stmt->execute([$template_id]);
$allMappings = $stmt->fetchAll(PDO::FETCH_ASSOC);
@@ -52,12 +34,18 @@ if (empty($allMappings)) {
// Trova il campo main_field
$mainFieldMapping = null;
foreach ($allMappings as $mapping) {
if ($mapping['main_field'] == 1) {
if ($mapping['main_field'] == 1 && $mapping['is_visible_import'] == 1) {
$mainFieldMapping = $mapping;
break;
}
}
// Recupera l'idclient di default dal template (se presente)
$template_stmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?");
$template_stmt->execute([$template_id]);
$template = $template_stmt->fetch(PDO::FETCH_ASSOC);
$default_idclient = $template['idclient'] ?? null;
$insertedIds = $_POST['inserted_ids'] ?? $_SESSION['inserted_ids'];
// Recupera i dati appena inseriti con i nomi degli utenti
@@ -97,6 +85,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<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" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
<style>
.cell-changed {
background-color: #fff3b0 !important;
@@ -415,6 +405,57 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
#exportResponseModal .modal-backdrop {
z-index: 1299 !important;
}
.add-part-btn {
padding: 2px 5px;
font-size: 10px;
line-height: 1;
border-radius: 3px;
}
.flatpickr-input {
cursor: pointer;
}
.client-input {
width: 100%;
box-sizing: border-box;
border: 1px solid #ced4da;
border-radius: 4px;
padding: 5px;
font-size: 14px;
color: #333;
}
.client-input:focus {
outline: none;
border-color: #80bdff;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}
.select2-container {
width: 100% !important;
}
.select2-dropdown-smaller {
font-size: 14px;
}
.select2-container--default .select2-selection--single {
height: 31px;
border: 1px solid #ced4da;
border-radius: 4px;
padding: 5px;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 20px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
height: 31px;
}
</style>
<title>Edit Imported Data - <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
</head>
@@ -453,7 +494,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<div class="grid-cell" style="flex: 0 0 150px;">
<?php
$fieldValue = $mainFieldMapping['manual_default'] ?? '';
if ($mainFieldMapping['data_type'] === 'DATE' && $mainFieldMapping['manual_default'] === 'today') {
if ($mainFieldMapping['data_type'] === 'Data' && $mainFieldMapping['manual_default'] === 'today') {
$fieldValue = date('Y-m-d');
}
$inputClass = $mainFieldMapping['is_manual'] ? 'manual-input' : 'auto-input';
@@ -463,8 +504,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo "<option value=''>Seleziona...</option>";
echo "</select>";
echo "<button type='button' class='propagate-btn' data-column='main_field'><i class='fas fa-arrow-down'></i></button>";
} elseif ($mainFieldMapping['data_type'] === 'DATE') {
echo "<input type='date' class='custom-field $inputClass' data-column='main_field' value='" . htmlspecialchars($fieldValue) . "' " . ($mainFieldMapping['is_required'] ? 'required' : '') . ">";
} elseif ($mainFieldMapping['data_type'] === 'Data') {
echo "<input type='text' class='custom-field date-picker $inputClass' data-column='main_field' value='" . htmlspecialchars($fieldValue) . "' " . ($mainFieldMapping['is_required'] ? 'required' : '') . ">";
echo "<button type='button' class='propagate-btn' data-column='main_field'><i class='fas fa-arrow-down'></i></button>";
} elseif ($mainFieldMapping['data_type'] === 'INT') {
echo "<input type='number' class='custom-field $inputClass' data-column='main_field' value='" . htmlspecialchars($fieldValue) . "' " . ($mainFieldMapping['is_required'] ? 'required' : '') . ">";
@@ -476,11 +517,18 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
?>
</div>
<?php endif; ?>
<div class="grid-cell" style="flex: 0 0 300px;">
<select class="custom-field dropdown-select client-select searchable-client" data-column="idclient" id="clientSelect" name="idclient">
<option value="">Select a client...</option>
</select>
<button type="button" class="propagate-btn" data-column="idclient"><i class="fas fa-arrow-down"></i></button>
<span id="clientLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Recupero clienti in corso...</span>
</div>
<div class="grid-cell" style="flex: 0 0 150px;"></div>
<?php
$autoIndex = 0;
foreach ($allMappings as $mapping) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) {
$inputClass = 'auto-input';
if ($mapping['is_required']) $inputClass .= ' required-input';
if ($mapping['data_type'] === 'SceltaMultipla') {
@@ -498,20 +546,20 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
}
$manualIndex = 0;
foreach ($allMappings as $mapping) {
if ($mapping['is_manual'] && $mapping['main_field'] != 1) {
if ($mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) {
$fieldValue = $mapping['manual_default'] ?? '';
if ($mapping['data_type'] === 'DATE' && $mapping['manual_default'] === 'today') {
if ($mapping['data_type'] === 'Data' && $mapping['manual_default'] === 'today') {
$fieldValue = date('Y-m-d');
}
$inputClass = 'manual-input';
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) . "' " . ($mainFieldMapping['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) . "' " . ($mapping['is_required'] ? 'required' : '') . ">";
echo "<option value=''>Seleziona...</option>";
echo "</select>";
} elseif ($mapping['data_type'] === 'DATE') {
echo "<input type='date' class='custom-field $inputClass' data-column='manual_$manualIndex' value='" . htmlspecialchars($fieldValue) . "' " . ($mapping['is_required'] ? 'required' : '') . ">";
} elseif ($mapping['data_type'] === 'Data') {
echo "<input type='text' class='custom-field date-picker $inputClass' data-column='manual_$manualIndex' value='" . htmlspecialchars($fieldValue) . "' " . ($mapping['is_required'] ? 'required' : '') . ">";
} elseif ($mapping['data_type'] === 'INT') {
echo "<input type='number' class='custom-field $inputClass' data-column='manual_$manualIndex' value='" . htmlspecialchars($fieldValue) . "' " . ($mapping['is_required'] ? 'required' : '') . ">";
} else {
@@ -522,6 +570,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$manualIndex++;
}
}
// Aggiunta per Tested Component (senza propagate)
echo "<div class='grid-cell' style='flex: 0 0 150px;'></div>";
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>";
@@ -538,22 +588,27 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<div class="resizer"></div>
</div>
<?php endif; ?>
<div class="grid-header" data-index="<?= $mainFieldMapping ? 2 : 1 ?>" style="flex: 0 0 150px; position: relative;">Status<div class="resizer"></div>
<div class="grid-header" data-index="<?= $mainFieldMapping ? 2 : 1 ?>" style="flex: 0 0 300px; position: relative;">Client<div class="resizer"></div>
</div>
<div class="grid-header" data-index="<?= $mainFieldMapping ? 3 : 2 ?>" style="flex: 0 0 150px; position: relative;">Status<div class="resizer"></div>
</div>
<?php
$headerIndex = $mainFieldMapping ? 3 : 2;
$headerIndex = $mainFieldMapping ? 4 : 3;
foreach ($allMappings as $mapping) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) {
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>" . htmlspecialchars($mapping['field_label']) . "<div class='resizer'></div></div>";
$headerIndex++;
}
}
foreach ($allMappings as $mapping) {
if ($mapping['is_manual'] && $mapping['main_field'] != 1) {
if ($mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) {
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>" . htmlspecialchars($mapping['field_label']) . "<div class='resizer'></div></div>";
$headerIndex++;
}
}
// Aggiunta header per Tested Component
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 150px; position: relative;'>Tested Component<div class='resizer'></div></div>";
$headerIndex++;
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 200px; position: relative;'>AWB Number<div class='resizer'></div></div>";
$headerIndex++;
echo "<div class='grid-header' data-index='$headerIndex' style='flex: 0 0 250px; position: relative;'>Tracking Info<div class='resizer'></div></div>";
@@ -583,7 +638,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$detail = array_filter($manualDetails, fn($d) => $d['mapping_id'] == $mainFieldMapping['id'] && $d['datadb_id'] == $row['iddatadb']);
$detail = reset($detail) ?: ['field_value' => $mainFieldMapping['manual_default']];
$fieldValue = $detail['field_value'] ?? $mainFieldMapping['manual_default'] ?? '';
if ($mainFieldMapping['data_type'] === 'DATE' && $mainFieldMapping['manual_default'] === 'today' && empty($fieldValue)) {
if ($mainFieldMapping['data_type'] === 'Data' && $mainFieldMapping['manual_default'] === 'today' && empty($fieldValue)) {
$fieldValue = date('Y-m-d');
}
$requiredClass = ($mainFieldMapping['is_required'] && (is_null($fieldValue) || $fieldValue === '')) ? 'missing-required' : '';
@@ -595,8 +650,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<select name="rows[<?= $index ?>][details][<?= $mainFieldMapping['id'] ?>][field_value]" class="cell-input dropdown-select <?= $inputClass ?>" data-mapping-id="<?= $mainFieldMapping['id'] ?>" data-field-id="<?= $mainFieldMapping['field_id'] ?>" data-selected-value="<?= htmlspecialchars($fieldValue) ?>" <?= $mainFieldMapping['is_required'] ? 'required' : '' ?>>
<option value="">Seleziona...</option>
</select>
<?php elseif ($mainFieldMapping['data_type'] === 'DATE'): ?>
<input type="date" name="rows[<?= $index ?>][details][<?= $mainFieldMapping['id'] ?>][field_value]" value="<?= htmlspecialchars($fieldValue) ?>" class="cell-input <?= $inputClass ?>" <?= $mainFieldMapping['is_required'] ? 'required' : '' ?>>
<?php elseif ($mainFieldMapping['data_type'] === 'Data'): ?>
<input type="text" name="rows[<?= $index ?>][details][<?= $mainFieldMapping['id'] ?>][field_value]" value="<?= htmlspecialchars($fieldValue) ?>" class="cell-input date-picker <?= $inputClass ?>" <?= $mainFieldMapping['is_required'] ? 'required' : '' ?>>
<?php elseif ($mainFieldMapping['data_type'] === 'INT'): ?>
<input type="number" name="rows[<?= $index ?>][details][<?= $mainFieldMapping['id'] ?>][field_value]" value="<?= htmlspecialchars($fieldValue) ?>" class="cell-input <?= $inputClass ?>" <?= $mainFieldMapping['is_required'] ? 'required' : '' ?>>
<?php else: ?>
@@ -604,18 +659,23 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<?php endif; ?>
</div>
<?php endif; ?>
<div class="grid-cell editable-cell" data-col="status" data-row="<?= $index ?>" data-index="<?= $mainFieldMapping ? 2 : 1 ?>" style="flex: 0 0 150px;">
<div class="grid-cell editable-cell" data-col="idclient" data-row="<?= $index ?>" data-index="<?= $mainFieldMapping ? 2 : 1 ?>" style="flex: 0 0 300px;">
<select name="rows[<?= $index ?>][idclient]" class="cell-input dropdown-select client-select searchable-client" data-current-value="<?= htmlspecialchars($row['idclient'] ?? $default_idclient) ?>">
<option value="">Select a client...</option>
</select>
</div>
<div class="grid-cell editable-cell" data-col="status" data-row="<?= $index ?>" data-index="<?= $mainFieldMapping ? 3 : 2 ?>" style="flex: 0 0 150px;">
<span class="status-badge status-<?= htmlspecialchars($row['status'] ?? 'i') ?>">
<?= htmlspecialchars($row['status'] === 'i' ? 'Imported' : ($row['status'] === 'P' ? 'In Progress' : 'To LIMS')) ?>
</span>
<input type="hidden" name="rows[<?= $index ?>][status]" value="<?= htmlspecialchars($row['status'] ?? 'i') ?>">
</div>
<?php
$cellIndex = $mainFieldMapping ? 3 : 2;
$cellIndex = $mainFieldMapping ? 4 : 3;
$rowDetails = array_filter($manualDetails, fn($d) => $d['datadb_id'] == $row['iddatadb']);
$autoIndex = 0;
foreach ($allMappings as $mapping) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1) {
if (!$mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) {
$detail = array_filter($rowDetails, fn($d) => $d['mapping_id'] == $mapping['id']);
$detail = reset($detail) ?: ['field_value' => $mapping['manual_default']];
$fieldValue = $detail['field_value'] ?? $mapping['manual_default'] ?? '';
@@ -627,8 +687,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo "<select name='rows[$index][details][{$mapping['id']}][field_value]' class='cell-input dropdown-select $inputClass' data-mapping-id='{$mapping['id']}' data-field-id='{$mapping['field_id']}' data-selected-value='" . htmlspecialchars($fieldValue) . "' " . ($mapping['is_required'] ? 'required' : '') . ">";
echo "<option value=''>Seleziona...</option>";
echo "</select>";
} elseif ($mapping['data_type'] === 'DATE') {
echo "<input type='date' name='rows[$index][details][{$mapping['id']}][field_value]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input $inputClass' " . ($mapping['is_required'] ? 'required' : '') . ">";
} elseif ($mapping['data_type'] === 'Data') {
echo "<input type='text' name='rows[$index][details][{$mapping['id']}][field_value]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input date-picker $inputClass' " . ($mapping['is_required'] ? 'required' : '') . ">";
} elseif ($mapping['data_type'] === 'INT') {
echo "<input type='number' name='rows[$index][details][{$mapping['id']}][field_value]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input $inputClass' " . ($mapping['is_required'] ? 'required' : '') . ">";
} else {
@@ -641,11 +701,11 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
}
$manualIndex = 0;
foreach ($allMappings as $mapping) {
if ($mapping['is_manual'] && $mapping['main_field'] != 1) {
if ($mapping['is_manual'] && $mapping['main_field'] != 1 && $mapping['is_visible_import'] == 1) {
$detail = array_filter($rowDetails, fn($d) => $d['mapping_id'] == $mapping['id']);
$detail = reset($detail) ?: ['field_value' => $mapping['manual_default']];
$fieldValue = $detail['field_value'] ?? $mapping['manual_default'] ?? '';
if ($mapping['data_type'] === 'DATE' && $mapping['manual_default'] === 'today' && empty($fieldValue)) {
if ($mapping['data_type'] === 'Data' && $mapping['manual_default'] === 'today' && empty($fieldValue)) {
$fieldValue = date('Y-m-d');
}
$requiredClass = ($mapping['is_required'] && (is_null($fieldValue) || $fieldValue === '')) ? 'missing-required' : '';
@@ -656,8 +716,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo "<select name='rows[$index][details][{$mapping['id']}][field_value]' class='cell-input dropdown-select $inputClass' data-mapping-id='{$mapping['id']}' data-field-id='{$mapping['field_id']}' data-selected-value='" . htmlspecialchars($fieldValue) . "' " . ($mapping['is_required'] ? 'required' : '') . ">";
echo "<option value=''>Seleziona...</option>";
echo "</select>";
} elseif ($mapping['data_type'] === 'DATE') {
echo "<input type='date' name='rows[$index][details][{$mapping['id']}][field_value]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input $inputClass' " . ($mapping['is_required'] ? 'required' : '') . ">";
} elseif ($mapping['data_type'] === 'Data') {
echo "<input type='text' name='rows[$index][details][{$mapping['id']}][field_value]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input date-picker $inputClass' " . ($mapping['is_required'] ? 'required' : '') . ">";
} elseif ($mapping['data_type'] === 'INT') {
echo "<input type='number' name='rows[$index][details][{$mapping['id']}][field_value]' value='" . htmlspecialchars($fieldValue) . "' class='cell-input $inputClass' " . ($mapping['is_required'] ? 'required' : '') . ">";
} else {
@@ -668,6 +728,12 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$manualIndex++;
}
}
// Aggiunta cella per Tested Component
echo "<div class='grid-cell editable-cell' data-col='tested_component' data-row='$index' data-index='$cellIndex' style='flex: 0 0 150px; display: flex; align-items: center;'>";
echo "<input type='text' name='rows[$index][tested_component]' value='' class='cell-input manual-input' style='flex: 1; margin-right: 5px;'>";
echo "<button type='button' class='add-part-btn btn btn-sm btn-primary' data-row='$index'><i class='fas fa-plus'></i></button>";
echo "</div>";
$cellIndex++;
?>
<div class="grid-cell" style="flex: 0 0 200px;">
<select name="rows[<?= $index ?>][carrier]" class="carrier-select">
@@ -706,7 +772,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<?php endforeach; ?>
</div>
</form>
<?php include 'modal_parts.php'; ?>
<div id="partsModalContainer"></div>
<div id="annotationsModalContainer"></div>
<?php include 'photos_functions.php'; ?>
</div>
</div>
@@ -719,11 +786,31 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
<?php include('jsinclude.php'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="photos.js"></script>
<script src="parts.js"></script>
<script src="annotationsModal.js"></script>
<script src="partsTable.js"></script>
<script src="tracking.js"></script>
<script src="export_to_lims.js"></script>
<script>
// Initialize Flatpickr for all date inputs
document.addEventListener("DOMContentLoaded", function() {
flatpickr(".date-picker", {
dateFormat: "Y-m-d",
allowInput: true,
onOpen: function(selectedDates, dateStr, instance) {
instance.input.closest('.grid-cell').classList.add('expanded');
},
onClose: function(selectedDates, dateStr, instance) {
instance.input.closest('.grid-cell').classList.remove('expanded');
// Trigger change event to handle unsaved changes
const event = new Event('change');
instance.input.dispatchEvent(event);
}
});
});
$(document).on("click", ".export-lims-btn", function() {
let rowId = $(this).data("row");
let idDataDb = $(this).data("iddatadb");
@@ -752,16 +839,13 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
});
document.addEventListener("DOMContentLoaded", function() {
console.log("Page loaded, initializing event listeners");
const inputs = document.querySelectorAll(".cell-input, .dropdown-select, .carrier-select, .awb-input");
const inputs = document.querySelectorAll(".cell-input, .dropdown-select, .carrier-select, .awb-input, .date-picker");
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];
@@ -776,7 +860,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
inputs.forEach(el => {
el.addEventListener("change", () => {
console.log("Input changed:", el.name);
hasChanges = true;
const gridCell = el.closest(".grid-cell");
const colIndex = gridCell?.dataset.index;
@@ -807,7 +890,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
document.querySelectorAll(".save-btn").forEach(btn => {
btn.addEventListener("click", () => {
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();
@@ -818,11 +900,16 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
if (matches) {
const mappingId = matches[1];
formData.append(`details${mappingId}field_value`, input.value);
if (input.tagName === 'SELECT' && input.classList.contains('dropdown-select')) {
if (input.tagName === 'SELECT') {
input.setAttribute('data-selected-value', input.value);
}
}
});
const idclientSelect = row.querySelector(`select[name="rows[${rowIndex}][idclient]"]`);
if (idclientSelect) {
formData.append('idclient', idclientSelect.value);
}
formData.append('iddatadb', iddatadb);
fetch('save_edited_row.php', {
@@ -834,7 +921,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
return response.json();
})
.then(data => {
console.log("Save response:", data);
if (data.success) {
const cells = row.querySelectorAll('.grid-cell');
cells.forEach(cell => {
@@ -858,14 +944,12 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
}
})
.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 = [];
@@ -873,16 +957,13 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
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]"]`);
@@ -896,6 +977,11 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
}
}
});
const idclientSelect = row.querySelector(`select[name="rows[${rowIndex}][idclient]"]`);
if (idclientSelect) {
formData.append('idclient', idclientSelect.value);
}
formData.append('iddatadb', iddatadb);
try {
@@ -906,7 +992,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
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');
@@ -926,14 +1011,12 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
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!`);
@@ -942,8 +1025,6 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
}
});
window.addEventListener("beforeunload", function(e) {
if (hasChanges) {
e.preventDefault();
@@ -955,10 +1036,8 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
// Gestisci la chiusura dei modali per rimuovere i backdrop
document.querySelectorAll('#exportConfirmModal, #exportResponseModal').forEach(modal => {
modal.addEventListener('hidden.bs.modal', () => {
console.log(`Modal ${modal.id} closed, removing backdrops`);
// Rimuovi tutti i backdrop residui
document.querySelectorAll('.modal-backdrop').forEach(backdrop => {
console.log('Removing backdrop:', backdrop);
backdrop.remove();
});
// Ripristina il body
@@ -974,8 +1053,91 @@ 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');
let clientData = []; // Dichiarazione di clientData qui
// Funzione per caricare i client
async function loadClients(retryCount = 0, maxRetries = 3) {
const clientLoadingStatus = document.getElementById("clientLoadingStatus");
try {
clientLoadingStatus.style.display = 'inline';
clientLoadingStatus.textContent = 'Recupero clienti in corso...';
const response = await fetch("get_clienti.php", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
const data = await response.json();
if (!response.ok) {
if (response.status === 500 && data.error.includes('Cannot persist the object') && retryCount < maxRetries) {
console.log(`Tentativo ${retryCount + 1}/${maxRetries}: Riprovo a caricare i clienti...`);
await new Promise(resolve => setTimeout(resolve, 1000));
return loadClients(retryCount + 1, maxRetries);
}
throw new Error(data.error || `Errore HTTP: ${response.status}`);
}
clientData = data.value || [];
const select = document.getElementById("clientSelect");
select.innerHTML = '<option value="">Select a client...</option>';
clientData.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile";
const id = client.IdCliente || "ID non disponibile";
const option = new Option(`${nome.trim()} - ${client.CodiceNazioneFatturazione} (ID: ${id})`, id);
if (parseInt(id) === parseInt(<?php echo json_encode($default_idclient ?? 0); ?>)) {
option.selected = true;
}
select.add(option);
});
populateClientDropdowns();
clientLoadingStatus.textContent = "Clienti caricati.";
} catch (error) {
clientLoadingStatus.textContent = "Errore nel caricamento.";
console.error("Errore nel caricamento dei client:", error);
Swal.fire({
title: "Errore!",
text: "Impossibile caricare i clienti: " + error.message,
icon: "error",
confirmButtonText: "OK"
});
} finally {
setTimeout(() => clientLoadingStatus.style.display = 'none', 2000);
}
}
// Funzione per popolare i dropdown dei client
function populateClientDropdowns() {
const clientDropdowns = document.querySelectorAll('select[name^="rows"][name$="[idclient]"]');
clientDropdowns.forEach(dropdown => {
const currentValue = dropdown.getAttribute('data-current-value') || '';
dropdown.innerHTML = '<option value="">Select a client...</option>';
clientData.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile";
const id = client.IdCliente || "ID non disponibile";
const option = new Option(`${nome.trim()} - ${client.CodiceNazioneFatturazione} (ID: ${id})`, id);
if (String(id) === String(currentValue)) {
option.selected = true;
}
dropdown.add(option);
});
// Ripristina il valore corrente
if (currentValue) {
dropdown.value = currentValue;
const event = new Event('change', {
bubbles: true
});
dropdown.dispatchEvent(event);
}
});
}
// Carica i client all'avvio
loadClients();
// Gestione degli input
inputs.forEach(input => {
input.addEventListener('focus', function() {
this.closest('.grid-cell').classList.add('expanded');
@@ -985,32 +1147,60 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
});
});
// Gestione della propagazione
const propagateButtons = document.querySelectorAll('.propagate-btn');
propagateButtons.forEach(button => {
button.addEventListener('click', function() {
console.log("Propagating value for column:", this.getAttribute('data-column'));
button.addEventListener('click', async function() {
const column = this.getAttribute('data-column');
const input = this.previousElementSibling;
const value = input.value;
const value = input.tagName === 'SELECT' ? input.value : input.value;
console.log('Propagate clicked for column:', column, 'with value:', value); // Debug
// Assicurati che i dropdown dei client siano popolati
if (column === 'idclient' && clientData.length === 0) {
await loadClients(); // Carica i client se non ancora caricati
}
const gridTopCells = document.querySelector('.grid-top').querySelectorAll('.grid-cell');
const targetTopIndex = Array.from(gridTopCells).findIndex(cell =>
cell.querySelector('.propagate-btn[data-column="' + column + '"]')
);
console.log('Target index found:', targetTopIndex); // Debug
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('input, select');
const targetInput = cells[targetTopIndex].querySelector('select, input');
if (targetInput) {
targetInput.value = value;
console.log('Setting value on target input:', targetInput, 'with value:', value); // Debug
if (targetInput.tagName === 'SELECT') {
targetInput.setAttribute('data-selected-value', value);
const event = new Event('change');
targetInput.value = value;
const event = new Event('change', {
bubbles: true
});
targetInput.dispatchEvent(event);
} else if (targetInput.classList.contains('date-picker')) {
const flatpickrInstance = targetInput._flatpickr;
if (flatpickrInstance && value) {
flatpickrInstance.setDate(value, true);
}
const event = new Event('change', {
bubbles: true
});
targetInput.dispatchEvent(event);
} else {
targetInput.value = value;
const event = new Event('change', {
bubbles: true
});
targetInput.dispatchEvent(event);
}
} else {
console.warn('No target input found in cell'); // Debug
}
}
});
@@ -1018,6 +1208,7 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
});
});
// Gestione del ridimensionamento delle colonne
const resizers = document.querySelectorAll('.resizer');
let currentResizer = null;
let startX = 0;
@@ -1025,7 +1216,6 @@ 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');
@@ -1048,7 +1238,6 @@ 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;
@@ -1059,13 +1248,11 @@ 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');
const dropdowns = document.querySelectorAll('.dropdown-select:not(.client-select)');
if (dropdowns.length === 0) {
console.log("No dropdowns found");
return;
}
@@ -1076,7 +1263,6 @@ 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(",")}`
@@ -1084,26 +1270,23 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
if (data.error) {
console.error("Fetch error:", data.error);
} else {
if (data.error) {} else {
for (const fieldId of Object.keys(data)) {
dropdownData[fieldId] = data[fieldId] || [];
}
}
} catch (error) {
console.error("Fetch error:", error);
console.error('Errore nel caricamento dei valori per dropdown:', error);
}
}
dropdowns.forEach(dropdown => {
const fieldId = dropdown.getAttribute('data-field-id');
const selectedValue = dropdown.getAttribute('data-selected-value') || '';
const currentValue = dropdown.value;
const currentValue = dropdown.value || '';
if (!fieldId || !dropdownData[fieldId]) {
dropdown.innerHTML = '<option value="">Errore nel caricamento</option>';
console.warn(`No data for fieldId ${fieldId}`);
return;
}
@@ -1120,15 +1303,266 @@ foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
dropdown.appendChild(option);
});
if ((currentValue || selectedValue) && dropdown.value !== (currentValue || selectedValue)) {
dropdown.value = '';
console.warn(`Value ${currentValue || selectedValue} not found for fieldId ${fieldId}`);
// Ripristina il valore corrente
if (currentValue || selectedValue) {
dropdown.value = currentValue || selectedValue;
const event = new Event('change', {
bubbles: true
});
dropdown.dispatchEvent(event);
}
});
}
populateDropdowns();
});
document.addEventListener("DOMContentLoaded", function() {
let clientData = [];
async function loadClients(retryCount = 0, maxRetries = 3) {
const clientLoadingStatus = document.getElementById("clientLoadingStatus");
try {
clientLoadingStatus.style.display = 'inline';
clientLoadingStatus.textContent = 'Recupero clienti in corso...';
const response = await fetch("get_clienti.php", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
const data = await response.json();
if (!response.ok) {
if (response.status === 500 && data.error.includes('Cannot persist the object') && retryCount < maxRetries) {
console.log(`Tentativo ${retryCount + 1}/${maxRetries}: Riprovo a caricare i clienti...`);
await new Promise(resolve => setTimeout(resolve, 1000));
return loadClients(retryCount + 1, maxRetries);
}
throw new Error(data.error || `Errore HTTP: ${response.status}`);
}
clientData = data.value || [];
const select = document.getElementById("clientSelect");
select.innerHTML = '<option value="">Select a client...</option>';
clientData.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile";
const id = client.IdCliente || "ID non disponibile";
const codice = (client.CodiceNazioneFatturazione || '').trim();
const option = new Option(`${nome.trim()} - ${codice} (ID: ${id})`, id);
if (parseInt(id) === parseInt(<?php echo json_encode($default_idclient ?? 0); ?>)) {
option.selected = true;
}
select.add(option);
});
populateClientDropdowns();
clientLoadingStatus.textContent = "Clienti caricati.";
} catch (error) {
clientLoadingStatus.textContent = "Errore nel caricamento.";
Swal.fire({
title: "Errore!",
text: "Impossibile caricare i clienti: " + error.message,
icon: "error",
confirmButtonText: "OK"
});
} finally {
setTimeout(() => clientLoadingStatus.style.display = 'none', 2000);
}
}
function populateClientDropdowns() {
const clientDropdowns = document.querySelectorAll('select[name^="rows"][name$="[idclient]"]');
clientDropdowns.forEach(dropdown => {
const currentValue = dropdown.getAttribute('data-current-value') || '';
dropdown.innerHTML = '<option value="">Select a client...</option>';
clientData.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile";
const id = client.IdCliente || "ID non disponibile";
const codice = (client.CodiceNazioneFatturazione || '').trim();
const option = new Option(`${nome.trim()} - ${codice} (ID: ${id})`, id);
if (String(id) === String(currentValue)) {
option.selected = true;
}
dropdown.add(option);
});
// Ripristina il valore corrente
if (currentValue) {
dropdown.value = currentValue;
const event = new Event('change', {
bubbles: true
});
dropdown.dispatchEvent(event);
}
});
}
loadClients();
document.getElementById('clientSelect').addEventListener('change', function() {
const gridCell = this.closest('.grid-cell');
const event = new Event('change', {
bubbles: true
});
gridCell.dispatchEvent(event);
});
document.addEventListener('change', function(e) {
if (e.target.matches('select[name^="rows"][name$="[idclient]"]')) {
const gridCell = e.target.closest('.grid-cell');
const event = new Event('change', {
bubbles: true
});
gridCell.dispatchEvent(event);
}
});
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Gestione del cambio valore per il dropdown principale dei client
document.getElementById('clientSelect').addEventListener('change', function() {
const gridCell = this.closest('.grid-cell');
const event = new Event('change', {
bubbles: true
});
gridCell.dispatchEvent(event);
});
// Gestione del cambio valore per i dropdown dei client nelle righe
document.addEventListener('change', function(e) {
if (e.target.matches('select[name^="rows"][name$="[idclient]"]')) {
const gridCell = e.target.closest('.grid-cell');
const event = new Event('change', {
bubbles: true
});
gridCell.dispatchEvent(event);
}
});
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Initialize Select2 for searchable client dropdowns
$('.searchable-client').select2({
placeholder: "Select a client...",
allowClear: true,
width: '100%',
dropdownCssClass: 'select2-dropdown-smaller',
minimumInputLength: 1
});
// Ensure Select2 dropdowns trigger change events for unsaved changes tracking
$('.searchable-client').on('select2:select select2:clear', function(e) {
const gridCell = this.closest('.grid-cell');
const event = new Event('change', {
bubbles: true
});
gridCell.dispatchEvent(event);
});
// Update propagate functionality for client dropdown
$('.propagate-btn[data-column="idclient"]').on('click', async function() {
const value = $('#clientSelect').val();
const rows = document.querySelectorAll('.grid-row');
rows.forEach(row => {
const clientSelect = row.querySelector('select[name$="[idclient]"]');
if (clientSelect) {
$(clientSelect).val(value).trigger('change.select2');
const event = new Event('change', {
bubbles: true
});
clientSelect.closest('.grid-cell').dispatchEvent(event);
}
});
});
$(document).on('click', '.parts-btn', function() {
const iddatadb = $(this).data('iddatadb') || null;
const idquotations = $(this).data('idquotations') || null;
const rowIndex = $(this).data('row');
const importRef = $("table tbody tr").eq(rowIndex).find("td").eq(1).text();
const description = $("table tbody tr").eq(rowIndex).find("td").eq(2).text() || "Sconosciuto";
$.ajax({
url: 'modal_partsTable.php',
method: 'GET',
data: {
iddatadb: iddatadb
},
success: function(response) {
$('#partsModalContainer').html(response);
const modalElement = document.getElementById('partsModal');
if (!modalElement) {
console.error('Elemento modale non trovato: #partsModal');
const errorMsg = $('<div class="alert alert-danger temp-alert" role="alert">Errore: Modale non trovato.</div>');
$("body").prepend(errorMsg);
setTimeout(() => errorMsg.fadeOut(500, function() {
$(this).remove();
}), 5000);
return;
}
$("#trfHeader").text(`${iddatadb || idquotations} - ${importRef} - ${description}`);
$("#partsModal").data("iddatadb", iddatadb).data("idquotations", idquotations);
let modal = bootstrap.Modal.getInstance(modalElement);
if (!modal) {
modal = new bootstrap.Modal(modalElement, {
backdrop: true,
keyboard: true,
focus: true
});
}
modal.show();
if (typeof window.loadParts === 'function') {
window.loadParts(iddatadb, idquotations);
} else {
console.error('Funzione loadParts non definita. Verifica partsTable.js.');
}
},
error: function(xhr, status, error) {
console.error('Errore nel caricamento del modale:', error);
const errorMsg = $('<div class="alert alert-danger temp-alert" role="alert">Errore nel caricamento del modale: ' + error + '</div>');
$("body").prepend(errorMsg);
setTimeout(() => errorMsg.fadeOut(500, function() {
$(this).remove();
}), 5000);
}
});
});
$(document).on('hidden.bs.modal', '#partsModal', function() {
const modalElement = document.getElementById('partsModal');
if (modalElement) {
const modal = bootstrap.Modal.getInstance(modalElement);
if (modal) {
modal.dispose();
}
}
$('#partsModalContainer').empty();
$('.modal-backdrop').remove();
$('body').removeClass('modal-open').css('padding-right', '');
$('.overlay.toggle-icon').css('display', 'none');
});
$(document).on('hidden.bs.modal', '#annotationsModal', function() {
const modalElement = document.getElementById('annotationsModal');
if (modalElement) {
const modal = bootstrap.Modal.getInstance(modalElement);
if (modal) {
modal.dispose();
}
}
$('#annotationsModalContainer').empty();
$('.modal-backdrop').remove();
$('body').removeClass('modal-open').css('padding-right', '');
$('.overlay.toggle-icon').css('display', 'none');
});
});
</script>
<!-- Modale di conferma per l'esportazione -->
<div class="modal fade" id="exportConfirmModal" tabindex="-1" aria-labelledby="exportConfirmModalLabel" aria-hidden="true">
+9 -2
View File
@@ -75,6 +75,12 @@ foreach ($selected_rows as $rowIndex) {
continue;
}
// Recupera l'idclient di default dal template
$template_stmt = $pdo->prepare("SELECT idclient FROM excel_templates WHERE id = ?");
$template_stmt->execute([$template_id]);
$template = $template_stmt->fetch(PDO::FETCH_ASSOC);
$default_idclient = $template['idclient'] ?? null;
$values = [
$template_id,
$importReferenceCode,
@@ -83,9 +89,10 @@ foreach ($selected_rows as $rowIndex) {
$user_id,
null,
date('Y-m-d'),
$excelrow // Aggiunto excelrow per la colonna excelrow
$excelrow,
$default_idclient // Aggiungi idclient
];
$sql = "INSERT INTO datadb (templateid, importreferencecode, filename_import, status, user_id, limscode, importdate, excelrow) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$sql = "INSERT INTO datadb (templateid, importreferencecode, filename_import, status, user_id, limscode, importdate, excelrow, idclient) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute($values);
@@ -0,0 +1,25 @@
<?php
require_once(__DIR__ . '/../class/db-functions.php');
$db = DBHandlerSelect::getInstance()->getConnection();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);
// Inizializza la sessione
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Imposta variabili di sessione di default per evitare errori
$_SESSION['iduserlogin'] = '1'; // Nessun utente loggato
$_SESSION['nameuser'] = 'Ospite';
$_SESSION['surnameuser'] = '';
$_SESSION['emailuser'] = '';
$_SESSION['photouser'] = '';
$photouser = $_SESSION['photouser'];
$photousername = '';
$iduserlogin = $_SESSION['iduserlogin'];
// Include file di lingua, se necessario
require_once(__DIR__ . '/../../languages/en/general.php');
+2 -2
View File
@@ -14,9 +14,9 @@ if (!$iddatadb) {
}
try {
$stmt = $pdo->prepare("SELECT id, iddatadb, part_number, part_description FROM identification_parts WHERE iddatadb = :iddatadb ORDER BY part_number ASC");
$stmt = $pdo->prepare("SELECT id, iddatadb, part_number, part_description, idmatrice, note, dateexpiry FROM identification_parts WHERE iddatadb = :iddatadb ORDER BY part_number ASC");
$stmt->execute([':iddatadb' => $iddatadb]);
$parts = $stmt->fetchAll();
$parts = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'parts' => $parts]);
} catch (PDOException $e) {
+32
View File
@@ -0,0 +1,32 @@
<?php
header('Content-Type: application/json');
include('include/headscript.php');
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
// Recupera l'ID dell'utente loggato
$user_id = $iduserlogin ?? 1;
if (!$user_id) {
echo json_encode(['success' => false, 'message' => "ID dell'utente autenticato mancante"]);
exit;
}
try {
$stmt = $pdo->prepare(
"SELECT DISTINCT q.*
FROM quotations q
INNER JOIN identification_parts ip
ON ip.idquotations = q.id
AND ip.iddatadb IS NULL
WHERE q.iduser = :iduser"
);
$stmt->execute([':iduser' => $user_id]);
$quotations = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'quotations' => $quotations]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Errore nel caricamento delle quotations: ' . $e->getMessage()]);
}
+258
View File
@@ -0,0 +1,258 @@
<!-- Modal per la gestione delle annotazioni -->
<div class="modal fade" id="annotationsModal" tabindex="-1" aria-labelledby="annotationsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" style="max-width: 90% !important; width: 90% !important;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="annotationsModalLabel">Annotazioni per TRF: <span id="trfHeaderAnnotations"></span></h5>
<!-- SLIDER PER DIMENSIONE MARKER -->
<div style="display: flex; align-items: center; gap: 10px; margin-left: 20px;">
<label for="markerSizeSlider" style="margin: 0; font-size: 0.9rem; white-space: nowrap;">Dimensione marker:</label>
<input type="range" id="markerSizeSlider" min="16" max="48" value="24" step="2" style="width: 120px;">
<span id="markerSizeValue" style="font-weight: bold; min-width: 30px;">24px</span>
</div>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<!-- COLONNA SINISTRA RIDOTTA -->
<div class="col-md-6">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<h6 style="margin: 0;">Elenco Parti</h6>
<div style="display: flex; align-items: center;">
<input type="checkbox" id="showMixPartsAnnotations" name="showMixPartsAnnotations" style="margin-right: 5px;">
<label for="showMixPartsAnnotations" style="font-size: 0.9rem;">Mix</label>
</div>
</div>
<ul id="partsListAnnotations" class="list-group" style="max-height: 500px; overflow-y: auto;"></ul>
</div>
<!-- COLONNA DESTRA PIÙ GRANDE -->
<div class="col-md-6">
<h6>Foto del Campione</h6>
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<button type="button" class="btn btn-primary btn-sm" id="downloadPhotoBtnAnnotations" style="padding: 0.1rem 0.5rem; font-size: 0.8rem; margin-right: 10px;"><i class="fas fa-download"></i></button>
<div id="photoSelectorContainerAnnotations" style="display: none;"></div>
</div>
<div style="position: relative; width: 100%; min-height: 500px; border: 1px solid #ddd; border-radius: 4px; overflow: hidden;">
<img id="samplePhotoAnnotations" src="" alt="Foto del campione" style="max-width: 100%; max-height: 100%; object-fit: contain; position: absolute; top: 0; left: 0;">
<canvas id="photoCanvasAnnotations" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></canvas>
<canvas id="overlayCanvasAnnotations" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000;"></canvas>
<div id="descriptionListAnnotations" class="draggable-description" style="display: none;"></div>
<div id="markerContainerAnnotations"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" id="addDescriptionsBtnAnnotations" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Aggiungi Lista Descrizioni</button>
<button type="button" class="btn btn-danger btn-sm" id="removeAnnotationsBtnAnnotations" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Rimuovi Descrizioni</button>
<button type="button" class="btn btn-warning btn-sm" id="undoMarkerBtnAnnotations" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Undo Marker</button>
<button type="button" class="btn btn-success btn-sm" id="savePhotoBtnAnnotations" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Salva Foto con Nome</button>
<button type="button" class="btn btn-primary btn-sm" id="backToPartsBtnAnnotations" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Torna alle Parti</button>
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Chiudi</button>
</div>
</div>
</div>
</div>
<style>
#annotationsModal {
z-index: 1070 !important;
}
#annotationsModal .modal-backdrop {
z-index: 1065 !important;
}
#annotationsModal .modal-content {
width: 100% !important;
max-width: 100% !important;
}
#partsListAnnotations .list-group-item {
cursor: pointer;
transition: background-color 0.2s;
display: flex;
justify-content: space-between;
align-items: center;
padding: 5px 10px;
}
#partsListAnnotations .list-group-item:hover {
background-color: #f5f5f5;
}
#partsListAnnotations .list-group-item.active {
background-color: #e9ecef;
border-color: #dee2e6;
}
.draggable-description {
position: absolute;
background: rgba(255, 255, 255, 0.8);
padding: 5px;
font-family: Arial, sans-serif;
color: #000000;
cursor: move;
user-select: none;
z-index: 1000;
min-width: 100px;
min-height: 50px;
overflow: visible;
border: 1px solid #ccc;
}
.draggable-description.active-interaction {
border: 2px dashed #000;
}
.draggable-description div {
white-space: nowrap;
}
.resize-handle {
position: absolute;
bottom: 0;
right: 0;
width: 10px;
height: 10px;
background: #888;
cursor: se-resize;
}
.draggable-marker {
position: absolute;
width: 24px;
height: 24px;
border-radius: 50%;
color: #ffffff;
text-align: center;
line-height: 24px;
font-size: 12px;
cursor: move;
user-select: none;
z-index: 1000;
}
#markerContainerAnnotations {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#savePhotoBtnAnnotations {
transition: all 0.3s ease-in-out;
}
#savePhotoBtnAnnotations.unsaved {
background-color: #dc3545 !important;
border-color: #dc3545 !important;
color: white !important;
animation: pulse 1.2s infinite;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7);
}
70% {
box-shadow: 0 0 10px 15px rgba(220, 53, 69, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(220, 53, 69, 0);
}
}
.color-picker-container {
position: relative;
display: inline-block;
overflow: visible;
z-index: 2000;
}
.color-picker {
display: none;
position: absolute;
right: 0;
top: 25px;
background: #fff;
border: 1px solid #ccc;
padding: 5px;
z-index: 2000;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
flex-wrap: wrap;
width: 120px;
}
.color-option {
width: 24px;
height: 24px;
margin: 3px;
border: 1px solid #000;
cursor: pointer;
display: inline-block;
pointer-events: auto;
}
.color-option:hover {
border: 2px solid #000;
margin: 2px;
}
.selected-color {
width: 24px;
height: 24px;
margin-left: 5px;
border: 1px solid #000;
cursor: pointer;
display: inline-block;
pointer-events: auto;
}
.selected-color:hover {
border: 2px solid #000;
margin-left: 4px;
}
.temp-alert {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
z-index: 3000;
}
/* Stile per lo slider */
#markerSizeSlider {
-webkit-appearance: none;
height: 6px;
border-radius: 3px;
background: #ddd;
outline: none;
}
#markerSizeSlider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: #007bff;
cursor: pointer;
}
#markerSizeSlider::-moz-range-thumb {
width: 16px;
height: 16px;
border-radius: 50%;
background: #007bff;
cursor: pointer;
border: none;
}
</style>
+64 -6
View File
@@ -1,4 +1,4 @@
<!-- Modal modificato con pulsante per riconoscimento vocale e download -->
<!-- Modal modificato con pulsante per riconoscimento vocale, download e selezione matrici -->
<div class="modal fade" id="partsModal" tabindex="-1" aria-labelledby="partsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" style="max-width: 80% !important; width: 80% !important;">
<div class="modal-content">
@@ -9,10 +9,12 @@
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; min-width: 0;">
<h6 style="margin: 0; white-space: nowrap;">Elenco Parti</h6>
<div style="display: flex; align-items: center;">
<input type="checkbox" id="showMixParts" name="showMixParts" style="margin-right: 5px;">
<div style="display: flex; align-items: center; min-width: 0;">
<select id="global-matrice" class="ms-2" style="width: 250px !important; min-width: 250px !important;">
</select>
<input type="checkbox" id="showMixParts" name="showMixParts" style="margin-right: 5px; margin-left: 10px;">
<label for="showMixParts" style="font-size: 0.9rem; margin-right: 10px;">Mix</label>
<button type="button" class="btn btn-info btn-sm" id="renumberPartsBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Rinumera Parti</button>
<button type="button" class="btn btn-secondary btn-sm ms-2" id="toggleVoiceBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;"><i class="fas fa-microphone"></i> Voce</button>
@@ -45,13 +47,14 @@
<div class="col-md-6">
<h6>Foto del Campione</h6>
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<button type="button" class="btn btn-primary btn-sm" id="downloadPhotoBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem; margin-right: 10px;"><i class="fas fa-download"></i> </button>
<button type="button" class="btn btn-primary btn-sm" id="downloadPhotoBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem; margin-right: 10px;"><i class="fas fa-download"></i></button>
<div id="photoSelectorContainer" style="display: none;"></div>
</div>
<div style="position: relative; width: 100%; min-height: 400px;">
<img id="samplePhoto" src="" alt="Foto del campione" style="max-width: 100%; max-height: 100%; object-fit: contain; position: absolute; top: 0; left: 0;">
<canvas id="photoCanvas" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></canvas>
<canvas id="overlayCanvas" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000;"></canvas> <!-- Nuovo canvas per Fabric.js -->
<canvas id="overlayCanvas" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000;"></canvas>
<div id="descriptionList" class="draggable-description" style="display: none;"></div>
<div id="markerContainer"></div>
</div>
</div>
@@ -249,4 +252,59 @@
border: 2px solid #000;
margin: 2px;
}
/* Stili per Select2 in #partsList e #global-matrice */
#partsList .select2-container,
.select2-container--default #global-matrice {
width: 250px !important;
min-width: 250px !important;
margin-left: 10px;
}
#partsList .select2-selection--single,
.select2-container--default #global-matrice .select2-selection--single {
height: 26px !important;
padding: 0.2rem 0.5rem !important;
font-size: 0.9rem !important;
border: 1px solid #ced4da !important;
background-color: #fff !important;
}
#partsList .select2-selection__rendered,
.select2-container--default #global-matrice .select2-selection__rendered {
line-height: 24px !important;
overflow: hidden !important;
text-overflow: ellipsis !important;
white-space: nowrap !important;
}
#partsList .select2-selection__arrow,
.select2-container--default #global-matrice .select2-selection__arrow {
height: 26px !important;
}
#partsList .save-status,
#partsList .save-loading {
margin-left: 5px;
}
.select2-container--open .select2-dropdown {
z-index: 1051 !important;
border: 1px solid #aaa !important;
border-radius: 4px !important;
background: white !important;
overflow-y: auto !important;
max-height: 200px !important;
}
.select2-container--default .select2-search--dropdown .select2-search__field {
width: 100% !important;
padding: 0.2rem !important;
}
.select2-container--default .part-matrice,
.select2-container--default #global-matrice {
width: 250px !important;
min-width: 250px !important;
}
</style>
+496
View File
@@ -0,0 +1,496 @@
<div class="modal fade" id="partsModal" tabindex="-1" aria-labelledby="partsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" style="max-width: 80% !important;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="partsModalLabel">Parti per TRF: <span id="trfHeader"></span></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row parts-row">
<div class="col-md-9">
<!-- Prima riga: Elenco Parti, Rinumera, Voce -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<h6 style="margin: 0;">Elenco Parti</h6>
<div style="display: flex; align-items: center;">
<button type="button" class="btn btn-info btn-sm" id="renumberPartsBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Rinumera Parti</button>
<button type="button" class="btn btn-secondary btn-sm ms-2" id="toggleVoiceBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;"><i class="fas fa-microphone"></i> Voce</button>
<button type="button" class="btn btn-info btn-sm ms-2 d-none" id="quotationeBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">Add Quotation</button>
<button type="button" class="btn btn-primary btn-sm ms-2" id="showHideImageBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;">
<i class="fas fa-eye-slash" style="font-size: 0.8rem;"></i>
<i class="fas fa-image ms-1" style="font-size: 0.8rem;"></i>
</button>
</div>
</div>
<!-- Seconda riga: +, M, MacroMatrice, Matrice globale, Propaga -->
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<button type="button" class="btn btn-success btn-sm add-row-global" style="padding: 0.1rem 0.3rem; font-size: 0.8rem; margin-right: 5px;"><i class="fas fa-plus fa-xs"></i></button>
<button type="button" class="btn btn-primary btn-sm add-mix-global" style="padding: 0.1rem 0.3rem; font-size: 0.8rem; margin-right: 10px;">M</button>
<select id="macro-matrice-filter" class="form-control form-control-sm ms-2" style="width: 200px !important; min-width: 200px !important; margin-right: 10px;">
<option value="">Tutte le MacroMatrici</option>
</select>
<select id="global-matrice" class="form-control form-control-sm" style="width: 350px !important; margin-right: 10px;"></select>
<button type="button" class="btn btn-primary btn-sm propagate-all-btn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem;"><i class="fas fa-arrow-right fa-xs"></i> Propaga a tutte</button>
</div>
<table class="table table-striped table-sm" id="partsTable">
<thead>
<tr>
<th style="width: 80px;">Numero</th>
<th>Descrizione</th>
<th style="width: 200px;">Matrice</th>
<th style="width: 150px;">
<input type="date" class="form-control form-control-sm propagate-date-input" style="width: 130px; margin-left: 5px; display: inline-block;" title="Propaga data a tutte le parti">
</th>
<th style="width: 200px;">
<button type="button" class="btn btn-light btn-sm propagate-note-btn" style="padding: 0.2rem 0.4rem; font-size: 0.9rem; margin-left: 5px;" title="Propaga nota a tutte le parti">
<i class="fas fa-sticky-note"></i>
</button>
Azioni
</th>
</tr>
</thead>
<tbody id="partsTableBody">
<tr data-part-id="new">
<td><input type="number" class="form-control form-control-sm part-number" value="1" style="width: 80px;"></td>
<td><input type="text" class="form-control form-control-sm part-description" placeholder="Inserisci descrizione"></td>
<td>
<div style="display: flex; align-items: center;">
<button type="button" class="btn btn-primary btn-sm propagate-matrice-btn" style="padding: 0.1rem 0.3rem; font-size: 0.8rem; margin-right: 3px;"><i class="fas fa-arrow-right fa-xs"></i></button>
<select class="part-matrice form-control form-control-sm" style="width: 150px;"></select>
</div>
</td>
<td><input type="date" class="form-control form-control-sm part-dateexpiry" style="width: 130px;"></td>
<td>
<button type="button" class="btn btn-light btn-sm note-btn" style="padding: 0.2rem 0.4rem; font-size: 0.9rem;" title="Aggiungi/Modifica nota"><i class="fas fa-sticky-note"></i></button>
<button type="button" class="btn btn-warning btn-sm add-mix-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;">M+</button>
<button type="button" class="btn btn-danger btn-sm remove-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem; display: none;"><i class="fas fa-trash fa-xs"></i></button>
<span class="save-status text-success" style="display: none; margin-left: 5px;"><i class="fas fa-check fa-xs"></i></span>
<span class="save-loading text-warning" style="display: none; margin-left: 5px;"><i class="fas fa-spinner fa-spin fa-xs"></i></span>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-3">
<h6>Foto del Campione</h6>
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<button type="button" class="btn btn-primary btn-sm" id="downloadPhotoBtn" style="padding: 0.1rem 0.5rem; font-size: 0.8rem; margin-right: 10px;"><i class="fas fa-download"></i></button>
<div id="photoSelectorContainer" style="display: none;"></div>
</div>
<div style="position: relative; width: 100%; min-height: 400px;">
<img id="samplePhoto" src="" alt="Foto del campione" style="max-width: 100%; max-height: 400px; object-fit: contain;">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" id="openAnnotationsBtn">Apri Annotazioni</button>
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Chiudi</button>
</div>
</div>
</div>
</div>
<!-- Modale per la nota -->
<div class="modal fade" id="noteModal" tabindex="-1" aria-labelledby="noteModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="noteModalLabel">Nota per Parte</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<textarea class="form-control part-note" rows="5" placeholder="Inserisci una nota"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annulla</button>
<button type="button" class="btn btn-primary btn-sm save-note-btn">Salva</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="commonNoteModal" tabindex="-1" aria-labelledby="commonNoteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="commonNoteModalLabel">Nota comune per tutte le parti</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<textarea class="form-control part-note" rows="4" placeholder="Inserisci nota comune"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary save-common-note-btn">Salva</button>
</div>
</div>
</div>
</div>
<!-- Modale di conferma per l'eliminazione -->
<div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="confirmDeleteModalLabel">Conferma Eliminazione</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Sei sicuro di voler eliminare questa parte?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annulla</button>
<button type="button" class="btn btn-danger btn-sm" id="confirmDeleteBtn">Elimina</button>
</div>
</div>
</div>
</div>
<!-- Finestra modale "Aggiungi preventivo" -->
<div class="modal fade" id="addQuotationModal" tabindex="-1" aria-labelledby="addQuotationModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addQuotationModalLabel">Choose a quotation</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<select id="addQuotationSelect" class="form-control form-control-sm" style="width: 100% !important; min-width: 100% !important"></select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Annulla</button>
<button type="button" class="btn btn-primary btn-sm" id="addQuotationBtn">Confirm</button>
</div>
</div>
</div>
</div>
<style>
/* --- Base --- */
#partsModal {
z-index: 1060 !important
}
#partsModal .modal-backdrop {
z-index: 1055 !important
}
#partsModal .modal-content {
width: 100% !important;
max-width: 100% !important
}
#addQuotationModal {
z-index: 1060 !important
}
#addQuotationModal .modal-backdrop {
z-index: 1055 !important
}
/* Tabelle */
#partsTable tr {
display: table-row !important
}
#partsTable tr:hover {
background: #f5f5f5
}
#partsTable td,
#partsTable th {
padding: .2rem;
vertical-align: middle
}
#partsTable input,
#partsTable select {
height: 24px;
padding: .1rem .3rem
}
#partsTable button {
padding: .1rem .3rem;
margin: 0 2px
}
#partsTable i {
font-size: .6rem !important
}
/* --- Larghezze fisse header --- */
/* MacroMatrici = 250px */
#macro-matrice-filter {
width: 250px !important;
min-width: 250px !important;
max-width: 250px !important;
flex: 0 0 250px !important;
box-sizing: border-box;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#macro-matrice-filter.select2-hidden-accessible+.select2 {
width: 250px !important;
min-width: 250px !important;
max-width: 250px !important;
flex: 0 0 250px !important;
}
#macro-matrice-filter.select2-hidden-accessible+.select2 .select2-selection__rendered {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Matrice globale = 450px */
#global-matrice {
width: 450px !important;
min-width: 450px !important;
max-width: 450px !important;
flex: 0 0 450px !important;
box-sizing: border-box;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#global-matrice.select2-hidden-accessible+.select2 {
width: 450px !important;
min-width: 450px !important;
max-width: 450px !important;
flex: 0 0 450px !important;
}
#global-matrice.select2-hidden-accessible+.select2 .select2-selection__rendered {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Select delle righe (colonna Matrice) = 150px */
.part-matrice {
width: 300px !important;
min-width: 300px !important;
max-width: 300px !important;
flex: 0 0 300px !important;
}
.part-matrice.select2-hidden-accessible+.select2 {
width: 300px !important;
min-width: 300px !important;
max-width: 300px !important;
flex: 0 0 300px !important;
}
/* Colonna Descrizione (2ª colonna) = 420px */
#partsTable th:nth-child(2),
#partsTable td:nth-child(2) {
width: 350 !important;
min-width: 350px !important;
max-width: 350px !important;
}
#partsTable td:nth-child(2) .part-description {
width: 100% !important;
max-width: 100% !important;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Aspetto Select2 */
.select2-container--default .select2-selection--single {
height: 24px !important;
padding: .1rem .3rem !important;
font-size: .8rem !important;
border: 1px solid #ced4da !important;
}
.select2-container--default .select2-selection__arrow {
height: 24px !important
}
.select2-container--open .select2-dropdown {
z-index: 1061 !important;
border: 1px solid #aaa !important;
border-radius: 4px !important;
background: #fff !important;
max-height: 200px !important;
overflow-y: auto !important;
}
/* Evita stretching del flex nella riga dei filtri */
#partsModal .modal-body>.row .col-md-9>div[style*="display: flex"]>* {
flex: 0 0 auto;
}
/* Altri modali e pulsanti */
.propagate-matrice-btn,
.propagate-all-btn {
padding: .1rem .3rem !important;
font-size: .8rem !important
}
.save-status,
.save-loading {
margin-left: 5px
}
#confirmDeleteModal {
z-index: 1070 !important
}
#confirmDeleteModal .modal-backdrop {
z-index: 1065 !important
}
.note-btn {
padding: .2rem .4rem !important;
font-size: .9rem !important
}
.note-btn.has-note {
color: #dc3545 !important
}
#noteModal {
z-index: 1090 !important
}
#noteModal .modal-backdrop {
z-index: 1085 !important
}
#noteModal .modal-dialog {
position: relative;
z-index: 1090 !important
}
#noteModal textarea,
#commonNoteModal textarea {
resize: vertical
}
#commonNoteModal {
z-index: 1095 !important
}
#commonNoteModal .modal-backdrop {
z-index: 1090 !important
}
#commonNoteModal .modal-dialog {
position: relative;
z-index: 1095 !important
}
/* Evidenza salvataggio riga nel parts table */
/* Aumenta la specificità per le classi di flash */
table#partsTable tr.row-saving {
background-color: #f0ad4e !important;
/* Arancione per salvataggio in corso */
transition: background-color 0.3s ease;
}
table#partsTable tr.row-success {
background-color: #5cb85c !important;
/* Verde per successo */
transition: background-color 0.3s ease;
}
table#partsTable tr.row-error {
background-color: #d9534f !important;
/* Rosso per errore */
transition: background-color 0.3s ease;
}
/* Stato base: nascosti (verrà sovrascritto dallo style inline di jQuery) */
#partsModal .save-loading,
#partsModal .save-status {
display: none;
align-items: center;
gap: 6px;
padding: 2px 8px;
border-radius: 999px;
font-weight: 700;
font-size: 12px;
line-height: 1.2;
margin-left: 5px;
}
/* Quando NON sono nascosti via style inline (jQuery .show()), forzali a inline-flex */
#partsModal .save-loading:not([style*="display: none"]),
#partsModal .save-status:not([style*="display: none"]) {
display: inline-flex;
}
/* Loading (giallo) */
/* Loading (giallo) */
#partsModal .save-loading {
background: #ffd753ff;
border: 1px solid #ffd042ff;
color: #111;
/* testo nero */
}
#partsModal .save-loading i {
color: #111;
}
/* icona nera */
#partsModal .save-loading::after {
content: " Salvataggio…";
color: #111;
}
/* Salvato (verde) */
#partsModal .save-status {
background: #5dff83ff;
border: 1px solid #4effafff;
color: #111;
/* testo nero */
}
#partsModal .save-status i {
color: #111;
}
/* icona nera */
#partsModal .save-status::after {
content: " Salvato";
color: #111;
}
/* Animazioni */
@keyframes pulse {
0%,
100% {
transform: scale(1);
opacity: .9
}
50% {
transform: scale(1.05);
opacity: 1
}
}
@keyframes pop {
0% {
transform: scale(.85);
opacity: 0
}
100% {
transform: scale(1);
opacity: 1
}
}
/* rosso */
</style>
+290 -14
View File
@@ -12,11 +12,13 @@ $(document).ready(function () {
let photoAnnotations = {};
let partColors = {};
let partMatrice = {};
let selectedPartNumber = null;
let unsavedChanges = false;
let fabricCanvas = null;
let descriptionTextbox = null;
let markerObjects = {};
let matrici = [];
// ===================
// VOICE RECOGNITION SETUP
@@ -137,22 +139,83 @@ $(document).ready(function () {
.data("iddatadb", iddatadb)
.data("idquotations", idquotations);
// Precarica le matrici se iddatadb (assumendo matrici solo per iddatadb)
if (iddatadb) {
if (matrici.length === 0) {
$.ajax({
url: "get_matrici_db.php",
method: "GET",
dataType: "json",
success: function (data) {
matrici = data.value || [];
initializeGlobalSelect2();
loadPhoto(iddatadb, idquotations);
loadExistingParts(iddatadb, idquotations);
const modal = new bootstrap.Modal(
document.getElementById("partsModal"),
},
error: function (xhr, status, error) {
matrici = [];
initializeGlobalSelect2();
loadPhoto(iddatadb, idquotations);
loadExistingParts(iddatadb, idquotations);
const errorMsg = $(
'<div class="alert alert-danger temp-alert" role="alert">Errore nel caricamento delle matrici: ' +
error +
" (" +
xhr.status +
")</div>",
);
$("#partsModal .modal-body").prepend(errorMsg);
setTimeout(function () {
errorMsg.fadeOut(500, function () {
$(this).remove();
});
}, 5000);
},
});
} else {
initializeGlobalSelect2();
loadPhoto(iddatadb, idquotations);
loadExistingParts(iddatadb, idquotations);
}
} else {
loadPhoto(iddatadb, idquotations);
loadExistingParts(iddatadb, idquotations);
}
const modalElement = document.getElementById("partsModal");
if (modalElement) {
// Verifica se il modale è già stato inizializzato
let modal = bootstrap.Modal.getInstance(modalElement);
if (!modal) {
modal = new bootstrap.Modal(modalElement, {
backdrop: true,
keyboard: true,
focus: true,
});
}
modal.show();
} else {
console.error("Elemento modale non trovato: #partsModal");
const errorMsg = $(
'<div class="alert alert-danger temp-alert" role="alert">Errore: Modale non trovato.</div>',
);
$("body").prepend(errorMsg);
setTimeout(function () {
errorMsg.fadeOut(500, function () {
$(this).remove();
});
}, 5000);
}
});
$("#partsModal .close-btn, #partsModal").on("click", function (event) {
if (event.target === this) {
const modal = bootstrap.Modal.getInstance(
document.getElementById("partsModal"),
);
if (event.target === this || $(event.target).hasClass("close-btn")) {
const modalElement = document.getElementById("partsModal");
const modal = bootstrap.Modal.getInstance(modalElement);
if (modal) {
modal.hide();
}
}
});
$("#partsModal").on("hide.bs.modal", function (e) {
@@ -165,7 +228,7 @@ $(document).ready(function () {
});
$("#partsModal").on("hidden.bs.modal", function () {
// Reset global state to initial values
// Resetta lo stato
photoData = {
naturalWidth: 0,
naturalHeight: 0,
@@ -175,21 +238,33 @@ $(document).ready(function () {
};
photoAnnotations = {};
partColors = {};
partMatrice = {};
selectedPartNumber = null;
unsavedChanges = false;
if (fabricCanvas) {
fabricCanvas.off(); // Rimuove tutti gli eventi
fabricCanvas.off();
fabricCanvas.dispose();
fabricCanvas = null;
}
descriptionTextbox = null;
markerObjects = {};
// Clear UI elements
matrici = [];
$("#photoSelectorContainer").empty().hide();
$("#samplePhoto").attr("src", "");
$("#partsTableBody").empty();
// Remove any temporary messages
$("#global-matrice").empty();
$(".temp-alert").remove();
// Rimuovi manualmente il backdrop e ripristina il body
const modalElement = document.getElementById("partsModal");
const modal = bootstrap.Modal.getInstance(modalElement);
if (modal) {
modal.dispose(); // Distrugge l'istanza del modale
}
$(".modal-backdrop").remove();
$("body").removeClass("modal-open");
$("body").css("padding-right", "");
$(":focus").blur();
});
// ===================
@@ -535,6 +610,7 @@ $(document).ready(function () {
if (response.success) {
$row.remove();
delete partColors[partNumber];
delete partMatrice[partNumber];
if (markerObjects[partNumber]) {
fabricCanvas.remove(markerObjects[partNumber]);
delete markerObjects[partNumber];
@@ -576,6 +652,7 @@ $(document).ready(function () {
} else {
$row.remove();
delete partColors[partNumber];
delete partMatrice[partNumber];
if (markerObjects[partNumber]) {
fabricCanvas.remove(markerObjects[partNumber]);
delete markerObjects[partNumber];
@@ -717,6 +794,9 @@ $(document).ready(function () {
</tr>`;
$("#partsTableBody").append(newRow);
partColors[part.part_number] = defaultColor;
if (part.idmatrice) {
partMatrice[part.part_number] = part.idmatrice;
}
});
} else {
addNewRow(1);
@@ -743,6 +823,163 @@ $(document).ready(function () {
});
}
// Funzione per inizializzare Select2 sulle tendine delle matrici
function initializeSelect2($select, partNumber, partId, idmatrice) {
if (typeof $.fn.select2 === "undefined") {
$select.replaceWith(
'<input type="text" class="form-control form-control-sm" placeholder="Select2 non disponibile" disabled>',
);
return;
}
const options = matrici.map(function (matrice) {
return {
id: matrice.IdMatrice,
text: matrice.NomeMatrice, // Updated to use NomeMatrice
};
});
$select.select2({
placeholder: "Seleziona matrice",
allowClear: true,
data: options,
dropdownParent: $("#partsModal"),
matcher: function (params, data) {
if (!params.term || params.term.length < 3) {
return data;
}
const term = params.term.toUpperCase();
if (data.text.toUpperCase().indexOf(term) >= 0) {
return data;
}
return null;
},
});
if (partId && partId !== "new" && idmatrice) {
const matrice = matrici.find((m) => m.IdMatrice == idmatrice);
if (matrice) {
const option = new Option(
matrice.NomeMatrice, // Updated to use NomeMatrice
matrice.IdMatrice,
true,
true,
);
$select.append(option).trigger("change");
partMatrice[partNumber] = matrice.IdMatrice;
}
}
$select.on("change", function () {
const idmatrice = $(this).val();
const $listItem = $(this).closest("li");
const $saveStatus = $listItem.find(".save-status");
const $saveLoading = $listItem.find(".save-loading");
partMatrice[partNumber] = idmatrice || null;
if (partId && partId !== "new") {
$saveLoading.show();
$saveStatus.hide();
const iddatadb = $("#partsModal").data("iddatadb");
const idquotations = $("#partsModal").data("idquotations");
const endpoint = idquotations
? "save_matrice_quotation.php"
: "save_matrice.php";
const data = idquotations
? { idquotations: idquotations }
: { iddatadb: iddatadb };
$.ajax({
url: endpoint,
method: "POST",
data: JSON.stringify({
...data,
parts: [
{
id: partId,
idmatrice: idmatrice || null,
},
],
}),
contentType: "application/json",
success: function (response) {
if (response.success) {
$saveLoading.hide();
$saveStatus.show();
setTimeout(() => $saveStatus.hide(), 2000);
} else {
const errorMsg = $(
'<div class="alert alert-danger temp-alert" role="alert">Errore nel salvataggio della matrice: ' +
response.message +
"</div>",
);
$("#partsModal .modal-body").prepend(errorMsg);
setTimeout(function () {
errorMsg.fadeOut(500, function () {
$(this).remove();
});
}, 5000);
$saveLoading.hide();
}
},
error: function (xhr, status, error) {
const errorMsg = $(
'<div class="alert alert-danger temp-alert" role="alert">Errore nel salvataggio della matrice: ' +
error +
" (" +
xhr.status +
")</div>",
);
$("#partsModal .modal-body").prepend(errorMsg);
setTimeout(function () {
errorMsg.fadeOut(500, function () {
$(this).remove();
});
}, 5000);
$saveLoading.hide();
},
});
}
});
}
// Funzione per inizializzare Select2 sul dropdown globale
function initializeGlobalSelect2() {
const $select = $("#global-matrice");
if (typeof $.fn.select2 === "undefined") {
$select.replaceWith(
'<input type="text" class="form-control form-control-sm" placeholder="Select2 non disponibile" disabled>',
);
return;
}
const options = matrici.map(function (matrice) {
return {
id: matrice.IdMatrice,
text: matrice.NomeMatrice, // Updated to use NomeMatrice
};
});
$select.select2({
placeholder: "Seleziona matrice globale",
allowClear: true,
data: options,
dropdownParent: $("#partsModal"),
matcher: function (params, data) {
if (!params.term || params.term.length < 3) {
return data;
}
const term = params.term.toUpperCase();
if (data.text.toUpperCase().indexOf(term) >= 0) {
return data;
}
return null;
},
});
}
// ===================
// PARTS LIST
// ===================
@@ -763,6 +1000,7 @@ $(document).ready(function () {
$("#partsTableBody tr").each(function () {
const partNumber = $(this).find(".part-number").val();
const partDescription = $(this).find(".part-description").val();
const partId = $(this).data("part-id");
const partColor =
partColors[partNumber] ||
(partDescription.startsWith("Mix") ? "#0000ff" : "#ff0000");
@@ -778,17 +1016,30 @@ $(document).ready(function () {
)
.join("");
const listItem = `
<li class="list-group-item" data-part-number="${partNumber}">
<li class="list-group-item" data-part-number="${partNumber}" data-part-id="${partId}">
${partNumber} - ${partDescription}
<div style="display: flex; align-items: center;">
<button type="button" class="btn btn-primary btn-sm propagate-matrice-btn" style="padding: 0.1rem 0.3rem; font-size: 0.8rem; margin-right: 3px;"><i class="fas fa-arrow-right fa-xs"></i></button>
<select class="part-matrice" style="width: 250px !important; margin-right: 10px;"></select>
<button type="button" class="btn btn-success btn-sm add-to-mix-btn" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-plus fa-xs"></i></button>
<div class="color-picker-container">
<div class="color-option selected-color" style="background-color: ${partColor}; margin-left: 5px;"></div>
<div class="color-picker">${colorOptions}</div>
</div>
<span class="save-status text-success" style="display: none; margin-left: 5px;"><i class="fas fa-check fa-xs"></i></span>
<span class="save-loading text-warning" style="display: none; margin-left: 5px;"><i class="fas fa-spinner fa-spin fa-xs"></i></span>
</div>
</li>`;
$("#partsList").append(listItem);
const $select = $("#partsList").find(
`li[data-part-number="${partNumber}"] .part-matrice`,
);
initializeSelect2(
$select,
partNumber,
partId,
partMatrice[partNumber],
);
}
});
@@ -862,11 +1113,32 @@ $(document).ready(function () {
}
});
$(document).on("click", ".propagate-matrice-btn", function () {
const $listItem = $(this).closest("li");
const globalVal = $("#global-matrice").val();
if (globalVal) {
$listItem.find(".part-matrice").val(globalVal).trigger("change");
} else {
const errorMsg = $(
'<div class="alert alert-danger temp-alert" role="alert">Seleziona una matrice globale prima di propagare.</div>',
);
$("#partsModal .modal-body").prepend(errorMsg);
setTimeout(function () {
errorMsg.fadeOut(500, function () {
$(this).remove();
});
}, 5000);
}
});
$("#partsList").on("click", "li", function (e) {
if (
$(e.target).hasClass("add-to-mix-btn") ||
$(e.target).hasClass("color-option") ||
$(e.target).closest(".color-picker-container").length
$(e.target).closest(".color-picker-container").length ||
$(e.target).hasClass("part-matrice") ||
$(e.target).closest(".select2-container").length ||
$(e.target).hasClass("propagate-matrice-btn")
)
return;
selectedPartNumber = $(this).data("part-number");
@@ -892,6 +1164,7 @@ $(document).ready(function () {
? { idquotations: idquotations }
: { iddatadb: iddatadb };
let newPartColors = {};
let newPartMatrice = {};
let newMarkerObjects = {};
let partsData = $rows
@@ -908,6 +1181,7 @@ $(document).ready(function () {
partsData.forEach((part, index) => {
const newNumber = index + 1;
newPartColors[newNumber] = partColors[part.partNumber] || "#ff0000";
newPartMatrice[newNumber] = partMatrice[part.partNumber] || null;
if (markerObjects[part.partNumber]) {
newMarkerObjects[newNumber] = markerObjects[part.partNumber];
}
@@ -934,6 +1208,7 @@ $(document).ready(function () {
}
partColors = newPartColors;
partMatrice = newPartMatrice;
markerObjects = newMarkerObjects;
const partsToSave = partsData.map((part) => ({
@@ -941,6 +1216,7 @@ $(document).ready(function () {
part_number: part.partNumber,
part_description: part.partDescription,
mix: part.partDescription.startsWith("Mix") ? "Y" : "N",
idmatrice: partMatrice[part.partNumber] || null,
}));
$.ajax({
@@ -1157,7 +1433,7 @@ $(document).ready(function () {
width: annotations.descriptionSize.width,
scaleX: 1,
scaleY: 1,
backgroundColor: "rgba(255, 255, 255, 0.8)",
backgroundColor: "rgba(255, 255, 255, 0)", // Changed to fully transparent
fontFamily: "Arial",
fontSize: 24,
fill: "#000000",
File diff suppressed because it is too large Load Diff
+41 -13
View File
@@ -185,13 +185,21 @@ document.addEventListener("DOMContentLoaded", function () {
return;
}
for (const file of files) {
loader.style.display = "flex";
console.log(`Inizio upload di ${files.length} file`);
let successCount = 0;
let errorMessages = [];
let uploadPromises = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith("image/")) {
alert("Per favore, carica solo immagini!");
alert(`File ${file.name} non è un'immagine, saltato!`);
continue;
}
loader.style.display = "flex";
console.log(`Preparazione upload file ${i + 1}: ${file.name}`);
const formData = new FormData();
formData.append("photo", file);
@@ -201,23 +209,43 @@ document.addEventListener("DOMContentLoaded", function () {
formData.append("iddatadb", iddatadb);
}
try {
const response = await fetch("upload_photo.php", {
const uploadPromise = fetch("upload_photo.php", {
method: "POST",
body: formData,
});
const result = await response.json();
})
.then((response) => response.json())
.then((result) => {
if (result.success) {
loadPopupContent(iddatadb, idquotations);
successCount++;
console.log(`Successo per ${file.name}`);
} else {
alert("Errore durante il caricamento: " + result.message);
errorMessages.push(
`Errore per ${file.name}: ${result.message}`,
);
}
} catch (error) {
alert("Errore durante il caricamento: " + error.message);
} finally {
})
.catch((error) => {
errorMessages.push(
`Errore per ${file.name}: ${error.message}`,
);
});
uploadPromises.push(uploadPromise);
}
await Promise.all(uploadPromises);
loader.style.display = "none";
console.log(
`Fine upload: ${successCount} riusciti, ${errorMessages.length} errori`,
);
if (errorMessages.length > 0) {
alert("Errori durante l'upload:\n" + errorMessages.join("\n"));
}
}
// Ricarica sempre alla fine per aggiornare la lista, anche se parziale successo
loadPopupContent(iddatadb, idquotations);
}
function attachPhotoEventListeners(iddatadb, idquotations) {
+12 -2
View File
@@ -21,6 +21,10 @@ try {
$idschema = intval($_POST['idschema'] ?? 0); // Nuovo campo
$schemaname = trim($_POST['schemaname'] ?? ''); // Corretto da schemamaname
$idroutine = isset($_POST['idroutine']) && $_POST['idroutine'] !== '' ? intval($_POST['idroutine']) : null; // Aggiunto idroutine
$button_size = trim($_POST['button_size'] ?? 'medium'); // Nuovo campo
$button_bg_color = trim($_POST['button_bg_color'] ?? '#007bff'); // Nuovo campo
$button_text_color = trim($_POST['button_text_color'] ?? '#ffffff'); // Nuovo campo
$button_label = trim($_POST['button_label'] ?? 'Click Me'); // Nuovo campo
// Controllo sui campi obbligatori
if (empty($id) || empty($name) || empty($header_row) || empty($start_column) || empty($target_table) || $idschema <= 0) {
@@ -36,10 +40,12 @@ try {
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Aggiorna il database, includendo idschema, schemaname e idroutine
// Aggiorna il database, includendo i nuovi campi
$stmt = $pdo->prepare("UPDATE excel_templates
SET name = ?, header_row = ?, start_column = ?, description = ?, target_table = ?,
idclient = ?, clientname = ?, schemaname = ?, idschema = ?, idroutine = ?, updated_at = NOW()
idclient = ?, clientname = ?, schemaname = ?, idschema = ?, idroutine = ?,
button_size = ?, button_bg_color = ?, button_text_color = ?, button_label = ?,
updated_at = NOW()
WHERE id = ?");
$stmt->execute([
$name,
@@ -52,6 +58,10 @@ try {
$schemaname,
$idschema,
$idroutine,
$button_size,
$button_bg_color,
$button_text_color,
$button_label,
$id
]);
+4 -1
View File
@@ -108,7 +108,7 @@ try {
}
// Recupera routine dal template
$stmt = $pdo->prepare("SELECT idroutine FROM excel_templates WHERE id = ?");
$stmt = $pdo->prepare("SELECT idroutine, idclient FROM excel_templates WHERE id = ?");
$stmt->execute([$template_id]);
$template = $stmt->fetch(PDO::FETCH_ASSOC);
@@ -133,6 +133,9 @@ try {
error_log("Nessuna routine associata al template {$template_id}");
}
// Aggiungi idclient alla risposta
$response['idclient'] = $template['idclient'] ?? null;
// Salva i dati in sessione
$_SESSION['excel_data'] = $excelData;
$_SESSION['template_id'] = $template_id;
+47 -9
View File
@@ -399,14 +399,18 @@ if (isset($_GET['edit_id'])) {
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<?php include('modal_parts.php'); ?>
<?php include('photos_functions.php'); ?>
<div id="partsModalContainer"></div>
<div id="annotationsModalContainer"></div>
<?php include 'photos_functions.php'; ?>
<?php include('jsinclude.php'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="photos.js"></script>
<script src="parts.js"></script>
<script src="annotationsModal.js"></script>
<script src="partsTable.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Mostra messaggi di stato se presenti
@@ -423,6 +427,45 @@ if (isset($_GET['edit_id'])) {
}, 5000);
}
$(document).on('click', '.parts-btn', function() {
const idquotations = $(this).data('idquotations');
$.ajax({
url: 'modal_partsTable.php',
method: 'GET',
data: {
idquotations: idquotations
},
success: function(response) {
$('#partsModalContainer').html(response);
const modalElement = document.getElementById('partsModal');
if (!modalElement) return;
$("#trfHeader").text(`Quotation #${idquotations}`);
$("#partsModal").data("idquotations", idquotations);
let modal = bootstrap.Modal.getInstance(modalElement) || new bootstrap.Modal(modalElement, {
backdrop: true
});
modal.show();
if (typeof window.loadParts === 'function') window.loadParts(null, idquotations);
},
error: function(xhr, status, error) {
alert('Errore nel caricamento del modale: ' + error);
}
});
});
$(document).on('hidden.bs.modal', '#partsModal', function() {
$('#partsModalContainer').empty();
$('.modal-backdrop').remove();
$('body').removeClass('modal-open').css('padding-right', '');
});
$(document).on('hidden.bs.modal', '#annotationsModal', function() {
$('#annotationsModalContainer').empty();
$('.modal-backdrop').remove();
$('body').removeClass('modal-open').css('padding-right', '');
});
// Inizializza DataTables se non siamo in modalità modifica
if (!document.querySelector('#editForm')) {
$('#quotationsTable').DataTable({
@@ -524,12 +567,7 @@ if (isset($_GET['edit_id'])) {
</script>
<!-- Modale per le foto in quotations.php -->
<div class="modal" id="photosModal">
<div class="modal-content">
<span class="close-btn">&times;</span>
<div class="popup-content"></div>
</div>
</div>
</body>
+22 -10
View File
@@ -11,13 +11,14 @@ try {
}
$iddatadb = intval($_POST['iddatadb']);
$idclient = isset($_POST['idclient']) ? (is_numeric($_POST['idclient']) ? intval($_POST['idclient']) : null) : null;
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$data = $_POST;
$details = [];
// 1. POST-დან ამოვიღოთ მხოლოდ details
// 1. Estrarre i dettagli da POST
foreach ($data as $key => $value) {
if (preg_match('/^details(\d+)field_value$/', $key, $matches)) {
$id = $matches[1];
@@ -25,16 +26,15 @@ try {
}
}
// 2. DB-დან წამოვიღოთ არსებული მნიშვნელობები
// 2. Recupera i valori esistenti da import_data_details
$stmt = $pdo->prepare("SELECT mapping_id, field_value FROM import_data_details WHERE id = ?");
$stmt->execute([$iddatadb]);
$currentValues = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$currentValues[$row['mapping_id']] = $row['field_value'];
}
// 3. შევადაროთ POST-ს და DB-ს
// 3. Confronta i valori nuovi con quelli esistenti
$changed = [];
foreach ($details as $id => $newValue) {
$oldValue = $currentValues[$id] ?? null;
@@ -46,7 +46,7 @@ try {
}
}
// 4. თუ არის ცვლილებები → UPDATE
// 4. Aggiorna i dettagli se ci sono modifiche
if (!empty($changed)) {
$updateStmt = $pdo->prepare("
UPDATE import_data_details
@@ -61,14 +61,26 @@ try {
':mappingId' => $mappingId
]);
}
}
// 5. Aggiorna idclient in datadb
if (isset($idclient)) {
$updateStmt = $pdo->prepare("
UPDATE datadb
SET idclient = :idclient
WHERE iddatadb = :iddatadb
");
$updateStmt->execute([
':idclient' => $idclient,
':iddatadb' => $iddatadb
]);
$response['message'] = !empty($changed) ? "Updated details and idclient successfully" : "Updated idclient successfully";
} else {
$response['message'] = !empty($changed) ? "Updated details successfully" : "No changes found";
}
$response['success'] = true;
$response['message'] = "Updated successfully";
$response['changed'] = $changed; // Debug / optional
} else {
$response['success'] = true;
$response['message'] = "No changes found";
}
} catch (Exception $e) {
$response['success'] = false;
+39
View File
@@ -0,0 +1,39 @@
<?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;
}
$part = $parts[0];
$partId = $part['id'] ?? null;
$idmatrice = $part['idmatrice'] ?? null;
if (!$partId) {
echo json_encode(['success' => false, 'message' => 'ID parte mancante']);
exit;
}
try {
$stmt = $pdo->prepare("UPDATE identification_parts
SET idmatrice = :idmatrice,
updated_at = NOW()
WHERE id = :id");
$stmt->execute([
':id' => $partId,
':idmatrice' => $idmatrice // Può essere NULL
]);
echo json_encode(['success' => true, 'message' => 'Matrice aggiornata con successo']);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Errore nel salvataggio della matrice: ' . $e->getMessage()]);
}
+37 -19
View File
@@ -15,46 +15,64 @@ if (!$iddatadb || empty($parts)) {
exit;
}
$part = $parts[0];
$partId = $part['id'] ?? null; // part_id თუ არსებობს
$partNumber = $part['part_number'] ?? null;
$partDescription = $part['part_description'] ?? '';
$mix = $part['mix'] ?? 'N';
try {
$pdo->beginTransaction();
$results = [];
if ($partDescription) {
try {
foreach ($parts as $part) {
$partId = $part['id'] ?? null;
$partNumber = $part['part_number'] ?? null;
$partDescription = $part['part_description'] ?? '';
$mix = $part['mix'] ?? 'N';
$idmatrice = $part['idmatrice'] ?? null;
$note = $part['note'] ?? null;
$dateexpiry = $part['dateexpiry'] ?? null;
if ($partDescription || $note || $dateexpiry) {
if ($partId) {
// UPDATE თუ უკვე არსებობს part
// UPDATE se la parte esiste
$stmt = $pdo->prepare("UPDATE identification_parts
SET part_number = :part_number,
part_description = :part_description,
mix = :mix,
idmatrice = :idmatrice,
note = :note,
dateexpiry = :dateexpiry,
updated_at = NOW()
WHERE id = :id");
$stmt->execute([
':id' => $partId,
':part_number' => $partNumber,
':part_description' => $partDescription,
':mix' => $mix
':mix' => $mix,
':idmatrice' => $idmatrice,
':note' => $note,
':dateexpiry' => $dateexpiry,
]);
echo json_encode(['success' => true, 'part_id' => $partId, 'part_number'=>$partNumber, 'message' => 'Parte aggiornata con successo']);
$results[] = ['part_id' => $partId, 'part_number' => $partNumber, 'message' => 'Parte aggiornata con successo'];
} else {
// INSERT თუ ახალია
// INSERT per nuova parte
$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())");
(iddatadb, part_number, part_description, mix, idmatrice, note, dateexpiry, created_at, updated_at)
VALUES (:iddatadb, :part_number, :part_description, :mix, :idmatrice, :note, :dateexpiry, NOW(), NOW())");
$stmt->execute([
':iddatadb' => $iddatadb,
':part_number' => $partNumber,
':part_description' => $partDescription,
':mix' => $mix
':mix' => $mix,
':idmatrice' => $idmatrice,
':note' => $note,
':dateexpiry' => $dateexpiry,
]);
$newId = $pdo->lastInsertId();
echo json_encode(['success' => true, 'part_id' => $newId, 'part_number'=>$partNumber, 'message' => 'Parte salvata con successo']);
$results[] = ['part_id' => $newId, 'part_number' => $partNumber, 'message' => 'Parte salvata con successo'];
}
} catch (PDOException $e) {
}
}
$pdo->commit();
echo json_encode(['success' => true, 'results' => $results]);
} catch (PDOException $e) {
$pdo->rollBack();
echo json_encode(['success' => false, 'message' => 'Errore nel salvataggio: ' . $e->getMessage()]);
}
} else {
echo json_encode(['success' => false, 'message' => 'Descrizione mancante']);
}
@@ -0,0 +1,48 @@
<?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;
$partIds = $data['partIds'] ?? [];
$photoList = $data['photoList'] ?? null;
if ($iddatadb) {
if (count($partIds) != 0) {
$idList = array_values(array_map('intval', $partIds));
$placeholders = [];
$parameters = [':iddatadb' => $iddatadb];
foreach ($idList as $index => $id) {
$paramName = ":id{$index}";
$placeholders[] = $paramName;
$parameters[$paramName] = $id;
}
$sql = 'UPDATE identification_parts SET iddatadb = :iddatadb WHERE id IN (' . implode(',', $placeholders) . ')';
$stmt = $pdo->prepare($sql);
$stmt->execute($parameters);
}
if (count($photoList) != 0) {
$placeholders = [];
$parameters = [':iddatadb' => $iddatadb];
foreach ($photoList as $index => $photo) {
$paramName = ":photo{$index}";
$placeholders[] = $paramName;
$parameters[$paramName] = $photo;
}
$stmt = $pdo->prepare('UPDATE datadb_photos SET iddatadb = :iddatadb WHERE file_path IN (' . implode(',', $placeholders) . ')');
$stmt->execute($parameters);
}
echo json_encode(['success' => true, 'message' => '']);
} else {
echo json_encode(['success' => false, 'message' => 'Dati mancanti']);
}
File diff suppressed because one or more lines are too long
+68
View File
@@ -0,0 +1,68 @@
<?php
require_once "class/VisualLimsApiClient.class.php";
include('include/headscript.php');
header("Content-Type: application/json");
// 🔹 Configura directory log (creala se non esiste)
$logDir = __DIR__ . '/logs/api/';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// 🔹 Base URL API
$apiBaseUrl = 'https://93.43.5.102/limsapi/api/odata/';
// 🔹 Hardcoded commessaId
$commessaId = 533357;
try {
// 🔹 Initialize API client
$api = VisualLimsApiClient::getInstance();
// 🔹 STEP 1: POST InviaCommessa
$logContentStep1 = "curl --location --request POST '{$apiBaseUrl}CommessaWeb({$commessaId})/InviaCommessa' \\\n" .
"--header 'Content-Type: application/json' \\\n" .
"--header 'Authorization: Bearer ••••••' \\\n" .
"--data '{}'\n\n";
$sendResult = $api->post("CommessaWeb({$commessaId})/InviaCommessa", []);
$logContentStep1 .= "RESPONSE:\n" . json_encode($sendResult, JSON_PRETTY_PRINT);
$logFileStep1 = $logDir . "commessa_{$commessaId}_send_step1_" . time() . ".txt";
file_put_contents($logFileStep1, $logContentStep1);
// 🔹 STEP 2: GET di controllo post-invio
$expand = "CommesseCustomFields(\$expand=CustomField)";
$commessaAfterSend = $api->get("CommessaWeb(" . $commessaId . ")?\$expand=" . $expand);
// Log curl-like per GET di controllo
$logContentStep2 = "curl --location --request GET '{$apiBaseUrl}CommessaWeb({$commessaId})?\$expand=CommesseCustomFields(\$expand=CustomField)' \\\n" .
"--header 'Authorization: Bearer ••••••'\n\n" .
"RESPONSE:\n" . json_encode($commessaAfterSend, JSON_PRETTY_PRINT);
$logFileStep2 = $logDir . "commessa_{$commessaId}_get_step2_" . time() . ".txt";
file_put_contents($logFileStep2, $logContentStep2);
// 🔹 Output a schermo
echo json_encode([
"success" => true,
"message" => "Commessa {$commessaId} inviata e verificata",
"sendResult" => $sendResult,
"commessaAfterSend" => $commessaAfterSend,
"logFiles" => [
"step1_send" => $logFileStep1,
"step2_get" => $logFileStep2
]
]);
} catch (Exception $e) {
error_log("Send/Check Error: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
echo json_encode([
"success" => false,
"message" => "Operation failed: " . $e->getMessage(),
"logFiles" => [
"step1_send" => $logFileStep1 ?? null,
"step2_get" => $logFileStep2 ?? null
]
]);
}
+7 -8
View File
@@ -90,11 +90,11 @@
<tr>
<th>ID</th>
<th><?= htmlspecialchars($nametemplate, ENT_QUOTES, 'UTF-8'); ?></th>
<th><?= htmlspecialchars($lastmodtemplate, ENT_QUOTES, 'UTF-8'); ?></th>
<th><?= htmlspecialchars($rowheader, ENT_QUOTES, 'UTF-8'); ?></th>
<th><?= htmlspecialchars($columnheader, ENT_QUOTES, 'UTF-8'); ?></th>
<th><?= htmlspecialchars($desctemplate, ENT_QUOTES, 'UTF-8'); ?></th>
<th>Client Name</th>
<th>Button Label</th>
<th>Status</th> <!-- Aggiunta colonna Status -->
<th><?= htmlspecialchars($action, ENT_QUOTES, 'UTF-8'); ?></th>
</tr>
@@ -147,13 +147,7 @@
data: 'name', // Nome del template
title: "Template Name"
},
{
data: 'updated_at', // Ultima modifica, formattata come data leggibile
title: "Last Modified",
render: function(data) {
return new Date(data).toLocaleDateString();
}
},
{
data: 'header_row', // Riga degli header
title: "Header Row"
@@ -176,6 +170,11 @@
return `${clientName} (ID: ${clientId})`;
}
},
{
data: 'button_label', // Nuova colonna per Button Label
title: "Button Label",
defaultContent: 'Click Me'
},
{
data: 'status', // Stato con Toggle Switch
title: "Status",
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
// upload_photos_mobile.php
include('include/headscript.php');
include('include/headscriptnologin.php');
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();