Implementado script principal

This commit is contained in:
unknown
2025-04-27 00:00:58 +02:00
parent e8958dc893
commit ae456c8890
4 changed files with 100 additions and 4 deletions

View File

@ -0,0 +1,74 @@
document.addEventListener('DOMContentLoaded', function () {
// Columnas requeridas
const REQUIRED_COLUMNS = ["cnt_pedida", "precio_compra", "idlinea", "input", "descripcion"];
let dataTable; // referencia al DataTable
// Inicializa el DataTable vacío
dataTable = $('#excelTable').DataTable();
document.getElementById('excelFile').addEventListener('change', function (e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (e) {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
validateAndLoadDataTable(jsonData);
};
reader.readAsArrayBuffer(file);
});
function validateAndLoadDataTable(data) {
const headers = data[0].map(h => h.toString().trim());
const missing = REQUIRED_COLUMNS.filter(col => !headers.includes(col));
if (missing.length > 0) {
alert('Faltan las siguientes columnas en el Excel: ' + missing.join(', '));
dataTable.clear().draw(); // limpia tabla
return;
}
const indexes = REQUIRED_COLUMNS.map(col => headers.indexOf(col));
const rows = [];
for (let i = 1; i < data.length; i++) {
const rowData = indexes.map(idx => data[i][idx] ?? '');
rowData.push('<button class="deleteRow">Eliminar</button>'); // Agrega botón
rows.push(rowData);
}
dataTable.clear().rows.add(rows).draw();
// Agregar eventos a los nuevos botones de eliminar
$('#excelTable tbody').on('click', '.deleteRow', function () {
dataTable.row($(this).parents('tr')).remove().draw();
});
}
document.getElementById('importBtn').addEventListener('click', function () {
const allData = dataTable.rows().data().toArray();
// Eliminar la última columna (botón) de cada fila
const rowsToSend = allData.map(row => row.slice(0, -1));
fetch('/importar', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
},
body: JSON.stringify({ data: rowsToSend })
}).then(res => res.json())
.then(response => {
alert(response.message);
});
});
});