HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/alq-cali.bikenow.co/public/js/paymentGateway.js
/**
 * metodos para administrar pasarelas de pagos
 *
 */

function saveImage(id) {
    var fImage = document.getElementById("image");
    fImage = fImage.files[0];
    if (fImage) {
        var formData = new FormData();
        formData.append("id", id);
        formData.append("image", fImage);

        $.ajax({
            type: "POST",
            dataType: "json",
            processData: false,
            contentType: false,
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            },
            data: formData,
            url: "/paymentGateway/saveImage",
            success: function (r) {
                if (r.r) {
                    swal(r.m, {
                        icon: "success",
                        buttons: {
                            Ok: true,
                        },
                    }).then((val) => {
                        if (val == "Ok") {
                            $(location).attr("href", "/paymentGateway");
                        }
                    });
                } else {
                    swal("Error", "¡Error al cargar imagen de la pasarela!", "error");
                    $("#btn-create-category").prop("disabled", false);
                }
            },
            error: function (e) {
                swal("Error", e.responseJSON.m ? e.responseJSON.m : "¡Error al cargar imagen de la pasarela!", "error");
                $("#btn-create-category").prop("disabled", false);
            },
        });
    }
}

function buildInfoForApi(form) {
    var values = {};
    $.each($(form).serializeArray(), function (i, field) {
        values[field.name] = field.value;
    });

    delete values._token;
    delete values._method;

    return values;
}

async function create() {
    try {
        $("#form_create").validator("update");
        $("#form_create").validator("update").on("submit", async function (e) {
            if (!e.isDefaultPrevented()) {
                e.preventDefault();

                let data = buildInfoForApi('#form_create');
                data.valid_payments = getMultiselectData('#valid_payments').toString();
                var img = document.getElementById("image");
                var img = img.files[0];
                if (!img) {
                    swal("Advertencia", "¡Debes seleccionar una imagen u/o logo para la pasarela!", "warning");
                    $('#form_create input[name="image"]')[0].focus();
                    return;
                } else if (!data.valid_payments) {
                    swal("Advertencia", "¡Debes seleccionar al menos una disponibilidad de pago para la pasarela!", "warning");
                    $('#form_create select[name="valid_payments"]')[0].focus();
                    return;
                }

                swal(Lang.get("messagesClient.paymentGateway.tag_1"), {
                    buttons: {
                        cancel: "No",
                        Ok: true,
                    },
                }).then(async (val) => {
                    if (val == "Ok") {
                        let enable_payment_gateway_authorizing_email = localStorage.getItem('enable_payment_gateway_authorizing_email') || $('input[name="_enable_payment_gateway_authorizing_email"]').val();
                        if (enable_payment_gateway_authorizing_email === '1') {
                            let payment_gateway_authorizing_email = localStorage.getItem('payment_gateway_authorizing_email') || $('input[name="_payment_gateway_authorizing_email"]').val();

                            // 1. Enviar OTP
                            const otpFormData = new FormData();
                            otpFormData.append('email', payment_gateway_authorizing_email || '');

                            const otpResponse = await fetch("/api/email-validation/send-code", {
                                method: "POST",
                                headers: {
                                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                                    "Accept": "application/json"
                                },
                                body: otpFormData
                            });

                            if (!otpResponse.ok) {
                                const errorData = await otpResponse.json();
                                throw new Error(errorData.message || "No se pudo generar el código de validación.");
                            }

                            const otpData = await otpResponse.json();
                            if (otpData.status !== 'success') {
                                throw new Error(otpData.message || "Error al generar código.");
                            }

                            // 2. Esperar validación OTP (esta función debe abrir el modal y resolver una promesa cuando el usuario confirme)
                            await waitForOtpVerification(payment_gateway_authorizing_email);
                        }

                        $("#btn-create").addClass("displayNone");
                        $("#spinnerButton").removeClass("displayNone");
                        $.ajax({
                            url: "/paymentGateway",
                            type: "POST",
                            contentType: "application/json",
                            headers: {
                                "X-CSRF-TOKEN": $(
                                    'meta[name="csrf-token"]'
                                ).attr("content"),
                                "Content-Type": "application/json",
                            },
                            data: JSON.stringify(data),
                            success: function (r) {
                                if (r.r) {
                                    onSuccesSave(r);
                                } else {
                                    swal("Error", r.m, "error");
                                    $("#btn-create").removeClass("displayNone");
                                    $("#spinnerButton").addClass("displayNone");
                                }
                            },
                            error: function (e) {
                                swal("Error", "¡Hubo un Error al crear!", "error");
                                $("#btn-create").removeClass("displayNone");
                                $("#spinnerButton").addClass("displayNone");
                            },
                        });
                    } else {
                        $("#btn-create").removeClass("displayNone");
                        $("#spinnerButton").addClass("displayNone");
                    }
                });
            }
        });
    } catch (error) {
        console.error(error);
        swal("Error", error.message || "Error de conexión. Intente de nuevo.", "error");
    }
}

function clickEdit(value) {
    $(location).attr("href", "/paymentGateway/" + value + "/edit");
}

async function edit() {
    try {
        $("#form_edit").validator("update");
        $("#form_edit").validator("update").on("submit", async function (e) {
            if (!e.isDefaultPrevented()) {
                e.preventDefault();

                var id = $("#form_edit").attr("paymentGateway_id");
                let data = buildInfoForApi('#form_edit');
                data.valid_payments = getMultiselectData('#valid_payments').toString();
                if (!data.valid_payments) {
                    swal("Advertencia", "¡Debes seleccionar al menos una disponibilidad de pago para la pasarela!", "warning");
                    $('#form_edit select[name="valid_payments"]')[0].focus();
                    return;
                }

                swal(Lang.get("messagesClient.paymentGateway.tag_2"), {
                    buttons: {
                        cancel: "No",
                        Ok: true,
                    },
                }).then(async (val) => {
                    if (val == "Ok") {
                        let enable_payment_gateway_authorizing_email = localStorage.getItem('enable_payment_gateway_authorizing_email') || $('input[name="_enable_payment_gateway_authorizing_email"]').val();
                        if (enable_payment_gateway_authorizing_email === '1') {
                            let payment_gateway_authorizing_email = localStorage.getItem('payment_gateway_authorizing_email') || $('input[name="_payment_gateway_authorizing_email"]').val();

                            // 1. Enviar OTP
                            const otpFormData = new FormData();
                            otpFormData.append('email', payment_gateway_authorizing_email || '');

                            const otpResponse = await fetch("/api/email-validation/send-code", {
                                method: "POST",
                                headers: {
                                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                                    "Accept": "application/json"
                                },
                                body: otpFormData
                            });

                            if (!otpResponse.ok) {
                                const errorData = await otpResponse.json();
                                throw new Error(errorData.message || "No se pudo generar el código de validación.");
                            }

                            const otpData = await otpResponse.json();
                            if (otpData.status !== 'success') {
                                throw new Error(otpData.message || "Error al generar código.");
                            }

                            // 2. Esperar validación OTP (esta función debe abrir el modal y resolver una promesa cuando el usuario confirme)
                            await waitForOtpVerification(payment_gateway_authorizing_email);
                        }

                        $("#btn-edit").addClass("displayNone");
                        $("#spinnerButton").removeClass("displayNone");
                        $.ajax({
                            url: "/paymentGateway/" + id,
                            type: "PUT",
                            contentType: "application/json",
                            headers: {
                                "X-CSRF-TOKEN": $(
                                    'meta[name="csrf-token"]'
                                ).attr("content"),
                                "Content-Type": "application/json",
                            },
                            data: JSON.stringify(data),
                            success: function (r) {
                                if (r.r) {
                                    onSuccesSave(r);
                                } else {
                                    swal("Error", r.m, "error");
                                    $("#btn-edit").removeClass("displayNone");
                                    $("#spinnerButton").addClass("displayNone");
                                }
                            },
                            error: function (e) {
                                swal("Error", "¡Hubo un Error al actualizar!", "error");
                                $("#btn-edit").removeClass("displayNone");
                                $("#spinnerButton").addClass("displayNone");
                            },
                        });
                    } else {
                        $("#btn-edit").removeClass("displayNone");
                        $("#spinnerButton").addClass("displayNone");
                    }
                });
            }
        });
    } catch (error) {
        console.error(error);
        swal("Error", error.message || "Error de conexión. Intente de nuevo.", "error");
    }
}

function setPageTable() {
    $(location).attr("href", "/paymentGateway");
}

async function chk(value) {
    let enable_payment_gateway_authorizing_email = $('input[name="_enable_payment_gateway_authorizing_email"]').val();

    try {
        if (enable_payment_gateway_authorizing_email === '1') {
            let payment_gateway_authorizing_email = $('input[name="_payment_gateway_authorizing_email"]').val();

            // 1. Enviar OTP
            const otpFormData = new FormData();
            otpFormData.append('email', payment_gateway_authorizing_email || '');

            const otpResponse = await fetch("/api/email-validation/send-code", {
                method: "POST",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                    "Accept": "application/json"
                },
                body: otpFormData
            });

            if (!otpResponse.ok) {
                const errorData = await otpResponse.json();
                throw new Error(errorData.message || "No se pudo generar el código de validación.");
            }

            const otpData = await otpResponse.json();
            if (otpData.status !== 'success') {
                throw new Error(otpData.message || "Error al generar código.");
            }

            // 2. Esperar validación OTP (esta función debe abrir el modal y resolver una promesa cuando el usuario confirme)
            await waitForOtpVerification(payment_gateway_authorizing_email);
        }

        // 3. Si OTP válido, proceder con el cambio de estado
        let state = $("#Checkactive" + value).is(":checked") ? 1 : 0;
        let info = { id: value, state: state };

        $.ajax({
            url: "/paymentGateway/active",
            type: "POST",
            contentType: "application/json",
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                "Content-Type": "application/json",
            },
            data: JSON.stringify(info),
            success: function (r) {
                if (r.r) {
                    onSuccesSave(r);
                } else {
                    swal("Error", r.m, "error");
                }
            },
            error: function (e) {
                swal("Error", Lang.get("messagesClient.paymentGateway.error_update_active"), "error");
            },
        });
    } catch (error) {
        console.error(error);
        swal("Error", error.message || "Error de conexión. Intente de nuevo.", "error");
    }
}

async function chkIsProductive(value) {
    let enable_payment_gateway_authorizing_email = $('input[name="_enable_payment_gateway_authorizing_email"]').val();

    try {
        if (enable_payment_gateway_authorizing_email === '1') {
            let payment_gateway_authorizing_email = $('input[name="_payment_gateway_authorizing_email"]').val();

            // 1. Enviar OTP
            const otpFormData = new FormData();
            otpFormData.append('email', payment_gateway_authorizing_email || '');

            const otpResponse = await fetch("/api/email-validation/send-code", {
                method: "POST",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                    "Accept": "application/json"
                },
                body: otpFormData
            });

            if (!otpResponse.ok) {
                const errorData = await otpResponse.json();
                throw new Error(errorData.message || "No se pudo generar el código de validación.");
            }

            const otpData = await otpResponse.json();
            if (otpData.status !== 'success') {
                throw new Error(otpData.message || "Error al generar código.");
            }

            // 2. Esperar validación OTP (esta función debe abrir el modal y resolver una promesa cuando el usuario confirme)
            await waitForOtpVerification(payment_gateway_authorizing_email);
        }

        // 3. Si OTP válido, proceder con el cambio de estado
        let state = $("#chkIsProductive" + value).is(":checked") ? 1 : 0;
        let info = { id: value, state: state };

        $.ajax({
            url: "/paymentGateway/isProductive",
            type: "POST",
            contentType: "application/json",
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                "Content-Type": "application/json",
            },
            data: JSON.stringify(info),
            success: function (r) {
                if (r.r) {
                    onSuccesSave(r);
                } else {
                    swal("Error", r.m, "error");
                }
            },
            error: function (e) {
                swal("Error", Lang.get("messagesClient.paymentGateway.error_update_active"), "error");
            },
        });
    } catch (error) {
        console.error(error);
        swal("Error", error.message || "Error de conexión. Intente de nuevo.", "error");
    }
}

async function clickDelete(value) {
    try {
        swal(Lang.get("messagesClient.paymentGateway.tag_6"), {
            buttons: {
                cancel: "No",
                Ok: true,
            },
        }).then(async (val) => {
            if (val == "Ok") {
                let enable_payment_gateway_authorizing_email = $('input[name="_enable_payment_gateway_authorizing_email"]').val();
                if (enable_payment_gateway_authorizing_email === '1') {
                    let payment_gateway_authorizing_email = $('input[name="_payment_gateway_authorizing_email"]').val();

                    // 1. Enviar OTP
                    const otpFormData = new FormData();
                    otpFormData.append('email', payment_gateway_authorizing_email || '');

                    const otpResponse = await fetch("/api/email-validation/send-code", {
                        method: "POST",
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                            "Accept": "application/json"
                        },
                        body: otpFormData
                    });

                    if (!otpResponse.ok) {
                        const errorData = await otpResponse.json();
                        throw new Error(errorData.message || "No se pudo generar el código de validación.");
                    }

                    const otpData = await otpResponse.json();
                    if (otpData.status !== 'success') {
                        throw new Error(otpData.message || "Error al generar código.");
                    }

                    // 2. Esperar validación OTP (esta función debe abrir el modal y resolver una promesa cuando el usuario confirme)
                    await waitForOtpVerification(payment_gateway_authorizing_email);
                }

                var info = {
                    _method: "DELETE",
                };

                $.ajax({
                    url: "/paymentGateway/" + value,
                    type: "POST",
                    contentType: "application/json",
                    headers: {
                        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                            "content"
                        ),
                        "Content-Type": "application/json",
                    },
                    data: JSON.stringify(info),
                    success: function (r) {
                        if (r.r) {
                            onSuccesSave(r);
                        } else {
                            swal("Error", r.m, "error");
                        }
                    },
                    error: function (e) {
                        swal("Error", Lang.get("messagesClient.paymentGateway.error_delete"), "error");
                    },
                });
            }
        });
    } catch (error) {
        console.error(error);
        swal("Error", error.message || "Error de conexión. Intente de nuevo.", "error");
    }
}

function onSuccesSave(response) {
    var img = document.getElementById("image");
    if (img && img.files) {
        img = img.files[0];
    }

    if (img != null) {
        saveImage(response.data);
    } else {
        swal(response.m, {
            icon: "success",
            buttons: {
                Ok: true,
            },
        }).then((val) => {
            if (val == "Ok") {
                $(location).attr("href", "/paymentGateway");
            }
        });
    }
}

function waitForOtpVerification(email) {
    return new Promise((resolve, reject) => {
        const modal = document.getElementById('otpModal');
        const input = document.getElementById('otpInput');
        const errorDiv = document.getElementById('otpError');
        const button = document.getElementById('verifyOtpBtn');
        const closeBtn = document.getElementById('closeOtpModal');

        // Mostrar modal
        modal.style.display = 'flex';
        input.value = '';
        errorDiv.textContent = '';
        button.disabled = true;

        input.focus();

        // Cerrar modal
        closeBtn.onclick = () => {
            modal.style.display = 'none';
            reject(new Error("Verificación cancelada."));
        };

        // Validar cantidad de dígitos
        input.addEventListener('input', () => {
            button.disabled = input.value.trim().length !== 6;
        });

        button.onclick = async () => {
            const code = input.value.trim();

            if (code.length !== 6) {
                errorDiv.textContent = "Debes ingresar 6 dígitos.";
                return;
            }

            errorDiv.textContent = "Verificando...";
            button.disabled = true;

            try {
                const response = await fetch("/api/email-validation/verify-code", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                    },
                    body: JSON.stringify({
                        code,
                        email
                    })
                });

                const data = await response.json();

                if (!response.ok || data.status !== 'success') {
                    errorDiv.textContent = data.message || "Código de validación inválido.";
                    button.disabled = false;
                    return;
                }

                modal.style.display = 'none';
                resolve(); // Continuar con la acción

            } catch (err) {
                errorDiv.textContent = "Error de conexión. Intenta de nuevo.";
                button.disabled = false;
            }
        };
    });
}

async function resendCode() {
    const input = document.getElementById('otpInput');
    const errorDiv = document.getElementById('otpError');
    const email = document.querySelector('input[name="_payment_gateway_authorizing_email"]').value;

    if (!email) {
        errorDiv.textContent = "No se puede reenviar el código porque falta el correo.";
        return;
    }

    errorDiv.textContent = "Enviando nuevo código...";
    try {
        const response = await fetch("/api/email-validation/send-code", {
            method: "POST",
            headers: {
                "X-CSRF-TOKEN": document.querySelector('input[name="_token"]').value
            },
            body: new URLSearchParams({
                email
            })
        });

        const data = await response.json();

        if (!response.ok || data.status !== 'success') {
            errorDiv.textContent = data.message || "No se pudo reenviar el código.";
            return;
        }

        errorDiv.textContent = "Se envió un nuevo código a tu correo.";
        input.value = '';
        document.getElementById('verifyOtpBtn').disabled = true;
        input.focus();
    } catch (err) {
        errorDiv.textContent = "Error al reenviar el código.";
    }
}