From 9d323bdb217b65a912464dca940db8b398ef53b6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 4 Jun 2024 14:38:09 +0200 Subject: [PATCH] refactor: refs #6555 create call fn & WIP: replace jquery --- js/index.js | 129 ++++++++++++++---------------- js/main.js | 225 ++++++++++++++++++++++++++-------------------------- 2 files changed, 170 insertions(+), 184 deletions(-) diff --git a/js/index.js b/js/index.js index 929e86d..34d0176 100644 --- a/js/index.js +++ b/js/index.js @@ -1,84 +1,73 @@ let pin = ""; +if ("addEventListener" in document) { + document.addEventListener("DOMContentLoaded", () => { + FastClick.attach(document.body); -$(document).ready(function () { - FastClick.attach(document.body); - setEvents(); -}); + const heartEl = document.querySelector("body > h1 > span"); + refreshDeviceLabel(); -function setEvents() { - const heartEl = document.querySelector('body > h1 > span'); - refreshDeviceLabel() + heartEl.addEventListener("click", () => { + Swal.fire({ + title: "Iniciar sesión", + html: ` + + + `, + confirmButtonText: "Login", + showCloseButton: true, + showCancelButton: false, + }).then(async (result) => { + if (result.isConfirmed) + signIn(document.querySelector("#user").value, document.querySelector("#pass").value, document.querySelector("#device").value); + }); + }); - heartEl.addEventListener('click', function() { - Swal.fire({ - title: 'Iniciar sesión', - html: - ` - - `, - confirmButtonText: 'Login', - showCloseButton: true, - showCancelButton: false, - }).then(async (result) => { - if(result.isConfirmed) { - const user = $('#user').val(); - const pass = $('#pass').val(); - const device = $('#device').val(); - signIn(user, pass, device); + $(".btnnum").on("click", function () { + pin += parseInt($(this).children().html()); + $("#txtPin").text(pin); + }); + + $(".btnCancel").on("click", function () { + pin = ""; + $("#txtPin").text("ID USUARIO"); + }); + + $(".btnOk").on("click", function () { + if (pin) { + login(); } }); - }); - - $(".btnnum").on("click", function () { - pin += parseInt($(this).children().html()); - $("#txtPin").text(pin); }); +} - $(".btnCancel").on("click", function () { +async function login() { + try { + const res = await call("WorkerTimeControls/login", { + method: "POST", + body: { pin }, + }); + const data = await res.json(); + localStorage.setItem("userData", JSON.stringify(data)); + window.location = "clockIn.html"; + } catch (e) { + document.querySelector("#txtPin").textContent = "ID USUARIO"; pin = ""; - $("#txtPin").text("ID USUARIO"); - }); - - $(".btnOk").on("click", function () { - if (pin) { - login(); - }; - }); + } } -function login() { - $.post({ - urlPath: 'WorkerTimeControls/login', - jsonData: {pin}, - processData: false, - success: function (data) { - localStorage.setItem("userData", JSON.stringify(data)); - window.location = "clockIn.html"; - }, - error: function() { - $("#txtPin").text("ID USUARIO"); - pin = ""; - } +async function signIn(user, password, device) { + const res = await call("vnUsers/sign-in", { + method: "POST", + body: { user, password }, }); + const data = await res.json(); + localStorage.setItem("token", data.token); + localStorage.setItem("ttl", data.ttl); + localStorage.setItem("user", user); + localStorage.setItem("device", device); + localStorage.setItem("created", Date.now()); + getTokenConfig(); + refreshDeviceLabel(); } -function signIn(user, password, device) { - $.post({ - urlPath: 'vnUsers/sign-in', - jsonData: {user, password}, - processData: false, - success: function (data) { - localStorage.setItem("token", data.token); - localStorage.setItem("ttl", data.ttl); - localStorage.setItem("user", user); - localStorage.setItem("device", device); - localStorage.setItem("created", Date.now()); - getTokenConfig(); - refreshDeviceLabel(); - }, - }) -} - -function refreshDeviceLabel() { - $("#deviceLabel").text(localStorage.getItem('device') ?? '') -} \ No newline at end of file +const refreshDeviceLabel = () => (document.querySelector("#deviceLabel").textContent = localStorage.getItem("device") ?? ""); diff --git a/js/main.js b/js/main.js index 1d4f89b..82636cd 100644 --- a/js/main.js +++ b/js/main.js @@ -1,130 +1,127 @@ -const renewPeriod = localStorage.getItem('renewPeriod'); +const renewPeriod = localStorage.getItem("renewPeriod"); let intervalId, isCheckingToken; +const txtConfirm = document.querySelector(".txtConfirm"); +const confirm = document.querySelector(".confirm"); function confirmReset() { - $(".confirm").removeClass('confirmKO'); - $(".txtConfirm").empty(); + confirm.classList.remove("confirmKO"); + confirm.style.display = "none"; + txtConfirm.textContent = ""; } -function printError(msg){ +// WIP: fadeIn / fadeOut +function printError(msg) { confirmReset(); - $(".txtConfirm").append(msg); - $(".confirm").addClass('confirmKO'); + const txtConfirm = document.querySelector(".txtConfirm"); + txtConfirm.textContent = msg; + const confirm = document.querySelector(".confirm"); + confirm.classList.add("confirmKO"); + confirm.style.display = "block"; + $(".confirm").fadeIn(200); - setTimeout(function() { + setTimeout(() => { $(".confirm").fadeOut(200); setTimeout(confirmReset, 200); }, 2300); } -function renewToken() { - $.post({ - urlPath: 'vnUsers/renewToken', - processData: false, - success: function (data) { - localStorage.setItem("token", data.id); - localStorage.setItem("ttl", data.ttl); - localStorage.setItem("created", Date.now()); - }, - }) +async function renewToken() { + const res = await call("AccessTokens/renewToken", {}); + + const data = await res.json(); + localStorage.setItem("ttl", data.ttl); + localStorage.setItem("created", Date.now()); } -function getTokenConfig() { - const filter = {fields: ['renewInterval', 'renewPeriod']}; - $.get({ - urlPath: 'AccessTokenConfigs/findOne', - jsonData: filter, - processData: false, - success: function (data) { - if (!data) return; - localStorage.setItem('renewPeriod', data.renewPeriod); - clearInterval(intervalId); - intervalId = setInterval(() => checkValidity(), data.renewInterval * 1000); - }, - }) -} - -function checkValidity() { - const created = +localStorage.getItem('created'); - const ttl = localStorage.getItem('ttl'); - - if (isCheckingToken || !created) return; - isCheckingToken = true; - - const renewPeriodInSeconds = Math.min(ttl, renewPeriod) * 1000; - const maxDate = created + renewPeriodInSeconds; - const now = new Date(); - - if (now.getTime() <= maxDate) return isCheckingToken = false; - - renewToken(); - isCheckingToken = false; -} - -$.ajaxPrefilter(function(xhr) { - const orgErrorHandler = xhr.error; - const token = localStorage.getItem('token') - - Object.assign(xhr, { - url: `/api/${xhr.urlPath}`, - headers: { - Authorization : token - }, - timeout: 2000, - contentType: 'application/json; charset=utf-8', - dataType: 'json', - processData: false, - data: JSON.stringify(xhr.jsonData), - error: function(xhr, textStatus, err) { - if (orgErrorHandler) { - try { - orgErrorHandler(xhr, textStatus, err); - } catch (e) { - err = e; - } - } - - if(xhr?.responseJSON?.error?.code == 'periodNotExceeded') return; - - switch (textStatus){ - case 'parsererror': - mensaje = 'Requested JSON parse failed'; - break; - case 'timeout': - mensaje = 'Time out error'; - break; - case 'abort': - mensaje = 'Ajax request aborted'; - break; - case 'error': - if (xhr?.responseJSON?.error?.name == 'UserError') { - mensaje = xhr.responseJSON.error.message; - break; - } - switch (xhr.status){ - case 0: - mensaje = 'Not connect: Verify Network'; - break; - case 504: - mensaje = 'No se ha podido conectar con Salix, consulta con informática'; - break; - case 555: - mensaje = JSON.parse(xhr.statusText).Message; - break; - default: - if (xhr.status >= 400 && xhr.status < 500) - mensaje = xhr.statusText; - else - mensaje = 'Ha ocurrido un error, consulta con informática'; - } - break; - default: - mensaje = 'Ha ocurrido un error, consulta con informática'; - } - printError(mensaje); - - } +async function getTokenConfig() { + const res = await call("AccessTokenConfigs/findOne", { + params: JSON.stringify({ + filter: { fields: ["renewInterval", "renewPeriod"] }, + }), }); -}); -if(renewPeriod) getTokenConfig(); \ No newline at end of file + const data = await res.json(); + if (!data) return; + + localStorage.setItem("renewPeriod", data.renewPeriod); + clearInterval(intervalId); + + intervalId = setInterval(() => { + const created = +localStorage.getItem("created"); + const ttl = localStorage.getItem("ttl"); + + if (isCheckingToken || !created) return; + isCheckingToken = true; + + const renewPeriodInSeconds = Math.min(ttl, renewPeriod) * 1000; + const maxDate = created + renewPeriodInSeconds; + + if (new Date().getTime() <= maxDate) return (isCheckingToken = false); + + renewToken(); + isCheckingToken = false; + }, data.renewInterval * 1000); +} + +/// WIP: MUST try thru it! +async function call(url, { method = "GET", body = {}, params = {} }) { + const controller = new AbortController(); + const { signal } = controller; + const timeoutId = setTimeout(() => controller.abort(), 2000); + let mensaje; + const opts = { + method, + headers: { + Authorization: localStorage.getItem("token"), + "Content-Type": "application/json; charset=utf-8", + }, + signal, + }; + + if (method === "GET") url += "?" + new URLSearchParams(params).toString(); + else if (method === "POST") opts.body = JSON.stringify(body); + + try { + const res = await fetch(`/api/${url}`, opts); + clearTimeout(timeoutId); + return res; + } catch (e) { + switch (e.name) { + case "SyntaxError": + mensaje = "Requested JSON parse failed"; + break; + case "TimeoutError": + mensaje = "Time out error"; + break; + case "AbortError": + mensaje = "Ajax request aborted"; + break; + case "UserError": + mensaje = e.message; + break; + case "error": + switch (e.code) { + case 0: + mensaje = "Not connect: Verify Network"; + break; + case 504: + mensaje = "No se ha podido conectar con Salix, consulta con informática"; + break; + case 555: + mensaje = e.message; + break; + case e.code >= 400 && e.code < 500: + mensaje = e.name; + break; + default: + mensaje = "Ha ocurrido un error, consulta con informática"; + } + break; + default: + mensaje = "Ha ocurrido un error, consulta con informática"; + } + printError(mensaje); + } +} + +if (renewPeriod) getTokenConfig();