Compare commits

..

1 Commits

Author SHA1 Message Date
solocla cf45a5bc31 fixed export to lims 2025-09-22 16:36:23 +02:00
4 changed files with 589 additions and 153 deletions
@@ -1,5 +1,5 @@
<?php <?php
require_once dirname(__DIR__, 3) . '/vendor/autoload.php'; // Torna al livello di public require_once dirname(__DIR__, 3) . '/vendor/autoload.php';
use Dotenv\Dotenv; use Dotenv\Dotenv;
@@ -13,7 +13,7 @@ class VisualLimsApiClient
private function __construct() private function __construct()
{ {
$dotenv = Dotenv::createImmutable(dirname(__DIR__, 3)); // Torna al livello di public $dotenv = Dotenv::createImmutable(dirname(__DIR__, 3)); // Corretto per C:\xampp8-2-12\htdocs\trf_certest\.env
$dotenv->load(); $dotenv->load();
$this->baseUrl = $_ENV['API_BASE_URL']; $this->baseUrl = $_ENV['API_BASE_URL'];
@@ -87,6 +87,7 @@ class VisualLimsApiClient
$token = $this->getToken(); $token = $this->getToken();
$url = "{$this->baseUrl}/api/odata/{$endpoint}"; $url = "{$this->baseUrl}/api/odata/{$endpoint}";
$ch = curl_init($url); $ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [ curl_setopt($ch, CURLOPT_HTTPHEADER, [
@@ -120,4 +121,88 @@ class VisualLimsApiClient
return $data; return $data;
} }
public function post($endpoint, $payload)
{
$token = $this->getToken();
$url = "{$this->baseUrl}/api/odata/{$endpoint}"; // Corretto per /api/odata/CommessaWeb
file_put_contents(__DIR__ . '/url_debug.log', date('Y-m-d H:i:s') . " - POST URL: {$url}\n", FILE_APPEND);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$token}",
"Content-Type: application/json",
"Accept: application/json"
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$log = fopen(__DIR__ . '/curl_request_debug.log', 'w') ?: fopen('php://stderr', 'w');
curl_setopt($ch, CURLOPT_STDERR, $log);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
fclose($log);
curl_close($ch);
if ($response === false) {
throw new Exception("Errore nella richiesta POST: {$curl_error}");
}
if ($http_code >= 400) {
throw new Exception("Errore nella richiesta POST: HTTP {$http_code}, Risposta: " . substr($response, 0, 1000));
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Risposta non JSON valida: " . substr($response, 0, 1000));
}
return $data;
}
public function patch($endpoint, $payload)
{
$token = $this->getToken();
$url = "{$this->baseUrl}/api/odata/{$endpoint}"; // Corretto per /api/odata/CommessaWeb({key})
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$token}",
"Content-Type: application/json",
"Accept: application/json"
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$log = fopen(__DIR__ . '/curl_request_debug.log', 'w') ?: fopen('php://stderr', 'w');
curl_setopt($ch, CURLOPT_STDERR, $log);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
fclose($log);
curl_close($ch);
if ($response === false) {
throw new Exception("Errore nella richiesta PATCH: {$curl_error}");
}
if ($http_code >= 400) {
throw new Exception("Errore nella richiesta PATCH: HTTP {$http_code}, Risposta: " . substr($response, 0, 1000));
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Risposta non JSON valida: " . substr($response, 0, 1000));
}
return $data;
}
} }
+413 -115
View File
@@ -20,10 +20,17 @@ if (!$template) {
exit; exit;
} }
// Recupera tutte le routine dal database // Debug del JSON
$stmt = $pdo->prepare("SELECT * FROM routine"); $clientSpecificFieldsJson = $template['client_specific_fields'] ?? '{}';
$stmt->execute(); error_log("Raw client_specific_fields JSON: " . $clientSpecificFieldsJson);
$routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
$clientSpecificFields = json_decode($clientSpecificFieldsJson, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("JSON decode error: " . json_last_error_msg());
$clientSpecificFields = [];
} else {
error_log("Decoded client_specific_fields: " . print_r($clientSpecificFields, true));
}
?> ?>
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
@@ -34,9 +41,28 @@ $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 --> <style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> .client-field-row .row {
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> margin-bottom: 0 !important;
display: flex;
align-items: center;
}
.client-field-row .col-md-1,
.client-field-row .col-md-2,
.client-field-row .col-md-3 {
padding: 0 5px;
overflow: hidden;
max-width: 100%;
flex: 0 0 auto;
}
.client-field-row input,
.client-field-row select {
width: 100%;
box-sizing: border-box;
}
</style>
<title>Edit Template <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title> <title>Edit Template <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
</head> </head>
@@ -56,7 +82,7 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<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>Row Header and Column Header: where the title of the excel starts</li>
<li>Schema</li> <li>Cheme</li>
</ul> </ul>
</div> </div>
</div> </div>
@@ -98,43 +124,96 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
<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']); ?>" readonly required>
</div> </div>
<!-- Aggiungi il campo per selezionare il cliente -->
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Select Client *</label> <label class="form-label">Select Client *</label>
<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>
<!-- Le opzioni verranno popolate tramite JavaScript -->
</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;">Recupero clienti in corso...</span>
</div> </div>
<!-- Aggiungi il campo per selezionare lo schema -->
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Select Schema *</label> <label class="form-label">Select Schema *</label>
<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>
<!-- Le opzioni verranno popolate tramite JavaScript -->
</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;">Caricamento schemi in corso...</span>
</div> </div>
<!-- Sezione per i campi specifici del cliente -->
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Select Routine</label> <label class="form-label">Client-Specific Fields</label>
<select name="idroutine" id="routineSelect" class="form-control">
<option value="">Select a routine...</option> <!-- Intestazioni colonne -->
<?php foreach ($routines as $routine): ?> <div class="row fw-bold text-secondary mb-1">
<option value="<?php echo $routine['idroutine']; ?>" <?php echo ($template['idroutine'] ?? '') == $routine['idroutine'] ? 'selected' : ''; ?>> <div class="col-md-3">Field Name</div>
<?php echo htmlspecialchars($routine['name']); ?> <div class="col-md-2">Type</div>
</option> <div class="col-md-2">Possible Values</div>
<?php endforeach; ?> <div class="col-md-1">Required</div>
</select> <div class="col-md-2">Export Column Name</div>
<div id="routineDetails" class="mt-2" style="display: none;"> <div class="col-md-1">Default Value</div>
<h6>Routine Details</h6> <div class="col-md-1">Actions</div>
<p><strong>Name:</strong> <span id="routineName"></span></p>
<p><strong>Description:</strong> <span id="routineDescription"></span></p>
<p><strong>Action 1:</strong> <span id="routineAction1"></span></p>
<p><strong>Action 2:</strong> <span id="routineAction2"></span></p>
<p><strong>Action 3:</strong> <span id="routineAction3"></span></p>
</div> </div>
<div id="clientSpecificFields">
<?php
$index = 0;
if (!empty($clientSpecificFields) && is_array($clientSpecificFields)) {
foreach ($clientSpecificFields as $fieldName => $fieldData) {
if (is_array($fieldData)) {
$type = $fieldData['type'] ?? 'text';
$possibleValues = implode(', ', $fieldData['possible_values'] ?? []);
$isRequired = isset($fieldData['is_required']) && $fieldData['is_required'] ? '1' : '0';
$exportColumnName = $fieldData['export_column_name'] ?? '';
$defaultValue = $fieldData['default_value'] ?? '';
?>
<div class="client-field-row mb-2">
<div class="row align-items-center">
<div class="col-md-3">
<input type="text" name="specific_fields[<?php echo $index; ?>][name]" class="form-control" value="<?php echo htmlspecialchars($fieldName); ?>" placeholder="Field Name (e.g., SKU)">
</div>
<div class="col-md-2">
<select name="specific_fields[<?php echo $index; ?>][type]" class="form-control" onchange="toggleDropdownValues(this)">
<option value="text" <?php echo $type === 'text' ? 'selected' : ''; ?>>Text</option>
<option value="dropdown" <?php echo $type === 'dropdown' ? 'selected' : ''; ?>>Dropdown</option>
<option value="date" <?php echo $type === 'date' ? 'selected' : ''; ?>>Date</option>
<option value="boolean" <?php echo $type === 'boolean' ? 'selected' : ''; ?>>Yes/No</option>
</select>
</div>
<div class="col-md-2 dropdown-values" style="<?php echo $type === 'dropdown' ? 'visibility: visible;' : 'visibility: hidden;'; ?>">
<input type="text" name="specific_fields[<?php echo $index; ?>][possible_values]" class="form-control" value="<?php echo htmlspecialchars($possibleValues); ?>" placeholder="Values (e.g., Red, Blue, Green)">
</div>
<div class="col-md-1">
<select name="specific_fields[<?php echo $index; ?>][required]" class="form-control">
<option value="1" <?php echo $isRequired === '1' ? 'selected' : ''; ?>>Yes</option>
<option value="0" <?php echo $isRequired === '0' ? 'selected' : ''; ?>>No</option>
</select>
</div>
<div class="col-md-2">
<input type="text" name="specific_fields[<?php echo $index; ?>][export_column_name]" class="form-control" value="<?php echo htmlspecialchars($exportColumnName); ?>" placeholder="Export Column Name (e.g., MONCLER_SKU)">
</div>
<div class="col-md-1">
<input type="text" name="specific_fields[<?php echo $index; ?>][default_value]" class="form-control" value="<?php echo htmlspecialchars($defaultValue); ?>" placeholder="Default Value (optional)">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-danger remove-field">-</button>
</div>
</div>
</div>
<?php
$index++;
}
}
}
?>
</div>
<button type="button" class="btn btn-primary mt-2" id="addField">Add Field</button>
</div> </div>
<br> <br>
<button type="submit" class="btn btn-primary"><?= htmlspecialchars($savechanges, ENT_QUOTES, 'UTF-8'); ?></button> <button type="submit" class="btn btn-primary"><?= htmlspecialchars($savechanges, ENT_QUOTES, 'UTF-8'); ?></button>
<a href="templates_dashboard.php" class="btn btn-secondary">Cancel</a> <a href="templates_dashboard.php" class="btn btn-secondary">Cancel</a>
@@ -144,78 +223,132 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
</div> </div>
</div> </div>
</div> </div>
<!--end page wrapper -->
<!--start overlay-->
<div class="overlay toggle-icon"></div> <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> <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'); ?> <?php include('include/footer.php'); ?>
</div> </div>
<!--end wrapper-->
<!-- search modal -->
<?php //include('include/searchmodal.php');
?>
<!-- end search modal -->
<!--start switcher-->
<?php //include('include/themeswitcher.php');
?>
<!--end switcher-->
<!-- Temporaneamente disabilitato jsinclude.php per test -->
<!-- <?php include('jsinclude.php'); ?> -->
<!-- Includi jQuery e Select2 -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// 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> <script>
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
// Verifica che jQuery sia caricato
if (typeof jQuery === 'undefined') {
alert("Errore: jQuery non è caricato. Contatta l'amministratore.");
return;
}
const form = document.getElementById("editTemplateForm"); const form = document.getElementById("editTemplateForm");
const addFieldButton = document.getElementById("addField");
const container = document.getElementById("clientSpecificFields");
const clientLoadingStatus = document.getElementById("clientLoadingStatus"); const clientLoadingStatus = document.getElementById("clientLoadingStatus");
const schemaLoadingStatus = document.getElementById("schemaLoadingStatus"); const schemaLoadingStatus = document.getElementById("schemaLoadingStatus");
const routineSelect = document.getElementById("routineSelect");
const routineDetails = document.getElementById("routineDetails");
const routineName = document.getElementById("routineName");
const routineDescription = document.getElementById("routineDescription");
const routineAction1 = document.getElementById("routineAction1");
const routineAction2 = document.getElementById("routineAction2");
const routineAction3 = document.getElementById("routineAction3");
if (!form || !clientLoadingStatus || !schemaLoadingStatus || !routineSelect || !routineDetails) { if (!form || !addFieldButton || !container || !clientLoadingStatus || !schemaLoadingStatus) {
alert("Errore: Uno o più elementi della pagina non sono stati trovati. Contatta l'amministratore."); console.error("One or more DOM elements not found:", {
form,
addFieldButton,
container,
clientLoadingStatus,
schemaLoadingStatus
});
return; return;
} }
// Inizializza Select2 console.log("All DOM elements found");
// Controllo che jQuery sia caricato
if (typeof jQuery === 'undefined') {
console.error("jQuery non è caricato!");
return;
}
// Inizializza Select2 sulla tendina dei clienti
$('#clientSelect').select2({ $('#clientSelect').select2({
placeholder: "Search for a client...", placeholder: "Search for a client...",
allowClear: true allowClear: true
}).on('select2:open', function() {
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({ $('#schemaSelect').select2({
placeholder: "Search for a schema...", placeholder: "Search for a schema...",
allowClear: true 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);
}); });
$('#routineSelect').select2({ // Carica i clienti al caricamento della pagina
placeholder: "Select a routine...",
allowClear: true
});
// Carica i clienti
async function loadClients() { async function loadClients() {
try { try {
clientLoadingStatus.style.display = 'inline'; clientLoadingStatus.style.display = 'inline';
clientLoadingStatus.textContent = 'Recupero clienti in corso...'; clientLoadingStatus.textContent = 'Recupero clienti in corso...';
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();
if (!response.ok) throw new Error(data.error || `Errore HTTP: ${response.status}`); const text = await response.text();
const select = document.getElementById("clientSelect"); console.log("Risposta raw (clienti):", text);
select.innerHTML = '<option value="">Select a client...</option>'; const data = JSON.parse(text);
data.value.forEach(client => {
const nome = client.Nominativo || "Nome non disponibile"; if (!response.ok) {
const id = client.IdCliente || "ID non disponibile"; throw new Error(data.error || `Errore HTTP: ${response.status}`);
const option = new Option(`${nome.trim()} (ID: ${id})`, id); }
if (parseInt(id) === parseInt(<?php echo json_encode($template['idclient'] ?? 0); ?>)) {
option.selected = true; if (data.value && Array.isArray(data.value)) {
} const select = document.getElementById("clientSelect");
select.add(option); select.innerHTML = '<option value="">Select a client...</option>';
}); data.value.forEach(client => {
$(select).trigger('change'); const nome = client.Nominativo || "Nome non disponibile";
clientLoadingStatus.textContent = "Clienti caricati."; const id = client.IdCliente || "ID non disponibile";
const option = new Option(`${nome.trim()} (ID: ${id})`, id);
if (parseInt(id) === parseInt(templateClientId)) {
option.selected = true;
}
select.add(option);
});
$(select).trigger('change');
console.log("Clienti caricati con successo.");
clientLoadingStatus.textContent = "Clienti caricati.";
} else {
console.error("Nessun cliente trovato o formato dati non valido.", data);
clientLoadingStatus.textContent = "Nessun cliente trovato.";
Swal.fire({
title: "Errore!",
text: "Nessun cliente trovato o formato dati non valido.",
icon: "error",
confirmButtonText: "OK"
});
}
} catch (error) { } catch (error) {
console.error("Errore nel caricamento dei clienti:", error);
clientLoadingStatus.textContent = "Errore nel caricamento."; clientLoadingStatus.textContent = "Errore nel caricamento.";
Swal.fire({ Swal.fire({
title: "Errore!", title: "Errore!",
@@ -224,37 +357,50 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
} finally { } finally {
setTimeout(() => clientLoadingStatus.style.display = 'none', 2000); setTimeout(() => {
clientLoadingStatus.style.display = 'none';
}, 2000);
} }
} }
// Carica gli schemi // Carica gli schemi al caricamento della pagina
async function loadSchemas() { async function loadSchemas() {
try { try {
schemaLoadingStatus.style.display = 'inline'; schemaLoadingStatus.style.display = 'inline';
schemaLoadingStatus.textContent = 'Caricamento schemi in corso...'; schemaLoadingStatus.textContent = 'Caricamento schemi in corso...';
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();
if (!response.ok) throw new Error(data.error || `Errore HTTP: ${response.status}`); 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"); 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 => { data.value.forEach(schema => {
const nome = schema.Nome || "Nome non disponibile"; const nome = schema.Nome || "Nome non disponibile";
const id = schema.IdSchemaCustomFields || "ID non disponibile"; const id = schema.IdSchemaCustomFields || "ID non disponibile";
const option = new Option(`${nome.trim()} (ID: ${id})`, id); const optionText = `${nome.trim()} (ID: ${id})`;
if (parseInt(id) === parseInt(<?php echo json_encode($template['idschema'] ?? 0); ?>)) { const option = new Option(optionText, id);
if (parseInt(id) === parseInt(templateSchemaId)) {
option.selected = true; option.selected = true;
} }
select.add(option); select.add(option);
}); });
$(select).trigger('change'); $(select).trigger('change');
console.log("Schemi caricati con successo.");
schemaLoadingStatus.textContent = "Schemi caricati."; schemaLoadingStatus.textContent = "Schemi caricati.";
} catch (error) { } catch (error) {
console.error("Errore nel caricamento degli schemi:", error);
schemaLoadingStatus.textContent = "Errore nel caricamento."; schemaLoadingStatus.textContent = "Errore nel caricamento.";
Swal.fire({ Swal.fire({
title: "Errore!", title: "Errore!",
@@ -263,68 +409,169 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
confirmButtonText: "OK" confirmButtonText: "OK"
}); });
} finally { } finally {
setTimeout(() => schemaLoadingStatus.style.display = 'none', 2000); setTimeout(() => {
schemaLoadingStatus.style.display = 'none';
}, 2000);
} }
} }
// Carica i dati // Carica i dati in sequenza
async function loadData() { async function loadData() {
try { try {
await loadClients(); await loadClients();
await loadSchemas(); await loadSchemas();
} catch (error) { } catch (error) {
Swal.fire({ console.error("Errore nel caricamento dei dati:", error);
title: "Errore!", }
text: "Errore nel caricamento dei dati: " + error.message, }
icon: "error",
confirmButtonText: "OK" loadData();
// Debug iniziale del DOM
const debugDom = () => {
const initialRows = container.getElementsByClassName("client-field-row");
console.log("Initial number of rows:", initialRows.length);
for (let i = 0; i < initialRows.length; i++) {
const inputs = initialRows[i].querySelectorAll("input, select");
const buttons = initialRows[i].querySelectorAll("button");
console.log(`Row ${i + 1} - Total inputs: ${inputs.length}, Total buttons: ${buttons.length}`);
inputs.forEach(input => console.log(`Input name: ${input.name}, value: ${input.value}, placeholder: ${input.placeholder}`));
buttons.forEach(button => console.log(`Button type: ${button.type}`));
}
};
debugDom();
// Pulizia del DOM da input extra
const cleanDom = () => {
const rows = container.getElementsByClassName("client-field-row");
for (let i = 0; i < rows.length; i++) {
const inputs = rows[i].querySelectorAll("input, select");
if (inputs.length > 6) { // 6 input/select attesi
console.warn(`Row ${i + 1}: Extra inputs detected, removing excess...`);
inputs.forEach((input, index) => {
if (index >= 6) {
console.log(`Removing extra input: ${input.name}`);
input.remove();
}
});
}
}
};
cleanDom();
// Osservatore del DOM per rilevare modifiche
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (mutation.addedNodes.length) {
console.log("DOM modified: New nodes added", mutation.addedNodes);
cleanDom(); // Pulisce il DOM ogni volta che viene modificato
}
});
});
observer.observe(container, {
childList: true,
subtree: true
});
// Gestione dinamica dei campi specifici
addFieldButton.addEventListener("click", function() {
console.log("Add Field button clicked");
const fieldCount = container.getElementsByClassName("client-field-row").length;
const newField = document.createElement("div");
newField.className = "client-field-row mb-2";
newField.innerHTML = `
<div class="row align-items-center">
<div class="col-md-3">
<input type="text" name="specific_fields[${fieldCount}][name]" class="form-control" placeholder="Field Name (e.g., SKU)">
</div>
<div class="col-md-2">
<select name="specific_fields[${fieldCount}][type]" class="form-control" onchange="toggleDropdownValues(this)">
<option value="text">Text</option>
<option value="dropdown">Dropdown</option>
<option value="date">Date</option>
<option value="boolean">Yes/No</option>
</select>
</div>
<div class="col-md-2 dropdown-values" style="visibility: hidden;">
<input type="text" name="specific_fields[${fieldCount}][possible_values]" class="form-control" placeholder="Values (e.g., Red, Blue, Green)">
</div>
<div class="col-md-1">
<select name="specific_fields[${fieldCount}][required]" class="form-control">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<div class="col-md-2">
<input type="text" name="specific_fields[${fieldCount}][export_column_name]" class="form-control" placeholder="Export Column Name (e.g., MONCLER_SKU)">
</div>
<div class="col-md-1">
<input type="text" name="specific_fields[${fieldCount}][default_value]" class="form-control" placeholder="Default Value (optional)">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-danger remove-field">-</button>
</div>
</div>
`;
container.appendChild(newField);
newField.querySelector(".remove-field").addEventListener("click", function() {
console.log("Remove Field button clicked");
container.removeChild(newField);
updateFieldIndices();
});
});
// Funzione per mostrare/nascondere il campo dei valori possibili per i dropdown
window.toggleDropdownValues = function(selectElement) {
console.log("Toggling dropdown values for:", selectElement.value);
const row = selectElement.closest(".row");
const dropdownValues = row.querySelector(".dropdown-values");
if (selectElement.value === "dropdown") {
dropdownValues.style.visibility = "visible";
} else {
dropdownValues.style.visibility = "hidden";
}
};
// Event listener per i pulsanti di rimozione esistenti
document.querySelectorAll(".remove-field").forEach(button => {
button.addEventListener("click", function() {
console.log("Existing remove button clicked");
const container = document.getElementById("clientSpecificFields");
container.removeChild(button.closest(".client-field-row"));
updateFieldIndices();
});
});
// Funzione per aggiornare gli indici dei campi
function updateFieldIndices() {
console.log("Updating field indices");
const rows = container.getElementsByClassName("client-field-row");
for (let i = 0; i < rows.length; i++) {
const inputs = rows[i].querySelectorAll("input, select");
inputs.forEach(input => {
const name = input.name.replace(/\[\d+\]/, `[${i}]`);
input.name = name;
}); });
} }
} }
loadData();
// Routine dettagli
const routines = <?php echo json_encode($routines); ?>;
function updateRoutineDetails() {
const selectedId = routineSelect.value;
routineDetails.style.display = selectedId ? 'block' : 'none';
if (selectedId) {
const routine = routines.find(r => r.idroutine == selectedId);
if (routine) {
routineName.textContent = routine.name || 'N/A';
routineDescription.textContent = routine.description || 'N/A';
routineAction1.textContent = routine.action1 || 'N/A';
routineAction2.textContent = routine.action2 || 'N/A';
routineAction3.textContent = routine.action3 || 'N/A';
} else {
routineName.textContent = 'N/A';
routineDescription.textContent = 'N/A';
routineAction1.textContent = 'N/A';
routineAction2.textContent = 'N/A';
routineAction3.textContent = 'N/A';
}
} else {
routineName.textContent = '';
routineDescription.textContent = '';
routineAction1.textContent = '';
routineAction2.textContent = '';
routineAction3.textContent = '';
}
}
routineSelect.addEventListener('change', updateRoutineDetails);
updateRoutineDetails(); // Inizializza dettagli se una routine è preselezionata
// Submit del form // Submit del form
form.addEventListener("submit", function(e) { form.addEventListener("submit", function(e) {
e.preventDefault(); e.preventDefault();
console.log("Form submitted");
let formData = new FormData(this); let formData = new FormData(this);
// Aggiungi il nome del cliente selezionato a FormData
const clientSelect = document.getElementById("clientSelect"); const clientSelect = document.getElementById("clientSelect");
const clientId = clientSelect.value; const clientId = clientSelect.value;
const selectedClientOption = clientSelect.options[clientSelect.selectedIndex]; const selectedClientOption = clientSelect.options[clientSelect.selectedIndex];
// Validazione: assicurati che un cliente sia selezionato
if (!clientId) { if (!clientId) {
Swal.fire({ Swal.fire({
title: "Errore!", title: "Errore!",
@@ -335,18 +582,22 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
return; return;
} }
// Estrai il nome del cliente in modo più robusto
let clientName = ""; let clientName = "";
if (selectedClientOption) { if (selectedClientOption) {
const optionText = selectedClientOption.text.trim(); const optionText = selectedClientOption.text.trim();
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/); const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
clientName = nameMatch ? nameMatch[1].trim() : optionText; clientName = nameMatch ? nameMatch[1].trim() : optionText;
} }
formData.append("client_name", clientName); formData.append("client_name", clientName);
// Aggiungi l'ID e il nome dello schema selezionato a FormData
const schemaSelect = document.getElementById("schemaSelect"); const schemaSelect = document.getElementById("schemaSelect");
const schemaId = schemaSelect.value; const schemaId = schemaSelect.value;
const selectedSchemaOption = schemaSelect.options[schemaSelect.selectedIndex]; const selectedSchemaOption = schemaSelect.options[schemaSelect.selectedIndex];
// Validazione: assicurati che uno schema sia selezionato
if (!schemaId) { if (!schemaId) {
Swal.fire({ Swal.fire({
title: "Errore!", title: "Errore!",
@@ -357,18 +608,63 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
return; return;
} }
// Estrai il nome dello schema in modo più robusto
let schemaName = ""; let schemaName = "";
if (selectedSchemaOption) { if (selectedSchemaOption) {
const optionText = selectedSchemaOption.text.trim(); const optionText = selectedSchemaOption.text.trim();
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("schemaname", schemaName);
// Aggiungi idroutine formData.append("idschema", schemaId);
const routineId = routineSelect.value; formData.append("schemamaname", schemaName);
formData.append("idroutine", routineId);
// 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 = {};
// Raccolta dei dati direttamente dal DOM
const fieldRows = container.getElementsByClassName("client-field-row");
for (let i = 0; i < fieldRows.length; i++) {
const row = fieldRows[i];
const inputs = row.querySelectorAll("input, select");
let fieldData = {};
inputs.forEach(input => {
const nameMatch = input.name.match(/specific_fields\[\d+\]\[(.*?)\]/);
if (nameMatch) {
const fieldName = nameMatch[1];
fieldData[fieldName] = input.value.trim();
}
});
if (fieldData.name) {
finalSpecificFields[fieldData.name] = {
type: fieldData.type || "text",
possible_values: (fieldData.possible_values && fieldData.type === "dropdown") ? fieldData.possible_values.split(",").map(v => v.trim()) : [],
is_required: fieldData.required === "1",
export_column_name: fieldData.export_column_name || "",
default_value: fieldData.default_value || ""
};
console.log(`Field ${fieldData.name}:`, finalSpecificFields[fieldData.name]);
}
}
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
console.log("FormData contents:");
for (let pair of formData.entries()) {
console.log(pair[0] + ': ' + pair[1]);
}
fetch("process_edit_template_xls.php", { fetch("process_edit_template_xls.php", {
method: "POST", method: "POST",
@@ -376,6 +672,7 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
console.log("Fetch response:", data);
if (data.success) { if (data.success) {
Swal.fire({ Swal.fire({
title: "Successo!", title: "Successo!",
@@ -395,6 +692,7 @@ $routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
} }
}) })
.catch(error => { .catch(error => {
console.error("Errore Fetch:", error);
Swal.fire({ Swal.fire({
title: "Errore!", title: "Errore!",
text: "Si è verificato un errore imprevisto.", text: "Si è verificato un errore imprevisto.",
+77 -30
View File
@@ -1,6 +1,6 @@
<?php <?php
// File: export_to_lims.php // File: export_to_lims.php
ini_set('display_errors', '0'); ini_set('display_errors', '1');
error_reporting(E_ALL); error_reporting(E_ALL);
ini_set('log_errors', 1); ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logsapi/export_lims_error.log'); ini_set('error_log', __DIR__ . '/logsapi/export_lims_error.log');
@@ -13,7 +13,7 @@ require_once __DIR__ . '/class/VisualLimsApiClient.class.php';
use Dotenv\Dotenv; use Dotenv\Dotenv;
// Carica il file .env // Carica il file .env
$dotenv = Dotenv::createImmutable(dirname(__DIR__, 3)); // Torna al livello di public $dotenv = Dotenv::createImmutable(dirname(__DIR__, 2)); // Torna al livello di public
$dotenv->load(); $dotenv->load();
// Leggi la variabile SIMULATE_EXPORT_LIMS // Leggi la variabile SIMULATE_EXPORT_LIMS
@@ -67,8 +67,8 @@ try {
$payloadCommessa = [ $payloadCommessa = [
'Cliente' => (int)$recordCommessa['Cliente'], 'Cliente' => (int)$recordCommessa['Cliente'],
'SchemaCustomField' => (int)$recordCommessa['SchemaCustomField'], 'SchemaCustomField' => (int)$recordCommessa['SchemaCustomField'],
'Richiedente' => null, 'Richiedente' => 'Richiedente test',
'Descrizione' => 'example' 'Descrizione' => 'esempio Claudio'
]; ];
// Step 2: Creazione payload per campi custom (CommesseCustomFields) // Step 2: Creazione payload per campi custom (CommesseCustomFields)
@@ -85,7 +85,6 @@ try {
$stmtCustomFields->execute(['iddatadb' => $iddatadb]); $stmtCustomFields->execute(['iddatadb' => $iddatadb]);
$customFields = $stmtCustomFields->fetchAll(PDO::FETCH_ASSOC); $customFields = $stmtCustomFields->fetchAll(PDO::FETCH_ASSOC);
// Costruisci l'array CommesseCustomFields
$commesseCustomFields = []; $commesseCustomFields = [];
foreach ($customFields as $field) { foreach ($customFields as $field) {
$commesseCustomFields[] = [ $commesseCustomFields[] = [
@@ -94,7 +93,6 @@ try {
]; ];
} }
// Payload per aggiornamento campi custom
$payloadCustomFields = [ $payloadCustomFields = [
'CommesseCustomFields' => $commesseCustomFields 'CommesseCustomFields' => $commesseCustomFields
]; ];
@@ -180,38 +178,87 @@ try {
$apiClient = VisualLimsApiClient::getInstance(); $apiClient = VisualLimsApiClient::getInstance();
// Step 1: Crea CommessaWeb // Step 1: Crea CommessaWeb
$response = $apiClient->post('/api/odata/CommessaWeb', $payloadCommessa); try {
if (!isset($response['success']) || !isset($response['CommessaId'])) { $response = $apiClient->post('CommessaWeb', $payloadCommessa);
throw new Exception('Errore nella creazione della CommessaWeb: ' . json_encode($response)); if (!isset($response['IdCommessa']) || !isset($response['CodiceCommessa'])) {
throw new Exception("Risposta API non valida: IdCommessa o CodiceCommessa mancanti: " . json_encode($response));
}
$idcommessaweb = (int)$response['IdCommessa'];
$commessaweb = $response['CodiceCommessa'];
error_log(date('Y-m-d H:i:s') . " - CommessaWeb creata: idcommessaweb {$idcommessaweb}, codice {$commessaweb} per iddatadb {$iddatadb}\n", 3, $logDir . '/export_lims_success.log');
// Salva payload CommessaWeb
$outputFileCommessa = $logDir . "/commessaweb_create_{$iddatadb}_{$idcommessaweb}.json";
file_put_contents($outputFileCommessa, json_encode($payloadCommessa, JSON_PRETTY_PRINT));
error_log(date('Y-m-d H:i:s') . " - Payload CommessaWeb salvato in {$outputFileCommessa}\n", 3, $logDir . '/export_lims_success.log');
} catch (Exception $e) {
error_log(date('Y-m-d H:i:s') . " - Errore nella creazione della CommessaWeb: " . $e->getMessage() . "\n", 3, $logDir . '/export_lims_error.log');
throw new Exception("Errore nella creazione della CommessaWeb: " . $e->getMessage());
} }
$idcommessaweb = (int)$response['CommessaId'];
// Salva idcommessaweb in datadb // Salva idcommessaweb e commessaweb in datadb
$updateStmt = $pdo->prepare("UPDATE datadb SET idcommessaweb = :idcommessaweb WHERE iddatadb = :iddatadb"); $updateStmt = $pdo->prepare("UPDATE datadb SET idcommessaweb = :idcommessaweb, commessaweb = :commessaweb WHERE iddatadb = :iddatadb");
$updateStmt->execute(['idcommessaweb' => $idcommessaweb, 'iddatadb' => $iddatadb]); $updateStmt->execute([
'idcommessaweb' => $idcommessaweb,
'commessaweb' => $commessaweb,
'iddatadb' => $iddatadb
]);
// Logga il successo della creazione CommessaWeb // Step 2: Crea Campioni
file_put_contents($logDir . '/export_lims_success.log', date('Y-m-d H:i:s') . " - CommessaWeb creata: idcommessaweb {$idcommessaweb} per iddatadb {$iddatadb}\n", FILE_APPEND); try {
foreach ($payloadsCampioni as $index => $payloadCampione) {
$payloadCampione['Commessa'] = $idcommessaweb;
// Salva payload Campione
$outputFileCampione = $logDir . "/campione_{$iddatadb}_{$idcommessaweb}_{$campioni[$index]['part_number']}.json";
file_put_contents($outputFileCampione, json_encode($payloadCampione, JSON_PRETTY_PRINT));
error_log(date('Y-m-d H:i:s') . " - Payload Campione salvato in {$outputFileCampione}\n", 3, $logDir . '/export_lims_success.log');
$apiClient->post('Campione', $payloadCampione);
$payloadsCampioni[$index] = $payloadCampione; // Aggiorna il payload con Commessa
error_log(date('Y-m-d H:i:s') . " - Campione creato: part_number {$campioni[$index]['part_number']} per idcommessaweb {$idcommessaweb}\n", 3, $logDir . '/export_lims_success.log');
}
} catch (Exception $e) {
error_log(date('Y-m-d H:i:s') . " - Errore nella creazione dei Campioni: " . $e->getMessage() . "\n", 3, $logDir . '/export_lims_error.log');
throw new Exception("Errore nella creazione dei Campioni: " . $e->getMessage());
}
// Step 2: Aggiorna CommesseCustomFields // Step 3: Aggiorna CommesseCustomFields
$apiClient->patch("/api/odata/CommessaWeb({$idcommessaweb})", $payloadCustomFields); try {
// Salva payload CustomFields
// Step 3: Crea Campioni $outputFileCustomFields = $logDir . "/commessaweb_customfields_{$iddatadb}_{$idcommessaweb}.json";
foreach ($payloadsCampioni as $index => $payloadCampione) { file_put_contents($outputFileCustomFields, json_encode($payloadCustomFields, JSON_PRETTY_PRINT));
$payloadCampione['Commessa'] = $idcommessaweb; error_log(date('Y-m-d H:i:s') . " - PayloadCustomFields per idcommessaweb {$idcommessaweb}: " . json_encode($payloadCustomFields, JSON_PRETTY_PRINT) . "\n", 3, $logDir . '/export_lims_success.log');
$apiClient->post('/api/odata/Campione', $payloadCampione); error_log(date('Y-m-d H:i:s') . " - Payload CustomFields salvato in {$outputFileCustomFields}\n", 3, $logDir . '/export_lims_success.log');
$payloadsCampioni[$index] = $payloadCampione; // Aggiorna il payload con Commessa $apiClient->patch("CommessaWeb({$idcommessaweb})", $payloadCustomFields);
error_log(date('Y-m-d H:i:s') . " - CommesseCustomFields aggiornati per idcommessaweb {$idcommessaweb}\n", 3, $logDir . '/export_lims_success.log');
} catch (Exception $e) {
error_log(date('Y-m-d H:i:s') . " - Errore nell'aggiornamento CommesseCustomFields: " . $e->getMessage() . "\n", 3, $logDir . '/export_lims_error.log');
throw new Exception("Errore nell'aggiornamento CommesseCustomFields: " . $e->getMessage());
} }
// Step 4: Invia Commessa // Step 4: Invia Commessa
$apiClient->post("/api/odata/CommessaWeb({$idcommessaweb})/InviaCommessa", $payloadInviaCommessa); try {
// Salva payload InviaCommessa
$outputFileInviaCommessa = $logDir . "/commessaweb_invia_{$iddatadb}_{$idcommessaweb}.json";
file_put_contents($outputFileInviaCommessa, json_encode($payloadInviaCommessa, JSON_PRETTY_PRINT));
error_log(date('Y-m-d H:i:s') . " - Payload InviaCommessa salvato in {$outputFileInviaCommessa}\n", 3, $logDir . '/export_lims_success.log');
$apiClient->post("CommessaWeb({$idcommessaweb})/InviaCommessa", $payloadInviaCommessa);
error_log(date('Y-m-d H:i:s') . " - Commessa inviata: idcommessaweb {$idcommessaweb}\n", 3, $logDir . '/export_lims_success.log');
} catch (Exception $e) {
error_log(date('Y-m-d H:i:s') . " - Errore nell'invio della Commessa: " . $e->getMessage() . "\n", 3, $logDir . '/export_lims_error.log');
throw new Exception("Errore nell'invio della Commessa: " . $e->getMessage());
}
// Step 5: Recupera il numero commessaweb (opzionale) // Step 5: Recupera il numero commessaweb
$commessaData = $apiClient->get("/api/odata/CommessaWeb({$idcommessaweb})"); try {
$commessaweb = $commessaData['Numero'] ?? ''; $commessaData = $apiClient->get("CommessaWeb({$idcommessaweb})");
if ($commessaweb) { $commessaweb = $commessaData['CodiceCommessaWeb'] ?? $commessaweb; // Usa CodiceCommessaWeb o fallback
$updateStmt = $pdo->prepare("UPDATE datadb SET commessaweb = :commessaweb WHERE iddatadb = :iddatadb"); if ($commessaweb) {
$updateStmt->execute(['commessaweb' => $commessaweb, 'iddatadb' => $iddatadb]); $updateStmt = $pdo->prepare("UPDATE datadb SET commessaweb = :commessaweb WHERE iddatadb = :iddatadb");
$updateStmt->execute(['commessaweb' => $commessaweb, 'iddatadb' => $iddatadb]);
}
error_log(date('Y-m-d H:i:s') . " - CommessaWeb recuperata: codice {$commessaweb} per idcommessaweb {$idcommessaweb}\n", 3, $logDir . '/export_lims_success.log');
} catch (Exception $e) {
error_log(date('Y-m-d H:i:s') . " - Errore nel recupero della CommessaWeb: " . $e->getMessage() . "\n", 3, $logDir . '/export_lims_error.log');
throw new Exception("Errore nel recupero della CommessaWeb: " . $e->getMessage());
} }
// Aggiorna lo status a 'l' (To LIMS) // Aggiorna lo status a 'l' (To LIMS)
+12 -6
View File
@@ -18,9 +18,9 @@ try {
$target_table = trim($_POST['target_table']); $target_table = trim($_POST['target_table']);
$idclient = intval($_POST['client_id'] ?? 0); // Usa client_id dal form $idclient = intval($_POST['client_id'] ?? 0); // Usa client_id dal form
$clientname = trim($_POST['client_name'] ?? ''); // Usa client_name 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 $idschema = intval($_POST['idschema'] ?? 0); // Nuovo campo
$schemaname = trim($_POST['schemaname'] ?? ''); // Corretto da schemamaname $schemamaname = trim($_POST['schemamaname'] ?? ''); // Nuovo campo
$idroutine = isset($_POST['idroutine']) && $_POST['idroutine'] !== '' ? intval($_POST['idroutine']) : null; // Aggiunto idroutine
// Controllo sui campi obbligatori // Controllo sui campi obbligatori
if (empty($id) || empty($name) || empty($header_row) || empty($start_column) || empty($target_table) || $idschema <= 0) { if (empty($id) || empty($name) || empty($header_row) || empty($start_column) || empty($target_table) || $idschema <= 0) {
@@ -32,14 +32,20 @@ try {
throw new Exception("Please select a valid client."); throw new Exception("Please select a valid client.");
} }
// Validazione opzionale del JSON (per sicurezza)
$decoded_fields = json_decode($client_specific_fields, true);
if (json_last_error() !== JSON_ERROR_NONE && $client_specific_fields !== '{}') {
throw new Exception("Invalid JSON format for client-specific fields.");
}
// Connessione al database // Connessione al database
$db = DBHandlerSelect::getInstance(); $db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection(); $pdo = $db->getConnection();
// Aggiorna il database, includendo idschema, schemaname e idroutine // Aggiorna il database, includendo idschema e schemaname
$stmt = $pdo->prepare("UPDATE excel_templates $stmt = $pdo->prepare("UPDATE excel_templates
SET name = ?, header_row = ?, start_column = ?, description = ?, target_table = ?, SET name = ?, header_row = ?, start_column = ?, description = ?, target_table = ?,
idclient = ?, clientname = ?, schemaname = ?, idschema = ?, idroutine = ?, updated_at = NOW() idclient = ?, clientname = ?, client_specific_fields = ?, schemaname = ?, idschema = ?, updated_at = NOW()
WHERE id = ?"); WHERE id = ?");
$stmt->execute([ $stmt->execute([
$name, $name,
@@ -49,9 +55,9 @@ try {
$target_table, $target_table,
$idclient, $idclient,
$clientname, $clientname,
$schemaname, $client_specific_fields,
$schemamaname,
$idschema, $idschema,
$idroutine,
$id $id
]); ]);