added routine functionalites to template
This commit is contained in:
parent
9826331545
commit
89d13699b4
@ -20,17 +20,10 @@ if (!$template) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// Debug del JSON
|
||||
$clientSpecificFieldsJson = $template['client_specific_fields'] ?? '{}';
|
||||
error_log("Raw client_specific_fields JSON: " . $clientSpecificFieldsJson);
|
||||
|
||||
$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));
|
||||
}
|
||||
// Recupera tutte le routine dal database
|
||||
$stmt = $pdo->prepare("SELECT * FROM routine");
|
||||
$stmt->execute();
|
||||
$routines = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
?>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
@ -41,28 +34,9 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
<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" />
|
||||
<?php include('cssinclude.php'); ?>
|
||||
<style>
|
||||
.client-field-row .row {
|
||||
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>
|
||||
<!-- 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://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>
|
||||
</head>
|
||||
|
||||
@ -82,7 +56,7 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
<ul class="mb-0">
|
||||
<li>Template Name</li>
|
||||
<li>Row Header and Column Header: where the title of the excel starts</li>
|
||||
<li>Cheme</li>
|
||||
<li>Schema</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@ -124,96 +98,43 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
<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>
|
||||
</div>
|
||||
<!-- Aggiungi il campo per selezionare il cliente -->
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Select Client *</label>
|
||||
<select name="client_id" id="clientSelect" class="form-control" required>
|
||||
<option value="">Select a client...</option>
|
||||
<!-- Le opzioni verranno popolate tramite JavaScript -->
|
||||
</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>
|
||||
|
||||
<!-- Intestazioni colonne -->
|
||||
<div class="row fw-bold text-secondary mb-1">
|
||||
<div class="col-md-3">Field Name</div>
|
||||
<div class="col-md-2">Type</div>
|
||||
<div class="col-md-2">Possible Values</div>
|
||||
<div class="col-md-1">Required</div>
|
||||
<div class="col-md-2">Export Column Name</div>
|
||||
<div class="col-md-1">Default Value</div>
|
||||
<div class="col-md-1">Actions</div>
|
||||
<label class="form-label">Select Routine</label>
|
||||
<select name="idroutine" id="routineSelect" class="form-control">
|
||||
<option value="">Select a routine...</option>
|
||||
<?php foreach ($routines as $routine): ?>
|
||||
<option value="<?php echo $routine['idroutine']; ?>" <?php echo ($template['idroutine'] ?? '') == $routine['idroutine'] ? 'selected' : ''; ?>>
|
||||
<?php echo htmlspecialchars($routine['name']); ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<div id="routineDetails" class="mt-2" style="display: none;">
|
||||
<h6>Routine Details</h6>
|
||||
<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 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>
|
||||
|
||||
|
||||
<br>
|
||||
<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>
|
||||
@ -223,132 +144,78 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
</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-->
|
||||
<!-- 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>
|
||||
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 addFieldButton = document.getElementById("addField");
|
||||
const container = document.getElementById("clientSpecificFields");
|
||||
const clientLoadingStatus = document.getElementById("clientLoadingStatus");
|
||||
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 || !addFieldButton || !container || !clientLoadingStatus || !schemaLoadingStatus) {
|
||||
console.error("One or more DOM elements not found:", {
|
||||
form,
|
||||
addFieldButton,
|
||||
container,
|
||||
clientLoadingStatus,
|
||||
schemaLoadingStatus
|
||||
});
|
||||
if (!form || !clientLoadingStatus || !schemaLoadingStatus || !routineSelect || !routineDetails) {
|
||||
alert("Errore: Uno o più elementi della pagina non sono stati trovati. Contatta l'amministratore.");
|
||||
return;
|
||||
}
|
||||
|
||||
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
|
||||
// Inizializza Select2
|
||||
$('#clientSelect').select2({
|
||||
placeholder: "Search for a client...",
|
||||
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({
|
||||
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
|
||||
$('#routineSelect').select2({
|
||||
placeholder: "Select a routine...",
|
||||
allowClear: true
|
||||
});
|
||||
|
||||
// Carica i clienti
|
||||
async function loadClients() {
|
||||
try {
|
||||
clientLoadingStatus.style.display = 'inline';
|
||||
clientLoadingStatus.textContent = 'Recupero clienti in corso...';
|
||||
|
||||
const response = await fetch("get_clienti.php", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
});
|
||||
|
||||
const text = await response.text();
|
||||
console.log("Risposta raw (clienti):", text);
|
||||
const data = JSON.parse(text);
|
||||
|
||||
if (!response.ok) {
|
||||
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>';
|
||||
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);
|
||||
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"
|
||||
});
|
||||
}
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || `Errore HTTP: ${response.status}`);
|
||||
const select = document.getElementById("clientSelect");
|
||||
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);
|
||||
if (parseInt(id) === parseInt(<?php echo json_encode($template['idclient'] ?? 0); ?>)) {
|
||||
option.selected = true;
|
||||
}
|
||||
select.add(option);
|
||||
});
|
||||
$(select).trigger('change');
|
||||
clientLoadingStatus.textContent = "Clienti caricati.";
|
||||
} catch (error) {
|
||||
console.error("Errore nel caricamento dei clienti:", error);
|
||||
clientLoadingStatus.textContent = "Errore nel caricamento.";
|
||||
Swal.fire({
|
||||
title: "Errore!",
|
||||
@ -357,50 +224,37 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
confirmButtonText: "OK"
|
||||
});
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
clientLoadingStatus.style.display = 'none';
|
||||
}, 2000);
|
||||
setTimeout(() => clientLoadingStatus.style.display = 'none', 2000);
|
||||
}
|
||||
}
|
||||
|
||||
// Carica gli schemi al caricamento della pagina
|
||||
// Carica gli schemi
|
||||
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 data = await response.json();
|
||||
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)) {
|
||||
const option = new Option(`${nome.trim()} (ID: ${id})`, id);
|
||||
if (parseInt(id) === parseInt(<?php echo json_encode($template['idschema'] ?? 0); ?>)) {
|
||||
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!",
|
||||
@ -409,169 +263,68 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
confirmButtonText: "OK"
|
||||
});
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
schemaLoadingStatus.style.display = 'none';
|
||||
}, 2000);
|
||||
setTimeout(() => schemaLoadingStatus.style.display = 'none', 2000);
|
||||
}
|
||||
}
|
||||
|
||||
// Carica i dati in sequenza
|
||||
// Carica i dati
|
||||
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 = () => {
|
||||
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;
|
||||
Swal.fire({
|
||||
title: "Errore!",
|
||||
text: "Errore nel caricamento dei dati: " + error.message,
|
||||
icon: "error",
|
||||
confirmButtonText: "OK"
|
||||
});
|
||||
}
|
||||
}
|
||||
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
|
||||
form.addEventListener("submit", function(e) {
|
||||
e.preventDefault();
|
||||
console.log("Form submitted");
|
||||
|
||||
let formData = new FormData(this);
|
||||
|
||||
// Aggiungi il nome del cliente selezionato a FormData
|
||||
const clientSelect = document.getElementById("clientSelect");
|
||||
const clientId = clientSelect.value;
|
||||
const selectedClientOption = clientSelect.options[clientSelect.selectedIndex];
|
||||
|
||||
// Validazione: assicurati che un cliente sia selezionato
|
||||
if (!clientId) {
|
||||
Swal.fire({
|
||||
title: "Errore!",
|
||||
@ -582,22 +335,18 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Estrai il nome del cliente in modo più robusto
|
||||
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);
|
||||
|
||||
// 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!",
|
||||
@ -608,63 +357,18 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
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);
|
||||
formData.append("schemaname", 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 = {};
|
||||
|
||||
// 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]);
|
||||
}
|
||||
// Aggiungi idroutine
|
||||
const routineId = routineSelect.value;
|
||||
formData.append("idroutine", routineId);
|
||||
|
||||
fetch("process_edit_template_xls.php", {
|
||||
method: "POST",
|
||||
@ -672,7 +376,6 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
console.log("Fetch response:", data);
|
||||
if (data.success) {
|
||||
Swal.fire({
|
||||
title: "Successo!",
|
||||
@ -692,7 +395,6 @@ if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error("Errore Fetch:", error);
|
||||
Swal.fire({
|
||||
title: "Errore!",
|
||||
text: "Si è verificato un errore imprevisto.",
|
||||
|
||||
@ -18,9 +18,9 @@ try {
|
||||
$target_table = trim($_POST['target_table']);
|
||||
$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
|
||||
$schemaname = trim($_POST['schemaname'] ?? ''); // Corretto da schemamaname
|
||||
$idroutine = isset($_POST['idroutine']) && $_POST['idroutine'] !== '' ? intval($_POST['idroutine']) : null; // Aggiunto idroutine
|
||||
|
||||
// Controllo sui campi obbligatori
|
||||
if (empty($id) || empty($name) || empty($header_row) || empty($start_column) || empty($target_table) || $idschema <= 0) {
|
||||
@ -32,20 +32,14 @@ try {
|
||||
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
|
||||
$db = DBHandlerSelect::getInstance();
|
||||
$pdo = $db->getConnection();
|
||||
|
||||
// Aggiorna il database, includendo idschema e schemaname
|
||||
// Aggiorna il database, includendo idschema, schemaname e idroutine
|
||||
$stmt = $pdo->prepare("UPDATE excel_templates
|
||||
SET name = ?, header_row = ?, start_column = ?, description = ?, target_table = ?,
|
||||
idclient = ?, clientname = ?, client_specific_fields = ?, schemaname = ?, idschema = ?, updated_at = NOW()
|
||||
idclient = ?, clientname = ?, schemaname = ?, idschema = ?, idroutine = ?, updated_at = NOW()
|
||||
WHERE id = ?");
|
||||
$stmt->execute([
|
||||
$name,
|
||||
@ -55,9 +49,9 @@ try {
|
||||
$target_table,
|
||||
$idclient,
|
||||
$clientname,
|
||||
$client_specific_fields,
|
||||
$schemamaname,
|
||||
$schemaname,
|
||||
$idschema,
|
||||
$idroutine,
|
||||
$id
|
||||
]);
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user