added schema details

This commit is contained in:
2025-07-05 20:31:44 +02:00
parent 3816bf5a20
commit 78089cadc1
16 changed files with 1117 additions and 108 deletions
+137 -27
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"
});