refactor: refs #6555 create call fn & WIP: replace jquery
gitea/worker-time-control/pipeline/pr-test This commit looks good Details

This commit is contained in:
jorgep 2024-06-04 14:38:09 +02:00
parent 08830756d1
commit 9d323bdb21
2 changed files with 170 additions and 184 deletions

View File

@ -1,31 +1,24 @@
let pin = "";
$(document).ready(function () {
if ("addEventListener" in document) {
document.addEventListener("DOMContentLoaded", () => {
FastClick.attach(document.body);
setEvents();
});
function setEvents() {
const heartEl = document.querySelector('body > h1 > span');
refreshDeviceLabel()
const heartEl = document.querySelector("body > h1 > span");
refreshDeviceLabel();
heartEl.addEventListener('click', function() {
heartEl.addEventListener("click", () => {
Swal.fire({
title: 'Iniciar sesión',
html:
`<input id="device" class="swal2-input" type="text" placeholder="Dispositivo" value="${localStorage.getItem('device') ?? ''}">
<input id="user" class="swal2-input" type="text" placeholder="Usuario" value="${localStorage.getItem('user') ?? ''}">
title: "Iniciar sesión",
html: `
<input id="device" class="swal2-input" type="text" placeholder="Dispositivo" value="${localStorage.getItem("device") ?? ""}">
<input id="user" class="swal2-input" type="text" placeholder="Usuario" value="${localStorage.getItem("user") ?? ""}">
<input id="pass" class="swal2-input" type="password" placeholder="Contraseña">`,
confirmButtonText: 'Login',
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);
}
if (result.isConfirmed)
signIn(document.querySelector("#user").value, document.querySelector("#pass").value, document.querySelector("#device").value);
});
});
@ -42,32 +35,32 @@ function setEvents() {
$(".btnOk").on("click", function () {
if (pin) {
login();
};
}
});
});
}
function login() {
$.post({
urlPath: 'WorkerTimeControls/login',
jsonData: {pin},
processData: false,
success: function (data) {
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";
},
error: function() {
$("#txtPin").text("ID USUARIO");
} catch (e) {
document.querySelector("#txtPin").textContent = "ID USUARIO";
pin = "";
}
});
}
function signIn(user, password, device) {
$.post({
urlPath: 'vnUsers/sign-in',
jsonData: {user, password},
processData: false,
success: function (data) {
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);
@ -75,10 +68,6 @@ function signIn(user, password, device) {
localStorage.setItem("created", Date.now());
getTokenConfig();
refreshDeviceLabel();
},
})
}
function refreshDeviceLabel() {
$("#deviceLabel").text(localStorage.getItem('device') ?? '')
}
const refreshDeviceLabel = () => (document.querySelector("#deviceLabel").textContent = localStorage.getItem("device") ?? "");

View File

@ -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 = "";
}
// 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);
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) {
async function getTokenConfig() {
const res = await call("AccessTokenConfigs/findOne", {
params: JSON.stringify({
filter: { fields: ["renewInterval", "renewPeriod"] },
}),
});
const data = await res.json();
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');
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;
const now = new Date();
if (now.getTime() <= maxDate) return isCheckingToken = false;
if (new Date().getTime() <= maxDate) return (isCheckingToken = false);
renewToken();
isCheckingToken = false;
}, data.renewInterval * 1000);
}
$.ajaxPrefilter(function(xhr) {
const orgErrorHandler = xhr.error;
const token = localStorage.getItem('token')
Object.assign(xhr, {
url: `/api/${xhr.urlPath}`,
/// 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 : token
Authorization: localStorage.getItem("token"),
"Content-Type": "application/json; charset=utf-8",
},
timeout: 2000,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
data: JSON.stringify(xhr.jsonData),
error: function(xhr, textStatus, err) {
if (orgErrorHandler) {
signal,
};
if (method === "GET") url += "?" + new URLSearchParams(params).toString();
else if (method === "POST") opts.body = JSON.stringify(body);
try {
orgErrorHandler(xhr, textStatus, err);
const res = await fetch(`/api/${url}`, opts);
clearTimeout(timeoutId);
return res;
} catch (e) {
err = e;
}
}
if(xhr?.responseJSON?.error?.code == 'periodNotExceeded') return;
switch (textStatus){
case 'parsererror':
mensaje = 'Requested JSON parse failed';
switch (e.name) {
case "SyntaxError":
mensaje = "Requested JSON parse failed";
break;
case 'timeout':
mensaje = 'Time out error';
case "TimeoutError":
mensaje = "Time out error";
break;
case 'abort':
mensaje = 'Ajax request aborted';
case "AbortError":
mensaje = "Ajax request aborted";
break;
case 'error':
if (xhr?.responseJSON?.error?.name == 'UserError') {
mensaje = xhr.responseJSON.error.message;
case "UserError":
mensaje = e.message;
break;
}
switch (xhr.status){
case "error":
switch (e.code) {
case 0:
mensaje = 'Not connect: Verify Network';
mensaje = "Not connect: Verify Network";
break;
case 504:
mensaje = 'No se ha podido conectar con Salix, consulta con informática';
mensaje = "No se ha podido conectar con Salix, consulta con informática";
break;
case 555:
mensaje = JSON.parse(xhr.statusText).Message;
mensaje = e.message;
break;
case e.code >= 400 && e.code < 500:
mensaje = e.name;
break;
default:
if (xhr.status >= 400 && xhr.status < 500)
mensaje = xhr.statusText;
else
mensaje = 'Ha ocurrido un error, consulta con informática';
mensaje = "Ha ocurrido un error, consulta con informática";
}
break;
default:
mensaje = 'Ha ocurrido un error, consulta con informática';
mensaje = "Ha ocurrido un error, consulta con informática";
}
printError(mensaje);
}
});
});
}
if (renewPeriod) getTokenConfig();