EVOLUTION-MANAGER
Edit File: crud-rendicion.js
const li = document.querySelectorAll('.li'); const bloque = document.querySelectorAll('.bloque'); var datos = window.appData.datos; var sorts = []; var sortable = null; let initialOrder = []; let aniocancelar = null; li.forEach((cadaLi, i) => { li[i].addEventListener('click', () => { if (aniocancelar != null) cancelacion_metodo(aniocancelar); li.forEach((cadaLi, i) => { li[i].classList.remove('activo'); bloque[i].classList.remove('activo'); }) li[i].classList.add('activo'); bloque[i].classList.add('activo'); }); }); function ordenar_informacion(id, clase) { Swal.fire({ title: "Está seguro de cambiar el orden?", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: "Sí" }).then((result) => { if (result.isConfirmed) { aniocancelar = id;//iniciar re-orden var btn = document.getElementById("boton-mover-" + id); var ok = document.getElementById("boton-ok-orden-" + id); var cancelar = document.getElementById("boton-cancelar-orden-" + id); btn.classList.add("disable-move"); ok.classList.add("show-orden-opc"); cancelar.classList.add("show-orden-opc"); var elemento = document.getElementById(id); // Guardar el orden inicial initialOrder = [...elemento.querySelectorAll('.ordenar-' + id)].map(item => item.getAttribute('data-id')) // Inicializar Sortable.js sortable = new Sortable(elemento, { handle: '.' + clase, animation: 150, ghostClass: 'background-class', store: { set: function (sortable) { sorts = sortable.toArray(); } } }); } }); } function cambiar_orden(id) { Swal.fire({ title: "Esta seguro de guardar los cambios realizados?", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: "Si" }).then((result) => { if (result.isConfirmed) { const loadingModal = document.getElementById('loadingModal'); loadingModal.style.display = 'block'; $.ajaxSetup({ headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content') } }); if (sorts.length > 0) { var formData = new FormData(); for (var i = 0; i < sorts.length; i++) { formData.append('id[]', sorts[i]); formData.append('orden[]', 1 + i); } $.ajax({ url: "/administrador/crud-rendicion-cuenta/re-ordenar-rendicion-cuenta", method: "POST", enctype: "multipart/form-data", data: formData, processData: false, contentType: false, success: function (response) { if (response.success) { loadingModal.style.display = 'none'; manejar_orden(id); sorts.forEach((sortId, index) => { datos.forEach(item => { if (item.id_r_cuentas == sortId) { item.orden = index + 1; // Actualiza el orden basado en la posición en sorts } }); }); aniocancelar = null; sorts = []; sortable.destroy(); mensaje_de_alerta("success", response.message); } else { loadingModal.style.display = 'none'; if (response.errors) { mensaje_de_alerta("error", "Error de validación, hubo un error intentolo más tarde"); } if (response.error) { mensaje_de_alerta("error", response.error); } } }, error: function (xhr) { loadingModal.style.display = 'none'; var message = JSON.parse(xhr.responseText); mensaje_de_alerta("error", message.message); } }); } else { loadingModal.style.display = 'none'; manejar_orden(id); } } }); } function manejar_orden(id) { var btn = document.getElementById("boton-mover-" + id); var ok = document.getElementById("boton-ok-orden-" + id); var cancelar = document.getElementById("boton-cancelar-orden-" + id); btn.classList.remove("disable-move"); ok.classList.remove("show-orden-opc"); cancelar.classList.remove("show-orden-opc"); } function cancelar_orden(id) { Swal.fire({ title: "Está seguro de cancelar la edición del orden?", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: "Sí" }).then((result) => { if (result.isConfirmed){ cancelacion_metodo(id); aniocancelar = null; } }); } function cancelacion_metodo(id) { var elemento = document.getElementById(id); // Restaurar el orden original let items = [...elemento.querySelectorAll('.ordenar-' + id)]; initialOrder.forEach(orderId => { let item = items.find(el => el.getAttribute('data-id') === orderId); if (item) { elemento.appendChild(item); // Reinsertar los elementos en el orden original } }); manejar_orden(id); sorts = []; sortable.destroy(); aniocancelar= null; } function delete_button(event, id) { if (aniocancelar != null) cancelacion_metodo(aniocancelar); event.preventDefault(); Swal.fire({ title: "Esta seguro de borrar este registro?", text: "Si lo hace no podra recuperarlo!", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: "Si, borralo!" }).then((result) => { if (result.isConfirmed) { const loadingModal = document.getElementById('loadingModal'); loadingModal.style.display = 'block'; $.ajaxSetup({ headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: "/administrador/crud-rendicion-cuenta/eliminar-rendicion-cuenta/" + id, method: "DELETE", enctype: "multipart/form-data", processData: false, contentType: false, success: function (response) { if (response.success) { loadingModal.style.display = 'none'; // Utilizando `findIndex` para encontrar el índice y luego `splice` para eliminar el elemento var index = datos.findIndex(dato => dato.id_r_cuentas == id); var anio = null; if (index !== -1) { anio = datos[index].anio; } window.appData = { datos: response.datos }; datos = window.appData.datos; document.getElementById(id).remove(); // Verificar si la tabla está vacía y eliminarla si es necesario const li = document.querySelector(`.li.activo`); if (datos.length == 0) { document.getElementById("drop-no-data").remove(); // Selecciona la sección donde quieres agregar el nuevo div var section = document.querySelector('.home-section'); // Crea un nuevo div var nuevoDiv = document.createElement('div'); nuevoDiv.className = 'no-informacion'; // Asigna la clase al div // Establece el contenido HTML dentro del nuevo div nuevoDiv.innerHTML = '<p>Aún no se han creado registros de <b>Rendición de Cuentas</b></p>'; // Agrega el nuevo div al final de la sección if (section) { section.appendChild(nuevoDiv); } } else verificarYEliminarTabla(anio, li); mensaje_de_alerta("success", response.success); } else { loadingModal.style.display = 'none'; if (response.error) { mensaje_de_alerta("error", response.error); } } }, error: function (xhr) { loadingModal.style.display = 'none'; var message = JSON.parse(xhr.responseText); mensaje_de_alerta("error", message.message); } }); } }); } function verificarYEliminarTabla(anio, li) { const tbody = document.getElementById(anio); const tabla = document.getElementById(`registros-rendicion-${anio}`); // Verificar si no hay filas en el tbody if (tbody && tbody.rows.length === 0) { // Eliminar la tabla completa si no hay registros tabla.remove(); // Eliminar el bloque completo const bloque = document.querySelector(`.bloque.activo`); if (bloque) { bloque.remove(); } // Eliminar el `li` correspondiente li.remove(); // Verificar si existe otro `li` para activar const listaTabs = document.querySelectorAll('.contenedor-tabs .li'); if (listaTabs.length > 0) { // Obtener el índice actual del `li` const indexActual = Array.from(listaTabs).indexOf(li); // Intentar activar el siguiente `li`, si no existe, activar el anterior let nuevoActivo; if (listaTabs[indexActual + 1]) { // Si hay un siguiente `li`, activarlo nuevoActivo = listaTabs[indexActual + 1]; } else if (listaTabs[indexActual - 1]) { // Si no hay siguiente, activar el anterior nuevoActivo = listaTabs[indexActual - 1]; } if (nuevoActivo) { // Remover la clase `activo` de todos los `li` para que solo uno esté activo listaTabs.forEach(li => li.classList.remove('activo')); nuevoActivo.classList.add('activo'); // Activar el bloque correspondiente al nuevo `li` const nuevoAnio = nuevoActivo.textContent.trim(); const nuevoBloque = document.querySelector(`.bloque[id="bt-bloque-${nuevoAnio}"]`); // Remover la clase 'activo' de todos los bloques antes de activar el nuevo document.querySelectorAll('.bloque').forEach(bloque => bloque.classList.remove('activo')); if (nuevoBloque) { nuevoBloque.classList.add('activo'); } } } } } function maximo(campo, limite) { if (campo.value.length >= limite) { campo.value = campo.value.substring(0, limite); } document.getElementById('caracteres-restantes').innerHTML = limite - campo.value.length; } function crear_rendicionadd(anio) { if (aniocancelar != null) cancelacion_metodo(aniocancelar); const ventana = document.getElementById('ventana-formulario'); ventana.classList.add('show'); let contenido = document.getElementById('agregar-contenido-form'); ventana.innerHTML = `<div class="crear-nueva-rendicion-add"> <form id="crear-rendicion" style="width: 100%;" method="POST" enctype="multipart/form-data"> <div id="agregar-contenido-form"> <input name="fecha" class="campo-ingresar" id="anio" type="text" value="` + anio + `" autocomplete="off" hidden> <label for="titulo" style="font-weight: 700;">INGRESE EL TÍTULO</label> <div style="position: relative; width: 100%;"> <textarea id="titulo" name="titulo" rows="4" cols="50" onKeyUp="maximo(this,260);" onKeyDown="maximo(this,260);"></textarea> <div id="caracteres-restantes">260</div> <div id="message-error-titulo"></div> </div> <div class="ventana-modal"> <h2 class="titulo-area-subir">Subir Archivo</h2> <input name="nombre_archivo" type="file" id="cargar" onchange="cambios_id(this);" accept=".pdf" hidden> <label for="cargar" class="cargar_archivo"> <span><i class="icon-upload-cloud"></i></span> <p>Click para Subir archivo</p> <div class="progressBar" id="progressBar"></div> </label> <div class="vista-archivos" id="documentos-cargados"> <h3 class="subidos-exito">Documentos subidos</h3> </div> </div> <div id="message-error-documento"></div> <div class="orden-ubicacion-opc"> <input type="submit" class="crear-rendicion" value="Agregar"> <div class="cerrar-ventana-modal" onclick="cerrar_ventana();">Cancelar</div> </div> </div> </form> </div>`; let formulario_actualizar = document.getElementById("crear-rendicion"); formulario_actualizar.addEventListener("submit", (e) => { e.preventDefault(); var anio = document.getElementById("anio"); var titulo = document.getElementById("titulo"); var pdf = document.getElementById("cargar"); // if (anio.value != "" && titulo.value != "" && pdf.value.length > 0) { const loadingModal = document.getElementById('loadingModal'); loadingModal.style.display = 'block'; $.ajaxSetup({ headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content') } }); var formData = new FormData(); formData.append('fecha', $('#anio').val()); formData.append('titulo', $('#titulo').val()); if ($('#cargar')[0].files[0]) { formData.append('nombre_archivo', $('#cargar')[0].files[0]); } //limpiar los campos que contienen los mensajes de error document.getElementById("message-error-titulo").innerHTML = ""; document.getElementById("message-error-documento").innerHTML = ""; $.ajax({ url: "/administrador/crud-rendicion-cuenta/agregar-rendicion-cuenta", method: "POST", enctype: "multipart/form-data", data: formData, processData: false, contentType: false, success: function (response) { if (response.success) { loadingModal.style.display = 'none'; cerrar_ventana(); mensaje_de_alerta("success", response.message); var tabla = document.getElementById("registros-rendicion-" + anio.value); var tbody = tabla.getElementsByTagName('tbody')[0]; var nuevaFila = tbody.insertRow(); var celdaId = nuevaFila.insertCell(0); var celdaTitulo = nuevaFila.insertCell(1); var celdaBorrar = nuevaFila.insertCell(2); var celdaEditar = nuevaFila.insertCell(3); let vista_documento = new URL(response.ruta); celdaId.innerHTML = response.id; celdaTitulo.innerHTML = `<a href="` + vista_documento + `/` + response.id_archivo + `/view" id="rendicion-` + response.id + `" class="titulo-rendicion" target="_blank"> `+ titulo.value + ` </a>`; celdaBorrar.innerHTML = `<form onsubmit="return delete_button(event, '` + response.id + `')"> <input type="submit" class="btn btn-danger" value="Borrar"> </form>`; celdaEditar.innerHTML = `<button class="btn btn-success" onclick="editar_rendicionadd(` + anio.value + `, ` + response.id + `);">Editar</button>`; nuevaFila.style = "cursor: pointer"; nuevaFila.id = response.id; datos.push({ 'anio': anio.value, 'id_r_cuentas': response.id, 'titulo': titulo.value, 'nombre_archivo': response.id_archivo, 'orden': response.orden_archivo }); } else { loadingModal.style.display = 'none'; if (response.errors) { mensaje_de_alerta("error", "Error de validación, revise que la información ingresada sea la correcta"); var campos = { "titulo": "message-error-titulo", "archivo": "message-error-documento", }; // Recorre los errores y asigna los mensajes a los elementos correspondientes $.each(response.errors, function (key, value) { $.each(campos, function (campo, elementoId) { if (value[0].includes(campo)) { document.getElementById(elementoId).innerHTML += '<p class="alert alert-danger">' + value[0] + '</p>'; } }); }); } if (response.error) { mensaje_de_alerta("error", response.error); } } }, error: function (xhr) { loadingModal.style.display = 'none'; var message = JSON.parse(xhr.responseText); mensaje_de_alerta("error", message.message); } }); // } else { // if (titulo.value == "") // document.getElementById('message-error-titulo').innerHTML = '<p class="alert alert-danger">Debe ingresar un titulo</p>'; // if (pdf.value.length == 0) // document.getElementById('message-error-documento').innerHTML = '<p class="alert alert-danger">Debe subir un archivo .pdf</p>'; // } }); } function cerrar_ventana() { var modal = document.getElementById("ventana-formulario"); modal.innerHTML = ""; modal.classList.remove("show"); } function cambios_id(e) { var input = document.getElementById("cargar"); var show_archivos = document.getElementById("documentos-cargados"); const fileshow = (filename, filetype) => { let container = document.createElement('div'); container.className = 'mostrar-archivos'; let leftdiv = document.createElement('div'); leftdiv.className = 'left'; let filespan = document.createElement('span'); filespan.className = 'tipo-archivo'; filespan.textContent = filetype; let fileh3 = document.createElement('h3'); fileh3.textContent = filename; leftdiv.appendChild(filespan); leftdiv.appendChild(fileh3); let rightdiv = document.createElement('div'); rightdiv.className = 'right'; rightdiv.id = 'borrar'; let filespan2 = document.createElement('span'); filespan2.innerHTML = '×'; rightdiv.appendChild(filespan2); container.appendChild(leftdiv); container.appendChild(rightdiv); show_archivos.innerHTML = ''; show_archivos.appendChild(container); var borrar = document.getElementById("borrar") borrar.addEventListener("click", () => { input.value = ""; show_archivos.innerHTML = `<h3 class="subidos-exito">Documentos subidos</h3>`; }); } if (e.files[0]) { let filename = e.files[0].name; let filetype = e.value.split(".").pop(); // const file = input.files[0]; const reader = new FileReader(); reader.readAsArrayBuffer(file); var porcentaje; const progressBar = document.getElementById('progressBar'); progressBar.classList.add('progressBarshow'); reader.onprogress = (e) => { porcentaje = Math.round((e.loaded / e.total) * 100); progressBar.style.width = porcentaje + '%'; progressBar.innerHTML = porcentaje + "%" } reader.onload = (e) => { progressBar.classList.remove('progressBarshow'); progressBar.style.width = '0%'; fileshow(filename, filetype); } } else { show_archivos.innerHTML = `<h3 class="subidos-exito">Documentos subidos</h3>`; input.value = ""; } } function mensaje_de_alerta(icon, title) { Swal.fire({ icon: icon, title: title, showConfirmButton: true, }); } function editar_rendicionadd(anio, id) { if (aniocancelar != null) cancelacion_metodo(aniocancelar); const datos = window.appData.datos; var titulo, archivo; datos.forEach(item => { if (item.anio == anio && item.id_r_cuentas == id) { titulo = item.titulo; archivo = item.nombre_archivo; } }); let contenido = document.getElementById('ventana-formulario'); contenido.classList.add('show'); contenido.innerHTML = ` <div class="crear-nueva-rendicion-add"> <form style="width: 100%;" id="actualizar-datos" enctype="multipart/form-data"> <div id="agregar-contenido-form"> <label for="titulo" style="font-weight: 700;">INGRESE EL TÍTULO</label> <div style="position: relative; width: 100%;"> <textarea id="titulo" name="titulo" rows="4" cols="50" onKeyUp="maximo(this,500);" onKeyDown="maximo(this,500);">`+ titulo + `</textarea> <div id="caracteres-restantes">500</div> <div id="message-error-titulo"></div> </div> <div class="ventana-modal"> <h2 class="titulo-area-subir">Subir Archivo</h2> <input name="cargar" type="file" id="cargar" onchange="cambios_id(this);" accept=".pdf" hidden> <label for="cargar" class="cargar_archivo"> <span><i class="icon-upload-cloud"></i></span> <p>Click para Subir archivo</p> <div class="progressBar" id="progressBar"></div> </label> <div class="vista-archivos" id="documentos-cargados"> <h3 class="subidos-exito">Documentos subidos</h3> </div> </div> <div id="message-error-documento"></div> <div class="orden-ubicacion-opc"> <input type="submit" class="crear-rendicion" value="Agregar"> <div class="cerrar-ventana-modal" onclick="cerrar_ventana();">Cancelar</div> </div> </div> </form> </div> `; let limite = 500; let campo = document.getElementById('titulo'); if (campo.value.length >= limite) { campo.value = campo.value.substring(0, limite); } document.getElementById('caracteres-restantes').innerHTML = limite - campo.value.length; let formulario_actualizar = document.getElementById("actualizar-datos"); formulario_actualizar.addEventListener("submit", (e) => { e.preventDefault(); const loadingModal = document.getElementById('loadingModal'); loadingModal.style.display = 'block'; $.ajaxSetup({ headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content') } }); var formData = new FormData(); formData.append('fecha', anio); formData.append('titulo', $('#titulo').val()); if ($('#cargar')[0].files[0]) { formData.append('nombre_archivo', $('#cargar')[0].files[0]); } formData.append('id', id); //limpiar los campos que contienen los mensajes de error document.getElementById("message-error-titulo").innerHTML = ""; document.getElementById("message-error-documento").innerHTML = ""; $.ajax({ url: "/administrador/crud-rendicion-cuenta/actualizar-rendicion-cuenta", method: "POST", enctype: "multipart/form-data", data: formData, processData: false, contentType: false, success: function (response) { if (response.success) { loadingModal.style.display = 'none'; document.getElementById("rendicion-" + id).innerHTML = $('#titulo').val(); if (response.id_archivo) { let url = new URL(response.ruta + "/" + response.id_archivo + "/view"); document.getElementById("rendicion-" + id).href = url; } datos.forEach(item => { if (item.anio == anio && item.id_r_cuentas == id) { item.titulo = $('#titulo').val(); } }); mensaje_de_alerta("success", response.message); cerrar_ventana(); } else { loadingModal.style.display = 'none'; if (response.errors) { mensaje_de_alerta("error", "Error de validación, revise que la información ingresada sea la correcta"); var campos = { "titulo": "message-error-titulo", "archivo": "message-error-documento", }; // Recorre los errores y asigna los mensajes a los elementos correspondientes $.each(response.errors, function (key, value) { $.each(campos, function (campo, elementoId) { if (value[0].includes(campo)) { document.getElementById(elementoId).innerHTML += '<p class="alert alert-danger">' + value[0] + '</p>'; } }); }); } if (response.error) { mensaje_de_alerta("error", response.error); } } }, error: function (xhr) { loadingModal.style.display = 'none'; var message = JSON.parse(xhr.responseText); mensaje_de_alerta("error", "hola" + message.message); } }); }); }