update API template

This commit is contained in:
Claudio 2026-03-28 10:33:28 +01:00
parent b3ce489348
commit bf18a904bd
2 changed files with 206 additions and 104 deletions

View File

@ -1,26 +1,27 @@
<?php include('include/headscript.php'); <?php include('include/headscript.php');
// Controlla se è stato passato un ID valido // Check if a valid ID was provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) { if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
header("Location: xlstemplates_grid.php?status=error&message=" . urlencode("Invalid ID")); header("Location: templates_dashboard.php?status=error&message=" . urlencode("Invalid ID"));
exit; exit;
} }
$id = intval($_GET['id']); // Sanifica l'ID $id = intval($_GET['id']);
// Recupera il template dal database // Retrieve template from database
$db = DBHandlerSelect::getInstance(); $db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection(); $pdo = $db->getConnection();
$stmt = $pdo->prepare("SELECT * FROM excel_templates WHERE id = ?"); $stmt = $pdo->prepare("SELECT * FROM excel_templates WHERE id = ?");
$stmt->execute([$id]); $stmt->execute([$id]);
$template = $stmt->fetch(PDO::FETCH_ASSOC); $template = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$template) { if (!$template) {
header("Location: template_dashboard.php?status=error&message=" . urlencode("Template not found")); header("Location: templates_dashboard.php?status=error&message=" . urlencode("Template not found"));
exit; exit;
} }
// Recupera tutte le routine dal database // Retrieve all routines
$stmt = $pdo->prepare("SELECT * FROM routine"); $stmt = $pdo->prepare("SELECT * FROM routine");
$stmt->execute(); $stmt->execute();
$routines = $stmt->fetchAll(PDO::FETCH_ASSOC); $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
@ -34,7 +35,6 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" /> <link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<?php include('cssinclude.php'); ?> <?php include('cssinclude.php'); ?>
<!-- Include jQuery prima di Select2 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<title>Edit Template <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title> <title>Edit Template <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
@ -44,19 +44,22 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<div class="wrapper"> <div class="wrapper">
<?php include('include/navbar.php'); ?> <?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?> <?php include('include/topbar.php'); ?>
<div class="page-wrapper"> <div class="page-wrapper">
<div class="page-content"> <div class="page-content">
<div class="card mb-4"> <div class="card mb-4">
<div class="card-header"> <div class="card-header">
<h5 class="mb-0">Update XLS Template</h5> <h5 class="mb-0">Update Template</h5>
</div> </div>
<div class="card-body"> <div class="card-body">
<p class="mb-2">Edit the following form in order to update the selected import XLS template</p> <p class="mb-2">Edit the following form in order to update the selected import template</p>
<p class="mb-2">Mandatory Fields</p> <p class="mb-2">Mandatory Fields</p>
<ul class="mb-0"> <ul class="mb-0">
<li>Template Name</li> <li>Template Name</li>
<li>Row Header and Column Header: where the title of the excel starts</li> <li>Source Type</li>
<li>Schema</li> <li>Schema and Client</li>
<li>Row Header and Column Header only for XLS templates</li>
</ul> </ul>
</div> </div>
</div> </div>
@ -69,34 +72,44 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
</div> </div>
</div> </div>
</div> </div>
<div class="card-body"> <div class="card-body">
<div class="col-12"> <div class="col-12">
<form id="editTemplateForm" method="POST"> <form id="editTemplateForm" method="POST">
<input type="hidden" name="id" value="<?php echo $template['id']; ?>"> <input type="hidden" name="id" value="<?php echo (int)$template['id']; ?>">
<div class="mb-3"> <div class="mb-3">
<label class="form-label"><?= htmlspecialchars($templatename, ENT_QUOTES, 'UTF-8'); ?> *</label> <label class="form-label"><?= htmlspecialchars($templatename, ENT_QUOTES, 'UTF-8'); ?> *</label>
<input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($template['name']); ?>" required> <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($template['name'] ?? ''); ?>" required>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Source Type *</label>
<select name="source_type" id="sourceType" class="form-control" required>
<option value="XLS" <?php echo (($template['source_type'] ?? 'XLS') === 'XLS') ? 'selected' : ''; ?>>XLS</option>
<option value="API" <?php echo (($template['source_type'] ?? 'XLS') === 'API') ? 'selected' : ''; ?>>API</option>
</select>
<small class="text-muted">Choose the source used by this template</small>
</div>
<div class="mb-3" id="headerRowWrapper">
<label class="form-label"><?= htmlspecialchars($rowheader, ENT_QUOTES, 'UTF-8'); ?> *</label> <label class="form-label"><?= htmlspecialchars($rowheader, ENT_QUOTES, 'UTF-8'); ?> *</label>
<input type="number" name="header_row" class="form-control" value="<?php echo $template['header_row']; ?>" required> <input type="number" name="header_row" id="headerRow" class="form-control" value="<?php echo htmlspecialchars($template['header_row'] ?? ''); ?>">
</div> </div>
<div class="mb-3"> <div class="mb-3" id="startColumnWrapper">
<label class="form-label"><?= htmlspecialchars($columnheader, ENT_QUOTES, 'UTF-8'); ?>*</label> <label class="form-label"><?= htmlspecialchars($columnheader, ENT_QUOTES, 'UTF-8'); ?> *</label>
<input type="text" name="start_column" class="form-control" value="<?php echo htmlspecialchars($template['start_column']); ?>" required> <input type="text" name="start_column" id="startColumn" class="form-control" value="<?php echo htmlspecialchars($template['start_column'] ?? ''); ?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label"><?= htmlspecialchars($desctemplate, ENT_QUOTES, 'UTF-8'); ?></label> <label class="form-label"><?= htmlspecialchars($desctemplate, ENT_QUOTES, 'UTF-8'); ?></label>
<textarea name="description" class="form-control"><?php echo htmlspecialchars($template['description']); ?></textarea> <textarea name="description" class="form-control"><?php echo htmlspecialchars($template['description'] ?? ''); ?></textarea>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label"><?= htmlspecialchars($desttable, ENT_QUOTES, 'UTF-8'); ?>*</label> <label class="form-label"><?= htmlspecialchars($desttable, ENT_QUOTES, 'UTF-8'); ?> *</label>
<input type="text" name="target_table" class="form-control" value="<?php echo htmlspecialchars($template['target_table']); ?>" readonly required> <input type="text" name="target_table" class="form-control" value="<?php echo htmlspecialchars($template['target_table'] ?? 'datadb'); ?>" readonly required>
</div> </div>
<div class="mb-3"> <div class="mb-3">
@ -110,12 +123,12 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Button Background Color</label> <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'); ?>"> <input type="color" name="button_bg_color" class="form-control form-control-color" value="<?php echo htmlspecialchars($template['button_bg_color'] ?? '#007bff'); ?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Button Text Color</label> <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'); ?>"> <input type="color" name="button_text_color" class="form-control form-control-color" value="<?php echo htmlspecialchars($template['button_text_color'] ?? '#ffffff'); ?>">
</div> </div>
<div class="mb-3"> <div class="mb-3">
@ -128,7 +141,7 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<select name="client_id" id="clientSelect" class="form-control" required> <select name="client_id" id="clientSelect" class="form-control" required>
<option value="">Select a client...</option> <option value="">Select a client...</option>
</select> </select>
<span id="clientLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Recupero clienti in corso...</span> <span id="clientLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Loading clients...</span>
</div> </div>
<div class="mb-3"> <div class="mb-3">
@ -136,7 +149,7 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<select name="schema_id" id="schemaSelect" class="form-control" required> <select name="schema_id" id="schemaSelect" class="form-control" required>
<option value="">Select a schema...</option> <option value="">Select a schema...</option>
</select> </select>
<span id="schemaLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Caricamento schemi in corso...</span> <span id="schemaLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Loading schemas...</span>
</div> </div>
<div class="mb-3"> <div class="mb-3">
@ -144,11 +157,12 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<select name="idroutine" id="routineSelect" class="form-control"> <select name="idroutine" id="routineSelect" class="form-control">
<option value="">Select a routine...</option> <option value="">Select a routine...</option>
<?php foreach ($routines as $routine): ?> <?php foreach ($routines as $routine): ?>
<option value="<?php echo $routine['idroutine']; ?>" <?php echo ($template['idroutine'] ?? '') == $routine['idroutine'] ? 'selected' : ''; ?>> <option value="<?php echo $routine['idroutine']; ?>" <?php echo (($template['idroutine'] ?? '') == $routine['idroutine']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($routine['name']); ?> <?php echo htmlspecialchars($routine['name']); ?>
</option> </option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
<div id="routineDetails" class="mt-2" style="display: none;"> <div id="routineDetails" class="mt-2" style="display: none;">
<h6>Routine Details</h6> <h6>Routine Details</h6>
<p><strong>Name:</strong> <span id="routineName"></span></p> <p><strong>Name:</strong> <span id="routineName"></span></p>
@ -166,8 +180,10 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="overlay toggle-icon"></div> <div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?> <?php include('include/footer.php'); ?>
@ -175,9 +191,8 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<script> <script>
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
// Verifica che jQuery sia caricato
if (typeof jQuery === 'undefined') { if (typeof jQuery === 'undefined') {
alert("Errore: jQuery non è caricato. Contatta l'amministratore."); alert("Error: jQuery is not loaded.");
return; return;
} }
@ -192,12 +207,15 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
const routineAction2 = document.getElementById("routineAction2"); const routineAction2 = document.getElementById("routineAction2");
const routineAction3 = document.getElementById("routineAction3"); const routineAction3 = document.getElementById("routineAction3");
if (!form || !clientLoadingStatus || !schemaLoadingStatus || !routineSelect || !routineDetails) { const sourceType = document.getElementById("sourceType");
alert("Errore: Uno o più elementi della pagina non sono stati trovati. Contatta l'amministratore."); const headerRowWrapper = document.getElementById("headerRowWrapper");
return; const startColumnWrapper = document.getElementById("startColumnWrapper");
} const headerRow = document.getElementById("headerRow");
const startColumn = document.getElementById("startColumn");
const selectedClientId = <?php echo json_encode((int)($template['idclient'] ?? 0)); ?>;
const selectedSchemaId = <?php echo json_encode((int)($template['idschema'] ?? 0)); ?>;
// Inizializza Select2
$('#clientSelect').select2({ $('#clientSelect').select2({
placeholder: "Search for a client...", placeholder: "Search for a client...",
allowClear: true allowClear: true
@ -213,108 +231,164 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
allowClear: true allowClear: true
}); });
// Carica i clienti function updateSourceFields() {
const selectedSource = sourceType.value;
if (selectedSource === 'API') {
headerRowWrapper.style.opacity = '0.6';
startColumnWrapper.style.opacity = '0.6';
headerRow.required = false;
startColumn.required = false;
headerRow.disabled = true;
startColumn.disabled = true;
} else {
headerRowWrapper.style.opacity = '1';
startColumnWrapper.style.opacity = '1';
headerRow.required = true;
startColumn.required = true;
headerRow.disabled = false;
startColumn.disabled = false;
}
}
sourceType.addEventListener('change', updateSourceFields);
updateSourceFields();
async function loadClients() { async function loadClients() {
try { try {
clientLoadingStatus.style.display = 'inline'; clientLoadingStatus.style.display = 'inline';
clientLoadingStatus.textContent = 'Recupero clienti in corso...'; clientLoadingStatus.textContent = 'Loading clients...';
const response = await fetch("get_clienti.php", { const response = await fetch("get_clienti.php", {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
}); });
const data = await response.json(); const data = await response.json();
if (!response.ok) throw new Error(data.error || `Errore HTTP: ${response.status}`);
if (!response.ok) {
throw new Error(data.error || `HTTP error: ${response.status}`);
}
const select = document.getElementById("clientSelect"); const select = document.getElementById("clientSelect");
select.innerHTML = '<option value="">Select a client...</option>'; select.innerHTML = '<option value="">Select a client...</option>';
data.value.forEach(client => { data.value.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile"; const nome = client.Nominativo || "Name not available";
const id = client.IdCliente || "ID non disponibile"; const id = client.IdCliente || "";
const option = new Option(`${nome.trim()} (ID: ${id})`, id); const option = new Option(`${nome.trim()} (ID: ${id})`, id);
if (parseInt(id) === parseInt(<?php echo json_encode($template['idclient'] ?? 0); ?>)) {
if (parseInt(id) === parseInt(selectedClientId)) {
option.selected = true; option.selected = true;
} }
select.add(option); select.add(option);
}); });
$(select).trigger('change'); $(select).trigger('change');
clientLoadingStatus.textContent = "Clienti caricati."; clientLoadingStatus.textContent = "Clients loaded.";
} catch (error) { } catch (error) {
clientLoadingStatus.textContent = "Errore nel caricamento."; clientLoadingStatus.textContent = "Loading error.";
Swal.fire({ Swal.fire({
title: "Errore!", title: "Error!",
text: "Impossibile caricare i clienti: " + error.message, text: "Unable to load clients: " + error.message,
icon: "error", icon: "error",
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
} finally { } finally {
setTimeout(() => clientLoadingStatus.style.display = 'none', 2000); setTimeout(() => clientLoadingStatus.style.display = 'none', 1500);
} }
} }
// Carica gli schemi
async function loadSchemas() { async function loadSchemas() {
try { try {
schemaLoadingStatus.style.display = 'inline'; schemaLoadingStatus.style.display = 'inline';
schemaLoadingStatus.textContent = 'Caricamento schemi in corso...'; schemaLoadingStatus.textContent = 'Loading schemas...';
const response = await fetch("get_schemi.php", { const response = await fetch("get_schemi.php", {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
}); });
const data = await response.json(); const data = await response.json();
if (!response.ok) throw new Error(data.error || `Errore HTTP: ${response.status}`);
if (!response.ok) {
throw new Error(data.error || `HTTP error: ${response.status}`);
}
const select = document.getElementById("schemaSelect"); const select = document.getElementById("schemaSelect");
select.innerHTML = '<option value="">Select a schema...</option>'; select.innerHTML = '<option value="">Select a schema...</option>';
data.value.forEach(schema => {
const nome = schema.Nome || "Nome non disponibile"; const sortedSchemas = [...data.value].sort((a, b) => {
const id = schema.IdSchemaCustomFields || "ID non disponibile"; const nomeA = (a.Nome || "").trim().toLowerCase();
const nomeB = (b.Nome || "").trim().toLowerCase();
return nomeA.localeCompare(nomeB, 'it', {
sensitivity: 'base'
});
});
sortedSchemas.forEach(schema => {
const nome = schema.Nome || "Name not available";
const id = schema.IdSchemaCustomFields || "";
const option = new Option(`${nome.trim()} (ID: ${id})`, id); const option = new Option(`${nome.trim()} (ID: ${id})`, id);
if (parseInt(id) === parseInt(<?php echo json_encode($template['idschema'] ?? 0); ?>)) {
if (parseInt(id) === parseInt(selectedSchemaId)) {
option.selected = true; option.selected = true;
} }
select.add(option); select.add(option);
}); });
$(select).trigger('change'); $(select).trigger('change');
schemaLoadingStatus.textContent = "Schemi caricati."; schemaLoadingStatus.textContent = "Schemas loaded.";
} catch (error) { } catch (error) {
schemaLoadingStatus.textContent = "Errore nel caricamento."; schemaLoadingStatus.textContent = "Loading error.";
Swal.fire({ Swal.fire({
title: "Errore!", title: "Error!",
text: "Impossibile caricare gli schemi: " + error.message, text: "Unable to load schemas: " + error.message,
icon: "error", icon: "error",
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
} finally { } finally {
setTimeout(() => schemaLoadingStatus.style.display = 'none', 2000); setTimeout(() => schemaLoadingStatus.style.display = 'none', 1500);
} }
} }
// Carica i dati
async function loadData() { async function loadData() {
try { try {
await loadClients(); await loadClients();
await loadSchemas(); await loadSchemas();
} catch (error) { } catch (error) {
Swal.fire({ Swal.fire({
title: "Errore!", title: "Error!",
text: "Errore nel caricamento dei dati: " + error.message, text: "Error while loading data: " + error.message,
icon: "error", icon: "error",
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
} }
} }
loadData(); loadData();
// Routine dettagli
const routines = <?php echo json_encode($routines); ?>; const routines = <?php echo json_encode($routines); ?>;
function updateRoutineDetails() { function updateRoutineDetails() {
const selectedId = routineSelect.value; const selectedId = routineSelect.value;
routineDetails.style.display = selectedId ? 'block' : 'none'; routineDetails.style.display = selectedId ? 'block' : 'none';
if (selectedId) { if (selectedId) {
const routine = routines.find(r => r.idroutine == selectedId); const routine = routines.find(r => r.idroutine == selectedId);
if (routine) { if (routine) {
routineName.textContent = routine.name || 'N/A'; routineName.textContent = routine.name || 'N/A';
routineDescription.textContent = routine.description || 'N/A'; routineDescription.textContent = routine.description || 'N/A';
@ -336,10 +410,10 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
routineAction3.textContent = ''; routineAction3.textContent = '';
} }
} }
routineSelect.addEventListener('change', updateRoutineDetails);
updateRoutineDetails(); // Inizializza dettagli se una routine è preselezionata
// Submit del form routineSelect.addEventListener('change', updateRoutineDetails);
updateRoutineDetails();
form.addEventListener("submit", function(e) { form.addEventListener("submit", function(e) {
e.preventDefault(); e.preventDefault();
@ -351,8 +425,8 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!clientId) { if (!clientId) {
Swal.fire({ Swal.fire({
title: "Errore!", title: "Error!",
text: "Per favore seleziona un cliente.", text: "Please select a client.",
icon: "error", icon: "error",
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
@ -373,8 +447,8 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!schemaId) { if (!schemaId) {
Swal.fire({ Swal.fire({
title: "Errore!", title: "Error!",
text: "Per favore seleziona uno schema.", text: "Please select a schema.",
icon: "error", icon: "error",
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
@ -387,10 +461,10 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/); const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
schemaName = nameMatch ? nameMatch[1].trim() : optionText; schemaName = nameMatch ? nameMatch[1].trim() : optionText;
} }
formData.append("idschema", schemaId); formData.append("idschema", schemaId);
formData.append("schemaname", schemaName); formData.append("schemaname", schemaName);
// Aggiungi idroutine
const routineId = routineSelect.value; const routineId = routineSelect.value;
formData.append("idroutine", routineId); formData.append("idroutine", routineId);
@ -402,8 +476,8 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
.then(data => { .then(data => {
if (data.success) { if (data.success) {
Swal.fire({ Swal.fire({
title: "Successo!", title: "Success!",
text: "Template aggiornato con successo!", text: "Template updated successfully!",
icon: "success", icon: "success",
confirmButtonText: "OK" confirmButtonText: "OK"
}).then(() => { }).then(() => {
@ -411,17 +485,17 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
}); });
} else { } else {
Swal.fire({ Swal.fire({
title: "Errore!", title: "Error!",
text: data.message, text: data.message,
icon: "error", icon: "error",
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
} }
}) })
.catch(error => { .catch(() => {
Swal.fire({ Swal.fire({
title: "Errore!", title: "Error!",
text: "Si è verificato un errore imprevisto.", text: "An unexpected error occurred.",
icon: "error", icon: "error",
confirmButtonText: "OK" confirmButtonText: "OK"
}); });

View File

@ -9,46 +9,76 @@ try {
throw new Exception("Invalid request method."); throw new Exception("Invalid request method.");
} }
// Recupera e sanifica i dati // Retrieve and sanitize form data
$id = intval($_POST['id']); $id = intval($_POST['id'] ?? 0);
$name = trim($_POST['name']); $name = trim($_POST['name'] ?? '');
$header_row = intval($_POST['header_row']); $source_type = strtoupper(trim($_POST['source_type'] ?? 'XLS'));
$start_column = trim($_POST['start_column']); $header_row = isset($_POST['header_row']) && $_POST['header_row'] !== '' ? intval($_POST['header_row']) : null;
$start_column = trim($_POST['start_column'] ?? '');
$description = trim($_POST['description'] ?? ''); $description = trim($_POST['description'] ?? '');
$target_table = trim($_POST['target_table']); $target_table = trim($_POST['target_table'] ?? 'datadb');
$idclient = intval($_POST['client_id'] ?? 0); // Usa client_id dal form $idclient = intval($_POST['client_id'] ?? 0);
$clientname = trim($_POST['client_name'] ?? ''); // Usa client_name dal form $clientname = trim($_POST['client_name'] ?? '');
$idschema = intval($_POST['idschema'] ?? 0); // Nuovo campo $idschema = intval($_POST['idschema'] ?? 0);
$schemaname = trim($_POST['schemaname'] ?? ''); // Corretto da schemamaname $schemaname = trim($_POST['schemaname'] ?? '');
$idroutine = isset($_POST['idroutine']) && $_POST['idroutine'] !== '' ? intval($_POST['idroutine']) : null; // Aggiunto idroutine $idroutine = isset($_POST['idroutine']) && $_POST['idroutine'] !== '' ? intval($_POST['idroutine']) : null;
$button_size = trim($_POST['button_size'] ?? 'medium'); // Nuovo campo $button_size = trim($_POST['button_size'] ?? 'medium');
$button_bg_color = trim($_POST['button_bg_color'] ?? '#007bff'); // Nuovo campo $button_bg_color = trim($_POST['button_bg_color'] ?? '#007bff');
$button_text_color = trim($_POST['button_text_color'] ?? '#ffffff'); // Nuovo campo $button_text_color = trim($_POST['button_text_color'] ?? '#ffffff');
$button_label = trim($_POST['button_label'] ?? 'Click Me'); // Nuovo campo $button_label = trim($_POST['button_label'] ?? 'Click Me');
// Controllo sui campi obbligatori if (!in_array($source_type, ['XLS', 'API'], true)) {
if (empty($id) || empty($name) || empty($header_row) || empty($start_column) || empty($target_table) || $idschema <= 0) { $source_type = 'XLS';
throw new Exception("All fields marked with * are required, including schema.");
} }
// Validazione del idclient // Required fields validation
if ($idclient <= 0) { if ($id <= 0 || $name === '' || $target_table === '' || $idclient <= 0 || $idschema <= 0) {
throw new Exception("Please select a valid client."); throw new Exception("All fields marked with * are required, including client and schema.");
} }
// Connessione al database // XLS-only validation
if ($source_type === 'XLS') {
if ($header_row === null || $header_row <= 0 || $start_column === '') {
throw new Exception("Header Row and Start Column are required for XLS templates.");
}
}
// API templates do not require XLS coordinates
if ($source_type === 'API') {
$header_row = null;
$start_column = null;
}
// Database connection
$db = DBHandlerSelect::getInstance(); $db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection(); $pdo = $db->getConnection();
// Aggiorna il database, includendo i nuovi campi // Update template
$stmt = $pdo->prepare("UPDATE excel_templates $stmt = $pdo->prepare("
SET name = ?, header_row = ?, start_column = ?, description = ?, target_table = ?, UPDATE excel_templates
idclient = ?, clientname = ?, schemaname = ?, idschema = ?, idroutine = ?, SET
button_size = ?, button_bg_color = ?, button_text_color = ?, button_label = ?, name = ?,
updated_at = NOW() source_type = ?,
WHERE id = ?"); header_row = ?,
start_column = ?,
description = ?,
target_table = ?,
idclient = ?,
clientname = ?,
schemaname = ?,
idschema = ?,
idroutine = ?,
button_size = ?,
button_bg_color = ?,
button_text_color = ?,
button_label = ?,
updated_at = NOW()
WHERE id = ?
");
$stmt->execute([ $stmt->execute([
$name, $name,
$source_type,
$header_row, $header_row,
$start_column, $start_column,
$description, $description,
@ -65,12 +95,10 @@ try {
$id $id
]); ]);
// rowCount potrebbe essere 0 se non ci sono modifiche, quindi consideriamo comunque un successo
$response["success"] = true; $response["success"] = true;
$response["message"] = "Template updated successfully!"; $response["message"] = "Template updated successfully!";
} catch (Exception $e) { } catch (Exception $e) {
$response["message"] = $e->getMessage(); $response["message"] = $e->getMessage();
} }
// Restituisce un JSON per il fetch
echo json_encode($response); echo json_encode($response);