';
});
htmlM += '';
$(".sidebarViewMenu").html(htmlM);
}
/**
* Displays the menu based on the provided data.
*
* @param {string} data - The JSON data containing the menu information.
*/
function showMenu(data) {
menuDataController = JSON.parse(data);
let htmlMenu = '
' +
'
' +
$("#userNameInternalL").val() + '
' +
'
Cambiar sede
' +
'
Cerrar sesión
';
htmlMenu += '';
htmlMenu += '';
$(".sidebarView").html(htmlMenu);
drawMenu(menuDataController);
$("#searchInputMenu").on('input', function (e) {
if (e.target.value.trim() != "") {
drawMenu(filterDataController(e.target.value));
$('.sidebarViewMenu .btn.menu-group').each(function () {
$($(this)[0].dataset.bsTarget).addClass('show');
});
} else {
$('.sidebarViewMenu .btn.menu-group').each(function () {
$($(this)[0].dataset.bsTarget).removeClass('show');
});
}
});
$("#searchInputMenu").on("keyup", function (event) {
const hrefMenu = $('.menu-item').first()?.attr('href');
if (event.key === 'Enter' && event.target.value.trim() != "" && hrefMenu) {
if (event.ctrlKey)
window.open(hrefMenu, '_blank');
else
window.location.href = hrefMenu;
}
if (event.key === 'Backspace' && $("#searchInputMenu").val().trim() == "") {
drawMenu(menuDataController);
}
});
$("#searchInputMenu").on('focus', function () {
this.select();
});
}
/**
* Filters the menu data based on the provided search term.
*
* @param {string} searchTerm - The search term to filter the menu data.
* @returns {Array} - The filtered menu data.
*/
function filterDataController(searchTerm) {
let lowerCaseSearchTerm = normalizeString(searchTerm);
return menuDataController.map(x => {
let filteredItems = x.items.filter(y => normalizeString(y.text).includes(lowerCaseSearchTerm));
if (filteredItems.length > 0) {
return {
...x,
items: filteredItems
};
}
return null;
}).filter(x => x !== null);
}
/**
* Normalizes a string by removing leading and trailing whitespace, converting it to lowercase,
* and replacing any diacritical marks with their base characters.
*
* @param {string} str - The string to normalize.
* @returns {string} - The normalized string.
*/
function normalizeString(str) {
return str.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
/**
* Loads the menu data from the server and displays it on the page.
*/
function loadMenu() {
var prefixUrl = window.location.protocol + '//' + window.location.host;
var pagePath = window.location.protocol + '//' + window.location.host + "/GeneralArea/Internal/";
LoadStart();
$.ajax({
type: 'POST',
url: pagePath + "getMenu",
dataType: 'json',
data: { prefixUrl: prefixUrl },
async: true
}).done(function (result) {
//Clean up sessionStorage before saving the new menu in case permissions have changed.
StopStart();
sessionStorage.removeItem($("#keyStorage").val());
sessionStorage.setItem($("#keyStorage").val(), result);
showMenu(result);
let title = getUrlTitleFromMenu(actualPosition);
if (title.length > 0) {
$("#titleSection").html(title);
}
});
}
/**
* Loads the menu data from the server and displays it on the page.
*/
function loadSessionData() {
var prefixUrl = window.location.protocol + '//' + window.location.host;
var pagePath = window.location.protocol + '//' + window.location.host + "/GeneralArea/Internal/";
$.ajax({
type: 'GET',
url: pagePath + "getBaseControllerData",
dataType: 'json',
data: { prefixUrl: prefixUrl },
async: false
}).done(function (result) {
//Clean up sessionStorage before sa ing the new menu in case permissions have changed.
sessionStorage.setItem(goPartitionKeyCookie, JSON.stringify(result));
kendo.culture(result.Culture);
cultureInfo = result.Culture;
showLicense = result.ShowLicense === "False" || result.ShowLicense === false ? false : true;
showSessionData(result);
});
}
function getAntiForgeryTokenForForm(formDestination) {
$.ajax({
url: '/api/AntiForgery/GetToken',
type: 'GET',
dataType: 'json',
async: true,
xhrFields: {
withCredentials: true
}
}).done(function (result) {
if (result && result.token) {
var $form = $("#" + formDestination);
if ($form.length) { // Check if the form exists
// Search for an existing hidden input with the name '__RequestVerificationToken'
var $existingTokenInput = $form.find("input[name='__RequestVerificationToken']");
if ($existingTokenInput.length) {
// If the token input exists, update its value
$existingTokenInput.val(result.token);
} else {
// If the token input does not exist, create it and append to the form
var tokenInput = $('')
.attr('type', 'hidden')
.attr('name', '__RequestVerificationToken')
.val(result.token);
$form.append(tokenInput);
}
} else {
console.error('Form with ID "' + formDestination + '" not found.');
}
} else {
console.error('Anti-forgery token not found in the response.');
}
});
}
function getAntiForgeryToken() {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/api/AntiForgery/GetToken',
type: 'GET',
dataType: 'json',
async: false,
xhrFields: {
withCredentials: true
}
}).done(function (result) {
if (result && result.Token) {
var inputs = document.querySelectorAll('input[name="__RequestVerificationToken"]');
inputs.forEach(function (input) {
input.value = result.Token;
});
resolve(true);
}
resolve(false);
});
});
}
function showSessionData(data) {
kendo.culture(data.Culture);
cultureInfo = data.Culture;
showLicense = data.ShowLicense === "False" || data.ShowLicense === false ? false : true;
$("#navbarlayoutbusinesnamexbname").text(data.BusinessName);
$("#navbarlayoutbusinesnamexoname").text("(Sede: " + data.OfficeName + ")");
callEvalLicence(data.LicenceMsg, data.LicenceSave, data.LicencePrint);
$("#newUser").val(data.NewUser);
$("#userDataidConnection").val(data.IdConnection);
$("#userDataidUserRecord").val(data.IdUserRecord);
$("#userDataidCompany").val(data.UserDataidCompany);
$("#userDataidSession").val(data.UserDataidSession);
$("#userDataidOffice").val(data.UserDataidOffice);
$("#userDataUserName").val(data.UserDataUserName);
$("#userNameInternalL").val(data.UserName);
$("#idActionField").val("");
$("#keyStorage").val(data.KeyStorage);
$("#decimalNumber").val(data.DecimalNumber);
$("#urlPhoto").val(data.UrlPhoto);
$("#idCashTurn").val(data.IdCashTurn);
$("#spnTaskUser").html(data.HasTask);
const cultureMap = {
"es-AR": "../../js/cultures/kendo.culture.es-ar.min.js",
"es-DO": "../../js/cultures/kendo.culture.es-do.min.js",
"es-EC": "../../js/cultures/kendo.culture.es-ec.min.js"
};
const scriptUrl = cultureMap[cultureInfo];
if (scriptUrl) {
$.ajax({
type: 'GET',
url: scriptUrl,
dataType: 'script',
success: function () {
kendo.culture(cultureInfo);
console.log(`${cultureInfo} Script loaded successfully.`);
if (typeof myFunction === 'function') {
myFunction();
}
},
error: function (jqxhr, settings, exception) {
console.log(`${cultureInfo}: Error loading script: ` + exception);
}
});
} else
console.log(`No culture script available for: ${cultureInfo}`);
if (data.StateReadUserSystem == false) {
$("#dialog").html('
' +
'NUEVAS FUNCIONALIDADES EN ESTA VERSIÓN. No te las pierdas ' +
'
' +
'
' +
'
' +
'' +
'
' +
'
' +
'No volver a ver este mensaje ' +
'
' +
'
' +
'' +
'
' +
'
');
$("#dialog").kendoWindow({
title: "¡¡¡ Nueva Actualización !!!",
width: 460,
position: {
top: "10%",
left: "50%"
},
close: function (e) {
let divModal = document.getElementById("divModal");
document.body.removeChild(divModal);
}
});
if (actualPosition == homePosition && statePopup == "NV")
openWindowUpdates();
}
goUrlSignal = data.UrlSignal;
if (data.HasFiles == true)
$("#contentFiles").show();
else
$("#contentFiles").hide();
startNotifications();
}
function callEvalLicence(licenceMsg, licenceSave, licencePrint) {
if (licenceMsg == null) {
let localPKData = sessionStorage.getItem(goPartitionKeyCookie);
if (localPKData != null) {
localPKData = JSON.parse(localPKData);
licenceMsg = localPKData.licenceMsg;
licenceSave = localPKData.licenceSave;
licencePrint = localPKData.licencePrint;
}
}
evalLicence(licenceMsg, licenceSave, licencePrint);
}
/**
* Logs out the user globally by removing the session data and submitting the logout form.
*/
function globalLogOut() {
SetMessageNotificationCenter(0, 320, "¿Desea cerrar sesión?", "Cerrar Sesión", "confirmation", false, 0, true, true, "logOutConfirm()", "Si", "", "No");
}
function logOutConfirm() {
sessionStorage.removeItem($("#keyStorage").val());
sessionStorage.removeItem(goPartitionKeyCookie);
sendSignalSignOutUser();
// Loop through all keys in sessionStorage and remove them
$.each(sessionStorage, function (key, value) {
sessionStorage.removeItem(key);
});
document.getElementById('logoutForm').submit();
}
/**
* Changes the company office by opening a settings window.
*/
function fnChangeCompanyOffice() {
var url = '../GeneralWebMethods/SettingsWindows/getSettingWindow';
$.when(
$.get(url, function (data) {
$('#dvSettingWindow').html(data);
$("#windowsSettingGeneral").kendoWindow({
modal: true,
title: "Cambio de Sede",
height: "70%",
width: "50%"
});
})).then(function (x) {
$("#windowsSettingGeneral").data("kendoWindow").open().center();
LoadOfficesAccessNavBar();
});
}
/**
* Retrieves the title of the URL from the menu data.
*
* @param {string} targetUrl - The target URL to retrieve the title for.
* @returns {string} - The title of the URL from the menu data.
*/
function getUrlTitleFromMenu(targetUrl) {
if (menuDataController == null || menuDataController.length == 0)
return "";
targetUrl = targetUrl.replace("#", "")?.split('?')[0] ?? "";
for (let section of menuDataController) {
let foundItem = section.items.find(item => item.url === targetUrl);
if (foundItem)
return foundItem.text;
}
return "";
}
/*
================================================================
End internallayout
================================================================
*/
function validate(evt) {
///
/// Validates the specified evt.
///
/// The evt.
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\.,/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
/**
* Executes a server-side method asynchronously using AJAX.
*
* @param {string} fn - The name of the server-side method to call.
* @param {object|array|string} data - The data to send to the server-side method.
* @param {function} successFn - The callback function to execute on successful AJAX call.
* @param {function} [errorFn] - The callback function to execute on AJAX call error.
* @param {boolean} [isAsync=true] - Indicates whether the AJAX call should be asynchronous or not.
* @param {string} pagePath - The path to the server-side page containing the method.
* @param {string} [_contentType="application/x-www-form-urlencoded; charset=utf-8"] - The content type of the AJAX request.
* @param {string} [_dataType="json"] - The expected data type of the AJAX response.
* @param {function} [alwaysFn=""] - The callback function to execute after the AJAX call, regardless of success or failure.
*/
function PageMethod(fn, data, successFn, errorFn, isAsync = true, pagePath,
_contentType = "application/x-www-form-urlencoded; charset=utf-8", _dataType = "json", alwaysFn = "", _type = "POST", _bRetry = true) {
let paramList = {};
if (_contentType.toLowerCase().includes("application/json")) {
paramList = data;
} else {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i += 2)
paramList[data[i]] = data[i + 1];
} else if (typeof data === "object") {
paramList = data;
} else if (typeof data === "string") { //JsonString
paramList = JSON.parse(data);
} else {
console.error("Invalid data type. Data should be an object or array.");
return;
}
if (typeof paramList === 'object') {
Object.keys(paramList).forEach(key => {
const value = paramList[key];
if (value instanceof Date)
paramList[key] = kendo.toString(value, "yyyy-MM-dd HH:mm:ss");
});
}
}
let ajaxPathSeparator = pagePath.endsWith("/") || fn.startsWith("/") ? "" : "/";
$.ajax({
type: _type,
async: isAsync,
url: pagePath + ajaxPathSeparator + fn,
contentType: _contentType,
data: paramList,
dataType: _dataType,
processData: true,
crossDomain: true
}).done(function (result) {
// Handle success
if (typeof successFn === 'function')
successFn(result);
}).fail(async function (jqXHR, textStatus, errorThrown) {
//Manejo general de errores
let retry = await generalAjaxControlError(jqXHR, textStatus, errorThrown, errorFn, "Inconvenientes en su conexión (PM)", fn, pagePath, _bRetry);
if (retry && _bRetry) {
PageMethod(fn, data, successFn, errorFn, isAsync, pagePath, _contentType, _dataType, alwaysFn, _type, false);
return;
}
}).always(function () {
if (typeof alwaysFn === 'function')
alwaysFn();
});
}
async function generalAjaxControlError(jqXHR, textStatus, errorThrown, errorFn, titleHeader = "Inconvenientes en su conexión", auxInfo = "", serverInfo = "", bRetryPMethod = false) {
let bRetry = false;
// Manejo extendido para depuración y registro detallado de errores
console.error(new Date() + ". Error en la petición AJAX (PageMethod)" + (auxInfo == "" ? "" : ": " + auxInfo));
// Detalles de la respuesta completa
let statusText = "";
switch (jqXHR.status) {
case 400:
statusText = "Solicitud incorrecta. Verifica los datos enviados.";
break;
case 401:
statusText = "No autorizado. Verifica tu sesión o credenciales.";
break;
case 403:
statusText = "Acceso denegado. No tienes los permisos necesarios.";
break;
case 404:
statusText = "El recurso solicitado no existe. Verifica la URL.";
break;
case 500:
statusText = "Error interno del servidor. Verifica los datos a guardar, formatos de fecha, campos çon números, longitud de textos e intenta guardar nuevamente.";
break;
case 0:
statusText = "Error de red. Verifica tu conexión a internet.";
break;
default:
statusText = "Error inesperado: " + jqXHR.status;
break;
}
console.log("Estado HTTP: " + jqXHR.status); // Código HTTP (ej. 404, 500)
console.log("Texto del estado: " + textStatus); // Texto del estado (ej. 'error', 'timeout')
console.log("Texto del estado interpretado: " + statusText); // Texto del estado (ej. 'error', 'timeout')
console.log("Mensaje de error: " + errorThrown); // Mensaje de error proporcionado por jQuery
if (serverInfo)
console.log("Link de conexión: ", serverInfo);
if (jqXHR.responseJSON)
console.log("Respuesta JSON del servidor (responseJSON):", jqXHR.responseJSON);
if (jqXHR.responseText)
console.log("Texto de la respuesta del servidor (responseText):", jqXHR.responseText);
try {
console.log("Encabezados de respuesta: " + (jqXHR.getAllResponseHeaders ? jqXHR.getAllResponseHeaders() : "Encabezados no disponibles"));
} catch (error) {
console.warn("No se pudieron obtener todos los encabezados. Intentando encabezados específicos...");
console.log("Encabezado Content-Type: " + jqXHR.getResponseHeader("Content-Type"));
console.log("Encabezado Server: " + jqXHR.getResponseHeader("Server"));
}
// Ejecutar la función de error personalizada si se proporciona
// Mostrar un error más detallado al usuario
var userMessage = "Ocurrió un error durante la solicitud" + (auxInfo == "" ? "" : ": " + auxInfo) + " " + new Date() + " " +
"Código de estado: " + jqXHR.status + " " +
"Texto del estado: " + (statusText != "" ? statusText : "") + " (" + textStatus + ")" + " " +
(errorThrown != "" ? "Descripción: " + errorThrown + " " : "") +
"Por favor, reintente su operación, en caso contrario, recarga la página";
// Si la respuesta contiene detalles en el cuerpo, mostrar más información
if (jqXHR.responseText) {
if (typeof errorFn !== 'function') {
userMessage += `
${jqXHR.responseText}
`;
}
}
if (jqXHR.status === 401 || jqXHR.status === 419 || jqXHR.status === 440) {
console.warn("No se encuentran datos de la sesión. Invocando revivir sesión manualmente.");
invokeKeepSessionAlive();
}
if (jqXHR.status === 400) {
console.warn("Reconstruyendo AFK automáticamente.");
let bDone = await getAntiForgeryToken();
if (bDone) {
userMessage = userMessage + " (Código: AFKRbld)";
if (bRetryPMethod) {
bRetry = true;
return bRetry;
}
}
}
// Handle error
if (typeof errorFn === 'function') {
userMessage = userMessage.replaceAll(" ", "\n");
errorFn(userMessage);
}
else
SetMessageNotificationCenter(0, 420, userMessage, titleHeader, "error", true, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
return bRetry;
}
// Función para mostrar/ocultar los detalles y cambiar el texto del botón
function toggleErrorDetails(event) {
event.stopPropagation(); // Evita que el clic cierre la notificación
let errorDetails = document.getElementById("errorDetails");
let toggleButton = document.getElementById("toggleInfoBtn");
if (errorDetails.style.display === "none" || errorDetails.style.maxHeight === "0px") {
errorDetails.style.display = "block";
errorDetails.style.maxHeight = "500px"; // Expande el contenedor
toggleButton.textContent = "- Info"; // Cambia el texto del botón
} else {
errorDetails.style.maxHeight = "0"; // Colapsa el contenedor
setTimeout(() => {
errorDetails.style.display = "none";
toggleButton.textContent = "+ Info"; // Cambia el texto del botón
}, 300); // Espera a que termine la animación antes de ocultar
}
// Ajusta dinámicamente el tamaño del Kendo Notification
let notificationElement = document.querySelector(".k-notification-error"); // Ajusta el selector si es necesario
if (notificationElement) {
notificationElement.style.height = "auto"; // Ajusta el tamaño automáticamente
}
}
function setAllDefaultValuesKendoCombo() {
$(".k-dropdown > input").each(function () {
if (this.name !== "")
setDefaultValueKendoComboByName(this.name);
});
}
function setDefaultValueKendoComboByName(KendoComboName) {
var comboList = $("#" + KendoComboName).data("kendoDropDownList");
if (typeof comboList === "undefined")
return;
if (comboList.value() === "" || comboList.value() == "0") {
var comboData = comboList.dataSource._data;
if (typeof comboData === "undefined")
return;
comboData.forEach(function (item) {
if (typeof item.Selected !== "undefined") {
if (item.Selected)
comboList.value(item.Value);
} else {
if (typeof item.isDefaultValue !== "undefined") {
if (item.isDefaultValue)
comboList.value(item.Value);
}
}
});
}
}
function LoadCombos(process, param1, param2, param3) {
///
/// Loads the combos.
///
/// The process.
/// The param1.
/// The param2.
/// The param3.
if (typeof param1 === "undefined" || param1 === null)
param1 = "0";
if (typeof param2 === "undefined" || param2 === null)
param2 = "0";
if (typeof param3 === "undefined" || param3 === null)
param3 = "0";
var fn = "getComboDataSourceJson";
var datas = ["process", process, "param1", param1, "param2", param2, "param3", param3];
var successFn = function (result) {
data1 = JSON.parse(result);
};
var errorFn = function (x, a, t) {
userLogStatus = 0;
};
var isAsync = false;
var pagePath = window.location.protocol + '//' + window.location.host + "/GeneralWebMethods/generalProviders";// window.location.pathname;
PageMethod(fn, datas, successFn, errorFn, isAsync, pagePath);
}
function LoadCombosAsync(process, callback, param1, param2, param3, errorCallback) {
if (typeof param1 === "undefined" || param1 === null)
param1 = "0";
if (typeof param2 === "undefined" || param2 === null)
param2 = "0";
if (typeof param3 === "undefined" || param3 === null)
param3 = "0";
LoadStart();
PageMethod("getComboDataSourceJson", ["process", process, "param1", param1, "param2", param2, "param3", param3], function success(result) {
StopStart();
if (typeof callback === "function")
callback(JSON.parse(result));
}, function error(x, y, z) {
if (typeof errorCallback == 'function') { errorCallback(y); }
StopStart();
}, true, window.location.protocol + '//' + window.location.host + "/GeneralWebMethods/generalProviders");
}
function LoadCombosExtended(process, param1, param2, param3) {
///
/// Loads the combos extended.
///
/// The process.
/// The param1.
if (typeof param1 === "undefined" || param1 === null)
param1 = "0";
if (typeof param2 === "undefined" || param2 === null)
param2 = "0";
if (typeof param3 === "undefined" || param3 === null)
param3 = "0";
var fn = "getComboDataSourceExtendedJson";
var datas = ["process", process, "param1", param1, "param2", param2, "param3", param3];
var successFn = function (result) {
data1 = JSON.parse(result);
if (data1.length > 0)
userLogStatus = 0;
};
var errorFn = function (x, a, t) {
alert("error en algo, favor revisar");
userLogStatus = 0;
};
var isAsync = false;
var pagePath = window.location.protocol + '//' + window.location.host + "/GeneralWebMethods/generalProviders";// window.location.pathname;
PageMethod(fn, datas, successFn, errorFn, isAsync, pagePath);
}
/**
* Generates an anti-forgery token and includes it in the AJAX request.
*
* @param {string} fn - The name of the server-side method to call.
* @param {object} data - The data to send to the server-side method.
* @param {function} successFn - The function to execute if the AJAX request is successful.
* @param {function} errorFn - The function to execute if the AJAX request encounters an error.
* @param {string} pagePath - The path to the server-side page containing the method.
* @param {object} form - The form element containing the anti-forgery token (optional).
*/
function PageMethodFormDataAntiForgeryToken(fn, data, successFn, errorFn, pagePath, form = null, _bRetry = true) {
let token = "";
if (form != null)
token = $('input[name="__RequestVerificationToken"]', form).val();
if (token == null || token == "")
token = $('input[name="__RequestVerificationToken"]').val();
let ajaxPathSeparator = pagePath.endsWith("/") || fn.startsWith("/") ? "" : "/";
var formData = new FormData();
formData.append('dataValue', data); // Añadir el string largo
$.ajax({
url: pagePath + ajaxPathSeparator + fn,
type: 'POST',
data: formData,
processData: false, // No proceses los datos, FormData lo hará por ti
contentType: false, // No establezcas un contentType, deja que FormData lo gestione
headers: {
"RequestVerificationToken": token,
},
}).done(function (response) {
// Handle success
if (typeof successFn === 'function')
successFn(response);
}).fail(async function (jqXHR, textStatus, errorThrown) {
//Manejo general de errores
let retry = await generalAjaxControlError(jqXHR, textStatus, errorThrown, errorFn, "Inconvenientes en su conexión (PMAFK)", fn, pagePath, _bRetry);
if (retry && _bRetry) {
PageMethodFormDataAntiForgeryToken(fn, data, successFn, errorFn, pagePath, form, false);
return;
}
});
}
function PageMethodAntiForgeryToken(fn, data, successFn, errorFn, pagePath, form = null, _bRetry = true) {
let dataParameters = {};
let token = "";
if (form != null)
token = $('input[name="__RequestVerificationToken"]', form).val();
if (token == null || token == "")
token = $('input[name="__RequestVerificationToken"]').val();
dataParameters = {
dataValue: data
};
let ajaxPathSeparator = pagePath.endsWith("/") || fn.startsWith("/") ? "" : "/";
$.ajax({
url: pagePath + ajaxPathSeparator + fn,
datatype: "json",
traditional: true,
type: 'POST',
data: dataParameters,
headers: {
"RequestVerificationToken": token
},
}).done(function (response) {
// Handle success
if (typeof successFn === 'function')
successFn(response);
}).fail(async function (jqXHR, textStatus, errorThrown) {
//Manejo general de errores
let retry = await generalAjaxControlError(jqXHR, textStatus, errorThrown, errorFn, "Inconvenientes en su conexión (PMAFK)", fn, pagePath, _bRetry);
if (retry && _bRetry) {
PageMethodAntiForgeryToken(fn, data, successFn, errorFn, pagePath, form, false);
return;
}
});
}
//Permite llamar un "Web method" pasando como parámetros un string json object
function PageMethodJson(fn, data, successFn, errorFn, pagePath, _bRetry = true) {
///
/// Pages the method json.
///
/// The function.
/// The data.
/// The success function.
/// The error function.
/// The page path.
$.ajax({
url: pagePath + "/" + fn,
datatype: "json",
traditional: true,
type: 'POST',
data: {
dataValue: data
},
}).done(function (response) {
// Handle success
if (typeof successFn === 'function') {
successFn(response);
}
}).fail(async function (jqXHR, textStatus, errorThrown) {
//Manejo general de errores
let retry = await generalAjaxControlError(jqXHR, textStatus, errorThrown, errorFn, "Inconvenientes en su conexión (PMJson)", fn, pagePath, _bRetry);
if (retry && _bRetry) {
PageMethodJson(fn, data, successFn, errorFn, pagePath, false);
return;
}
});
}
//permite llamar un método del controlador asincronamente (no requere etiquetado) pasando un objeto json puro, permite uso de monitores y
//utiliza el pensador del systema (loader) por si solo. Los parametros errorCallback y noInterfer son opcionales.
//2024-09-16: Se añade parametro de contexto para poder enviar datos adicionales al callback al resolver promesas.
//2024-09-16: Se cambia por then y catch para resolver promesas. se añade el metodo progress para poder enviar el progreso de la carga.
function sendAsync(url, data, successCallback, errorCallback, noInterfer = false, context = {}, progress = null) {
if (!noInterfer) { LoadStart(); }
var deRef = $.ajax({
type: 'POST',
dataType: 'json',
data: data,
url: url
}).then(function (result) {
if (!noInterfer) { StopStart(); }
if (typeof successCallback === 'function') {
successCallback(result, context);
}
}).catch(function (error) {
let message = "";
if (error.status == 0 && error.statusText.includes("timeout")) {
message += "Error procesando su solicitud en este momento. Por favor, intentelo mas tarde (TimeOut)"
}
if (!noInterfer) { StopStart(); }
SetMessageNotificationCenter(100, 400, message, "Error al cargar los datos", "error", true, 0);
if (typeof errorCallback === "function") { errorCallback(error); }
}).progress(function (event) {
if (typeof progress === "function") { progress(event, event.loaded / event.total); }
});
return deRef;
}
//Permite llamar el cuadro de mensajes de texto para mandar las notificaciones (version centrada)
function SetMessageNotificationCenter(height, width, message, tittle, type, hideOnClick, autoHideAfter, visibleYes,
visibleNo, functionYes, textYes, functionNo, textNo, contentIsHTML = false) {
///
/// Sets the message notification center.
///
/// The height.
/// The width.
/// The message.
/// The tittle.
/// The type.
/// The hide on click.
/// The automatic hide after.
/// The visible yes.
/// The visible no.
/// The function yes.
/// The text yes.
/// The function no.
/// The text no.
var notification = $("#popupNotification").data("kendoNotification");
hideOnClick = hideOnClick ? hideOnClick : true;
autoHideAfter = autoHideAfter ? autoHideAfter : 0;
var eWidth = width,
eHeight = height,
wWidth = $(window).width(),
wHeight = $(window).height(),
newTop, newLeft;
newLeft = Math.floor(wWidth / 2 - 300 / 2);
newTop = Math.floor(wHeight / 2 - eHeight / 2);
if (typeof (notification) !== "undefined") {
notification.setOptions({
position: {
left: newLeft,
bottom: null,
right: null,
top: newTop
},
height: height == 0 ? "auto" : height,
width: width,
show: onShow,
hideOnClick: hideOnClick,
autoHideAfter: autoHideAfter
});
ShowMessageNotification(notification, message, tittle, type, functionYes,
textYes,
visibleYes,
functionNo,
textNo,
visibleNo,
contentIsHTML);
}
}
function onShow(e) {
if (!$("." + e.sender._guid)[1]) {
var element = e.element.parent(),
eWidth = element.width(),
eHeight = element.height(),
wWidth = $(window).width(),
wHeight = $(window).height(),
newLeft;
newLeft = Math.floor(wWidth / 2 - eWidth / 2);
}
e.element.parent().css({
left: newLeft,
zIndex: 22222
});
}
//Permite llamar el cuadro de mensajes de texto para mandar las notificaciones (version cualquier posicion)
function SetMessageNotification(leftPosition, topPosition, height, width, message, tittle, type, hideOnClick, autoHideAfter,
visibleYes, visibleNo, functionYes, textYes, functionNo, textNo, rightPosition, bottomPosition) {
//var element = popupNotification.element.parent(),
///
/// Sets the message notification.
///
/// The left position.
/// The top position.
/// The height.
/// The width.
/// The message.
/// The tittle.
/// The type.
/// The hide on click.
/// The automatic hide after.
/// The visible yes.
/// The visible no.
/// The function yes.
/// The text yes.
/// The function no.
/// The text no.
/// The right position.
/// The bottom position.
var notification = $("#popupNotification").data("kendoNotification");
hideOnClick = hideOnClick ? hideOnClick : true;
autoHideAfter = autoHideAfter ? autoHideAfter : 0;
notification.setOptions({
position: {
left: leftPosition,
bottom: bottomPosition,
right: rightPosition,
top: topPosition
},
height: height == 0 ? "" : height,
width: width,
hideOnClick: hideOnClick,
autoHideAfter: autoHideAfter
});
ShowMessageNotification(notification, message, tittle, type, functionYes,
textYes,
visibleYes,
functionNo,
textNo,
visibleNo,
false);
}
//Funcion interna para mostrar el mensaje con notificaciones
function ShowMessageNotification(notification, messageNot, titleNot, typeNot, functionYesNot,
textYesNot, visibleYesNot, functionNoNot, textNoNot, visibleNoNot, contentIsHTML = false) {
///
/// Shows the message notification.
///
/// The notification.
/// The message not.
/// The title not.
/// The type not.
/// The function yes not.
/// The text yes not.
/// The visible yes not.
/// The function no not.
/// The text no not.
/// The visible no not.
functionYesNot = functionYesNot ? functionYesNot : '';
textYesNot = textYesNot ? textYesNot : '';
visibleYesNot = visibleYesNot ? visibleYesNot : false;
functionNoNot = functionNoNot ? functionNoNot : '';
textNoNot = textNoNot ? textNoNot : '';
visibleNoNot = visibleNoNot ? visibleNoNot : false;
if (visibleYesNot === true && functionYesNot == '') {
functionYesNot = "btnYes();";
textYesNot = "Si";
}
if (visibleNoNot === true && functionNoNot == '') {
functionNoNot = "btnNo();";
textNoNot = "No";
}
checkOverflow(notification);
if (contentIsHTML)
notification.show({
title: titleNot,
message: messageNot,
functionYes: functionYesNot,
textYes: textYesNot,
visibleYes: visibleYesNot,
functionNo: functionNoNot,
textNo: textNoNot,
visibleNo: visibleNoNot
}, typeNot);
else
notification.show({
title: titleNot,
message: kendo.toString(htmlEncode(messageNot)),
functionYes: functionYesNot,
textYes: textYesNot,
visibleYes: visibleYesNot,
functionNo: functionNoNot,
textNo: textNoNot,
visibleNo: visibleNoNot
}, typeNot);
}
function checkOverflow(notification) {
var notificationArea = $(".notification-flex");
if (notificationArea.length > 0)
if ((notificationArea[notificationArea.length - 1]?.getBoundingClientRect().top ?? 1) < 0)
notification.hide();
}
function btnNo() { }
function btnYes() { }
//Prmite resetear todo un formulario con una sobrecarag de jquery
jQuery.fn.reset = function () {
$(this).each(function () { this.reset(); });
};
function enabledToolbar(opcion) {
///
/// Enableds the toolbar.
///
/// The opcion.
$("#btnDeleteRecord").css('display', opcion);
$("#btnNewRecord").css('display', opcion);
$("#generalbtnToolBarPrint").css('display', opcion);
$("#btnSaveRecord").css('display', opcion);
$("#btnSearchRecord").css('display', opcion);
$("#btnInbox").css('display', opcion);
}
function loadToolBarManual(options) {
///
/// Loads the tool bar manual.
///
/// The options.
$("#toolbarPrincipal").css('display', 'none');
var n = -1;
if (options == '')
$("#toolbarPrincipal").css('display', 'none');
else {
$("#toolbarPrincipal").css('display', 'inline');
$("#btnNewRecord").css('display', 'none');
$("#generalbtnToolBarPrint").css('display', 'none');
$("#btnSearchRecord").css('display', 'none');
$("#btnSaveRecord").css('display', 'none');
$("#btnDeleteRecord").css('display', 'none');
$("#btnInbox").css('display', 'none');
$("#btnInboxToMe").css('display', 'none');
n = options.indexOf("D");
if (n >= 0)
$("#btnDeleteRecord").css('display', 'inline');
n = options.indexOf("N");
if (n >= 0)
$("#btnNewRecord").css('display', 'inline');
n = options.indexOf("P");
if (n >= 0)
$("#generalbtnToolBarPrint").css('display', 'inline');
n = options.indexOf("S");
if (n >= 0)
$("#btnSaveRecord").css('display', 'inline');
n = options.indexOf("F");
if (n >= 0)
$("#btnSearchRecord").css('display', 'inline');
n = options.indexOf("E");
if (n >= 0)
$("#btnInbox").css('display', 'inline');
n = options.indexOf("M");
if (n >= 0)
$("#btnInboxToMe").css('display', 'inline');
}
}
function LoadToolbar(showMandatory, isAsync = false) {
///
/// Loads the toolbar.
///
/// The show mandatory.
if (typeof bLicenceToPrint === "undefined")
callEvalLicence();
enabledToolbar('inline');
if (typeof showMandatory === "undefined" || showMandatory === null)
showAny = "0";
else
showAny = showMandatory;
var fn = "getRolePermission";
var datas = ["urlPathName", window.location.pathname];
statusToolBar.canSave = true;
statusToolBar.canNew = true;
statusToolBar.canDelete = true;
statusToolBar.canPrint = true;
var successFn = function (result) {
data1 = JSON.parse(result);
var cntItem = 0;
if (showAny == "0") {
if (data1 === null) {
$("#toolbarPrincipal").css('display', 'none');
}
else {
if (result != "" && result != "{}" && data1.length == undefined) {
cntItem = 0;
if (data1.sumDelete == 0) {
cntItem = cntItem + 1;
$("#btnDeleteRecord").css('display', 'none');
statusToolBar.canDelete = false;
}
if (data1.sumNew == 0) {
cntItem = cntItem + 1;
$("#btnNewRecord").css('display', 'none');
statusToolBar.canNew = false;
}
if (data1.sumPrint == 0 || !bLicenceToPrint) {
cntItem = cntItem + 1;
$("#generalbtnToolBarPrint").css('display', 'none');
statusToolBar.canPrint = false;
}
if (data1.sumSave == 0 || !bLicenceToSave) {
cntItem = cntItem + 1;
$("#btnSaveRecord").css('display', 'none');
statusToolBar.canSave = false;
}
if (data1.sumFind == 0) {
cntItem = cntItem + 1;
$("#btnSearchRecord").css('display', 'none');
}
if (data1.sumMail == 0) {
cntItem = cntItem + 1;
$("#btnInbox").css('display', 'none');
}
if (data1.sumMailToMe == 0) {
cntItem = cntItem + 1;
$("#btnInboxToMe").css('display', 'none');
}
//if (cntItem >= 5) {
// $("#btnInbox").css('display', 'none');
//}
}
}
}
else {
switch (showAny) {
case "F":
enabledToolbar('none');
$("#btnSearchRecord").css('display', 'inline');
break;
case "P":
enabledToolbar('none');
$("#generalbtnToolBarPrint").css('display', 'inline');
break;
case "S":
enabledToolbar('none');
$("#btnSaveRecord").css('display', 'inline');
break;
case "N":
enabledToolbar('none');
$("#btnNewRecord").css('display', 'inline');
break;
case "D":
enabledToolbar('none');
$("#btnDeleteRecord").css('display', 'inline');
break;
case "E":
enabledToolbar('none');
$("#btnInbox").css('display', 'inline');
break;
case "M":
enabledToolbar('none');
$("#btnInboxToMe").css('display', 'inline');
break;
default:
$("#toolbarPrincipal").css('display', 'inline');
break;
}
}
};
var errorFn = function (x, a, t) { };
var pagePath = window.location.protocol + '//' + window.location.host + "/GeneralWebMethods/generalProviders";// window.location.pathname;
PageMethod(fn, datas, successFn, errorFn, isAsync, pagePath);
}
function validateRolPermisions(permission = "", individual = false) {
///
/// muestra en un mensaje de advertencia indicando que el rol del usuario no tiene permisos no tiene asignados para realizar modificaciones en la pantalla
///
/// habilita mensajes de permiso solo para una funcionalidad, true = muestra un mensaje paya un permiso en especifico, false = muestra un mensaje para los permisios en general
/// indica el nombre del permiso que se tiene restringido
var errorRolPermissionsOptions = "";
var validError = false;
if (statusToolBar.canSave == false) {
errorRolPermissionsOptions += "Guardar/Editar ";
validError = true;
}
if (statusToolBar.canDelete == false) {
errorRolPermissionsOptions += ", Eliminar/Cancelar ";
validError = true;
}
if (statusToolBar.canNew == false) {
errorRolPermissionsOptions += ", Crear ";
validError = true;
}
if (statusToolBar.canPrint == false) {
errorRolPermissionsOptions += ", Imprimir ";
validError = true;
}
if (validError && individual) {
if (individual && permission === "Guardar/Editar" && statusToolBar.canSave == false) {
SetMessageNotificationCenter(80, 400, "Su rol de usuario no tiene permiso para " + permission + " en esta pantalla", "Advertencia", "info", true, 11500);
return true;
} else if (individual && permission === "Eliminar/Cancelar" && statusToolBar.canDelete == false) {
SetMessageNotificationCenter(80, 400, "Su rol de usuario no tiene permiso para " + permission + " en esta pantalla", "Advertencia", "info", true, 11500);
return true;
} else if (individual && permission === "Crear" && statusToolBar.canNew == false) {
SetMessageNotificationCenter(80, 400, "Su rol de usuario no tiene permiso para " + permission + " en esta pantalla", "Advertencia", "info", true, 11500);
return true;
} else if (individual && permission === "Imprimir" && statusToolBar.canPrint == false) {
SetMessageNotificationCenter(80, 400, "Su rol de usuario no tiene permiso para " + permission + " en esta pantalla", "Advertencia", "info", true, 11500);
return true;
} else {
return false;
}
} else if (validError == false) {
return false;
} else {
SetMessageNotificationCenter(80, 400, "Su rol de usuario no tiene permiso para " + errorRolPermissionsOptions + " en esta pantalla", "Advertencia", "info", true, 11500);
}
}
if (window.JSON && !window.JSON.dateParser) {
/// The re iso
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
/// The re ms ajax
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.dateParser = function (key, value) {
///
///
///
/// The key.
/// The value.
if (typeof value === 'string') {
var a = reISO.exec(value);
if (a)
return new Date(value);
a = reMsAjax.exec(value);
if (a) {
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
}
return value;
};
}
//PERMITE CALCULAR LA DIFERENCIA ENTRE DOS FECHAS DADO UN INTERVALO
function getDateDiff(date1, date2, interval) {
///
/// Gets the date difference.
///
/// The date1.
/// The date2.
/// The interval.
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
date1 = new Date(date1);
date2 = (date2 == 'now') ? new Date() : new Date(date2);
var timediff = date2 - date1;
if (isNaN(timediff)) return 0;
switch (interval) {
case "years":
return date2.getFullYear() - date1.getFullYear();
case "months":
return ((date2.getFullYear() * 12 + date2.getMonth()) - (date1.getFullYear() * 12 + date1.getMonth()));
case "weeks":
return Math.floor(timediff / week);
case "days":
return Math.floor(timediff / day);
case "hours":
return Math.floor(timediff / hour);
case "minutes":
return Math.floor(timediff / minute);
case "seconds":
return Math.floor(timediff / second);
default:
return undefined;
}
}
//PERMITE IMPRIMIR
function PrintingStikers(_texto, _mensajeImp) {
///
/// Printings the specified _texto.
///
/// The _texto.
/// The _mensaje imp.
var mywindow = window.open('', 'printMe', 'height=600,width=1000');
var iframe = mywindow.document.createElement('IFRAME');
var doc = null;
$(iframe).attr('style', 'position:absolute;width:100%;height:0px;left:-500px;top:-500px;');
mywindow.document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write('');
doc.write(_texto);
doc.close();
if (_mensajeImp != "")
alert(_mensajeImp);
else if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
alert("Imprimiendo documento...");
mywindow.focus();
setTimeout(function () {
iframe.contentWindow.focus();
iframe.contentWindow.print();
}, 50);
iframe.contentWindow.focus = function () {
setTimeout(function () {
mywindow.document.body.removeChild(iframe);
mywindow.close();
}, 1000);
};
}
//PERMITE IMPRIMIR
function Printing(_texto, _mensajeImp) {
_mensajeImp = _mensajeImp || "";
var iframe = document.createElement('iframe');
var doc = null;
$(iframe).attr('style', 'position:absolute;width:100%;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write('');
doc.write(_texto);
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (_mensajeImp != "")
alert(_mensajeImp);
else if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
alert("Imprimiendo documento...");
}
//Evento a agregar en los KENDO DROPDOWNLIST para cuando el numero de elementos es igual a uno (1), lo selecciona por defecto
//Usar como: .Events(e => e.DataBound("kendoDDdataBound"))
function kendoDDdataBound(e) {
///
/// Kendoes the d ddata bound.
///
/// The e.
var ds = this.dataSource.data();
if (ds.length === 1)
this.select(1);
try {
if (typeof ($(e.sender.element[0]).data("kendoDropDownList")) != "undefined") {
if ($(e.sender.element[0]).data("kendoDropDownList").value() == "") {
let ddData = $(e.sender.element[0]).data("kendoDropDownList").dataSource.data().filter(x => x.Selected === true);
if (ddData.length > 0)
$(e.sender.element[0]).data("kendoDropDownList").value(ddData[0].Value);
}
}
} catch (e) {
}
}
//Evento a agregar en los KENDO COMBOBOX para cuando el numero de elementos es igual a uno (1), lo selecciona por defecto
//Usar como: .Events(e => e.DataBound("kendoCombodataBound"))
function kendoCombodataBound(e) {
///
/// Kendoes the d ddata bound.
///
/// The e.
var ds = this.dataSource.data();
if (ds.length === 1)
this.select(0);
}
function hiddenField(form) {
$.ajax({
type: 'POST',
url: window.location.protocol + '//' + window.location.host + "/GeneralWebMethods/generalProviders/getConfigFieldsByCountry",
dataType: 'json',
data: "form=" + form
,
traditional: true,
error: function (request, error) {
alert(request.responseText);
StopStart();
$("#btnSaveRecord").attr('data-execute', false);
}
}).done(function (result) {
result = JSON.parse(result);
$.each(result, function (i, val) {
if (result[i].isVisible === false)
$(result[i].nameField).css("display", "none");
else
$(result[i].nameField).css("display", "inline");
});
StopStart();
return false;
});
}
//Evento a agregar en los KENDO DATEPICKER-DATETIMEPICKER para cuando se desea validar la fecha maxima
//Usar como: .Events(e => e.Change("dtChangeValidateMax"))
function dtChangeValidateMax() {
///
/// Dts the change validate maximum.
///
var startDate = this.value();
if (startDate === null || typeof startDate === "undefined")
this.value(this.max());
}
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
function getUserMessages(type, takeValue = null, isWithFilters = false) {
///
/// Gets the user messages.
///
/// The type.
/// number of messages to return (null return all).
type = typeof type !== 'undefined' ? type : "";
$("body").css("cursor", "progress");
var dateFromMs = "";
var dateUntilMs = "";
var isNotViewed = false;
var isDeletedMessage = false;
var fromNameFilter = "";
if (isWithFilters) {
dateFromMs = $("#dateFromMessage").data("kendoDatePicker").value() == null || $("#dateFromMessage").data("kendoDatePicker").value() == "" ? "" : kendo.toString($("#dateFromMessage").data("kendoDatePicker").value(), "yyyy/MM/dd");
dateUntilMs = $("#dateUntilMessage").data("kendoDatePicker").value() == null || $("#dateUntilMessage").data("kendoDatePicker").value() == "" ? "" : kendo.toString($("#dateUntilMessage").data("kendoDatePicker").value(), "yyyy/MM/dd");
isNotViewed = $("#isNotViewedMessage")[0].checked;
isDeletedMessage = $("#isDeletedMessage")[0].checked;
fromNameFilter = $("#fromNameFilter").val().trim();
}
var fn = "getUserMessagesJson";
var datas = ["varType", type, "takeValue", takeValue, "dateFrom", dateFromMs, "dateUntil", dateUntilMs, "isNotReaded", isNotViewed, "isDeleted", isDeletedMessage, "filterName", fromNameFilter];
var isAsync = true;
var errorFnP = function (x, a, t) {
$("body").css("cursor", "default");
alert(t);
alert(a);
};
var successFn = function (result) {
$("body").css("cursor", "default");
var content = "
";
content += '' +
'
' +
'
Ver
' +
'
Mensaje
' +
(isWithFilters && !isDeletedMessage ? '
' : '') +
'
' +
'';
content += '';
$.each(result, function (e) {
if (!result[e].isDeleted) {
if (result[e].indViewed === true) {
content += "
" +
"
";
}
else {
content += "
" +
"
";
}
var id = result[e].RowKey;
var dateExecute = result[e].dateExecutionString;
if ($.grep(fromMessagesNames, function (obj) { return obj.name == result[e].nameUserFrom; }).length <= 0)
fromMessagesNames.push({ name: result[e].nameUserFrom, id: result[e].nameUserFrom });
var dataSourceFromMessagesNames = new kendo.data.DataSource({
data: fromMessagesNames
});
$("#fromNameFilter").data("kendoComboBox").setDataSource(dataSourceFromMessagesNames);
content += "" +
"
";
}
var name = "#tableUserMessages" + type;
$(name).html(content);
validateChecksMs();
};
var pagePath = window.location.protocol + '//' + window.location.host + "/GeneralWebMethods/generalProviders";// window.location.pathname;
PageMethod(fn, datas, successFn, errorFnP, isAsync, pagePath);
}
function selectAllMs() {
if ($("#generalChkMessages")[0].checked)
$('.chkMess').prop("checked", true);
else
$('.chkMess').prop("checked", false);
validateChecksMs();
}
function validateChecksMs() {
if ($('input:checkbox[id^="chkMs"]:checked').length > 0 && typeof $("#deleteMessages") !== "undefined")
$("#deleteMessages").show();
else
$("#deleteMessages").hide();
}
function deleteChecksMs() {
SetMessageNotificationCenter(100, 320, "¿Desea eliminar los mensajes seleccionados?", "CONFIRMAR EVENTO", "confirmation", false, 0, true, true, "confirmDeleteChecksMs()", "Si", "", "No");
}
function confirmDeleteChecksMs() {
var allChecksMs = $('input:checkbox[id^="chkMs"]:checked');
var messagesIdDelete = [];
$.each(allChecksMs, function (k, v) {
messagesIdDelete.push(v.name);
});
var fn = "updateDeleteData";
var datas = ["idMessagesString", JSON.stringify(messagesIdDelete)];
var pagePath = window.location.protocol + "//" + window.location.host + "/GeneralWebMethods/generalProviders";
if (messagesIdDelete.length > 0) {
LoadStart();
var successFn = function (result) {
if (result == true)
SetMessageNotificationCenter(90, 300, "Mensajes eliminados correctamente", "Info", "info", true, 5500);
getUserMessages("ALL", 200, true);
getCountUserMessagesJson();
StopStart();
};
var errorFn = function (jqXhr, textStatus, errorThrown) {
StopStart();
};
PageMethod(fn, datas, successFn, errorFn, true, pagePath);
}
}
function cleanMessageFilters() {
$("#dateFromMessage").val("");
$("#dateUntilMessage").val("");
$("#isNotViewedMessage").prop("checked", false);
$("#isDeletedMessage").prop("checked", false);
$("#fromNameFilter").val("");
}
function isNumber(evt, isDecimal, isNegative) {
///
/// Determines whether the specified evt is number.
///
/// The evt.
/// The is decimal.
/// true if the specified evt is number; otherwise, false.
isDecimal = isDecimal || false;
isNegative = isNegative || false;
var charCode = evt.which ? evt.which : event.keyCode;
if (charCode !== 46 && charCode !== 45 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
else {
// If the number field already has . then don't allow to enter . again.
if (charCode === 46 && ((evt.target.value.search(/\./) > -1 && isDecimal === true) || !isDecimal))
return false;
else {
if (charCode == 45 && isNegative == true) {
if (evt.target.value.search(/\-/) > -1)
return false;
else
if (evt.target.selectionStart > 0)
return false;
}
if (charCode == 45 && !isNegative)
return false;
return true;
}
}
}
function isNumberComa(evt, isDecimal, isNegative) {
///
/// Determines whether the specified evt is number.
///
/// The evt.
/// The is decimal.
/// true if the specified evt is number; otherwise, false.
isDecimal = isDecimal || false;
isNegative = isNegative || false;
var charCode = evt.which ? evt.which : event.keyCode;
if (charCode !== 44 && charCode !== 45 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
} else {
// If the number field already has . then don't allow to enter . again.
if (charCode === 44 && ((evt.target.value.search(/\,/) > -1 && isDecimal === true) || !isDecimal))
return false;
else {
if (charCode == 45 && isNegative == true) {
if (evt.target.value.search(/\-/) > -1)
return false;
else
if (evt.target.selectionStart > 0)
return false;
}
if (charCode == 45)
return false;
return true
}
}
}
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
};
function generalMaxLength(control) {
if (control !== undefined && control.length > 0)
if (control[0].maxLength > 0)
if (control.val().length > control[0].maxLength) {
control.val(control.val().substring(0, control[0].maxLength));
SetMessageNotificationCenter(90, 300, "La longitud del texto excede el máximo permitido", "Info", "info", true, 5500);
}
}
function getDateFromString(sDateSend) {
if (typeof sDateSend === "undefined" || sDateSend === null || sDateSend === "")
return null;
sDateSend = sDateSend.replace("a. m", "a.m").replace("p. m", "p.m");
var dateReturn = kendo.parseDate(sDateSend, ["yyyy/MM/dd", "dd/MM/yyyy", "yyyy/MMM/dd", "dd/MMM/yyyy", "dd-MM-yyyy"]);
if (dateReturn === null)
dateReturn = new Date(sDateSend);
return dateReturn;
}
function getDateStringFromDateValue(sDateSend) {
if (typeof sDateSend === "undefined" || sDateSend === null || sDateSend === "")
return "";
var dateReturn = kendo.parseDate(sDateSend);
if (dateReturn === null)
dateReturn = new Date(sDateSend);
if (dateReturn === null)
return "";
else
return kendo.toString(dateReturn, "yyyy/MM/dd");
}
function getDateTimeStringFromDateValue(sDateSend) {
if (typeof sDateSend === "undefined" || sDateSend === null || sDateSend === "")
return "";
var dateReturn = kendo.parseDate(sDateSend);
if (dateReturn === null)
dateReturn = new Date(sDateSend);
if (dateReturn === null)
return "";
else
return kendo.toString(dateReturn, "yyyy/MM/dd HH:mm:ss");
}
function generalCompareDatePickers(dateStart, dateEnd, maxDate, minDate) {
var dMaxDate = new Date(2099, 12, 31);
var dMinDate = new Date(1900, 1, 1);
if (typeof maxDate !== "undefined")
dMaxDate = maxDate;
if (typeof minDate !== "undefined")
dMinDate = minDate;
var dStart = $("#" + dateStart).data("kendoDatePicker").value();
var dEnd = $("#" + dateEnd).data("kendoDatePicker").value();
if (dStart !== null) {
if ($("#" + dateEnd).data("kendoDatePicker").min() !== kendo.parseDate(dStart))
$("#" + dateEnd).data("kendoDatePicker").min(kendo.parseDate(dStart));
} else {
$("#" + dateEnd).data("kendoDatePicker").min(dMinDate);
$("#" + dateStart).data("kendoDatePicker").min(dMinDate);
}
if (dEnd !== null) {
if ($("#" + dateStart).data("kendoDatePicker").max() !== kendo.parseDate(dEnd))
$("#" + dateStart).data("kendoDatePicker").max(dEnd);
} else {
$("#" + dateEnd).data("kendoDatePicker").max(dMaxDate);
$("#" + dateStart).data("kendoDatePicker").max(dMaxDate);
}
if (dStart !== null && dEnd !== null)
if (Date.parse(dEnd) < Date.parse(dStart))
$("#" + dateEnd).data("kendoDatePicker").value(null);
}
function generalCompareDateTimePickers(dateStart, dateEnd, dateStartMin, dateStartMax, dateEndMin, dateEndMax) {
if (typeof (dateStartMin) === "undefined")
dateStartMin = new Date(1900, 0, 1);
if (typeof (dateEndMin) === "undefined")
dateEndMin = new Date(1900, 0, 1);
if (typeof (dateStartMax) === "undefined")
dateStartMax = new Date(2099, 12, 31);
if (typeof (dateEndMax) === "undefined")
dateEndMax = new Date(2099, 12, 31);
var dStart = $("#" + dateStart).data("kendoDateTimePicker").value();
var dEnd = $("#" + dateEnd).data("kendoDateTimePicker").value();
if (dStart !== null) {
if ($("#" + dateEnd).data("kendoDateTimePicker").min() !== kendo.parseDate(dStart))
$("#" + dateEnd).data("kendoDateTimePicker").min(kendo.parseDate(dStart));
} else {
$("#" + dateStart).data("kendoDateTimePicker").value(null);
$("#" + dateEnd).data("kendoDateTimePicker").min(dateEndMin);
$("#" + dateStart).data("kendoDateTimePicker").min(dateStartMin);
}
if (dEnd !== null) {
if ($("#" + dateStart).data("kendoDateTimePicker").max() !== kendo.parseDate(dEnd))
$("#" + dateStart).data("kendoDateTimePicker").max(kendo.parseDate(dEnd));
} else {
$("#" + dateEnd).data("kendoDateTimePicker").value(null);
$("#" + dateEnd).data("kendoDateTimePicker").max(dateEndMax);
$("#" + dateStart).data("kendoDateTimePicker").max(dateStartMax);
}
if (dStart !== null && dEnd !== null)
if (Date.parse(dEnd) < Date.parse(dStart))
$("#" + dateEnd).data("kendoDateTimePicker").value(null);
}
Number.prototype.getPrecision = function () {
var s = this + "",
d = s.indexOf('.') + 1;
return !d ? 0 : s.length - d;
};
function sortJSON(data, key, way) {
///
/// Sorts the json.
///
/// The data.
/// The key.
/// The way.
if (data == undefined || data.lenght <= 1)
return data;
return data.sort(function (a, b) {
var x = a[key]; var y = b[key];
if (way === '123') { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }
if (way === '321') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }
});
}
var filtering = {
//funcion general para agregar un filtro inline propio a un kendogrid filtrable:
//use: [true/false], dtSource: referencia al datasource de kendogrid, customfilter: { operator: "", value: "", field: "" }
applyCustomFilter: function (use, dtSource, customfilter) {
//transformar en array en caso de que venga solo:
if (!Array.isArray(customfilter)) {
let arr = [];
arr.push(customfilter);
customfilter = arr;
}
//Remover el filtro si existe:
if (dtSource && dtSource.filter()) {
let otherfilters = $.grep(dtSource.filter().filters, (x) => !$.map(customfilter, y => [y.field]).includes(x.field));
dtSource.filter(otherfilters);
}
if (use) {
//agregar los nuevos filtros:
$.each(customfilter, function (idx, item) {
if (dtSource.filter()) {
let currfilters = dtSource.filter().filters;
currfilters.push(item);
dtSource.filter(currfilters);
} else
dtSource.filter(item);
});
}
}
};
//se llama en cada pantalla:
function evalLicence(licenceMsg, licenceSave, licencePrint) {
bLicenceToPrint = true;
bLicenceToSave = true;
bLicenceWarning = false;
$("#dvLicense").css("display", "none");
let today = kendo.parseDate(new Date());
//si tiene licencia:
if (licenceMsg !== "") {
//Si se superó fecha de inicio de mensaje:
if (!(kendo.parseDate(licenceMsg) >= today)) {
bLicenceWarning = true;
let sMsg = "";
let pMsg = "";
//deteminar guardado:
if (kendo.parseDate(licenceSave) < today) {
bLicenceToSave = false;
sMsg = "NO PODRÁ REGISTRAR";
} else
sMsg = "No podrá registrar a partir del dia " + kendo.toString(kendo.parseDate(licenceSave), 'dd-MM-yyyy hh:mm tt');
//determinar impresión:
if (kendo.parseDate(licencePrint) < today) {
bLicenceToPrint = false;
pMsg = "NO PODRÁ IMPRIMIR";
} else
pMsg = "No podrá imprimir a partir del dia " + kendo.toString(kendo.parseDate(licencePrint), 'dd-MM-yyyy hh:mm tt');
//construir mensaje de alerta:
let aMsg = (!bLicenceToSave || !bLicenceToPrint) ? "Su acceso a GOMEDISYS tiene restricciones." : "Su licencia para GOMEDISYS está próxima a vencer"
$("#txtLicence").html("
" + aMsg + "
");
$("#txtLicence").append("
" + sMsg + "
");
$("#txtLicence").append("
" + pMsg + "
");
//mostrar si hay mensaje de alerta y tiene perfil o si es cualquier usuario y tiene restricciones:
$("#dvLicense").css("display", (showLicense === true || !bLicenceToSave || !bLicenceToPrint) ? "grid" : "none");
}
} else {
//si no tiene licencia:
bLicenceWarning = true;
bLicenceToPrint = false;
bLicenceToSave = false;
$("#txtLicence").text("Su acceso a GOMEDISYS no ha sido asignado. NO PODRA REGISTRAR NI IMPRIMIR actividades");
$("#dvLicense").css("display", (showLicense === true) ? "grid" : "none");
}
}
//se llama solo en el index de home:
function showMsgLicence(licencePrint) {
//si tiene perfil para ver la licencia:
if (showLicense === true) {
//llamar si no se ha llamado antes:
if (typeof bLicenceToPrint === "undefined")
callEvalLicence();
//Mostrar mensaje de alerta:
if (!bLicenceToPrint || !bLicenceToSave)
SetMessageNotificationCenter(0, 400, kendo.toString(htmlEncode("Su licencia para GOMEDISYS Tiene restricciones.")), "LICENCIA", "error", true, 12500);
else if (bLicenceWarning)
SetMessageNotificationCenter(0, 400, kendo.toString(htmlEncode("Su licencia para GOMEDISYS está próxima a vencer.")), "LICENCIA", "error", true, 12500);
}
}
function LoadStart() {
$("#loader").fadeIn();
};
function StopStart() {
$("#loader").fadeOut(500);
};
function getClientFiles() {
LoadStart();
$("#contentIcons").empty();
$.get("/GeneralArea/clientFiles/_filesUser", function (data) {
$('#contentIcons').html(data);
})
}
function ConsultTasks() {
url = window.location.protocol + '//' + window.location.host + "/EncounterArea/EncounterTask/_getEncounterConsultTask";
url = url.replace(/&/g, "&");
$("body").css("cursor", "progress");
$.when($.get(url, function (data) {
$("body").css("cursor", "default");
$("#contentIcons").html('
' + data + '
');
})
).then(function (x) {
$("body").css("cursor", "default");
createKendoWindowIcons("Consulta de tareas", $(document).width() * 0.8 + "px");
});
event?.preventDefault();
}
function createKendoWindowIcons(windowTitle, customWidth) {
var window = $("#contentIcons");
if (customWidth === undefined || customWidth === null)
customWidth = "600px";
if (!window.data("kendoWindow")) {
window.kendoWindow({
width: customWidth,
resizable: false,
modal: true,
title: windowTitle,
position: {
top: "5px"
},
close: onCloseWindowIcons,
actions: [
"Close"
]
});
}
window.data("kendoWindow").title(windowTitle);
window.data("kendoWindow").center().open();
}
function onCloseWindowIcons(e) {
$("#contentIcons").empty();
}
function htmlEncode(value) {
var encodedValue = $('').text(value).html();
return encodedValue;
}
function showprivacyPolicy() {
$("#showPrivacyPolicyWindows").kendoWindow({
modal: true,
title: '',
height: "80%",
width: "75%",
open: function (e) {
$("#resultPPW").empty();
}
});
$("#resultPPW").load(window.location.protocol + '//' + window.location.host + "/html/privacyPolicy.html");
$("#showPrivacyPolicyWindows").data("kendoWindow").open().center();
}
function solvePagerGrid() {
$("div[data-role='pager']").children()[0].children[0].className = "";
$("div[data-role='pager']").children()[1].children[0].className = "";
$("div[data-role='pager']").children()[3].children[0].className = "";
$("div[data-role='pager']").children()[4].children[0].className = "";
}
function validateNumberLength(idField, lenght) {
///
/// controla la longitud de un campo numerico
///
/// identificacion del campo a validar
///el numero de longitud que se necesita para controlar
///
$(idField).on("keyup", function (e) {
var $field = $(this),
val = this.value,
$thisIndex = parseInt($field.data("idx"), lenght);//captura elementos como la "e",".", "," y "-" y los elimina del input
if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid")) {
this.value = $thisIndex;
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val = val.slice(0, lenght);
$field.val(val);
}
});
}
function validateMail(tEmail) {
if (tEmail === "")
return true;
var expr = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (!expr.test(tEmail))
return false;
else
return true;
}
/**
* Checks if a string is a valid time string in the format HH:mm:ss.
*
* @param {string} str - The string to check.
* @returns {boolean} - True if the string is a valid time string, false otherwise.
*/
function isTimeString(str) {
if (typeof str === 'string') {
const timeFormat = /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/;
return timeFormat.test(str);
}
return false;
}
function setMaxLength(e) {
var controlText = $(e);
//get the limit from maxlength attribute
var limit = parseInt(controlText.attr('maxlength'));
if (limit > 0) {
//get the current text inside the textarea
var text = controlText.val();
//count the number of characters in the text
var chars = text.length;
//check if there are more characters then allowed
if (chars > limit) {
//and if there are use substr to get the text before the limit
var new_text = text.substr(0, limit);
//and change the current text with the new text
controlText.val(new_text);
}
}
}
function formatDateToISO(dateString) {
var date = new Date(dateString);
return date.toISOString();
}
// Función para validar la cadena SQL
function containsRestrictedKeyword(sqlString) {
var sqlLower = sqlString.toLowerCase();
return restrictedKeywords.some(function (keyword) {
return sqlLower.includes(keyword);
});
}
function fnChangeCompanyOffice() {
var url = window.location.protocol + "//" + window.location.host + "/GeneralWebMethods/SettingsWindows/getSettingWindow";
$.when(
$.get(url, function (data) {
///
///
///
/// The data.
$('#dvSettingWindow').html(data);
$("#windowsSettingGeneral").kendoWindow({
modal: true,
title: "Cambio de Sede",
height: "70%",
width: "50%"
});
})).then(function (x) {
///
///
///
/// The x.
$("#windowsSettingGeneral").data("kendoWindow").open().center();
LoadOfficesAccessNavBar();
});
}
// Función para limpiar texto: elimina caracteres no visibles y verifica longitud
function sanitizeAndValidateInput(inputElement) {
let text = inputElement.value;
// Lee el valor de maxlength desde el atributo del campo de entrada
const maxLength = inputElement.getAttribute('maxlength') || 256; // Usa 256 como valor por defecto si no hay maxlength
// Contar los caracteres especiales como parte de la longitud sin eliminarlos
if (text.length > maxLength)
// Si la longitud total excede maxLength, recorta el texto hasta maxLength
inputElement.value = text.substring(0, maxLength);
}
function controlInputLength(inputElement) {
let text = inputElement.value;
// Obtén el valor de maxlength desde el atributo
const maxLength = inputElement.getAttribute('maxlength') || 256; // Usa 256 como valor por defecto si no hay maxlength
// Limita el valor a la longitud especificada en maxlength
if (text.length > maxLength)
inputElement.value = text.slice(0, maxLength);
}
function fieldParseDateTimeFromText(fieldValue, defaultValue = null) {
// Attempt to parse the date-time value
let parsedDate = fieldValue ? kendo.parseDate(fieldValue) : null;
// Handle cases where the parsed date is invalid or empty
if (!parsedDate && !defaultValue)
parsedDate = defaultValue; // Use default value or current date
// Return the formatted date-time string or null if parsing fails
return parsedDate ? kendo.toString(parsedDate, "yyyy/MM/dd HH:mm:ss") : null;
}
/**
* Parses a date-time string from an input field and returns it in "yyyy/MM/dd HH:mm:ss" format.
*
* @param {string} fieldName - The ID of the input field (without "#").
* @param {Date|null} [defaultValue=null] - The default value to use if the field is empty or null.
* @returns {string|null} - The formatted date-time string in "yyyy/MM/dd HH:mm:ss" format, or null if parsing fails.
*/
function fieldParseDateTime(fieldName, defaultValue = null) {
// Cache the jQuery object for the field
const field = $("#" + fieldName);
const fieldValue = field.val();
// Attempt to parse the date-time value
let parsedDate = fieldValue ? kendo.parseDate(fieldValue) : null;
// Handle cases where the parsed date is invalid or empty
if (!parsedDate) {
parsedDate = defaultValue || new Date(); // Use default value or current date
}
// Return the formatted date-time string or null if parsing fails
return parsedDate ? kendo.toString(parsedDate, "yyyy/MM/dd HH:mm:ss") : null;
}
/**
* Parses a Kendo DateTimePicker field value and returns it in "yyyy/MM/dd" format.
* If the field is empty or null, it uses a default value or the current date.
*
* @param {string} fieldName - The ID of the Kendo DateTimePicker field (without "#").
* @param {Date|null} [defaultValue=null] - The default value to use if the field is empty or null.
* @returns {string|null} - The formatted date string in "yyyy/MM/dd" format, or null if parsing fails.
*/
function fieldParseKendoDate(fieldName, defaultValue = null) {
// Cache the jQuery object for the field
const field = $("#" + fieldName);
const kendoPicker = field.data("kendoDatePicker");
let parsedDate = null;
// Check if the Kendo DateTimePicker has a valid value
if (kendoPicker && kendoPicker.value()) {
parsedDate = kendoPicker.value();
} else {
// Fallback to manually parsing the input field's value
const fieldValue = field.val();
if (fieldValue)
parsedDate = kendo.parseDate(fieldValue) || new Date(fieldValue);
// Handle cases where the parsed date is invalid or empty
if ((isNaN(parsedDate) || !parsedDate) && defaultValue)
parsedDate = defaultValue; // Use default value or current date
else
parsedDate = null;
}
// Return the parsed date in "yyyy/MM/dd" format, or null if parsing fails
return parsedDate ? kendo.toString(parsedDate, "yyyy/MM/dd") : null;
}
function fieldParseKendoDateTime(fieldName, defaultValue = null) {
// Cache the jQuery object for the field
const field = $("#" + fieldName);
const kendoPicker = field.data("kendoDateTimePicker");
let parsedDate = null;
// Check if the Kendo DateTimePicker has a valid value
if (kendoPicker && kendoPicker.value()) {
parsedDate = kendoPicker.value();
} else {
// Fallback to manually parsing the input field's value
const fieldValue = field.val();
if (fieldValue)
parsedDate = kendo.parseDate(fieldValue) || new Date(fieldValue);
// Handle cases where the parsed date is invalid or empty
if (isNaN(parsedDate) || !parsedDate)
parsedDate = defaultValue || new Date(); // Use default value or current date
}
// Return the parsed date in "yyyy/MM/dd" format, or null if parsing fails
return parsedDate ? kendo.toString(parsedDate, "yyyy/MM/dd HH:mm:ss") : null;
}