added schema details

This commit is contained in:
Claudio 2025-07-05 20:31:44 +02:00
parent 3816bf5a20
commit 78089cadc1
16 changed files with 1117 additions and 108 deletions

View File

@ -31,6 +31,6 @@ Content-Length: 51
< strict-transport-security: max-age=2592000
< x-powered-by: ASP.NET
< x-content-type-options: nosniff
< date: Wed, 02 Jul 2025 12:18:49 GMT
< date: Fri, 04 Jul 2025 16:25:36 GMT
<
* Connection #0 to host 93.43.5.102 left intact

View File

@ -10,26 +10,19 @@
* issuer: C=US; O=Corporation Service Company; CN=Corporation Service Company RSA OV SSL CA
* SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway.
* using HTTP/2
* [HTTP/2] [1] OPENED stream for https://93.43.5.102/limsapi/api/odata/Rapporto(515081)?$expand=CampioniDatiRapporto($expand=AnalisiDatiRapporto,CustomFieldsDatiRapporto)
* [HTTP/2] [1] OPENED stream for https://93.43.5.102/limsapi/api/odata/Cliente
* [HTTP/2] [1] [:method: GET]
* [HTTP/2] [1] [:scheme: https]
* [HTTP/2] [1] [:authority: 93.43.5.102]
* [HTTP/2] [1] [:path: /limsapi/api/odata/Rapporto(515081)?$expand=CampioniDatiRapporto($expand=AnalisiDatiRapporto,CustomFieldsDatiRapporto)]
* [HTTP/2] [1] [authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1MTQ2NTkyOSwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.FNZzl12U_ixDiKE3bkILSUVGvAJd8HGAmL0VUEYS__0]
* [HTTP/2] [1] [:path: /limsapi/api/odata/Cliente]
* [HTTP/2] [1] [authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1MTY1MzUzNiwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.uKseoLi3vffY69suryyXBm3DsL83Cfz8P8_lLgLcjak]
* [HTTP/2] [1] [accept: application/json]
> GET /limsapi/api/odata/Rapporto(515081)?$expand=CampioniDatiRapporto($expand=AnalisiDatiRapporto,CustomFieldsDatiRapporto) HTTP/2
> GET /limsapi/api/odata/Cliente HTTP/2
Host: 93.43.5.102
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1MTQ2NTkyOSwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.FNZzl12U_ixDiKE3bkILSUVGvAJd8HGAmL0VUEYS__0
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjQ5MiIsIlhhZlNlY3VyaXR5QXV0aFBhc3NlZCI6IlhhZlNlY3VyaXR5QXV0aFBhc3NlZCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJXZWJBcGlVc2VyIiwiWGFmU2VjdXJpdHkiOiJYYWZTZWN1cml0eSIsIlhhZkxvZ29uUGFyYW1zIjoicTFZS0xVNHQ4a3ZNVFZXeVVncFBUWElzeUFRSktPa29CU1FXRjVmbkY2VUF4Y3RUa3hJTE1rdUI0Z2FHU3JVQSIsImV4cCI6MTc1MTY1MzUzNiwiaXNzIjoiTXkiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjQyMDAifQ.uKseoLi3vffY69suryyXBm3DsL83Cfz8P8_lLgLcjak
Accept: application/json
< HTTP/2 200
< cache-control: max-age=0
< content-type: application/json; odata.metadata=minimal; odata.streaming=true; charset=utf-8
< server: Microsoft-IIS/10.0
< strict-transport-security: max-age=2592000
< odata-version: 4.0
< x-powered-by: ASP.NET
< x-content-type-options: nosniff
< date: Wed, 02 Jul 2025 12:18:50 GMT
<
* Recv failure: Connection was reset
* OpenSSL SSL_read: Connection was reset, errno 10054
* Failed receiving HTTP2 data: 56(Failure when receiving data from the peer)
* Connection #0 to host 93.43.5.102 left intact

File diff suppressed because one or more lines are too long

View File

@ -133,6 +133,15 @@ if (json_last_error() !== JSON_ERROR_NONE) {
</select>
<span id="clientLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Recupero clienti in corso...</span>
</div>
<!-- Aggiungi il campo per selezionare lo schema -->
<div class="mb-3">
<label class="form-label">Select Schema *</label>
<select name="schema_id" id="schemaSelect" class="form-control" required>
<option value="">Select a schema...</option>
<!-- Le opzioni verranno popolate tramite JavaScript -->
</select>
<span id="schemaLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Caricamento schemi in corso...</span>
</div>
<!-- Sezione per i campi specifici del cliente -->
<div class="mb-3">
<label class="form-label">Client-Specific Fields</label>
@ -240,8 +249,10 @@ if (json_last_error() !== JSON_ERROR_NONE) {
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// Dati del cliente associato al template
// Dati del cliente e dello schema associati al template
const templateClientId = <?php echo json_encode($template['idclient'] ?? 0); ?>;
const templateSchemaId = <?php echo json_encode($template['idschema'] ?? 0); ?>;
const templateSchemaName = "<?php echo htmlspecialchars($template['schemaname'] ?? ''); ?>";
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
@ -249,13 +260,15 @@ if (json_last_error() !== JSON_ERROR_NONE) {
const addFieldButton = document.getElementById("addField");
const container = document.getElementById("clientSpecificFields");
const clientLoadingStatus = document.getElementById("clientLoadingStatus");
const schemaLoadingStatus = document.getElementById("schemaLoadingStatus");
if (!form || !addFieldButton || !container || !clientLoadingStatus) {
if (!form || !addFieldButton || !container || !clientLoadingStatus || !schemaLoadingStatus) {
console.error("One or more DOM elements not found:", {
form,
addFieldButton,
container,
clientLoadingStatus
clientLoadingStatus,
schemaLoadingStatus
});
return;
}
@ -273,16 +286,26 @@ if (json_last_error() !== JSON_ERROR_NONE) {
placeholder: "Search for a client...",
allowClear: true
}).on('select2:open', function() {
console.log("Select2 initialized successfully");
console.log("Select2 initialized successfully for clientSelect");
}).on('select2:select', function(e) {
console.log("Client selected:", e.params.data.id, e.params.data.text);
});
// Inizializza Select2 sulla tendina degli schemi
$('#schemaSelect').select2({
placeholder: "Search for a schema...",
allowClear: true
}).on('select2:open', function() {
console.log("Select2 initialized successfully for schemaSelect");
}).on('select2:select', function(e) {
console.log("Schema selected:", e.params.data.id, e.params.data.text);
});
// Carica i clienti al caricamento della pagina
async function loadClients() {
try {
// Mostra il messaggio di caricamento
clientLoadingStatus.style.display = 'inline';
clientLoadingStatus.textContent = 'Recupero clienti in corso...';
const response = await fetch("get_clienti.php", {
method: "GET",
@ -296,23 +319,21 @@ if (json_last_error() !== JSON_ERROR_NONE) {
const data = JSON.parse(text);
if (!response.ok) {
throw new Error(data.error || `Errore HTTP: ${response.status}, Dettagli: ${JSON.stringify(data)}`);
throw new Error(data.error || `Errore HTTP: ${response.status}`);
}
if (data.value && Array.isArray(data.value)) {
const select = document.getElementById("clientSelect");
select.innerHTML = '<option value="">Select a client...</option>'; // Resetta la tendina
select.innerHTML = '<option value="">Select a client...</option>';
data.value.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile";
const id = client.IdCliente || "ID non disponibile";
const option = new Option(`${nome.trim()} (ID: ${id})`, id);
// Pre-seleziona il cliente associato al template
if (parseInt(id) === parseInt(templateClientId)) {
option.selected = true;
}
select.add(option);
});
// Forza l'aggiornamento di Select2
$(select).trigger('change');
console.log("Clienti caricati con successo.");
clientLoadingStatus.textContent = "Clienti caricati.";
@ -320,8 +341,8 @@ if (json_last_error() !== JSON_ERROR_NONE) {
console.error("Nessun cliente trovato o formato dati non valido.", data);
clientLoadingStatus.textContent = "Nessun cliente trovato.";
Swal.fire({
title: "Error!",
text: "No clients found or invalid data format.",
title: "Errore!",
text: "Nessun cliente trovato o formato dati non valido.",
icon: "error",
confirmButtonText: "OK"
});
@ -330,21 +351,81 @@ if (json_last_error() !== JSON_ERROR_NONE) {
console.error("Errore nel caricamento dei clienti:", error);
clientLoadingStatus.textContent = "Errore nel caricamento.";
Swal.fire({
title: "Error!",
text: "Failed to load clients: " + error.message,
title: "Errore!",
text: "Impossibile caricare i clienti: " + error.message,
icon: "error",
confirmButtonText: "OK"
});
} finally {
// Nasconde il messaggio dopo un breve ritardo per leggibilità
setTimeout(() => {
clientLoadingStatus.style.display = 'none';
}, 2000);
}
}
// Chiama la funzione per caricare i clienti
loadClients();
// Carica gli schemi al caricamento della pagina
async function loadSchemas() {
try {
schemaLoadingStatus.style.display = 'inline';
schemaLoadingStatus.textContent = 'Caricamento schemi in corso...';
const response = await fetch("get_schemi.php", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
const text = await response.text();
console.log("Risposta raw (schemi):", text);
const data = JSON.parse(text);
if (!response.ok) {
throw new Error(data.error || `Errore HTTP: ${response.status}`);
}
const select = document.getElementById("schemaSelect");
select.innerHTML = '<option value="">Select a schema...</option>';
data.value.forEach(schema => {
const nome = schema.Nome || "Nome non disponibile";
const id = schema.IdSchemaCustomFields || "ID non disponibile";
const optionText = `${nome.trim()} (ID: ${id})`;
const option = new Option(optionText, id);
if (parseInt(id) === parseInt(templateSchemaId)) {
option.selected = true;
}
select.add(option);
});
$(select).trigger('change');
console.log("Schemi caricati con successo.");
schemaLoadingStatus.textContent = "Schemi caricati.";
} catch (error) {
console.error("Errore nel caricamento degli schemi:", error);
schemaLoadingStatus.textContent = "Errore nel caricamento.";
Swal.fire({
title: "Errore!",
text: "Impossibile caricare gli schemi: " + error.message,
icon: "error",
confirmButtonText: "OK"
});
} finally {
setTimeout(() => {
schemaLoadingStatus.style.display = 'none';
}, 2000);
}
}
// Carica i dati in sequenza
async function loadData() {
try {
await loadClients();
await loadSchemas();
} catch (error) {
console.error("Errore nel caricamento dei dati:", error);
}
}
loadData();
// Debug iniziale del DOM
const debugDom = () => {
@ -488,13 +569,13 @@ if (json_last_error() !== JSON_ERROR_NONE) {
// Aggiungi il nome del cliente selezionato a FormData
const clientSelect = document.getElementById("clientSelect");
const clientId = clientSelect.value;
const selectedOption = clientSelect.options[clientSelect.selectedIndex];
const selectedClientOption = clientSelect.options[clientSelect.selectedIndex];
// Validazione: assicurati che un cliente sia selezionato
if (!clientId) {
Swal.fire({
title: "Error!",
text: "Please select a client.",
title: "Errore!",
text: "Per favore seleziona un cliente.",
icon: "error",
confirmButtonText: "OK"
});
@ -503,17 +584,46 @@ if (json_last_error() !== JSON_ERROR_NONE) {
// Estrai il nome del cliente in modo più robusto
let clientName = "";
if (selectedOption) {
const optionText = selectedOption.text.trim();
if (selectedClientOption) {
const optionText = selectedClientOption.text.trim();
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
clientName = nameMatch ? nameMatch[1].trim() : optionText;
}
formData.append("client_name", clientName);
// Aggiungi l'ID e il nome dello schema selezionato a FormData
const schemaSelect = document.getElementById("schemaSelect");
const schemaId = schemaSelect.value;
const selectedSchemaOption = schemaSelect.options[schemaSelect.selectedIndex];
// Validazione: assicurati che uno schema sia selezionato
if (!schemaId) {
Swal.fire({
title: "Errore!",
text: "Per favore seleziona uno schema.",
icon: "error",
confirmButtonText: "OK"
});
return;
}
// Estrai il nome dello schema in modo più robusto
let schemaName = "";
if (selectedSchemaOption) {
const optionText = selectedSchemaOption.text.trim();
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
schemaName = nameMatch ? nameMatch[1].trim() : optionText;
}
formData.append("idschema", schemaId);
formData.append("schemamaname", schemaName);
// Log per debug
console.log("Client ID:", clientId);
console.log("Client Name:", clientName);
console.log("Schema ID:", schemaId);
console.log("Schema Name:", schemaName);
// Genera il JSON per client_specific_fields
let finalSpecificFields = {};
@ -565,8 +675,8 @@ if (json_last_error() !== JSON_ERROR_NONE) {
console.log("Fetch response:", data);
if (data.success) {
Swal.fire({
title: "Success!",
text: "Template updated successfully!",
title: "Successo!",
text: "Template aggiornato con successo!",
icon: "success",
confirmButtonText: "OK"
}).then(() => {
@ -574,7 +684,7 @@ if (json_last_error() !== JSON_ERROR_NONE) {
});
} else {
Swal.fire({
title: "Error!",
title: "Errore!",
text: data.message,
icon: "error",
confirmButtonText: "OK"
@ -582,10 +692,10 @@ if (json_last_error() !== JSON_ERROR_NONE) {
}
})
.catch(error => {
console.error("Fetch error:", error);
console.error("Errore Fetch:", error);
Swal.fire({
title: "Error!",
text: "An unexpected error occurred.",
title: "Errore!",
text: "Si è verificato un errore imprevisto.",
icon: "error",
confirmButtonText: "OK"
});

View File

@ -2,3 +2,6 @@
2025-06-16 11:15:30 - Errore nel recupero dati: HTTP 404, Risposta: {"title":"Not Found","status":404,"detail":"Not Found","instance":"GET /api/odata/Rapporto(2523026)","errorCode":"d25cbd678"}
2025-06-16 11:34:59 - Autenticazione fallita: HTTP 0, Errore cURL: Failed to connect to 93.43.5.102 port 443 after 21033 ms: Couldn't connect to server, Risposta:
2025-06-16 11:42:03 - Errore nella richiesta: Recv failure: Connection was reset
2025-07-04 10:42:49 - Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2025-07-04 10:44:13 - Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}
2025-07-04 10:48:07 - Autenticazione fallita: HTTP 400, Errore cURL: , Risposta: {"title":"Bad Request","status":400,"detail":"Cannot persist the object. It was modified or deleted (purged) by another application.","instance":"POST /api/authentication/authenticate","errorCode":"96bfc1252b"}

View File

@ -0,0 +1,30 @@
<?php
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/class/VisualLimsApiClient.class.php';
header('Content-Type: application/json');
ini_set('display_errors', '0');
error_reporting(E_ALL);
try {
$api = VisualLimsApiClient::getInstance();
// ID dello schema passato via GET o default 45
$schemaId = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 42;
// IMPORTANTE: $expand va dentro la stringa endpoint per entità singola
$endpoint = "SchemaCustomField($schemaId)?\$expand=SchemiCustomFieldsDettagli(\$expand=CustomField)";
// Nessun parametro aggiuntivo
$data = $api->get($endpoint);
// Salva la risposta per debug
file_put_contents(__DIR__ . '/schema_dettagli_response.json', json_encode($data));
echo json_encode($data);
} catch (Exception $e) {
http_response_code(500);
echo json_encode([
'error' => $e->getMessage()
]);
}

View File

@ -1,38 +1,36 @@
```php
<?php
require_once dirname(__DIR__, 2) . '/vendor/autoload.php'; // Torna al livello di public per trovare vendor/
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/class/VisualLimsApiClient.class.php';
header('Content-Type: application/json');
// Disabilita la visualizzazione degli errori PHP per evitare output HTML
ini_set('display_errors', '0');
error_reporting(E_ALL);
try {
$api = VisualLimsApiClient::getInstance();
$cliente_id = 4202; // Usa l'ID cliente fornito dal cliente
$options = ['$expand' => 'SchemiAbilitati']; // Usa $expand con il prefisso $
// Debug: Costruisci manualmente l'URL per verifica
// Nessun filtro o espansione: solo la lista degli schemi
$endpoint = 'SchemaCustomField';
// (Opzionale) aggiungi $top se vuoi limitare i risultati
$options = []; // oppure ad esempio: ['$top' => 100]
// Debug: salva URL usato
$base_url = 'https://93.43.5.102/limsapi/api/odata/';
$endpoint = "Cliente({$cliente_id})";
$query = http_build_query($options);
$full_url = $base_url . $endpoint . '?' . $query;
$full_url = $base_url . $endpoint . ($query ? '?' . $query : '');
file_put_contents(__DIR__ . '/last_url.txt', $full_url . PHP_EOL, FILE_APPEND);
$data = $api->get($endpoint, $options); // Recupera il cliente con schemi abilitati
// Chiamata API
$data = $api->get($endpoint, $options);
// Salva la risposta in un file per debug
file_put_contents(__DIR__ . '/schemi_response.json', json_encode($data));
// Salva il JSON in locale
file_put_contents(__DIR__ . '/schemi_base_response.json', json_encode($data, JSON_PRETTY_PRINT));
echo json_encode($data);
} catch (Exception $e) {
// Log dell'errore per debug
file_put_contents(__DIR__ . '/error_log.txt', date('Y-m-d H:i:s') . ' - ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
http_response_code(500);
echo json_encode([
'error' => $e->getMessage()
]);
echo json_encode(['error' => $e->getMessage()]);
}
?>

View File

@ -107,6 +107,15 @@
</select>
<span id="clientLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Recupero clienti in corso...</span>
</div>
<!-- Aggiungi il campo per selezionare lo schema -->
<div class="mb-3">
<label class="form-label">Select Schema *</label>
<select name="schema_id" id="schemaSelect" class="form-control" required>
<option value="">Select a schema...</option>
</select>
<span id="schemaLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Loading schemas...</span>
</div>
<!-- new section for specific client field -->
<div class="mb-3">
<label class="form-label">Client-Specific Fields</label>
@ -207,13 +216,15 @@
const addFieldButton = document.getElementById("addField");
const container = document.getElementById("clientSpecificFields");
const clientLoadingStatus = document.getElementById("clientLoadingStatus");
const schemaLoadingStatus = document.getElementById("schemaLoadingStatus");
if (!form || !addFieldButton || !container || !clientLoadingStatus) {
if (!form || !addFieldButton || !container || !clientLoadingStatus || !schemaLoadingStatus) {
console.error("One or more DOM elements not found:", {
form,
addFieldButton,
container,
clientLoadingStatus
clientLoadingStatus,
schemaLoadingStatus
});
return;
}
@ -231,16 +242,24 @@
placeholder: "Search for a client...",
allowClear: true
}).on('select2:open', function() {
console.log("Select2 initialized successfully");
console.log("Select2 initialized successfully for clientSelect");
}).on('select2:select', function(e) {
console.log("Client selected:", e.params.data.id, e.params.data.text);
});
// Carica i clienti al caricamento della pagina
// Inizializza Select2 sulla tendina degli schemi
$('#schemaSelect').select2({
placeholder: "Search for a schema...",
allowClear: true
}).on('select2:open', function() {
console.log("Select2 initialized successfully for schemaSelect");
});
// Funzione per caricare i clienti
async function loadClients() {
try {
// Mostra il messaggio di caricamento
clientLoadingStatus.style.display = 'inline';
clientLoadingStatus.textContent = 'Recupero clienti in corso...';
const response = await fetch("get_clienti.php", {
method: "GET",
@ -259,7 +278,7 @@
if (data.value && Array.isArray(data.value)) {
const select = document.getElementById("clientSelect");
select.innerHTML = '<option value="">Select a client...</option>'; // Resetta la tendina
select.innerHTML = '<option value="">Select a client...</option>';
data.value.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile";
const id = client.IdCliente || "ID non disponibile";
@ -272,8 +291,8 @@
console.error("Nessun cliente trovato o formato dati non valido.", data);
clientLoadingStatus.textContent = "Nessun cliente trovato.";
Swal.fire({
title: "Error!",
text: "No clients found or invalid data format.",
title: "Errore!",
text: "Nessun cliente trovato o formato dati non valido.",
icon: "error",
confirmButtonText: "OK"
});
@ -282,21 +301,90 @@
console.error("Errore nel caricamento dei clienti:", error);
clientLoadingStatus.textContent = "Errore nel caricamento.";
Swal.fire({
title: "Error!",
text: "Failed to load clients: " + error.message,
title: "Errore!",
text: "Impossibile caricare i clienti: " + error.message,
icon: "error",
confirmButtonText: "OK"
});
} finally {
// Nasconde il messaggio dopo un breve ritardo per leggibilità
setTimeout(() => {
clientLoadingStatus.style.display = 'none';
}, 2000);
}
}
// Chiama la funzione per caricare i clienti
loadClients();
// Funzione per caricare gli schemi con ritentativi
async function loadSchemas() {
const maxRetries = 3;
let attempt = 0;
while (attempt < maxRetries) {
try {
schemaLoadingStatus.style.display = 'inline';
schemaLoadingStatus.textContent = 'Caricamento schemi in corso...';
const response = await fetch("get_schemi.php", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
const text = await response.text();
console.log("Risposta raw (schemi):", text);
const data = JSON.parse(text);
if (!response.ok) {
throw new Error(data.error || `Errore HTTP: ${response.status}, Dettagli: ${JSON.stringify(data)}`);
}
const select = document.getElementById("schemaSelect");
select.innerHTML = '<option value="">Select a schema...</option>';
data.value.forEach(schema => { // Nota: usa data.value per coerenza con il JSON restituito
const option = new Option(`${schema.Nome} (ID: ${schema.IdSchemaCustomFields})`, schema.IdSchemaCustomFields);
select.add(option);
});
schemaLoadingStatus.textContent = "Schemi caricati.";
break; // Esci dal ciclo se la chiamata ha successo
} catch (error) {
attempt++;
console.error(`Tentativo ${attempt} fallito per schemi:`, error);
if (attempt === maxRetries) {
console.error("Errore finale nel caricamento degli schemi:", error);
schemaLoadingStatus.textContent = "Errore nel caricamento.";
Swal.fire({
title: "Errore!",
text: "Impossibile caricare gli schemi: " + error.message,
icon: "error",
confirmButtonText: "OK"
});
} else {
// Ritardo prima di riprovare
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
} finally {
if (attempt === maxRetries || schemaLoadingStatus.textContent === "Schemi caricati.") {
setTimeout(() => {
schemaLoadingStatus.style.display = 'none';
}, 2000);
}
}
}
}
// Funzione combinata per caricare i dati in sequenza
async function loadData() {
try {
await loadClients(); // Carica prima i clienti
await loadSchemas(); // Poi carica gli schemi
} catch (error) {
console.error("Errore nel caricamento dei dati:", error);
}
}
// Avvia il caricamento dei dati
loadData();
// Gestione dinamica dei campi specifici
addFieldButton.addEventListener("click", function() {
@ -387,36 +475,44 @@
// Aggiungi il nome del cliente selezionato a FormData
const clientSelect = document.getElementById("clientSelect");
const clientId = clientSelect.value;
const selectedOption = clientSelect.options[clientSelect.selectedIndex];
const selectedClientOption = clientSelect.options[clientSelect.selectedIndex];
let clientName = "";
if (selectedClientOption) {
const optionText = selectedClientOption.text.trim();
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
clientName = nameMatch ? nameMatch[1].trim() : optionText;
}
formData.append("client_name", clientName);
// Validazione: assicurati che un cliente sia selezionato
if (!clientId) {
// Aggiungi l'ID e il nome dello schema selezionato a FormData
const schemaSelect = document.getElementById("schemaSelect");
const schemaId = schemaSelect.value;
const selectedSchemaOption = schemaSelect.options[schemaSelect.selectedIndex];
let schemaName = "";
if (selectedSchemaOption && schemaId) {
const optionText = selectedSchemaOption.text.trim();
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
schemaName = nameMatch ? nameMatch[1].trim() : optionText;
formData.append("idschema", schemaId);
formData.append("schemamaname", schemaName);
} else {
Swal.fire({
title: "Error!",
text: "Please select a client.",
title: "Errore!",
text: "Per favore seleziona uno schema.",
icon: "error",
confirmButtonText: "OK"
});
return;
}
// Estrai il nome del cliente in modo più robusto
let clientName = "";
if (selectedOption) {
const optionText = selectedOption.text.trim();
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
clientName = nameMatch ? nameMatch[1].trim() : optionText;
}
formData.append("client_name", clientName);
// Log per debug
console.log("Client ID:", clientId);
console.log("Client Name:", clientName);
console.log("Schema ID:", schemaId);
console.log("Schema Name:", schemaName);
// Genera il JSON per client_specific_fields
let finalSpecificFields = {};
const fieldRows = container.getElementsByClassName("client-field-row");
for (let i = 0; i < fieldRows.length; i++) {
const row = fieldRows[i];
@ -444,8 +540,6 @@
}
console.log("Generated JSON for client_specific_fields:", JSON.stringify(finalSpecificFields));
// Aggiungi il JSON al FormData
formData.append("client_specific_fields", JSON.stringify(finalSpecificFields));
// Debug del FormData
@ -463,8 +557,8 @@
console.log("Fetch response:", data);
if (data.success) {
Swal.fire({
title: "Success!",
text: "Template created successfully!",
title: "Successo!",
text: "Template creato con successo!",
icon: "success",
confirmButtonText: "OK"
}).then(() => {
@ -472,7 +566,7 @@
});
} else {
Swal.fire({
title: "Error!",
title: "Errore!",
text: data.message,
icon: "error",
confirmButtonText: "OK"
@ -480,10 +574,10 @@
}
})
.catch(error => {
console.error("Fetch error:", error);
console.error("Errore Fetch:", error);
Swal.fire({
title: "Error!",
text: "An unexpected error occurred.",
title: "Errore!",
text: "Si è verificato un errore imprevisto.",
icon: "error",
confirmButtonText: "OK"
});

View File

@ -6,3 +6,38 @@ https://93.43.5.102/limsapi/api/odata/Cliente(4202)?%24expand=SchemiAbilitati
https://93.43.5.102/limsapi/api/odata/Cliente(4202)?%24expand=SchemiAbilitati
https://93.43.5.102/limsapi/api/odata/Rapporto(2523026)?%24expand=CampioniDatiRapporto%2CAnalisiDatiRapporto%2CCustomFieldsDatiRapporto
https://93.43.5.102/limsapi/api/odata/Cliente(4202)?%24expand=SchemiAbilitati
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField
https://93.43.5.102/limsapi/api/odata/SchemaCustomField

View File

@ -0,0 +1,614 @@
<?php include('include/headscript.php');
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid template ID");
}
$id = intval($_GET['id']);
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
$stmt = $pdo->prepare("SELECT name, header_row, start_column, target_table, sample_xlsx, idclient, clientname, idschema, schemaname, schemajson FROM excel_templates WHERE id = ?");
$stmt->execute([$id]);
$template = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$template) {
die("Template not found");
}
// Opzionale: se clientname o schemaname non sono disponibili, potresti volerli recuperare dinamicamente
$clientName = $template['clientname'] ?: '';
$schemaName = $template['schemaname'] ?: '';
$schemajson = $template['schemajson'] ?: ''; // Recupera il valore di schemajson
$isSchemajsonEmpty = empty(trim($template['schemajson']));
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--favicon-->
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title>Mapping XLS Template <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>
<body>
<!--wrapper-->
<div class="wrapper">
<!--sidebar wrapper -->
<?php include('include/navbar.php'); ?>
<!--end sidebar wrapper -->
<!--start header -->
<?php include('include/topbar.php'); ?>
<!--end header -->
<!--start page wrapper -->
<div class="page-wrapper">
<div class="page-content">
<?php include('top_stat_widget.php'); ?>
<div class="card radius-10">
<div class="card-header">
<div class="d-flex align-items-center">
<div>
<h6 class="mb-0">Associate Columns - Template: <span id="templateName"><?php echo htmlspecialchars($template['name']); ?></span></h6>
<p>
Client: <span id="clientName"><?php echo htmlspecialchars($clientName); ?></span> |
Schema: <span id="schemaName"><?php echo htmlspecialchars($schemaName); ?></span> |
Header Row: <span id="headerRow"><?php echo $template['header_row']; ?></span> |
Start Column: <span id="startColumn"><?php echo htmlspecialchars($template['start_column']); ?></span>
</p>
</div>
</div>
</div>
<div class="card-body">
<!-- Upload Section -->
<div class="mb-4">
<label class="form-label">Upload XLS Example:</label>
<input type="file" id="xlsUpload" class="form-control">
<small id="uploadStatus" class="text-muted">
<?php if (!empty($template['sample_xlsx'])): ?>
Current file: <a href="xlstemplates/<?php echo htmlspecialchars($template['sample_xlsx']); ?>" target="_blank">
<?php echo htmlspecialchars($template['sample_xlsx']); ?>
</a>
<?php else: ?>
No file uploaded yet.
<?php endif; ?>
</small>
</div>
<!-- Association Section -->
<div class="row">
<div class="col-md-5">
<h5>XLS Column</h5>
<ul id="xlsColumns" class="list-group border p-3" style="height: 300px; overflow-y: auto;"></ul>
</div>
<div class="col-md-2 text-center d-flex align-items-center justify-content-center">
<button class="btn btn-dark" id="addAssociation"> Add</button>
</div>
<div class="col-md-5">
<div class="d-flex align-items-center mb-2">
<h5>Schema Fields</h5>
<button id="loadSchemaButton" class="btn btn-primary ms-2" data-empty="<?php echo $isSchemajsonEmpty ? 'true' : 'false'; ?>">
<?php echo $isSchemajsonEmpty ? 'Load Schema Details' : 'Update Schema Details'; ?>
</button>
</div>
<table id="schemaFieldsTable" class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>ID</th>
<th>Type</th>
</tr>
</thead>
<tbody id="schemaFieldsBody">
<!-- I dettagli dello schema verranno caricati qui -->
</tbody>
</table>
</div>
</div>
<!-- Associations List -->
<div class="mt-4">
<h5>Current Associations</h5>
<ul id="associationsList" class="list-group border p-3"></ul>
</div>
<!-- Save Button -->
<div class="mt-4 text-end">
<a href="templates_dashboard.php" class="btn btn-primary"> Back to Template Dashboard</a>
</div>
</div>
</div>
</div>
</div>
<!--end page wrapper -->
<!--start overlay-->
<div class="overlay toggle-icon"></div>
<!--end overlay-->
<!--Start Back To Top Button-->
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<!--End Back To Top Button-->
<?php include('include/footer.php'); ?>
</div>
<!--end wrapper-->
<!-- search modal -->
<?php //include('include/searchmodal.php');
?>
<!-- end search modal -->
<!--start switcher-->
<?php //include('include/themeswitcher.php');
?>
<!--end switcher-->
<?php include('jsinclude.php'); ?>
<script>
document.getElementById('xlsUpload').addEventListener('change', function(event) {
let file = event.target.files[0];
if (!file) {
console.error("❌ No file selected");
return;
}
console.log("📂 File selected:", file.name);
let formData = new FormData();
formData.append("xls_file", file);
formData.append("template_id", <?php echo $id; ?>);
let statusText = document.getElementById('uploadStatus');
statusText.innerText = "Uploading...";
fetch('upload_xls_example.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (!data.success) {
console.error("❌ Error uploading file:", data.message);
statusText.innerText = "❌ Upload failed: " + data.message;
return;
}
console.log("✅ File uploaded successfully:", data.filepath);
statusText.innerHTML = `✅ File uploaded: <a href="xlstemplates/${data.filename}" target="_blank">${data.filename}</a>`;
processXLSX(file);
})
.catch(error => {
console.error("❌ Fetch error:", error);
statusText.innerText = "❌ Upload failed. Check console.";
});
});
function processXLSX(file) {
let reader = new FileReader();
reader.onload = function(e) {
let data = new Uint8Array(e.target.result);
let workbook = XLSX.read(data, {
type: 'array'
});
let sheet = workbook.Sheets[workbook.SheetNames[0]];
console.log("📄 Sheet found:", workbook.SheetNames[0]);
let rowIndex = parseInt(document.getElementById('headerRow').textContent) || 1;
let startColumn = parseInt(document.getElementById('startColumn').textContent) || 1;
console.log("📌 Using Header Row:", rowIndex, "Start Column:", startColumn);
let sheetData = XLSX.utils.sheet_to_json(sheet, {
header: 1,
defval: "",
raw: false,
range: 0
});
console.log("📊 Sheet Data:", sheetData);
if (!sheetData[rowIndex - 1]) {
console.warn("⚠️ No headers found in the specified row:", rowIndex);
document.getElementById('xlsColumns').innerHTML = "<li class='list-group-item text-danger'>No headers found</li>";
return;
}
let headers = sheetData[rowIndex - 1] || [];
console.log("🔎 Raw Headers:", headers);
if (!headers.length || headers.every(h => h.trim() === "")) {
console.warn("⚠️ Header row is empty at row:", rowIndex);
document.getElementById('xlsColumns').innerHTML = "<li class='list-group-item text-warning'>No headers found in the specified row</li>";
return;
}
let adjustedHeaders = headers.slice(startColumn - 1).filter(header => header !== undefined && header.trim() !== "");
console.log("✅ Extracted Headers:", adjustedHeaders);
let xlsColumns = document.getElementById('xlsColumns');
xlsColumns.innerHTML = '';
adjustedHeaders.forEach(header => {
let li = document.createElement('li');
li.className = 'list-group-item';
li.textContent = header;
xlsColumns.appendChild(li);
});
};
reader.readAsArrayBuffer(file);
}
document.addEventListener("DOMContentLoaded", function() {
let selectedXLSColumn = null;
let selectedSchemaField = null;
let templateId = <?php echo $id; ?>;
let schemaId = <?php echo json_encode($template['idschema'] ?? 0); ?>;
let clientId = <?php echo json_encode($template['idclient'] ?? 0); ?>;
let isSchemajsonEmpty = <?php echo json_encode($isSchemajsonEmpty); ?>;
async function loadClientAndSchemaNames() {
if (clientId && clientId > 0) {
try {
const response = await fetch(`get_clienti.php?id=${clientId}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
const data = await response.json();
if (response.ok && data.value && data.value.length > 0) {
document.getElementById('clientName').textContent = data.value[0].Nominativo || 'N/A';
}
} catch (error) {
console.error("❌ Error loading client name:", error);
}
}
if (schemaId && schemaId > 0) {
try {
const response = await fetch(`get_schemi.php?id=${schemaId}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
const data = await response.json();
if (response.ok && data.value && data.value.length > 0) {
document.getElementById('schemaName').textContent = data.value[0].Nome || 'N/A';
}
} catch (error) {
console.error("❌ Error loading schema name:", error);
}
}
}
loadClientAndSchemaNames();
async function loadOrUpdateSchemaDetails() {
if (!schemaId || schemaId === 0) {
console.warn("⚠️ No schema ID available for template:", templateId);
document.getElementById('schemaFieldsBody').innerHTML = '<tr><td colspan="3" class="text-warning">No schema associated with this template.</td></tr>';
return;
}
const loadSchemaButton = document.getElementById('loadSchemaButton');
loadSchemaButton.disabled = true;
loadSchemaButton.textContent = 'Loading...';
try {
// Chiamata a get_schema_details.php
const response = await fetch(`get_schema_details.php?id=${schemaId}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
console.log("📡 HTTP Status (get_schema_details):", response.status);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const rawResponse = await response.text();
console.log("📡 Raw Response (get_schema_details):", rawResponse);
let data;
try {
data = JSON.parse(rawResponse);
} catch (e) {
throw new Error('Invalid JSON response from get_schema_details: ' + e.message);
}
console.log("📡 Parsed Schema Details Response:", data);
if (!data || typeof data !== 'object') {
throw new Error('Invalid schema details response: Response is not an object');
}
if (!data.SchemiCustomFieldsDettagli) {
throw new Error('Invalid schema details response: Missing "SchemiCustomFieldsDettagli"');
}
const schemaJson = JSON.stringify(data);
// Salva il JSON
await saveSchemaJson(templateId, schemaJson);
// Rileggi i dati aggiornati
const updatedTemplateResponse = await fetch(`mapping_template_xls_scheme.php?id=${templateId}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
console.log("📡 HTTP Status (updated_template):", updatedTemplateResponse.status);
const rawUpdatedResponse = await updatedTemplateResponse.text();
console.log("📡 Raw Response (updated_template):", rawUpdatedResponse);
let updatedTemplateData;
try {
updatedTemplateData = JSON.parse(rawUpdatedResponse);
} catch (e) {
throw new Error('Invalid JSON response from updated_template: ' + e.message);
}
const updatedSchemaJson = updatedTemplateData.schemajson;
const schemaDetails = JSON.parse(updatedSchemaJson);
if (schemaDetails && schemaDetails.SchemiCustomFieldsDettagli) {
const schemaFieldsBody = document.getElementById('schemaFieldsBody');
schemaFieldsBody.innerHTML = '';
schemaDetails.SchemiCustomFieldsDettagli.forEach(detail => {
const field = detail.CustomField;
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${field.Titolo || 'N/A'}</td>
<td>${field.IdCustomField || 'N/A'}</td>
<td>${field.Tipo || 'N/A'}</td>
`;
tr.setAttribute('data-field', JSON.stringify({
id: field.IdCustomField,
title: field.Titolo,
type: field.Tipo
}));
tr.addEventListener('click', function() {
document.querySelectorAll('#schemaFieldsBody tr').forEach(el => el.classList.remove('table-active'));
tr.classList.add('table-active');
selectedSchemaField = JSON.parse(tr.getAttribute('data-field'));
console.log("📌 Selected Schema Field:", selectedSchemaField);
});
schemaFieldsBody.appendChild(tr);
});
} else {
throw new Error('No schema details available after update');
}
loadSchemaButton.textContent = 'Update Schema Details';
} catch (error) {
console.error("❌ Error details:", error);
document.getElementById('schemaFieldsBody').innerHTML = '<tr><td colspan="3" class="text-danger">Error: ' + error.message + '</td></tr>';
} finally {
loadSchemaButton.disabled = false; // Assicura che il pulsante torni attivo
loadSchemaButton.textContent = isSchemajsonEmpty ? 'Load Schema Details' : 'Update Schema Details';
}
}
async function saveSchemaJson(templateId, schemaJson) {
console.log("Saving Schema JSON - templateId:", templateId, "schemaJson:", schemaJson); // Debug
try {
const response = await fetch('update_schemajson.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
template_id: templateId,
schemajson: schemaJson
})
});
const data = await response.json();
console.log("Response from update_schemajson.php:", data); // Debug
if (!data.success) {
throw new Error(data.message || 'Failed to save schema JSON');
}
console.log("✅ Schema JSON saved:", data);
} catch (error) {
console.error("❌ Error saving schema JSON:", error);
throw error;
}
}
const loadSchemaButton = document.getElementById('loadSchemaButton');
if (isSchemajsonEmpty) {
loadSchemaButton.textContent = 'Load Schema Details';
} else {
const initialSchema = JSON.parse('<?php echo addslashes($schemajson); ?>');
if (initialSchema && initialSchema.SchemiCustomFieldsDettagli) {
const schemaFieldsBody = document.getElementById('schemaFieldsBody');
schemaFieldsBody.innerHTML = '';
initialSchema.SchemiCustomFieldsDettagli.forEach(detail => {
const field = detail.CustomField;
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${field.Titolo || 'N/A'}</td>
<td>${field.IdCustomField || 'N/A'}</td>
<td>${field.Tipo || 'N/A'}</td>
`;
tr.setAttribute('data-field', JSON.stringify({
id: field.IdCustomField,
title: field.Titolo,
type: field.Tipo
}));
tr.addEventListener('click', function() {
document.querySelectorAll('#schemaFieldsBody tr').forEach(el => el.classList.remove('table-active'));
tr.classList.add('table-active');
selectedSchemaField = JSON.parse(tr.getAttribute('data-field'));
console.log("📌 Selected Schema Field:", selectedSchemaField);
});
schemaFieldsBody.appendChild(tr);
});
}
}
loadSchemaButton.addEventListener('click', loadOrUpdateSchemaDetails);
function loadMappings() {
fetch('load_existing_mappings.php?template_id=' + templateId)
.then(response => response.json())
.then(data => {
if (!data.success) {
console.error("❌ Error loading mappings:", data.message);
return;
}
let associationsList = document.getElementById('associationsList');
let xlsColumnsList = document.getElementById('xlsColumns');
data.mappings.forEach(mapping => {
let li = document.createElement('li');
li.className = 'list-group-item d-flex justify-content-between align-items-center';
li.innerHTML = `
${mapping.excel_column} ${mapping.schema_field_id || 'N/A'}
<button class="btn btn-danger btn-sm removeAssociation" data-excel="${mapping.excel_column}" data-mysql="${mapping.schema_field_id}">X</button>
`;
associationsList.appendChild(li);
});
if (Array.isArray(data.remaining_xls_columns)) {
data.remaining_xls_columns.forEach(header => {
let li = document.createElement('li');
li.className = 'list-group-item';
li.textContent = header;
xlsColumnsList.appendChild(li);
});
}
// ❌ RIMOSSA: non ricaricare i dati dello schema automaticamente!
// if (!isSchemajsonEmpty) {
// loadOrUpdateSchemaDetails();
// }
})
.catch(error => console.error("❌ Error fetching mappings:", error));
}
loadMappings();
document.getElementById('xlsColumns').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
document.querySelectorAll('#xlsColumns li').forEach(el => el.classList.remove('active'));
event.target.classList.add('active');
selectedXLSColumn = event.target.textContent;
console.log("📌 Selected XLS Column:", selectedXLSColumn);
}
});
document.getElementById('schemaFieldsBody').addEventListener('click', function(event) {
if (event.target.tagName === 'TR') {
document.querySelectorAll('#schemaFieldsBody tr').forEach(el => el.classList.remove('table-active'));
event.target.classList.add('table-active');
selectedSchemaField = JSON.parse(event.target.getAttribute('data-field') || '{}');
console.log("📌 Selected Schema Field:", selectedSchemaField);
}
});
document.getElementById('addAssociation').addEventListener('click', function() {
if (!selectedXLSColumn || !selectedSchemaField) {
alert("Please select both an XLS column and a schema field.");
return;
}
saveAssociation(selectedXLSColumn, selectedSchemaField.id);
selectedXLSColumn = null;
selectedSchemaField = null;
});
function saveAssociation(excelColumn, schemaFieldId) {
let allHeaders = [...document.querySelectorAll('#xlsColumns li')].map(el => el.textContent).join(",");
fetch('save_column_mapping.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
template_id: templateId,
tablename: "<?php echo $template['target_table']; ?>",
excel_column: excelColumn,
schema_field_id: schemaFieldId,
data_type: "VARCHAR",
is_required: 0,
default_value: "",
headerexcel: allHeaders
})
})
.then(response => response.json())
.then(data => {
if (!data.success) {
console.error("❌ Error saving mapping:", data.message);
alert("Error saving mapping: " + data.message);
} else {
console.log("✅ Association saved:", data);
loadMappings();
}
})
.catch(error => console.error("❌ Fetch error:", error));
}
document.getElementById('associationsList').addEventListener('click', function(event) {
if (event.target.classList.contains('removeAssociation')) {
let excelColumn = event.target.getAttribute("data-excel");
let mysqlColumn = event.target.getAttribute("data-mysql");
removeAssociation(excelColumn, mysqlColumn);
}
});
function removeAssociation(excelColumn, mysqlColumn) {
fetch('remove_column_mapping.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
template_id: templateId,
excel_column: excelColumn,
mysql_column: mysqlColumn,
tablename: "<?php echo $template['target_table']; ?>"
})
})
.then(response => response.json())
.then(data => {
if (!data.success) {
console.error("❌ Error removing mapping:", data.message);
alert("Error removing mapping: " + data.message);
} else {
console.log("🗑️ Association removed:", data);
loadMappings();
}
})
.catch(error => console.error("❌ Fetch error:", error));
}
});
</script>
</body>
</html>

View File

@ -19,10 +19,12 @@ try {
$idclient = intval($_POST['client_id'] ?? 0); // Usa client_id dal form
$clientname = trim($_POST['client_name'] ?? ''); // Usa client_name dal form
$client_specific_fields = trim($_POST['client_specific_fields'] ?? '{}'); // Recupera il JSON dei campi specifici
$idschema = intval($_POST['idschema'] ?? 0); // Nuovo campo
$schemamaname = trim($_POST['schemamaname'] ?? ''); // Nuovo campo
// Controllo sui campi obbligatori
if (empty($id) || empty($name) || empty($header_row) || empty($start_column) || empty($target_table)) {
throw new Exception("All fields marked with * are required.");
if (empty($id) || empty($name) || empty($header_row) || empty($start_column) || empty($target_table) || $idschema <= 0) {
throw new Exception("All fields marked with * are required, including schema.");
}
// Validazione del idclient
@ -40,10 +42,10 @@ try {
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Aggiorna il database, includendo idclient, clientname e client_specific_fields
// Aggiorna il database, includendo idschema e schemaname
$stmt = $pdo->prepare("UPDATE excel_templates
SET name = ?, header_row = ?, start_column = ?, description = ?, target_table = ?,
idclient = ?, clientname = ?, client_specific_fields = ?, updated_at = NOW()
idclient = ?, clientname = ?, client_specific_fields = ?, schemaname = ?, idschema = ?, updated_at = NOW()
WHERE id = ?");
$stmt->execute([
$name,
@ -54,6 +56,8 @@ try {
$idclient,
$clientname,
$client_specific_fields,
$schemamaname,
$idschema,
$id
]);

View File

@ -31,9 +31,13 @@ try {
throw new Exception("Invalid JSON format for client-specific fields.");
}
// Recupera idschema e schemaname
$idschema = intval($_POST['idschema'] ?? 0); // Nuovo campo
$schemamaname = trim($_POST['schemamaname'] ?? ''); // Nuovo campo
// Controllo sui campi obbligatori
if (empty($name) || empty($header_row) || empty($start_column) || empty($target_table)) {
throw new Exception("All fields marked with * are required.");
if (empty($name) || empty($header_row) || empty($start_column) || empty($target_table) || $idschema <= 0) {
throw new Exception("All fields marked with * are required, including schema.");
}
// Validazione del idclient
@ -45,10 +49,10 @@ try {
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Inserisci nel database, usando idclient e clientname
// Inserisci nel database, aggiungendo idschema e schemaname
$stmt = $pdo->prepare("INSERT INTO excel_templates
(name, header_row, start_column, description, target_table, button_size, button_bg_color, button_text_color, button_label, idclient, clientname, status, client_specific_fields, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
(name, header_row, start_column, description, target_table, button_size, button_bg_color, button_text_color, button_label, idclient, clientname, status, client_specific_fields, schemaname, idschema, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
$stmt->execute([
$name,
$header_row,
@ -62,7 +66,9 @@ try {
$idclient,
$clientname,
$status,
$client_specific_fields
$client_specific_fields,
$schemamaname,
$idschema
]);
if ($stmt->rowCount() > 0) {

View File

@ -0,0 +1 @@
{"@odata.context":"https:\/\/93.43.5.102\/limsapi\/api\/odata\/$metadata#SchemaCustomField(SchemiCustomFieldsDettagli(CustomField()))\/$entity","IdSchemaCustomFields":45,"Nome":"Borse","Descrizione":null,"SchemiCustomFieldsDettagli":[{"IdSchemaCustomFieldsDettaglio":430,"Ordine":1,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":142,"TitoloTraduzione":"Fornitore:","Titolo":"Fornitore:","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":true,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":431,"Ordine":2,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":162,"TitoloTraduzione":"Stagione:","Titolo":"Stagione:","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":false,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":432,"Ordine":3,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":157,"TitoloTraduzione":"Stile: ","Titolo":"Stile: ","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":true,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":433,"Ordine":4,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":144,"TitoloTraduzione":"Committente: ","Titolo":"Committente: ","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":false,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":434,"Ordine":5,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":156,"TitoloTraduzione":"Tipologia di Materiale:","Titolo":"Tipologia di Materiale:","Descrizione":null,"Tipo":"SceltaMultipla","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":false,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":435,"Ordine":6,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":148,"TitoloTraduzione":"Articolo: ","Titolo":"Articolo: ","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":false,"DefaultCurrDate":false,"ObbligatorioWeb":true}},{"IdSchemaCustomFieldsDettaglio":436,"Ordine":7,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":149,"TitoloTraduzione":"Colore: ","Titolo":"Colore: ","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":false,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":437,"Ordine":8,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":150,"TitoloTraduzione":"Destinazione d'uso: ","Titolo":"Destinazione d'uso: ","Descrizione":null,"Tipo":"SceltaMultipla","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":true,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":438,"Ordine":9,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":166,"TitoloTraduzione":"Note:","Titolo":"Note:","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":false,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":440,"Ordine":9,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":161,"TitoloTraduzione":"Categoria:","Titolo":"Categoria:","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":true,"DefaultCurrDate":false,"ObbligatorioWeb":false}},{"IdSchemaCustomFieldsDettaglio":439,"Ordine":10,"ObbligatorioWeb":"Predefinito","RaggruppamentoWeb":null,"CustomField":{"IdCustomField":160,"TitoloTraduzione":"Riferimento Standard: ","Titolo":"Riferimento Standard: ","Descrizione":null,"Tipo":"Testo","Decimali":0,"Lunghezza":0,"Minimo":null,"Massimo":null,"ValoreDefault":null,"Elenco":true,"DefaultCurrDate":false,"ObbligatorioWeb":false}}]}

View File

@ -0,0 +1,65 @@
{
"@odata.context": "https:\/\/93.43.5.102\/limsapi\/api\/odata\/$metadata#SchemaCustomField",
"value": [
{
"IdSchemaCustomFields": 41,
"Nome": "Labostudio",
"Descrizione": null
},
{
"IdSchemaCustomFields": 42,
"Nome": "Schema 1",
"Descrizione": null
},
{
"IdSchemaCustomFields": 43,
"Nome": "Schema1",
"Descrizione": null
},
{
"IdSchemaCustomFields": 44,
"Nome": "Cuoio\/Pelle Standard \/ Leather",
"Descrizione": "Schema per tutti i campioni in cuoio\/pelle per i quali non \u00e8 specificato un destinatario.\r\n"
},
{
"IdSchemaCustomFields": 45,
"Nome": "Borse",
"Descrizione": null
},
{
"IdSchemaCustomFields": 46,
"Nome": "Borse Burberry",
"Descrizione": null
},
{
"IdSchemaCustomFields": 47,
"Nome": "pelle calzatura",
"Descrizione": null
},
{
"IdSchemaCustomFields": 48,
"Nome": "Standard Generico \/ Generic Standard",
"Descrizione": "Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"
},
{
"IdSchemaCustomFields": 49,
"Nome": "Accessori Metallici \/ Metallic Accessories",
"Descrizione": "Schema per tutti gli Accessori Metallici\r\n\r\n\r\n"
},
{
"IdSchemaCustomFields": 50,
"Nome": "Tessile \/ Textiles",
"Descrizione": "Schema per tutti i Tessuti\r\n"
},
{
"IdSchemaCustomFields": 183,
"Nome": "TWINSET",
"Descrizione": "Schema da usare per Twinset - come da mail di EP del 20\/05\/2025\r\n\r\n"
},
{
"IdSchemaCustomFields": 186,
"Nome": "TWINSET",
"Descrizione": "Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"
}
]
}

View File

@ -1 +1 @@
{"@odata.context":"https:\/\/93.43.5.102\/limsapi\/api\/odata\/$metadata#Cliente\/$entity","IdCliente":4202,"DataUltimaModifica":"2025-01-09T12:58:07.743+01:00","EMails":["elisa.memo@moncler.com"],"EMailsPec":[],"CodiceCliente":"BL01858_RM-ACC_E","Nominativo":"INDUSTRIES SPA_RM-ACC","Indirizzo":"VIA STENDHAL 47","Citt\u00e0":"MILANO","Cap":"20144","Provincia":"MI","CodiceASL":null,"PartitaIva":"04804070961","CodiceFiscale":null,"FattureCodiceDestinatario":"SN4CSRI","FattureRiferimento":null,"CodiceNazioneFatturazione":"IT"}
{"@odata.context":"https:\/\/93.43.5.102\/limsapi\/api\/odata\/$metadata#SchemaCustomField","value":[{"IdSchemaCustomFields":41,"Nome":"Labostudio","Descrizione":null},{"IdSchemaCustomFields":42,"Nome":"Schema 1","Descrizione":null},{"IdSchemaCustomFields":43,"Nome":"Schema1","Descrizione":null},{"IdSchemaCustomFields":44,"Nome":"Cuoio\/Pelle Standard \/ Leather","Descrizione":"Schema per tutti i campioni in cuoio\/pelle per i quali non \u00e8 specificato un destinatario.\r\n"},{"IdSchemaCustomFields":45,"Nome":"Borse","Descrizione":null},{"IdSchemaCustomFields":46,"Nome":"Borse Burberry","Descrizione":null},{"IdSchemaCustomFields":47,"Nome":"pelle calzatura","Descrizione":null},{"IdSchemaCustomFields":48,"Nome":"Standard Generico \/ Generic Standard","Descrizione":"Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"},{"IdSchemaCustomFields":49,"Nome":"Accessori Metallici \/ Metallic Accessories","Descrizione":"Schema per tutti gli Accessori Metallici\r\n\r\n\r\n"},{"IdSchemaCustomFields":50,"Nome":"Tessile \/ Textiles","Descrizione":"Schema per tutti i Tessuti\r\n"},{"IdSchemaCustomFields":183,"Nome":"TWINSET","Descrizione":"Schema da usare per Twinset - come da mail di EP del 20\/05\/2025\r\n\r\n"},{"IdSchemaCustomFields":186,"Nome":"TWINSET","Descrizione":"Schema per tutti i campioni di qualsiasi matrice escluso cuoio\/pelle\r\n\r\n"}]}

View File

@ -0,0 +1,56 @@
<?php
header('Content-Type: application/json');
require_once 'class/db-functions.php';
// Disabilita l'output di errori HTML
ini_set('display_errors', '0');
error_reporting(E_ALL);
$response = ["success" => false, "message" => ""];
try {
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
throw new Exception("Invalid request method.");
}
// Recupera i dati dal body JSON (non da $_POST direttamente)
$input = json_decode(file_get_contents('php://input'), true);
$template_id = isset($input['template_id']) ? intval($input['template_id']) : null;
$schemajson = isset($input['schemajson']) ? trim($input['schemajson']) : '';
// Controllo sui campi obbligatori
if (empty($template_id) || empty($schemajson)) {
throw new Exception("All fields marked with * are required, including schemajson.");
}
// Validazione del JSON
$decoded_json = json_decode($schemajson, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Invalid JSON format for schemajson.");
}
// Connessione al database
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
// Aggiorna il database
$stmt = $pdo->prepare("UPDATE excel_templates
SET schemajson = ?, updated_at = NOW()
WHERE id = ?");
$stmt->execute([
$schemajson,
$template_id
]);
if ($stmt->rowCount() > 0) {
$response["message"] = "Schema JSON updated successfully!";
} else {
$response["message"] = "No changes detected, but operation completed.";
}
$response["success"] = true;
} catch (Exception $e) {
$response["message"] = $e->getMessage();
}
// Restituisce un JSON per il fetch
echo json_encode($response);