$(document).ready(function () { // Variables globales para almacenar los IDs de los elementos de la fila let newSelectDat, newSelectId, newSelectCuentaId, newSelectProveedorId, newSelectDescripcionId, newSelectCargoId, newSelectAbonoId; // Cargar datos para Select2 y almacenarlos en variables async function loadSelect2Options() { try { const [polizaDataResponse, cuentaDataResponse, proveedorDataResponse] = await Promise.all([polizaData(), cuentaData(), proveedorData()]); select2Options = polizaDataResponse; select2CuentaOptions = cuentaDataResponse; select2Proveedor = proveedorDataResponse; } catch (error) { console.error('Error al cargar los datos de Select2:', error); select2Options = []; select2CuentaOptions = []; select2Proveedor = []; } } // Llamar a la función para cargar los datos de Select2 de forma asíncrona loadSelect2Options(); function cargarDatos() { $('#overlay').css('visibility', 'visible'); $.ajax({ url: 'https://panel.fivetwofive.tech/yaaxlum/public/tableFinanzas', method: 'GET', dataType: 'json', success: function (data) { $('#flujoTable').DataTable().clear().destroy(); $('#flujoTable tbody').empty(); $.each(data, function (index, item) { const rowIdT = 'idrow_' + item.ID_REGISTRO; const editIdT = 'edit_' + item.ID_REGISTRO; const deletIdT = 'dele_' + item.ID_REGISTRO; const polId = 'pol_' + item.ID_POLIZA; const cuenId = 'cuent_' + item.ID_CAT; const provId = 'proId_' + item.ID_PROVEEDOR; let fila = `` + '' + `    ` + item.ID_REGISTRO + `` + '' + item.FECHA + '' + `` + item.POLIZA + '' + ` ` + item.CUENTA + '' + `` + item.PROVEEDOR + '' + '' + item.DESCRIPCION + '' + '' + item.CARGO + '' + '' + item.ABONO + '' + ''; $('#flujoTable tbody').append(fila); }); $('#flujoTable').DataTable({ paging: true, pageLength: 10, searching: true, info: true, ordering: false, lengthChange: true, language: { emptyTable: 'No hay datos disponibles en la tabla', info: 'Mostrando _START_ a _END_ de _TOTAL_ entradas', infoEmpty: 'Mostrando 0 a 0 de 0 entradas', infoFiltered: '(filtrado de _MAX_ entradas totales)', lengthMenu: 'Mostrar _MENU_ entradas', search: 'Buscar:', zeroRecords: 'No se encontraron coincidencias', paginate: { first: 'Primero', last: 'Último', next: 'Siguiente', previous: 'Anterior' } } }); $('#overlay').css('visibility', 'hidden'); }, error: function (xhr, status, error) { console.error('Error al cargar los datos:', error); $('#overlay').css('visibility', 'hidden'); } }); } cargarDatos(); $('#sidebarToggle, .navbar-toggler').on('click', function () { $('#sidebar, #content').toggleClass('active'); }); $(document).on('click', function (e) { if (!$(e.target).closest('.navbar, .sidebar, #sidebarToggle').length) { $('#sidebar, #content').removeClass('active'); } }); $('#addRowBtn').on('click', function () { // Apertura para el botón de guardado let rowBtn = document.getElementById('divAddSave'); if (!document.getElementById('saveBtn')) { const saveBtn = document.createElement('button'); // Añadir texto saveBtn.textContent = 'Guardar '; // Añadir id saveBtn.id = 'saveBtn'; // Añadir clase saveBtn.classList.add('btn', 'btn-primary', 'ml-2'); // Añadir icono al botón const iconSave = document.createElement('i'); iconSave.className = 'fas fa-save'; // Añadir icono al botón saveBtn.appendChild(iconSave); rowBtn.appendChild(saveBtn); } // Asignación de IDs únicos para los elementos de la fila const uniqueId = new Date().getTime(); //Asignamos un unico ID para que no sea variable y sea unico newSelectDel = 'deletDate_' + uniqueId; newSelectDat = 'selectDate_' + uniqueId; newSelectId = 'selectPoliza_' + uniqueId; newSelectCuentaId = 'selectCuenta_' + uniqueId; newSelectProveedorId = 'selectProveedor_' + uniqueId; newSelectDescripcionId = 'descripcion_' + uniqueId; newSelectCargoId = 'cargo_' + uniqueId; newSelectAbonoId = 'abono_' + uniqueId; const placeholderOption = ''; let nuevaFila = `` + `` + `` + `` + `` + `` + `` + `` + `` + ''; $('#flujoTable tbody').prepend(nuevaFila); // Inicializar Select2 en los nuevos elementos function initializeSelect2() { if (select2Options.length) { $('#' + newSelectId).select2({ data: select2Options, placeholder: 'Seleccione una opción', width: 'resolve' }); } if (select2CuentaOptions.length) { $('#' + newSelectCuentaId).select2({ data: select2CuentaOptions, placeholder: 'Seleccione una opción', width: 'resolve' }); } if (select2Proveedor.length) { $('#' + newSelectProveedorId).select2({ data: select2Proveedor, placeholder: 'Seleccione una opción', width: 'resolve' }); } } initializeSelect2(); // Inicializar el Datepicker en el nuevo campo de fecha // $('.datepicker').datepicker({ // dateFormat: 'yy-mm-dd', // }); }); $(document).on('click', '#saveBtn', function () { $('#overlay').css('visibility', 'visible'); let isValid = true; let allData = []; // Iterar sobre cada fila en el tbody $('#flujoTable tbody tr').each(function() { let $row = $(this); // Verificar si la fila tiene elementos válidos (es decir, al menos un input o select con un valor) if ($row.find('input, select').length > 0) { // Obtener los valores de cada campo en la fila const valorFecha = $row.find('input[name="FECHA"]').val(); const valorSelectPoliza = $row.find('.selectPoliza').val(); const valorSelectCuenta = $row.find('.selectCuenta').val(); const textCuenta = $row.find('.selectCuenta option:selected').text(); const valorSelectProveedor = $row.find('.selectProveedor').val(); const valorDescripcion = $row.find('input[name="DESCRIPCION"]').val(); let valorCargo = $row.find('input[name="CARGO"]').val(); let valorAbono = $row.find('input[name="ABONO"]').val(); // Si CARGO o ABONO están vacíos o son null, asignarles el valor de 0 valorCargo = valorCargo ? valorCargo : 0; valorAbono = valorAbono ? valorAbono : 0; // Verificar si la fila tiene datos completos if (valorFecha && valorSelectPoliza && valorSelectCuenta && valorSelectProveedor && valorDescripcion && (valorCargo !== "" || valorAbono !== "")) { // Agregar los datos de la fila al array solo si todos los campos están completos allData.push({ fecha: valorFecha, selectPoliza: valorSelectPoliza, selectCuenta: valorSelectCuenta, selectProveedor: valorSelectProveedor, descripcion: valorDescripcion, cargo: valorCargo, abono: valorAbono, textCuenta: textCuenta }); } else { isValid = false; return false; // Rompe el each loop si una fila es inválida } } }); // Si todos los campos son válidos, enviar la solicitud AJAX if (isValid && allData.length > 0) { $.ajax({ url: 'https://panel.fivetwofive.tech/yaaxlum/public/addEntradasSalidas', type: 'POST', dataType: 'json', data: { rows: allData }, // Enviar todos los datos en un solo objeto success: function (response) { $('#overlay').css('visibility', 'hidden'); saveBtn.remove(); cargarDatos(); // Recargar los datos de la tabla }, error: function (xhr, status, error) { alert('Hubo un error en la inserción'); console.error('Error en la solicitud:', error); $('#overlay').css('visibility', 'hidden'); } }); } else { alert('Por favor, completa todos los campos en cada fila antes de guardar.'); $('#overlay').css('visibility', 'hidden'); } }); //Borrar Filas $(document).on('click', '.delete-row', function () { let tamanoDeletes = $('.delete-row').length; if(tamanoDeletes > 1){ $(this).closest('tr').remove(); // Eliminar la fila correspondiente }else{ saveBtn.remove(); $(this).closest('tr').remove(); } }); //EDITAR FILA $(document).on('click', '[id^="edit_"]', function () { let buttonId = $(this).attr('id'); let rowId = buttonId.split('_')[1]; // Extrae el ID_REGISTRO de la ID del botón let $row = $('#idrow_' + rowId); let row = $(this).closest('tr'); // Obtener la fila que contiene el botón de edición // Obtener los datos actuales de la fila let fecha = $row.find('td').eq(1).text().trim(); let poliza = $row.find('td').eq(2).attr('id').split('pol_')[1]; let cuenta = $row.find('td').eq(3).attr('id').split('cuent_')[1]; let proveedor = $row.find('td').eq(4).attr('id').split('proId_')[1]; let descripcion = $row.find('td').eq(5).text().trim(); let cargo = $row.find('td').eq(6).text().trim(); let abono = $row.find('td').eq(7).text().trim(); // Asignación de IDs únicos para los elementos de la fila const uniqueId = rowId; // Usar el ID original para mantener la consistencia const newSelectEd = 'editDate_' + uniqueId; const newSelectCan = 'cancDate_' + uniqueId; const newSelectDat = 'selectDate_' + uniqueId; const newSelectId = 'selectPoliza_' + uniqueId; const newSelectCuentaId = 'selectCuenta_' + uniqueId; const newSelectProveedorId = 'selectProveedor_' + uniqueId; const newSelectDescripcionId = 'descripcion_' + uniqueId; const newSelectCargoId = 'cargo_' + uniqueId; const newSelectAbonoId = 'abono_' + uniqueId; const placeholderOption = ''; const filaOriginal = row.html(); // Guardar el HTML original de la fila antes de reemplazarla // Reemplazar la fila con la versión editable let nuevaFila = `` + `      ` + `` + `` + `` + `` + `` + `` + `` + ''; // Reemplazar la fila en la tabla $row.replaceWith(nuevaFila); // Inicializar Select2 en los nuevos elementos function initializeSelect2() { if (select2Options.length) { $('#' + newSelectId).select2({ data: select2Options, placeholder: 'Seleccione una opción', width: 'resolve' }).val(poliza).trigger('change'); // Establecer el valor actual } if (select2CuentaOptions.length) { $('#' + newSelectCuentaId).select2({ data: select2CuentaOptions, placeholder: 'Seleccione una opción', width: 'resolve' }).val(cuenta).trigger('change'); // Establecer el valor actual } if (select2Proveedor.length) { $('#' + newSelectProveedorId).select2({ data: select2Proveedor, placeholder: 'Seleccione una opción', width: 'resolve' }).val(proveedor).trigger('change'); // Establecer el valor actual } } initializeSelect2(); // Inicializar el Datepicker en el nuevo campo de fecha // $('.datepicker').datepicker({ // dateFormat: 'yy-mm-dd', // }); //cancelar $(document).on('click', '[id^="cancDate_"]', function () { // Restaurar la fila original $(this).closest('tr').html(filaOriginal); }); }); // GUARDAR CAMBIOS $(document).on('click', '[id^="editDate_"]', function () { // Obtener el ID único del botón de guardar let buttonId = $(this).attr('id'); let rowId = buttonId.split('_')[1]; let $row = $('#idrow_' + rowId); $('#overlay').css('visibility', 'visible'); // Recopilar los datos de la fila editable let fecha = $row.find('input[name="FECHA"]').val(); let poliza = $row.find('select[id^="selectPoliza_"]').val(); let cuenta = $row.find('select[id^="selectCuenta_"]').val(); const textCuenta = $row.find('.selectCuenta option:selected').text(); let proveedor = $row.find('select[id^="selectProveedor_"]').val(); let descripcion = $row.find('input[name="DESCRIPCION"]').val(); let cargo = $row.find('input[name="CARGO"]').val(); let abono = $row.find('input[name="ABONO"]').val(); //OBTENER DATOS PARA MOSTRAR let polizaText = $row.find('select[id^="selectPoliza_"] option:selected').text(); let cuentaText = $row.find('select[id^="selectCuenta_"] option:selected').text(); let proveedorText = $row.find('select[id^="selectProveedor_"] option:selected').text(); // Enviar datos al servidor mediante AJAX let data = [{ ID_REGISTRO: rowId, // Asegúrate de que el ID se envía aquí FECHA: fecha, POLIZA: poliza, CUENTA: cuenta, PROVEEDOR: proveedor, DESCRIPCION: descripcion, CARGO: cargo, ABONO: abono, textCuenta: textCuenta }]; $.ajax({ url: 'https://panel.fivetwofive.tech/yaaxlum/public/updateEntradasSalidas', // Cambia esta URL a la ruta de tu controlador type: 'POST', data: { data: data }, success: function (response) { // Manejar la respuesta del servidor if (response.success) { $('#overlay').css('visibility', 'hidden'); // Construir la nueva fila con los datos actualizados let updatedRow = `    ${rowId} ${fecha} ${polizaText} ${cuentaText} ${proveedorText} ${descripcion} ${cargo} ${abono} `; // Reemplazar la fila en la tabla $row.replaceWith(updatedRow); // Inicializar Select2 en los nuevos elementos function initializeSelect2() { $('#' + `selectPoliza_${rowId}`).select2({ data: select2Options, placeholder: 'Seleccione una opción', width: 'resolve' }); $('#' + `selectCuenta_${rowId}`).select2({ data: select2CuentaOptions, placeholder: 'Seleccione una opción', width: 'resolve' }); $('#' + `selectProveedor_${rowId}`).select2({ data: select2Proveedor, placeholder: 'Seleccione una opción', width: 'resolve' }); } initializeSelect2(); // Inicializar el Datepicker en el nuevo campo de fecha // $('.datepicker').datepicker({ // dateFormat: 'yy-mm-dd', // }); } else { $('#overlay').css('visibility', 'hidden'); alert('Error al actualizar la fila'); } }, error: function () { $('#overlay').css('visibility', 'hidden'); alert('Error de conexión'); } }); $('#myModal').on('shown.bs.modal', function () { $('#myInput').trigger('focus'); }); }); //BORRAR FILA BD // Variable global para almacenar el rowId a eliminar let rowIdToDelete = null; // Manejo del clic en los botones de eliminar en la tabla $(document).on('click', '[id^="dele_"]', function () { let buttonId = $(this).attr('id'); rowIdToDelete = buttonId.split('_')[1]; // Extrae el ID_REGISTRO de la ID del botón // Obtener la fila que contiene el botón de eliminación let $row = $('#idrow_' + rowIdToDelete); let row = $(this).closest('tr'); // Obtener la fila actual // Limpiar el modal antes de agregar nuevos botones $('.modal-footer').empty(); // Agregar los botones let buttonsHtml = ` `; $('.modal-footer').append(buttonsHtml); // Mostrar el modal $('#myModal').modal('show'); }); // Manejo del clic en el botón de eliminar dentro del modal $(document).on('click', '[id^="btnEliminarPer_"]', function () { if (rowIdToDelete !== null) { $('#overlay').css('visibility', 'visible'); $.ajax({ url: 'https://panel.fivetwofive.tech/yaaxlum/public/delEntradasSalidas', // Reemplaza con tu URL type: 'POST', contentType: 'application/json', data: JSON.stringify({ idFila: rowIdToDelete }), // Reemplaza con los datos que quieras enviar success: function(response) { $('#overlay').css('visibility', 'hidden'); console.log(response); }, error: function(xhr, status, error) { $('#overlay').css('visibility', 'visible'); console.log('hubo un error:' + error); } }); $('#idrow_' + rowIdToDelete).remove(); // Ocultar el modal después de eliminar la fila $('#myModal').modal('hide'); // Limpiar el modal después de ocultarlo $('.modal-footer').empty(); // Restablecer la variable global rowIdToDelete = null; } }); const yesterdaySet = new Date(); yesterdaySet.setDate(yesterdaySet.getDate() - 1); const formattedDate = yesterday.toISOString().split('T')[0]; document.getElementById('dateGc').value = formattedDate; });