var dtTemp; var clienteTemp; var lista_clientes; var fileInput; var file; var cadenaB64 = ''; var textoCliente = ''; var dataTable; $(document).ready(function () { construyeDT(); inicializarDataTable(dataTable); //agregar la funcion de recuperar CFDI document.getElementById("btnCerrar").addEventListener("click", function () { var formulario = document.getElementById("miFormulario"); formulario.style.display = "none"; $("#overlay").addClass("hidden"); }); document.getElementById("btnEnviar").addEventListener("click", function () { var folio = document.getElementsByName("folioFactura")[0].value; // UUID var correo = document.getElementById("correo").value; // CORREO console.log(folio); const enviarFolio = async () => { const datosXML = { uuid: folio, correo1: correo, }; console.log("datos a enviar " + JSON.stringify(datosXML)); try { const response = await fetch("php/recuperarPDF.php", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(datosXML), }); if (!response.ok) { throw new Error("Error en la petición"); } const data = await response.json(); console.log("Respuesta de la API:", data); var formulario = document.getElementById("miFormulario"); formulario.style.display = "none"; $("#overlay").addClass("hidden"); alertify.success("La factura se ha enviado al correo especificado!"); } catch (error) { console.error("Error:", error); } }; enviarFolio(); // Realizar la petición AJAX // Formar la URL del archivo XML basado en el folio //var xmlFile = "xml/" + folio + ".xml"; // Ruta del archivo XML /* // Realizar una solicitud HEAD para verificar la existencia del archivo fetch(xmlFile, { method: 'HEAD' }) .then(response => { if (!response.ok) { throw new Error('Archivo no encontrado'); } // Si la solicitud es exitosa, el archivo existe return true; }) .then(fileExists => { if (fileExists) { // Si el archivo existe, muestra el contenido fetch(xmlFile) .then(response => response.text()) .then(xmlContent => { // Convertir contenido a base64 var xmlBase64 = btoa(xmlContent); enviarXML(folio, xmlBase64, correo); }); } else { // Si el archivo no existe, muestra un mensaje de error alertify.error('Folio no encontrado!'); } }) .catch(error => { // Si ocurre un error, muestra un mensaje de error alertify.error('Folio no encontrado!'); }); */ }); $("#motivoSAT").change(function () { // Obtener el valor de la opción seleccionada var valorSeleccionado = $(this).val(); // Verificar si la opción seleccionada es la que deseas if (valorSeleccionado === "01") { // Agregar la parte de HTML $("#motivo_relacionado").append( '' ); } else { $("#motivo_relacionado").empty(); } }); //Agregar la funcion de cancelar CFDI $("#enviarFormulario").click(function () { var id = document.getElementById("idFolioSis").value; var UUID = document.getElementById("uuidInput").value; var folio = document.getElementById("folioSis").value; var monto = document.getElementById("montoSis").value; var motivo = document.getElementById("motivoInput").value; var motivoSAT = document.getElementById("motivoSAT").value; var uuid_relacionado = document.getElementById("uuid_relacionado"); if (uuid_relacionado) { uuid_relacionado = document.getElementById("uuid_relacionado").value; } else { uuid_relacionado = ""; } var user_id = document.getElementById("UsuarioSolicita").value; UNIDAD_NEGOCIO = document.getElementById("centroInput").value; var rfcReceptor = document.getElementById("rfcReceptor").value; $.ajax({ data: { idFactura: id, user_id: user_id, STATUS: 7, UNIDAD_NEGOCIO: UNIDAD_NEGOCIO, url: "url", FOLIO: folio, UUID: UUID, TOTAL: monto, RFC: rfcReceptor, portal: 0, motivo: motivo, motivoSAT: motivoSAT, uuid_relacionado: uuid_relacionado, }, //datos que se envian a traves de ajax url: "php/cancelacionAdministradoresCP.php", //archivo que recibe la peticion type: "post", //método de envio beforeSend: function () {}, }) .done(function (response) { console.log(response); if (response != 1) { console.log(response); err = JSON.parse(response); alertify.error(err.message); if (typeof err.code !== "undefined" && err.code !== null) { alertify.error(err.message); } else { console.log("Error al cancelar la factura"); } /* setTimeout(function(){ location.reload(true); }, 3000); */ } else { alertify.success("Factura cancelada"); setTimeout(function () { location.reload(true); }, 3000); } }) .fail(function (error) { //EN CASO DE FALLO, SE PINTA UN ERROR EN CONSOLA console.log(error); err = JSON.parse(error); alertify.error(err.message); /* setTimeout(function(){ location.reload(true); }, 3000); */ }); }); }); function cancelarAdmin(data) { var string = "OK"; alertify.confirm( "Confirmacion de cancelación", "¿Estas seguro que deseas cancelar la factura? No se podrán modificar los cambios posteriormente.", function () { limpiarForm(); $("#modalCancel").modal("show"); console.log(data); var input = document.getElementById("uuidInput"); input.value = data.UUID; var folio = document.getElementById("folioSis"); folio.value = data.folio; var monto = document.getElementById("montoSis"); monto.value = data.monto; var id = document.getElementById("idFolioSis"); id.value = data.id; }, function () { alertify.error("Factura no cancelada"); } ); } function limpiarForm() { document.getElementById("SolCancelacion").reset(); } function construyeDT() { var columns = [ { data: 'folio', title: 'Folio' }, { data: 'fecha_ppd', title: 'Fecha pago' }, { data: 'fecha_creacion', title: 'Fecha solicitud' }, { data: 'unidad', title: 'Unidad Venta' }, { data: 'cliente', title: 'Cliente' }, { data: 'monto', title: 'Monto pagado' }, { data: 'email', title: 'Correo' }, { data: 'forma_pago', visible: false}, { data: 'descripcion_pago', title: 'Forma Pago' }, { data: 'id', title: 'Accion', render: function (data, type, row) { if (row.estatus == '2') { return ''; } else if (row.estatus == '4') { //return 'Timbrado'; return ( 'Timbrado" ); } } }, { data: 'UUID', title : 'UUID'} ]; // Destruye la DataTable si ya existe if ($.fn.DataTable.isDataTable('#pagosDT')) { $('#pagosDT').DataTable().destroy(); } // Construye la DataTable dataTable = $('#pagosDT').DataTable({ destroy: true, lengthMenu: [10, 25, 50, 100, 500, 1000], pageLength: 10, searching: true, paging: true, ordering: true, info: true, responsive: true, dom: 'Blfrtip', buttons: [{ extend: 'pdfHtml5', text: 'PDF', exportOptions: { modifier: { page: 'current' } }, className: 'btn-danger' }, { extend: 'excelHtml5', text: 'Excel', exportOptions: { modifier: { page: 'current' } }, className: 'btn-success' }], initComplete: function () { // Agregar un input de texto al lado de los botones /*$(".dt-buttons").append('
'); $(".dt-buttons").append(''); $(".dt-buttons").append(' '); */ $(".dt-buttons").append(`
`); fetch("php/unidad_negocio.php") .then((response) => { // Verificar que la respuesta sea correcta if (!response.ok) { throw new Error(`Error en la solicitud: ${response.status}`); } return response.json(); // Convertir la respuesta a JSON }) .then((data) => { console.log("Datos obtenidos:", data); // Usar los datos obtenidos const selectElement = document.getElementById("unidadNeg"); selectElement.innerHTML = ""; // Recorrer los datos y agregarlos como opciones data.forEach((item) => { const option = document.createElement("option"); option.value = item.codigo_unidad; option.textContent = item.descripcion; selectElement.appendChild(option); }); }) .catch((error) => { console.error("Error:", error); // Manejar errores }); }, columns: columns, data: [] }); // Agrega un mensaje si no hay datos en la DataTable $('#pagosDT tbody').html('Sin facturas'); // Agrega el botón #getSelectedRows al contenedor de botones } function timbra(data) { Swal.fire({ icon: 'info', title: 'Mensaje', text: '¿Desea timbrar este pago?', showCancelButton: true, confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then((result) => { if (result.isConfirmed) { toggleLoader4() var centro = data.id_unidad; var fecha_pago = data.fecha_ppd; var monto = data.monto; var email = data.email; var id_solicitud = data.id; var id_cliente = data.id_cliente; var folio = data.folio; var formaPago = data.forma_pago; var solicitud = { unidad_negocio: centro, fecha_pago: fecha_pago, pagado: monto, email: email, solicitud: id_solicitud, folioP: folio, id_cliente: id_cliente, formaPago : formaPago }; var titulo = document.getElementById('titulo_modal'); var mensaje = document.getElementById('p_errores'); $.ajax({ url: 'php/Timbrado/pagos_api.php', type: 'POST', data: solicitud, dataType: 'json', success: function (data) { //--------Si es nula la respuesta console.log('Respuesta', data) if(data===null) { titulo.innerText = '¡Mensaje, intento de timbrado!'; mensaje.innerText = 'No se puede timbrar. Error en datos'; $('#mensajes').modal('show') toggleLoader4() } else{ if (data.code == "200") { titulo.innerText = '¡Timbrado!'; mensaje.innerHTML = data.message + '
UUID: ' + data.uuid; inicializarDataTable(dataTable); } else { titulo.innerText = '¡Mensaje, intento de timbrado!'; mensaje.innerText = data.message; } $('#mensajes').modal('show') toggleLoader4() } }, error: function (error) { console.log(error) titulo.innerText = '¡Mensaje, intento de timbrado!'; mensaje.innerText = 'No es posible realizar timbrado, consulte a soporte'; $('#mensajes').modal('show') toggleLoader4() } }); } }); } function inicializarDataTable(dataTable) { $.ajax({ url: 'php/ConsultasTablas/ManipulacionConsultas.php', type: 'POST', data: { opcion: '8' }, dataType: 'json', success: function (data) { // console.log(data) if (data.length > 0) { console.log('Agregar filas') dataTable.clear().rows.add(data).draw(); } else { $('#pagosDT tbody').html('No hay facturas PPD'); } }, error: function (error) { console.error('Error en la llamada AJAX', error); } }); } function toggleLoader4() { console.log('ENTRA') var loaderWrapper = document.getElementById("loaderWrapper4"); if (loaderWrapper.classList.contains("hidden")) { loaderWrapper.classList.remove("hidden"); $('#overlay').removeClass('hidden'); } else { loaderWrapper.classList.add("hidden"); $('#overlay').addClass('hidden'); } } function recargarPag() { location.reload(); } function filtrarPPD() { var mes = document.getElementById("meses").value; var unidadNeg = document.getElementById("unidadNeg").value; console.log("mes" + mes + " unidadNeg" + unidadNeg); construyeDT(); $.ajax({ url: "php/ConsultasTablas/ManipulacionConsultas.php", type: "POST", data: { opcion: "11", mes: mes, unidadNeg: unidadNeg }, dataType: "json", success: function (data) { // console.log(data) if (data.length > 0) { console.log("Agregar filas"); dataTable.clear().rows.add(data).draw(); } else { $("#pagosDT tbody").html( 'No hay facturas PPD' ); } }, error: function (error) { console.error("Error en la llamada AJAX", error); }, }); } function recuperarCFDI(data) { console.log(data.UUID); var formulario = document.getElementById("miFormulario"); formulario.style.display = "block"; $("#overlay").removeClass("hidden"); var inputFolio = formulario.querySelector('input[name="folioFactura"]'); // Ajusta el selector según el atributo del input if (inputFolio) { inputFolio.value = data.UUID; console.log("Folio actualizado:", inputFolio.value); } else { console.error("El input con name='folio' no se encontró en el formulario."); } } function enviarXML(uuid, xml, correo) { console.log(uuid); console.log(xml); $.ajax({ type: "POST", url: "php/Timbrado/recuperarCFDI1.php", data: { uuid: uuid, correo: correo, xml: xml, }, dataType: "json", success: function (response) { console.log(response); if (response.respuesta === "OK") { alertify.success("Se ha enviado el correo!"); var folio = document.getElementById("folio"); // UUID var correo = document.getElementById("correo"); // CORREO var formulario = document.getElementById("miFormulario"); formulario.style.display = "none"; $("#overlay").addClass("hidden"); folio.value = ""; correo.value = ""; } }, error: function (error) { console.error("Error en la segunda llamada AJAX", error); }, }); } function timbra(data) { Swal.fire({ icon: "info", title: "Mensaje", text: "¿Desea timbrar este pago?", showCancelButton: true, confirmButtonText: "Aceptar", cancelButtonText: "Cancelar", }).then((result) => { if (result.isConfirmed) { toggleLoader4(); var centro = data.id_unidad; var fecha_pago = data.fecha_ppd; var monto = data.monto; var email = data.email; var id_solicitud = data.id; var id_cliente = data.id_cliente; var folio = data.folio; var formaPago = data.forma_pago; var solicitud = { unidad_negocio: centro, fecha_pago: fecha_pago, pagado: monto, email: email, solicitud: id_solicitud, folioP: folio, id_cliente: id_cliente, formaPago: formaPago, }; var titulo = document.getElementById("titulo_modal"); var mensaje = document.getElementById("p_errores"); $.ajax({ url: "php/Timbrado/pagos_api.php", type: "POST", data: solicitud, dataType: "json", success: function (data) { console.log("Respuesta", data); if (data.code == "200") { titulo.innerText = "¡Timbrado!"; mensaje.innerHTML = data.message + "
UUID: " + data.uuid; inicializarDataTable(dataTable); } else { titulo.innerText = "¡Mensaje, intento de timbrado!"; mensaje.innerText = data.message; } $("#mensajes").modal("show"); toggleLoader4(); }, error: function (error) { console.log(error); titulo.innerText = "¡Mensaje, intento de timbrado!"; mensaje.innerText = "No es posible realizar timbrado, consulte a soporte"; $("#mensajes").modal("show"); toggleLoader4(); }, }); } }); }