#6555 refactor to js #28
|
@ -11,7 +11,6 @@ and open the template in the editor.
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link href="css/style.css" rel="stylesheet" type="text/css"/>
|
||||
<link rel="icon" type="image/png" href="img/favicon.ico">
|
||||
<script src="node_modules/jquery/dist/jquery.min.js" type="text/javascript"></script>
|
||||
<script src="node_modules/fastclick/lib/fastclick.js" type="text/javascript"></script>
|
||||
</head>
|
||||
<body class="pinLogin">
|
||||
|
@ -36,12 +35,12 @@ and open the template in the editor.
|
|||
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<footer>
|
||||
<div class="in">Inicio jornada</div>
|
||||
<div class="inMiddle">Inicio descanso</div>
|
||||
<div class="outMiddle">Fin descanso</div>
|
||||
<div class="out">Fin jornada</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<div class="confirm">
|
||||
<div class="contConfirm">
|
||||
|
|
|
@ -193,17 +193,15 @@ h3 {
|
|||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
.footer {
|
||||
display: none;
|
||||
footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
height: 100px;
|
||||
height: 115px;
|
||||
text-align: center;
|
||||
animation: fadeIn 0.2s ease-in-out;
|
||||
}
|
||||
.footer {
|
||||
animation: faceIn 0.2s ease-in-out;
|
||||
}
|
||||
|
||||
.in, .inMiddle {
|
||||
display: inline;
|
||||
position: static;
|
||||
|
@ -342,7 +340,7 @@ header {
|
|||
opacity: 1;
|
||||
}
|
||||
.confirm {
|
||||
display: none;
|
||||
visibility: hidden;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
|
@ -371,6 +369,14 @@ header {
|
|||
font-size: 2.5em;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.fade-in {
|
||||
visibility: visible;
|
||||
animation: fadeIn 0.2s ease-in-out forwards;
|
||||
}
|
||||
.fade-out {
|
||||
visibility: hidden;
|
||||
animation: fadeOut 0.2s ease-in-out forwards;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
0% {
|
||||
|
@ -382,7 +388,7 @@ header {
|
|||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes faceIn {
|
||||
@keyframes fadeIn {
|
||||
0% {
|
||||
opacity: 0;
|
||||
}
|
||||
|
@ -390,6 +396,14 @@ header {
|
|||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes fadeOut {
|
||||
0% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Poppins';
|
||||
|
|
|
@ -11,7 +11,6 @@ and open the template in the editor.
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link href="css/style.css" rel="stylesheet" type="text/css"/>
|
||||
<link rel="icon" type="image/png" href="img/favicon.ico">
|
||||
<script src="node_modules/jquery/dist/jquery.min.js" type="text/javascript"></script>
|
||||
<script src="node_modules/fastclick/lib/fastclick.js" type="text/javascript"></script>
|
||||
</head>
|
||||
<body class="pinLogin">
|
||||
|
@ -80,7 +79,7 @@ and open the template in the editor.
|
|||
</div>
|
||||
</div>
|
||||
<h1>
|
||||
developed by Verdnatura with<span class="heart"></span>
|
||||
powered by Verdnatura with<span class="heart"></span>
|
||||
</h1>
|
||||
<h2 class="device">
|
||||
<p id="deviceLabel"></p>
|
||||
|
|
291
js/clockIn.js
291
js/clockIn.js
|
@ -1,237 +1,142 @@
|
|||
let userData = "";
|
||||
const footer = document.querySelector("footer");
|
||||
const txtName = document.querySelector("#txtNombre");
|
||||
const inBtn = document.querySelector(".in");
|
||||
const inMiddleBtn = document.querySelector(".inMiddle");
|
||||
const outMiddleBtn = document.querySelector(".outMiddle");
|
||||
const outBtn = document.querySelector(".out");
|
||||
const timetableList = document.querySelector(".listHorario");
|
||||
const weekDays = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
|
||||
|
||||
$(document).ready(function () {
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
userData = JSON.parse(localStorage.getItem("userData"));
|
||||
FastClick.attach(document.body);
|
||||
setView();
|
||||
setEvents();
|
||||
});
|
||||
|
||||
function setEvents() {
|
||||
document.querySelector(".btnSalir").addEventListener("click", close);
|
||||
|
||||
$(".btnSalir").on("click", function () {
|
||||
cerrar();
|
||||
});
|
||||
inBtn.addEventListener("click", () => clockIn("in"));
|
||||
inMiddleBtn.addEventListener("click", () => clockIn("middle"));
|
||||
outMiddleBtn.addEventListener("click", () => clockIn("middle"));
|
||||
outBtn.addEventListener("click", () => clockIn("out"));
|
||||
|
||||
$(".in").on("click", function () {
|
||||
fichar('in');
|
||||
});
|
||||
|
||||
$(".inMiddle").on("click", function () {
|
||||
fichar('middle');
|
||||
});
|
||||
|
||||
$(".outMiddle").on("click", function () {
|
||||
fichar('middle');
|
||||
});
|
||||
|
||||
$(".out").on("click", function () {
|
||||
fichar('out');
|
||||
});
|
||||
|
||||
setTimeout(function () {
|
||||
cerrar();
|
||||
}, 5000);
|
||||
setTimeout(close, 5000);
|
||||
}
|
||||
|
||||
function setView() {
|
||||
$(".footer").hide();
|
||||
$("#txtNombre").text(userData["name"] + " " + userData["surname"]);
|
||||
getInfo();
|
||||
$("." + userData["button1"]).show();
|
||||
$("." + userData["button2"]).show();
|
||||
}
|
||||
|
||||
function fichar(direction) {
|
||||
const data = {
|
||||
workerFk: userData['userFk'],
|
||||
async function clockIn(direction) {
|
||||
let timeout = 1000;
|
||||
const data = await call("WorkerTimeControls/clockIn", {
|
||||
method: "POST",
|
||||
body: {
|
||||
workerFk: userData["userFk"],
|
||||
direction,
|
||||
device: localStorage.getItem("device")
|
||||
device: localStorage.getItem("device"),
|
||||
},
|
||||
});
|
||||
|
||||
if (data.error) {
|
||||
let msg = "";
|
||||
for (const val of data) if (val.error) msg += `${val.error}\n`;
|
||||
printError(msg);
|
||||
} else {
|
||||
document.querySelector(".confirm").classList.add("fade-in");
|
||||
txtConfirm.textContent = "Fichada registrada correctamente";
|
||||
timeout = 2000;
|
||||
}
|
||||
|
||||
$.post({
|
||||
urlPath: 'WorkerTimeControls/clockIn',
|
||||
jsonData: data,
|
||||
processData: false,
|
||||
success: function (msg) {
|
||||
if (msg.error){
|
||||
printErrores(msg);
|
||||
setTimeout(function () {
|
||||
cerrar();
|
||||
}, 2000);
|
||||
}else {
|
||||
$(".confirm").fadeIn(200);
|
||||
$(".txtConfirm").append('Fichada registrada correctamente');
|
||||
setTimeout(function () {
|
||||
cerrar();
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
});
|
||||
setTimeout(close, timeout);
|
||||
}
|
||||
|
||||
function setView() {
|
||||
$(".footer").hide();
|
||||
$(".in").hide();
|
||||
$(".inMiddle").hide();
|
||||
$(".outMiddle").hide();
|
||||
$(".out").hide();
|
||||
$("#txtNombre").text(userData["name"] + " " + userData["surname"]);
|
||||
footer.style.hidden = true;
|
||||
inBtn.style.display = "none";
|
||||
inMiddleBtn.style.display = "none";
|
||||
outMiddleBtn.style.display = "none";
|
||||
outBtn.style.display = "none";
|
||||
|
||||
txtName.textContent = `${userData.name} ${userData.surname}`;
|
||||
getInfo();
|
||||
if(userData["button1"] === null && userData["button2"] === null ) {
|
||||
printError ("Contacta con tu responsable")
|
||||
} else {
|
||||
$("." + userData["button1"]).show();
|
||||
$("." + userData["button2"]).show();
|
||||
}
|
||||
|
||||
if (userData.button1 === null && userData.button2 === null) return printError("Contacta con tu responsable");
|
||||
|
||||
document.querySelector(`.${userData.button1}`).style.display = "inline-block";
|
||||
if (userData.button2) document.querySelector(`.${userData.button2}`).style.display = "inline-block";
|
||||
}
|
||||
|
||||
function getInfo() {
|
||||
const queryString = $.param({ workerFk: userData['userFk'] });
|
||||
|
||||
$.get({
|
||||
urlPath: `WorkerTimeControls/getClockIn?${queryString}`,
|
||||
processData: false,
|
||||
success: function (data) {
|
||||
$('.footer').show();
|
||||
async function getInfo() {
|
||||
const data = await call("WorkerTimeControls/getClockIn", { params: { workerFk: userData["userFk"] } });
|
||||
footer.style.hidden = false;
|
||||
printTimetable(data);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function printTimetable(timetable) {
|
||||
const listWeekName = [
|
||||
'Domingo',
|
||||
'Lunes',
|
||||
'Martes',
|
||||
'Miércoles',
|
||||
'Jueves',
|
||||
'Viernes',
|
||||
'Sábado'
|
||||
];;
|
||||
let dated = new Date();
|
||||
const dated = new Date();
|
||||
dated.setDate(dated.getDate() - 6);
|
||||
|
||||
for (let i = 0; i < 6; i++) {
|
||||
$(".listHorario").append('<label>' + listWeekName[dated.getDay()] +'</label>');
|
||||
const table = document.createDocumentFragment();
|
||||
const totalEl = document.querySelector(".total");
|
||||
let totalHr = 0;
|
||||
|
||||
for (let day = 0; day < weekDays.length - 1; day++) {
|
||||
const label = createElement("label", { text: weekDays[dated.getDay()] });
|
||||
table.append(label);
|
||||
dated.setDate(dated.getDate() + 1);
|
||||
}
|
||||
$(".listHorario").append('<label class="hoy">HOY</label>');
|
||||
$(".listHorario").append('<li class="hrTop"></li>');
|
||||
|
||||
for (let i = 0; i < timetable.length; i++) {
|
||||
table.append(createElement("label", { text: "HOY", classes: ["hoy"] }), createElement("li", { classes: ["hrTop"] }));
|
||||
|
||||
$(".listHorario").append(
|
||||
'<li>' +
|
||||
'<div class="time ' + ifIsEmpty(timetable[i]["6daysAgo"]) + '">' +
|
||||
'<div>' +
|
||||
'<img src="' + ifIsEmptyImage(timetable[i]["6daysAgoDirection"]) + '" />' +
|
||||
'<p>' + ifIsEmptyText(timetable[i]["6daysAgo"]) + '</p>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="time ' + ifIsEmpty(timetable[i]["5daysAgo"]) + '">' +
|
||||
'<div>' +
|
||||
'<img src="' + ifIsEmptyImage(timetable[i]["5daysAgoDirection"]) + '" />' +
|
||||
'<p>' + ifIsEmptyText(timetable[i]["5daysAgo"]) + '</p>'+
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="time ' + ifIsEmpty(timetable[i]["4daysAgo"]) + '">' +
|
||||
'<div>' +
|
||||
'<img src="' + ifIsEmptyImage(timetable[i]["4daysAgoDirection"]) + '" />' +
|
||||
'<p>' + ifIsEmptyText(timetable[i]["4daysAgo"]) + '</p>'+
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="time ' + ifIsEmpty(timetable[i]["3daysAgo"]) + '">' +
|
||||
'<div>' +
|
||||
'<img src="' + ifIsEmptyImage(timetable[i]["3daysAgoDirection"]) + '" />' +
|
||||
'<p>' + ifIsEmptyText(timetable[i]["3daysAgo"]) + '</p>'+
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="time ' + ifIsEmpty(timetable[i]["2daysAgo"]) + '">' +
|
||||
'<div>' +
|
||||
'<img src="' + ifIsEmptyImage(timetable[i]["2daysAgoDirection"]) + '" />' +
|
||||
'<p>' + ifIsEmptyText(timetable[i]["2daysAgo"]) + '</p>'+
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="time ' + ifIsEmpty(timetable[i]["1daysAgo"]) + '">' +
|
||||
'<div>' +
|
||||
'<img src="' + ifIsEmptyImage(timetable[i]["1daysAgoDirection"]) + '" />' +
|
||||
'<p>' + ifIsEmptyText(timetable[i]["1daysAgo"]) + '</p>'+
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="time ' + ifIsEmpty(timetable[i]["0daysAgo"]) + '">' +
|
||||
'<div>' +
|
||||
'<img src="' + ifIsEmptyImage(timetable[i]["0daysAgoDirection"]) + '" />' +
|
||||
'<p>' + ifIsEmptyText(timetable[i]["0daysAgo"]) + '</p>'+
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'</li>'
|
||||
);
|
||||
}
|
||||
printTotalHours(timetable);
|
||||
}
|
||||
const liContent = createElement("li", {});
|
||||
const liTotals = createElement("li", {});
|
||||
timetable.forEach((row, index) => {
|
||||
for (let day = weekDays.length - 1; day >= 0; day--) {
|
||||
const img = createElement("img", { attrs: { src: isEmpty(row[`${day}daysAgoDirection`], "image") } });
|
||||
const p = createElement("p", { text: isEmpty(row[`${day}daysAgo`], "text") });
|
||||
|
||||
function printTotalHours(timetable) {
|
||||
if(timetable.length > 0) {
|
||||
const innerDiv = createElement("div", { childs: [img, p] });
|
||||
const outerDiv = createElement("div", { classes: ["time", isEmpty(row[`${day}daysAgo`])], childs: [innerDiv] });
|
||||
liContent.append(outerDiv);
|
||||
|
||||
$(".listHorario").append('<hr>');
|
||||
$(".listHorario").append('<li><div class="time">' + secondsToHm(ifIsEmptyText(timetable[0]["6daysAgoTotal"]))
|
||||
+ ' h</div><div class="time">' + secondsToHm(ifIsEmptyText(timetable[0]["5daysAgoTotal"]))
|
||||
+ ' h</div><div class="time">' + secondsToHm(ifIsEmptyText(timetable[0]["4daysAgoTotal"]))
|
||||
+ ' h</div><div class="time">' + secondsToHm(ifIsEmptyText(timetable[0]["3daysAgoTotal"]))
|
||||
+ ' h</div><div class="time">' + secondsToHm(ifIsEmptyText(timetable[0]["2daysAgoTotal"]))
|
||||
+ ' h</div><div class="time">' + secondsToHm(ifIsEmptyText(timetable[0]["1daysAgoTotal"]))
|
||||
+ ' h</div><div class="time">' + secondsToHm(ifIsEmptyText(timetable[0]["0daysAgoTotal"]))
|
||||
+ ' h</div></li>');
|
||||
|
||||
$(".total").text('Total: ' +
|
||||
secondsToHm(
|
||||
Number(timetable[0]["6daysAgoTotal"] == null) +
|
||||
Number(timetable[0]["5daysAgoTotal"]) +
|
||||
Number(timetable[0]["4daysAgoTotal"]) +
|
||||
Number(timetable[0]["3daysAgoTotal"]) +
|
||||
Number(timetable[0]["2daysAgoTotal"]) +
|
||||
Number(timetable[0]["1daysAgoTotal"]) +
|
||||
Number(timetable[0]["0daysAgoTotal"])
|
||||
) + ' h');
|
||||
} else{
|
||||
$(".total").text('Total: 0h');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function printErrores(errores) {
|
||||
let error = '';
|
||||
for (let i = 0; i < errores.length; i++) {
|
||||
if (errores[i].error) {
|
||||
error += errores[i].error + "<br>";
|
||||
if (index === 0) {
|
||||
const div = createElement("div", { classes: ["time"], text: secondsToHm(timetable[0][`${day}daysAgoTotal`]) });
|
||||
liTotals.append(div);
|
||||
totalHr += timetable[0][`${day}daysAgoTotal`] || 0;
|
||||
}
|
||||
}
|
||||
printError(error);
|
||||
table.append(liContent);
|
||||
if (index === timetable.length - 1) table.append(createElement("hr", {}), liTotals);
|
||||
});
|
||||
|
||||
totalEl.innerText = `Total: ${totalHr ? secondsToHm(totalHr) : 0} h`;
|
||||
timetableList.append(table);
|
||||
}
|
||||
|
||||
function ifIsEmpty(value) {
|
||||
return value.trim() ? "show" : "hide";
|
||||
}
|
||||
const isEmpty = (value, type) => {
|
||||
const val = value?.toString()?.trim();
|
||||
if (!type) return val ? "show" : "hide";
|
||||
if (type === "image") return val ? `img/${val}.svg` : "img/in.svg";
|
||||
if (type === "text") return val ? val : "00:00";
|
||||
};
|
||||
|
||||
function ifIsEmptyImage(value) {
|
||||
return value.trim() ? `img/${value}.svg` :"img/in.svg";
|
||||
}
|
||||
|
||||
function ifIsEmptyText(value) {
|
||||
return value.toString().trim() ? value : "00:00";
|
||||
}
|
||||
|
||||
function cerrar(){
|
||||
function close() {
|
||||
localStorage.removeItem("userData");
|
||||
setTimeout(function () {
|
||||
window.location='index.html';
|
||||
}, 200);
|
||||
setTimeout(() => (window.location = "index.html"), 200);
|
||||
}
|
||||
|
||||
function secondsToHm(seconds) {
|
||||
seconds = Number(seconds);
|
||||
seconds = +seconds;
|
||||
let hours = Math.floor(seconds / 3600);
|
||||
let minutes = Math.floor(seconds % 3600 / 60);
|
||||
return hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0');
|
||||
let minutes = Math.floor((seconds % 3600) / 60);
|
||||
return hours.toString().padStart(2, "0") + ":" + minutes.toString().padStart(2, "0");
|
||||
}
|
||||
|
||||
function createElement(tag, { classes = [], text, attrs = {}, childs = [] }) {
|
||||
const el = document.createElement(tag);
|
||||
if (classes) el.classList.add(...classes);
|
||||
if (text) el.textContent = text;
|
||||
for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, value);
|
||||
if (childs) el.append(...childs);
|
||||
|
||||
return el;
|
||||
}
|
84
js/index.js
84
js/index.js
|
@ -1,73 +1,63 @@
|
|||
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");
|
||||
const txtPin = document.querySelector("#txtPin");
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
$(".btnnum").on("click", function () {
|
||||
pin += parseInt($(this).children().html());
|
||||
$("#txtPin").text(pin);
|
||||
document.querySelectorAll(".btnnum").forEach((btn) => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
pin += +e.currentTarget.children[0].innerHTML;
|
||||
txtPin.textContent = pin;
|
||||
});
|
||||
});
|
||||
|
||||
$(".btnCancel").on("click", function () {
|
||||
document.querySelector(".btnCancel").addEventListener("click", () => {
|
||||
pin = "";
|
||||
$("#txtPin").text("ID USUARIO");
|
||||
txtPin.textContent = "ID USUARIO";
|
||||
});
|
||||
|
||||
$(".btnOk").on("click", function () {
|
||||
if (pin) {
|
||||
login();
|
||||
};
|
||||
document.querySelector(".btnOk").addEventListener("click", () => pin && login());
|
||||
});
|
||||
}
|
||||
|
||||
function login() {
|
||||
$.post({
|
||||
urlPath: 'WorkerTimeControls/login',
|
||||
jsonData: {pin},
|
||||
processData: false,
|
||||
success: function (data) {
|
||||
async function login() {
|
||||
try {
|
||||
const data = await call("WorkerTimeControls/login", {
|
||||
method: "POST",
|
||||
body: { pin },
|
||||
});
|
||||
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 data = await call("vnUsers/sign-in", {
|
||||
method: "POST",
|
||||
body: { user, password },
|
||||
});
|
||||
localStorage.setItem("token", data.token);
|
||||
localStorage.setItem("ttl", data.ttl);
|
||||
localStorage.setItem("user", user);
|
||||
|
@ -75,10 +65,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") ?? "");
|
||||
|
|
156
js/main.js
156
js/main.js
|
@ -1,130 +1,124 @@
|
|||
const renewPeriod = localStorage.getItem('renewPeriod');
|
||||
const renewPeriod = localStorage.getItem("renewPeriod");
|
||||
let intervalId, isCheckingToken;
|
||||
const txtConfirm = document.querySelector(".txtConfirm");
|
||||
const confirmBtn = document.querySelector(".confirm");
|
||||
|
||||
function confirmReset() {
|
||||
$(".confirm").removeClass('confirmKO');
|
||||
$(".txtConfirm").empty();
|
||||
confirmBtn.classList.remove("confirmKO", "fade-in", "fade-out");
|
||||
confirmBtn.style.hidden = true;
|
||||
txtConfirm.textContent = "";
|
||||
}
|
||||
|
||||
function printError(msg){
|
||||
function printError(msg) {
|
||||
confirmReset();
|
||||
$(".txtConfirm").append(msg);
|
||||
$(".confirm").addClass('confirmKO');
|
||||
$(".confirm").fadeIn(200);
|
||||
setTimeout(function() {
|
||||
$(".confirm").fadeOut(200);
|
||||
const txtConfirm = document.querySelector(".txtConfirm");
|
||||
txtConfirm.textContent = msg;
|
||||
confirmBtn.classList.add("confirmKO");
|
||||
confirmBtn.style.hidden = false;
|
||||
|
||||
confirmBtn.classList.add("fade-in");
|
||||
setTimeout(() => {
|
||||
confirmBtn.classList.add("fade-out");
|
||||
setTimeout(confirmReset, 200);
|
||||
}, 2300);
|
||||
}
|
||||
|
||||
function renewToken() {
|
||||
$.post({
|
||||
urlPath: 'vnUsers/renewToken',
|
||||
processData: false,
|
||||
success: function (data) {
|
||||
localStorage.setItem("token", data.id);
|
||||
async function renewToken() {
|
||||
const data = await call("vnUsers/renewToken", { method: "POST" });
|
||||
|
||||
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 data = await call("AccessTokenConfigs/findOne", {
|
||||
params: { filter: { fields: ["renewInterval", "renewPeriod"] } },
|
||||
});
|
||||
|
||||
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}`,
|
||||
async function call(url, { method = "GET", body = {}, params = {} }) {
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const timeoutId = setTimeout(() => controller.abort(), 2000);
|
||||
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") {
|
||||
const searchParams = new URLSearchParams();
|
||||
for (let [key, value] of Object.entries(params)) {
|
||||
searchParams.append(key, typeof value === "object" ? JSON.stringify(value) : value);
|
||||
}
|
||||
url += "?" + searchParams.toString();
|
||||
} else if (method === "POST") opts.body = JSON.stringify(body);
|
||||
|
||||
try {
|
||||
orgErrorHandler(xhr, textStatus, err);
|
||||
const res = await fetch(`/api/${url}`, opts);
|
||||
const data = await res.json();
|
||||
|
||||
if (res.ok) return data;
|
||||
clearTimeout(timeoutId);
|
||||
throw data.error;
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
}
|
||||
let mensaje = "Ha ocurrido un error, consulta con informática";
|
||||
|
||||
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){
|
||||
default:
|
||||
switch (e.statusCode) {
|
||||
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 = "Error 555";
|
||||
break;
|
||||
default:
|
||||
if (xhr.status >= 400 && xhr.status < 500)
|
||||
mensaje = xhr.statusText;
|
||||
else
|
||||
mensaje = 'Ha ocurrido un error, consulta con informática';
|
||||
if (e.statusCode >= 400 && e.statusCode < 500) mensaje = e.message;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
mensaje = 'Ha ocurrido un error, consulta con informática';
|
||||
}
|
||||
printError(mensaje);
|
||||
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if(renewPeriod) getTokenConfig();
|
||||
if (renewPeriod) getTokenConfig();
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -18,11 +18,10 @@
|
|||
"dependencies": {
|
||||
"dotenv": "^16.3.1",
|
||||
"fastclick": "^1.0.6",
|
||||
"jquery": "^3.7.0",
|
||||
"sweetalert2": "11.10.1"
|
||||
"sweetalert2": "^11.6.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"express": "^4.18.2",
|
||||
"express": "^4.19.2",
|
||||
"http-proxy-middleware": "^2.0.6"
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue