mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
Trabajando JS
This commit is contained in:
@ -2,13 +2,21 @@ import Ajax from '../../../components/ajax.js';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
|
||||
// Columnas que espera la tabla (en el orden de HTML)
|
||||
const TABLE_COLUMNS = ["input", "idlinea", "descripcion", "cnt_pedida", "precio_compra"];
|
||||
let dataTable; // referencia al DataTable
|
||||
let dataTable;
|
||||
|
||||
dataTable = $('#excelTable').DataTable({
|
||||
orderCellsTop: true,
|
||||
fixedHeader: true
|
||||
responsive: true,
|
||||
scrollX: true,
|
||||
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
|
||||
pageLength: 25,
|
||||
lengthChange: true,
|
||||
dom: 'lfrtip',
|
||||
language: {
|
||||
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
|
||||
},
|
||||
order: [[1, 'asc']]
|
||||
});
|
||||
|
||||
document.getElementById('excelFile').addEventListener('change', function (e) {
|
||||
@ -28,124 +36,156 @@ document.addEventListener('DOMContentLoaded', function () {
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
|
||||
function validateAndLoadDataTable(data) {
|
||||
async function validateAndLoadDataTable(data) {
|
||||
if (data.length === 0) return;
|
||||
|
||||
const headers = data[0].map(h => h.toString().trim());
|
||||
|
||||
// Crear un índice rápido de nombreColumna => posicion
|
||||
const headerMap = {};
|
||||
headers.forEach((name, idx) => {
|
||||
headerMap[name.toLowerCase()] = idx; // pasar todo a minúsculas para evitar errores
|
||||
headerMap[name.toLowerCase()] = idx;
|
||||
});
|
||||
|
||||
// Verificar si todas las columnas requeridas existen
|
||||
const missing = TABLE_COLUMNS.filter(col => !(col in headerMap));
|
||||
if (missing.length > 0) {
|
||||
Swal.fire({
|
||||
title: 'Error',
|
||||
text: 'Faltan las siguientes columnas en el Excel: ' + missing.join(', '),
|
||||
text: 'Faltan las siguientes columnas: ' + missing.join(', '),
|
||||
icon: 'error',
|
||||
confirmButtonText: 'Aceptar',
|
||||
buttonsStyling: true,
|
||||
customClass: {
|
||||
confirmButton: 'btn btn-danger'
|
||||
}
|
||||
customClass: { confirmButton: 'btn btn-danger' }
|
||||
});
|
||||
dataTable.clear().draw(); // limpia tabla
|
||||
dataTable.clear().draw();
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = [];
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const row = [];
|
||||
const rowData = TABLE_COLUMNS.map(col => data[i][headerMap[col]] ?? '');
|
||||
|
||||
TABLE_COLUMNS.forEach(col => {
|
||||
const idx = headerMap[col];
|
||||
row.push(data[i][idx] ?? '');
|
||||
});
|
||||
// Llamar backend para validar la fila
|
||||
const isValid = await validarFila(rowData);
|
||||
|
||||
// Agregar botón al final
|
||||
row.push('<button type="button" class="btn btn-danger btn-sm deleteRow">Eliminar</button>');
|
||||
let checkboxHtml = '';
|
||||
let actionBtnsHtml = '';
|
||||
|
||||
rows.push(row);
|
||||
if (isValid) {
|
||||
checkboxHtml = `<input type="checkbox" class="select-row form-check-input" checked>`;
|
||||
|
||||
actionBtnsHtml = `
|
||||
<div class="d-flex flex-column align-items-start">
|
||||
<button type="button" class="btn btn-outline-success btn-sm mb-1 importRow">
|
||||
<i class="fas fa-file-import me-1"></i> Importar
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-danger btn-sm deleteRow">
|
||||
<i class="fas fa-trash-alt me-1"></i> Eliminar
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
checkboxHtml = `<input type="checkbox" class="select-row form-check-input" disabled>`;
|
||||
|
||||
actionBtnsHtml = `
|
||||
<div class="d-flex flex-column align-items-start">
|
||||
<span class="badge rounded-pill bg-danger mb-2">No Apto</span>
|
||||
<button type="button" class="btn btn-outline-danger btn-sm deleteRow">
|
||||
<i class="fas fa-trash-alt me-1"></i> Eliminar
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
rows.push([checkboxHtml, ...rowData, actionBtnsHtml]);
|
||||
}
|
||||
|
||||
dataTable.clear().rows.add(rows).draw();
|
||||
|
||||
// Agregar eventos dinámicos para eliminar
|
||||
setupEventListeners();
|
||||
}
|
||||
|
||||
async function validarFila(rowData) {
|
||||
try {
|
||||
const response = await fetch('/importador/catalogo/validar-fila', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
|
||||
},
|
||||
body: JSON.stringify({ fila: rowData })
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
return result.apto === true;
|
||||
} catch (error) {
|
||||
console.error('Error validando fila', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function setupEventListeners() {
|
||||
$('#excelTable tbody').off('click', '.deleteRow').on('click', '.deleteRow', function () {
|
||||
dataTable.row($(this).parents('tr')).remove().draw();
|
||||
});
|
||||
|
||||
$('#excelTable tbody').off('click', '.importRow').on('click', '.importRow', function () {
|
||||
const rowData = dataTable.row($(this).parents('tr')).data();
|
||||
console.log('Importar esta fila:', rowData);
|
||||
// Aquí podrías enviar sólo esta fila al servidor si quieres importar individualmente
|
||||
});
|
||||
}
|
||||
|
||||
$('#excelTable thead tr:eq(1) th').each(function (i) {
|
||||
const title = $(this).text();
|
||||
|
||||
if (title.trim() !== '') { // Solo si el th tiene título
|
||||
$(this).html('<input type="text" class="form-control form-control-sm" placeholder="Filtrar..." />');
|
||||
|
||||
$('input', this).on('keyup change', function () {
|
||||
if (dataTable.column(i).search() !== this.value) {
|
||||
dataTable
|
||||
.column(i)
|
||||
.search(this.value)
|
||||
.draw();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('importBtn').addEventListener('click', function () {
|
||||
const allData = dataTable.rows().data().toArray();
|
||||
const rowsToSend = allData.map(row => row.slice(0, -1)); // sin botón
|
||||
|
||||
if (rowsToSend.length === 0) {
|
||||
const selectedRows = [];
|
||||
|
||||
dataTable.rows().every(function () {
|
||||
const data = this.data();
|
||||
const checkboxHtml = $(data[0]).find('input.select-row');
|
||||
if (checkboxHtml.length > 0 && checkboxHtml.is(':checked') && !checkboxHtml.is(':disabled')) {
|
||||
selectedRows.push(data.slice(1, -1)); // sin checkbox ni botones
|
||||
}
|
||||
});
|
||||
|
||||
if (selectedRows.length === 0) {
|
||||
Swal.fire({
|
||||
title: 'Atención',
|
||||
text: 'No hay datos para importar.',
|
||||
text: 'No hay filas aptas seleccionadas para importar.',
|
||||
icon: 'warning',
|
||||
confirmButtonText: 'Aceptar',
|
||||
buttonsStyling: true,
|
||||
customClass: {
|
||||
confirmButton: 'btn btn-warning'
|
||||
}
|
||||
customClass: { confirmButton: 'btn btn-warning' }
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
fetch('/importar', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
|
||||
},
|
||||
body: JSON.stringify({ data: rowsToSend })
|
||||
body: JSON.stringify({ data: selectedRows })
|
||||
}).then(res => res.json())
|
||||
.then(response => {
|
||||
Swal.fire({
|
||||
title: 'Importación exitosa',
|
||||
text: response.message,
|
||||
icon: 'success',
|
||||
confirmButtonText: 'Aceptar',
|
||||
buttonsStyling: true,
|
||||
customClass: {
|
||||
confirmButton: 'btn btn-success'
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
Swal.fire({
|
||||
title: 'Error',
|
||||
text: 'Hubo un problema al importar los datos.',
|
||||
icon: 'error',
|
||||
confirmButtonText: 'Aceptar',
|
||||
buttonsStyling: true,
|
||||
customClass: {
|
||||
confirmButton: 'btn btn-danger'
|
||||
}
|
||||
});
|
||||
});
|
||||
.then(response => {
|
||||
Swal.fire({
|
||||
title: 'Importación exitosa',
|
||||
text: response.message,
|
||||
icon: 'success',
|
||||
confirmButtonText: 'Aceptar',
|
||||
buttonsStyling: true,
|
||||
customClass: { confirmButton: 'btn btn-success' }
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
Swal.fire({
|
||||
title: 'Error',
|
||||
text: 'Error importando datos.',
|
||||
icon: 'error',
|
||||
confirmButtonText: 'Aceptar',
|
||||
buttonsStyling: true,
|
||||
customClass: { confirmButton: 'btn btn-danger' }
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user