590 lines
30 KiB
PHP
590 lines
30 KiB
PHP
<?php include('include/headscript.php'); ?>
|
|
<!doctype html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<!-- Required meta tags -->
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<!--favicon-->
|
|
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
|
|
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
|
|
<?php include('cssinclude.php'); ?>
|
|
<title>Insert XLS Template <?= htmlspecialchars($titlewebsite, ENT_QUOTES, 'UTF-8'); ?></title>
|
|
</head>
|
|
|
|
<body>
|
|
<!--wrapper-->
|
|
<div class="wrapper">
|
|
<!--sidebar wrapper -->
|
|
<?php include('include/navbar.php'); ?>
|
|
<!--end sidebar wrapper -->
|
|
<!--start header -->
|
|
<?php include('include/topbar.php'); ?>
|
|
<!--end header -->
|
|
<!--start page wrapper -->
|
|
<div class="page-wrapper">
|
|
<div class="page-content">
|
|
<div class="card mb-4">
|
|
<div class="card-header">
|
|
<h5 class="mb-0">Insert new XLS Template</h5>
|
|
</div>
|
|
<div class="card-body">
|
|
<p class="mb-2">Fill the following form in order to create a new import XLS template</p>
|
|
<p class="mb-2">Mandatory Fields</p>
|
|
<ul class="mb-0">
|
|
<li>Template Name</li>
|
|
<li>Row Header and Column Header: where the title of the excel starts</li>
|
|
<li>Destination Table: already prefilled</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="card radius-10">
|
|
<div class="card-header">
|
|
<div class="d-flex align-items-center">
|
|
<div>
|
|
<h6 class="mb-0">Fill the form and click "Create Template"</h6>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="card-body">
|
|
<div class="col-12">
|
|
<form id="insertTemplateForm" method="POST">
|
|
<div class="mb-3">
|
|
<label class="form-label"><?= htmlspecialchars($templatename, ENT_QUOTES, 'UTF-8'); ?> *</label>
|
|
<input type="text" name="name" class="form-control" required>
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label"><?= htmlspecialchars($rowheader, ENT_QUOTES, 'UTF-8'); ?> *</label>
|
|
<input type="number" name="header_row" class="form-control" required>
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label"><?= htmlspecialchars($columnheader, ENT_QUOTES, 'UTF-8'); ?> *</label>
|
|
<input type="text" name="start_column" class="form-control" required>
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label"><?= htmlspecialchars($desctemplate, ENT_QUOTES, 'UTF-8'); ?></label>
|
|
<textarea name="description" class="form-control"></textarea>
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label"><?= htmlspecialchars($desttable, ENT_QUOTES, 'UTF-8'); ?> *</label>
|
|
<input type="text" name="target_table" class="form-control" value="datadb" readonly required style="background-color: #f0f0f0;">
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label">Button Size</label>
|
|
<select name="button_size" class="form-control">
|
|
<option value="small">Small</option>
|
|
<option value="medium" selected>Medium</option>
|
|
<option value="large">Large</option>
|
|
</select>
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label">Button Background Color</label>
|
|
<input type="color" name="button_bg_color" class="form-control" value="#007bff">
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label">Button Text Color</label>
|
|
<input type="color" name="button_text_color" class="form-control" value="#ffffff">
|
|
</div>
|
|
|
|
<div class="mb-3">
|
|
<label class="form-label">Button Label</label>
|
|
<input type="text" name="button_label" class="form-control" value="Click Me">
|
|
</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>
|
|
</select>
|
|
<span id="clientLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Recupero clienti in corso...</span>
|
|
</div>
|
|
<!-- Aggiungi il campo per selezionare lo schema -->
|
|
<div class="mb-3">
|
|
<label class="form-label">Select Schema *</label>
|
|
<select name="schema_id" id="schemaSelect" class="form-control" required>
|
|
<option value="">Select a schema...</option>
|
|
</select>
|
|
<span id="schemaLoadingStatus" class="text-muted" style="margin-left: 10px; display: none;">Loading schemas...</span>
|
|
</div>
|
|
|
|
<!-- new section for specific client field -->
|
|
<div class="mb-3">
|
|
<label class="form-label">Client-Specific Fields</label>
|
|
|
|
<!-- Intestazioni -->
|
|
<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 dropdown-values">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>
|
|
</div>
|
|
|
|
<div id="clientSpecificFields">
|
|
<!-- Contenitore per i campi dinamici -->
|
|
<div class="client-field-row mb-2">
|
|
<div class="row">
|
|
<div class="col-md-3">
|
|
<input type="text" name="specific_fields[0][name]" class="form-control" placeholder="Field Name (e.g., SKU)">
|
|
</div>
|
|
<div class="col-md-2">
|
|
<select name="specific_fields[0][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[0][possible_values]" class="form-control" placeholder="Values (e.g., Red, Blue, Green)">
|
|
</div>
|
|
<div class="col-md-1">
|
|
<select name="specific_fields[0][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[0][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[0][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>
|
|
</div>
|
|
</div>
|
|
|
|
<button type="button" class="btn btn-primary mt-2" id="addField">Add Field</button>
|
|
</div>
|
|
|
|
<br>
|
|
<button type="submit" class="btn btn-primary">Create Template</button>
|
|
<a href="templates_dashboard.php" class="btn btn-secondary">Cancel</a>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!--end page wrapper -->
|
|
<!--start overlay-->
|
|
<div class="overlay toggle-icon"></div>
|
|
<!--end overlay-->
|
|
<!--Start Back To Top Button-->
|
|
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
|
|
<!--End Back To Top Button-->
|
|
<?php include('include/footer.php'); ?>
|
|
</div>
|
|
<!--end wrapper-->
|
|
|
|
<!-- search modal -->
|
|
<?php //include('include/searchmodal.php');
|
|
?>
|
|
<!-- end search modal -->
|
|
|
|
<!--start switcher-->
|
|
<?php //include('include/themeswitcher.php');
|
|
?>
|
|
<!--end switcher-->
|
|
|
|
<!-- Includi Select2 JS -->
|
|
|
|
<?php include('jsinclude.php'); ?>
|
|
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
|
|
<script>
|
|
// Debug iniziale
|
|
console.log("JavaScript is loaded and running!");
|
|
|
|
document.addEventListener("DOMContentLoaded", function() {
|
|
console.log("DOM is loaded");
|
|
|
|
const form = document.getElementById("insertTemplateForm");
|
|
const addFieldButton = document.getElementById("addField");
|
|
const container = document.getElementById("clientSpecificFields");
|
|
const clientLoadingStatus = document.getElementById("clientLoadingStatus");
|
|
const schemaLoadingStatus = document.getElementById("schemaLoadingStatus");
|
|
|
|
if (!form || !addFieldButton || !container || !clientLoadingStatus || !schemaLoadingStatus) {
|
|
console.error("One or more DOM elements not found:", {
|
|
form,
|
|
addFieldButton,
|
|
container,
|
|
clientLoadingStatus,
|
|
schemaLoadingStatus
|
|
});
|
|
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
|
|
$('#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");
|
|
});
|
|
|
|
// Funzione per caricare 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}, Dettagli: ${JSON.stringify(data)}`);
|
|
}
|
|
|
|
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);
|
|
select.add(option);
|
|
});
|
|
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) {
|
|
console.error("Errore nel caricamento dei clienti:", error);
|
|
clientLoadingStatus.textContent = "Errore nel caricamento.";
|
|
Swal.fire({
|
|
title: "Errore!",
|
|
text: "Impossibile caricare i clienti: " + error.message,
|
|
icon: "error",
|
|
confirmButtonText: "OK"
|
|
});
|
|
} finally {
|
|
setTimeout(() => {
|
|
clientLoadingStatus.style.display = 'none';
|
|
}, 2000);
|
|
}
|
|
}
|
|
|
|
// Funzione per caricare gli schemi con ritentativi
|
|
async function loadSchemas() {
|
|
const maxRetries = 3;
|
|
let attempt = 0;
|
|
|
|
while (attempt < maxRetries) {
|
|
try {
|
|
schemaLoadingStatus.style.display = 'inline';
|
|
schemaLoadingStatus.textContent = 'Caricamento schemi in corso...';
|
|
|
|
const response = await fetch("get_schemi.php", {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json"
|
|
}
|
|
});
|
|
|
|
const text = await response.text();
|
|
console.log("Risposta raw (schemi):", text);
|
|
const data = JSON.parse(text);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(data.error || `Errore HTTP: ${response.status}, Dettagli: ${JSON.stringify(data)}`);
|
|
}
|
|
|
|
const select = document.getElementById("schemaSelect");
|
|
select.innerHTML = '<option value="">Select a schema...</option>';
|
|
data.value.forEach(schema => { // Nota: usa data.value per coerenza con il JSON restituito
|
|
const option = new Option(`${schema.Nome} (ID: ${schema.IdSchemaCustomFields})`, schema.IdSchemaCustomFields);
|
|
select.add(option);
|
|
});
|
|
|
|
schemaLoadingStatus.textContent = "Schemi caricati.";
|
|
break; // Esci dal ciclo se la chiamata ha successo
|
|
} catch (error) {
|
|
attempt++;
|
|
console.error(`Tentativo ${attempt} fallito per schemi:`, error);
|
|
if (attempt === maxRetries) {
|
|
console.error("Errore finale nel caricamento degli schemi:", error);
|
|
schemaLoadingStatus.textContent = "Errore nel caricamento.";
|
|
Swal.fire({
|
|
title: "Errore!",
|
|
text: "Impossibile caricare gli schemi: " + error.message,
|
|
icon: "error",
|
|
confirmButtonText: "OK"
|
|
});
|
|
} else {
|
|
// Ritardo prima di riprovare
|
|
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
|
|
}
|
|
} finally {
|
|
if (attempt === maxRetries || schemaLoadingStatus.textContent === "Schemi caricati.") {
|
|
setTimeout(() => {
|
|
schemaLoadingStatus.style.display = 'none';
|
|
}, 2000);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Funzione combinata per caricare i dati in sequenza
|
|
async function loadData() {
|
|
try {
|
|
await loadClients(); // Carica prima i clienti
|
|
await loadSchemas(); // Poi carica gli schemi
|
|
} catch (error) {
|
|
console.error("Errore nel caricamento dei dati:", error);
|
|
}
|
|
}
|
|
|
|
// Avvia il caricamento dei dati
|
|
loadData();
|
|
|
|
// Gestione dinamica dei campi specifici
|
|
addFieldButton.addEventListener("click", function() {
|
|
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">
|
|
<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();
|
|
});
|
|
});
|
|
|
|
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";
|
|
}
|
|
};
|
|
|
|
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();
|
|
});
|
|
});
|
|
|
|
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;
|
|
});
|
|
}
|
|
}
|
|
|
|
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];
|
|
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];
|
|
let schemaName = "";
|
|
if (selectedSchemaOption && schemaId) {
|
|
const optionText = selectedSchemaOption.text.trim();
|
|
const nameMatch = optionText.match(/^(.+?)(?:\s*\(ID:\s*\d+\))?$/);
|
|
schemaName = nameMatch ? nameMatch[1].trim() : optionText;
|
|
formData.append("idschema", schemaId);
|
|
formData.append("schemamaname", schemaName);
|
|
} else {
|
|
Swal.fire({
|
|
title: "Errore!",
|
|
text: "Per favore seleziona uno schema.",
|
|
icon: "error",
|
|
confirmButtonText: "OK"
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Log per debug
|
|
console.log("Client ID:", clientId);
|
|
console.log("Client Name:", clientName);
|
|
console.log("Schema ID:", schemaId);
|
|
console.log("Schema Name:", schemaName);
|
|
|
|
// Genera il JSON per client_specific_fields
|
|
let finalSpecificFields = {};
|
|
const fieldRows = container.getElementsByClassName("client-field-row");
|
|
for (let i = 0; i < fieldRows.length; i++) {
|
|
const row = fieldRows[i];
|
|
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));
|
|
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_insert_template_xls.php", {
|
|
method: "POST",
|
|
body: formData
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
console.log("Fetch response:", data);
|
|
if (data.success) {
|
|
Swal.fire({
|
|
title: "Successo!",
|
|
text: "Template creato con successo!",
|
|
icon: "success",
|
|
confirmButtonText: "OK"
|
|
}).then(() => {
|
|
window.location.href = "templates_dashboard.php";
|
|
});
|
|
} else {
|
|
Swal.fire({
|
|
title: "Errore!",
|
|
text: data.message,
|
|
icon: "error",
|
|
confirmButtonText: "OK"
|
|
});
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error("Errore Fetch:", error);
|
|
Swal.fire({
|
|
title: "Errore!",
|
|
text: "Si è verificato un errore imprevisto.",
|
|
icon: "error",
|
|
confirmButtonText: "OK"
|
|
});
|
|
});
|
|
});
|
|
});
|
|
</script>
|
|
</body>
|
|
|
|
</html>
|