File "interprete.js"

Full Path: C:/wamp64/www/INTERPRETE2/frontend/node_modules/base64-arraybuffer/interprete.js
File size: 19.59 KB
MIME-type: text/plain
Charset: utf-8


// Insertar estilos CSS dinámicamente en el head del HTML
const style = document.createElement('style');
style.innerHTML = `
    .success-message {
        background-color:rgb(134, 243, 160);
        color:rgb(0, 0, 0);
        border: 1px solid rgb(0, 0, 0);
        padding: 10px;
        border-radius: 5px;
        margin-top: 10px;
        font-size: 30px;
        text-align:center;
    }

    .error-message {
        background-color: #f8d7da;
        color: #721c24; , 
        border: 1px solid #f5c6cb;
        padding: 10px;
        border-radius: 5px;
        margin-top: 10px;
    }
`;

document.head.appendChild(style);

// Esta funcion procesa el archivo plano que pueden ser dos formatos diferentes .PJJ y .PVY y segun se determinara como se dividira.
function processFile() {
    const fileInput = document.getElementById('fileInput');
    const lineCount = document.getElementById('lineCount').value;
    const splitWord = document.getElementById('splitWord').value;

    if (!fileInput.files[0]) {
        alert("Por favor, selecciona un archivo.");
        return;
    }

    const file = fileInput.files[0];
    const reader = new FileReader();

    reader.onload = function (event) {
        const content = event.target.result;
        let result = "";

        if (lineCount) {
            result = splitByLines(content, lineCount);
        } else if (content.includes("\f")) {
            //  Archivo contable .pjj con saltos de página
            result = content.split("\f").filter(sec => sec.trim() !== "");
            console.log("Dividido por \\f, total secciones:", result.length);
        } else if (splitWord) {
            result = splitByWord(content, splitWord);
        } else {
            alert('Por favor ingresa un número o palabra para dividir el archivo');
            return;
        }

        if (content.includes("CERTIFICADO DE RETENCION")) {
            generatedRetencionesPDFs(result);
        } else {
            generatedSeparatedPDFs(result);
        }
    };

    reader.readAsText(file);
}


function splitByLines(content, lineCount) {
    const lines = content.split('\n').filter(line => line.trim() !== "");
    let chunks = [];
    let chunk = [];

    lines.forEach(line => {
        chunk.push(line);
        if (chunk.length === parseInt(lineCount)) {
            chunks.push(chunk.join('\n'));
            chunk = [];
        }
    });

    if (chunk.length > 0) chunks.push(chunk.join('\n'));
    return chunks.filter(chunk => chunk.trim() !== "");
}

function splitByWord(content, splitWord) {
    const regex = new RegExp(`(${splitWord})`, `g`);
    const sections = content.split(regex).filter(sec => sec.trim() !== "");
    let chunks = [];
    let currentChunk = "";

    sections.forEach(part => {
        if (part.match(regex)) {
            if (currentChunk) chunks.push(currentChunk);
            currentChunk = part;
        } else {
            currentChunk += part;
        }
    });

    if (currentChunk.trim() !== "") chunks.push(currentChunk);
    return chunks;
}

// funcion para archivo plano comprobantes de egreso .PVY
function generatedSeparatedPDFs(sections) {
    const { jsPDF } = window.jspdf;
    if (!sections || sections.length === 0) {
        console.error("Error: No hay contenido para procesar en generatedSeparatedPDFs");
        return;
    }

    const groupedSections = {};

    sections.filter(sec => sec.trim() !== "").forEach(section => {
        const numberMatch = section.match(/Numero\s*:\s*([\w-]+)/);
        const fileName = numberMatch ? numberMatch[1] : "unidentified";

        if (!groupedSections[fileName]) groupedSections[fileName] = [];
        groupedSections[fileName].push(section);
    });

    Object.keys(groupedSections).forEach(fileName => {
        const doc = new jsPDF();
        doc.setFont("courier");
        doc.setFontSize(9);

        groupedSections[fileName].forEach((section, index) => {
            if (index > 0) doc.addPage();
            doc.text(section, 9, 10);
        });

        const pdfBlob = doc.output("blob");
        const firstSection = groupedSections[fileName][0];

        const nitMatch    = firstSection.match(/NIT:\s*(\d+)/);
        const bancoMatch  = firstSection.match(/\d{2}\s+\d{2}\s+([\p{L}\s\/]+?)\s+\d+/u);
        const valorMatch  = firstSection.match(/Valor:\s*\$([\d,.]+)/);
        const fechaCMatch = firstSection.match(/Fecha\s*:\s*([\d]{4}-[A-Z]{3}-\d{2})/);
        const cuentaMatch = firstSection.match(/\s+(\d{6,})/);

        let NITproveedor     = nitMatch    ? nitMatch[1]          : "desconocido";
        let banco            = bancoMatch  ? bancoMatch[1].trim() : "desconocido";
        let valor            = valorMatch  ? valorMatch[1]        : "0";
        let cuenta           = cuentaMatch ? cuentaMatch[1]       : "desconocida";
        let fechaCertificado = fechaCMatch ? fechaCMatch[1]       : "Desconocida";

        sendToServer(fileName, NITproveedor, banco, valor, fechaCertificado, cuenta, pdfBlob);
    });
}


//  Funcion para archivos planos certificados de retención .PJJ
async function generatedRetencionesPDFs(sections) {
    const { jsPDF } = window.jspdf;
    if (!sections || sections.length === 0) {
        console.error("Error: No hay contenido para procesar");
        return;
    }

    const groupedSections = {};

    sections.filter(sec => sec.trim() !== "").forEach(section => {
        const nitMatch = section.match(/[NC]\s*\.\s*NIT\s*:\s*(\d[\d-]*\d|\d+)/);
        const fileName = nitMatch
            ? nitMatch[1].trim().replace(/-\d+$/, "").concat("_1")
            : "unidentified";

        if (!groupedSections[fileName]) groupedSections[fileName] = [];
        groupedSections[fileName].push(section);
    });

    const keys = Object.keys(groupedSections);
    console.log(`Total PDFs a generar: ${keys.length}`);

    for (let i = 0; i < keys.length; i++) {
        const fileName = keys[i];
        console.log(`Procesando ${i + 1}/${keys.length}: ${fileName}`);

        const doc = new jsPDF();
        doc.setFont("courier");
        doc.setFontSize(9);

        groupedSections[fileName].forEach((section, index) => {
            if (index > 0) doc.addPage();
            doc.text(section, 9, 10);
        });

        const pdfBlob = doc.output("blob");
        const firstSection = groupedSections[fileName][0];

        const nitMatch      = firstSection.match(/[NC]\s*\.\s*NIT\s*:\s*(\d[\d-]*\d|\d+)/);
        const retenidoMatch = firstSection.match(/RETENIDO\s*:\s*(.+)/);
        const fechaMatch    = firstSection.match(/Fecha Expedicion:\s*(.+)/);
        const valorMatch    = firstSection.match(/\*\* TOTAL\s+([\d,]+\.\d{2})\s+([\d,]+\.\d{2})/);

        let NITretenido     = nitMatch      ? nitMatch[1].trim().replace(/-\d+$/, "").concat("_1") : "desconocido";
        let nombreRetenido  = retenidoMatch ? retenidoMatch[1].trim()                              : "desconocido";
        let fechaExpedicion = fechaMatch    ? fechaMatch[1].trim().replace(/\s+/g, ' ')            : "desconocida";
        let valorRetenido   = valorMatch    ? valorMatch[2]                                        : "0";

        // Espera a que termine antes de enviar el siguiente
        await sendToServer(fileName, NITretenido, nombreRetenido, valorRetenido, fechaExpedicion, "", pdfBlob);
    }

    console.log("✅ Todos los PDFs procesados");
}

// Funcion para mostrar mensaje de exito o error.
function showMessage(message, isSuccess) {
    const messageBox = document.getElementById('messageBox');

    if (isSuccess) {
        messageBox.className = 'success-message';  // Estilo para mensaje de éxito
    } else {
        messageBox.className = 'error-message';  // Estilo para mensaje de error
    }

    // Limpiamos el contenido previo
    messageBox.innerHTML = '';

    // Creamos el elemento de texto para el mensaje
    const textNode = document.createElement('p');
    textNode.innerText = message;
    messageBox.appendChild(textNode);

    // Si es un mensaje de éxito, añadimos el botón
    if (isSuccess) {
        const button = document.createElement('button');
        button.textContent = 'Enviar Correos...';
        button.className = 'email';
        button.onclick = function () {
            alert('Enviando Correos...');
            window.open('http://192.200.100.40:8002/INTERPRETE2/Correo.php', '_blank');
        };
        messageBox.appendChild(button);
    }

    // Mostramos el contenedor del mensaje
    messageBox.style.display = 'block';
}

function sendToServer(fileName, NITproveedor, banco, valor, fechaC, cuenta, pdfBlob) {
    const formData = new FormData();

    formData.append("pdf", pdfBlob, `${fileName}.pdf`);
    formData.append("nombre", fileName);
    formData.append("NITproveedor", NITproveedor);
    formData.append("banco", banco);
    formData.append("valor", valor);
    formData.append("fechaCertificado", fechaC);
    formData.append("cuenta", cuenta);


    //  console.log("Enviando datos:", Object.fromEntries(formData)); 

    showMessage("Enviando el archivo...", true);

    return fetch("http://192.200.100.40:8002/INTERPRETE2/backend/server.php", {
        method: "POST",
        body: formData,

    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`Error en la solicitud: ${response.statusText}`);
            }
            return response.text();
        })
        .then(text => {
            console.log(text); // Para depuración
            try {
                const data = JSON.parse(text);
                if (data.status === 'success') {
                    console.log('Éxito: Los datos se han guardado exitosamente.');
                    // Mensaje visible en la página
                    showMessage('✅¡Los datos se han guardado exitosamente!', true);  // Éxito

                } else {
                    console.log('Error: Hubo un problema al guardar los datos.');
                    // Mensaje visible en la página
                    showMessage('Hubo un problema al guardar el dato.', false);  // Error
                }
            } catch (e) {
                console.error('Error al procesar la respuesta del servidor:', e);
                // Si ocurre un error al procesar la respuesta
                showMessage('Hubo un error al procesar la respuesta del servidor.', false);
            }
        })
        .catch(error => {
            console.log('Error en el envío del archivo: ', error);
            // En caso de error en la solicitud
            showMessage('Error en el envío del archivo a la base de datos.', false);
        });
}

function showToast(mensaje, tipo = "exito") {
    const toast = $('#toast2');
    toast.removeClass(); // Limpiar clases previas

    toast.addClass('toast2 show');
    toast.css('background-color', tipo === 'exito' ? '#28a745' : '#dc3545');
    toast.text(mensaje);

    setTimeout(() => {
        toast.removeClass('show');
    }, 3000);
}

function processData() {
    const nit = document.getElementById("NIT").value;
    const razonSocial = document.getElementById("razonSocial").value;
    const email = document.getElementById("email").value;

    if (!nit || !razonSocial || !email) {
        showToast("⚠️ Por favor, complete todos los campos.", "error");
        return;
    }

    const formData = new FormData();
    formData.append("NIT", nit);
    formData.append("razonSocial", razonSocial);
    formData.append("email", email);

    fetch("http://192.200.100.40:8002/INTERPRETE2/backend/server2.php", {
        method: "POST",
        body: formData,
    })
        .then(response => response.json())
        .then(data => {
            if (data.status === "success") {
                showToast("✅ Datos registrados correctamente.", "exito");
                limpiarCampos();
            } else {
                showToast("❌ Error: " + data.message, "error");
            }
        })
        .catch(error => {
            console.error("Error al enviar datos:", error);
            showToast("❌ Error de red al enviar datos.", "error");
        });
}

function limpiarCampos() {
    const container = document.querySelector('.container2');
    if (container) {
        const inputs = container.querySelectorAll('input');
        inputs.forEach(input => {
            input.value = '';
        });
    }
}


//--------------------------------------------------------------------------//-----------------------------------------------------------------//-----
// Funcion para obtener los datos de la base de datos y almacenarlos en un select para el reeenvio de correos

let mapaCorreos = {}; // clave: razon social, valor: correo
document.addEventListener("DOMContentLoaded", function () {
    fetch('http://192.200.100.40:8002/INTERPRETE2/backend/server3.php')
        .then(response => response.json())
        .then(data => {
            const select = document.getElementById("selectCorreo");

            if (!select) return;

            select.innerHTML = '<option value="">Seleccione un cliente</option>';
            data.forEach(cliente => {
                const razon = cliente.RAZON_SOCIAL;
                const correo = cliente.EMAIL;

                // Guardamos la relación
                mapaCorreos[razon] = correo;

                const option = document.createElement("option");
                option.value = razon;
                option.textContent = razon;
                select.appendChild(option);
            });

            $('#selectCorreo').select2({
                width: '100%',
                placeholder: "Seleccione un cliente"
            });
        });
});
//------------------------------------------------------------------------//----------------
//funcion para enviar los pdf con el correo en reeenvio de correo 
document.addEventListener("DOMContentLoaded", function () {
    const botonReenviar = document.getElementById("resend");
    const mensajeEnvio = document.getElementById("mensajeEnvio");

    if (botonReenviar) {
        botonReenviar.addEventListener("click", function () {
            const razon = document.getElementById("selectCorreo").value;
            const correo = mapaCorreos[razon];
            const archivo = document.getElementById("archivoReenvio").files[0];
            console.log("RAZÓN:", razon);
            console.log("CORREO:", correo);
            console.log("ARCHIVO:", archivo);

            if (!razon || !correo || !archivo) {
                alert("Seleccione proveedor y archivo .");
                return;
            }

            // Mostrar el loader y mensaje de envío
            mensajeEnvio.style.display = "block";
            mensajeEnvio.innerHTML = `<span class="spinner"></span> <span style ="font-size:30px">Enviando correo...</span>`;

            const formData = new FormData();
            formData.append("archivo", archivo);
            formData.append("EMAIL", correo);
            formData.append("RAZON_SOCIAL", razon);

            fetch("http://192.200.100.40:8002/INTERPRETE2/backend/reenviar_manual.php", {
                method: "POST",
                body: formData
            })
                .then(res => res.text())
                .then(resp => {
                    console.log("Respuesta del servidor:", resp);

                    if (resp.includes("Correo enviado")) {
                        mensajeEnvio.innerHTML = `<span class="success">✅ Correo enviado exitosamente.</span>`;
                    } else {
                        mensajeEnvio.innerHTML = `<span class="error">❌ Error al enviar: ${resp}</span>`;
                    }
                    // Limpiar campos
                    $('#selectCorreo').val('').trigger('change.select2');  // reset Select2
                    document.getElementById("archivoReenvio").value = "";    // limpiar input file

                    // Ocultar mensaje después de 6 segundos
                    setTimeout(() => {
                        mensajeEnvio.style.display = "none";
                    }, 3000);
                })
                .catch(err => {
                    console.error("Error al enviar:", err);
                    mensajeEnvio.innerHTML = `<span class="error">❌ Error al enviar: ${err}</span>`;
                    setTimeout(() => {
                        mensajeEnvio.style.display = "none";
                    }, 6000);
                });
        });
    } else {
        console.error("Botón con ID 'resend' no encontrado.");
    }
});

//--//------------------------------------------------------------------------------//----------------------------------
//-----------Buscar y actualizar datos de proveedores ----------------------------------------///----
$(document).ready(function () {

    // Realizar búsqueda del proveedor
    $('#buscarForm').submit(function (event) {
        event.preventDefault(); // Evitar el envío tradicional del formulario

        var nit = $('#nit').val(); // Obtener el NIT ingresado

        // Realizar la petición AJAX
        $.get("../backend/server4.php", { nit: nit }, function (data) {
            // Convertir la respuesta en objeto JSON
            const response = JSON.parse(data);

            if (response.exito) {
                // Llenar los campos del formulario con los datos del proveedor
                $('[name="NIT"]').val(response.cliente.NIT);
                $('[name="RAZON_SOCIAL"]').val(response.cliente.RAZON_SOCIAL);
                $('[name="EMAIL"]').val(response.cliente.EMAIL);

                // Poner el NIT original para actualizar
                $('[name="nit_original"]').val(response.cliente.NIT);
            } else {
                alert(response.mensaje); // Mostrar mensaje si no se encontró el proveedor
            }
        });
    });

    // Realizar actualización del proveedor
    $('#editarForm').submit(function (event) {
        event.preventDefault(); // Evitar el envío tradicional del formulario

        var formData = $(this).serialize(); // Obtener todos los datos del formulario

        // Enviar los datos de la actualización mediante AJAX
        $.ajax({
            url: '../backend/server4.php',
            type: 'POST',
            data: formData,
            success: function (response) {
                const res = JSON.parse(response); // Parsear la respuesta JSON

                // Mostrar el mensaje de éxito o error 
                if (res.exito) {
                    mostrarToast(res.mensaje, "exito");
                    $('#editarForm')[0].reset(); // limpiar campos
                } else {
                    mostrarToast(res.mensaje, "error");
                }

            },
            error: function () {
                $('#mensaje').html('<p><strong>Error al actualizar el proveedor.</strong></p>');
                $('#mensaje').css('color', 'red');
                $('#mensaje').show(); // Asegurarnos de que el mensaje se muestre
            }
        });
    });
});


function mostrarToast(mensaje, tipo = "exito") {
    const toast = $('#toast');
    toast.removeClass(); // Limpiar clases previas

    toast.addClass('toast show');
    toast.css('background-color', tipo === 'exito' ? '#28a745' : '#dc3545'); // verde o rojo
    toast.text(mensaje);


    setTimeout(() => {
        toast.removeClass('show');
    }, 3000);
}
//---------------------------------------------------------------------------------------