class EdeskSupports { #TokenConnect = ''; #UrlSupport = ''; #boxSupport = ''; #TypeSupport = ''; #IsLoadSupport = false; #IsLoadQuestion = false; #ObjectSupport = {}; #IsOpen = false; #colorConnect = ''; isMobileSupport = false; CSAT = ''; #properties = {}; startX = ''; startY = ''; startWidth = ''; startHeight = ''; startCallback = {}; constructor() {} /** * * @param {UrlSupport, TypeSupport, IdProduct, IdProject, IdApplication, Token, IsAuthenticated, TypeUser, IsFloat} params */ Init(params) { if (!this.#IsLoadSupport) { this.#setMobilePlatform(); this.#ObjectSupport = { IdProduct: params.IdProduct ?? null, IdProject: params.IdProject ?? null, IdApplication: params.IdApplication ?? null, tagClient: params.tagClient ?? null, TokenMain: params.Token ?? null, Token: params.Token ?? null, IsAuthenticated: params.IsAuthenticated ?? false, TypeUser: params.TypeUser ?? 'EXTERNO', IsFloat: !!(params.IsFloat || this.isMobileSupport), startCallback: params.startCallback ?? null, position: params.position ?? 'right', }; if (params.colorConnect && params.colorConnect.trim()) { this.#colorConnect = params.colorConnect; } const validate = this.#ValidateParams(params); if (validate != '') { return alert(validate); } localStorage.setItem('CONNECT Producto', this.#ObjectSupport.IdProduct); localStorage.setItem('CONNECT Proyecto', this.#ObjectSupport.IdProject); localStorage.setItem( 'CONNECT Aplicación', this.#ObjectSupport.IdApplication ); localStorage.setItem( 'CONNECT Cliente', sessionStorage.getItem('tagCliente') ); localStorage.setItem('connect_token', this.#ObjectSupport.Token); this.#UrlSupport = this.#extraerDominioBase(params.UrlSupport); this.#TypeSupport = params.TypeSupport; this.startCallback = params.startCallback; if (this.startCallback) { this.startCallback(); } this.#getProperties() .then((res) => { this.#properties = res.data.properties ? res.data.properties : {}; if ( 1 == this.#properties.new_online_support && 1 == params.TypeSupport ) { this.#loadNewSupport({ position: params.position }); return; } this.#CreateContainerSupport(); this.#loadOldSupport(params); }) .catch(() => { this.#loadOldSupport(params); }); } } InitSatisfaction(params) { let url = params.url.replace(/\/?$/, '/'); if (!url.includes('connect')) { url = url + 'connect/'; } let versionAds = '?v=' + this.#GenerateVersion(); this.#loadDynamicCss([`${url}css/satisfaccion.css${versionAds}`]); this.#cargarScript( `${url}js/satisfaction/satisfaction.js${versionAds}`, 'EdeskSatisfaction' ) .then(() => { this.CSAT = new EdeskSatisfaction(url); }) .catch((err) => console.error('Error cargando script encuesta:', err)); } #cargarScript(url, nameWait) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = url; script.onload = () => { if (nameWait) { // Esperar a que la variable global esté disponible this.#esperarVariable(nameWait, 5000).then(resolve).catch(reject); } }; script.onerror = reject; document.head.appendChild(script); }); } #esperarVariable(nombreVariable, timeout = 5000) { return new Promise((resolve, reject) => { const startTime = Date.now(); const checkVariable = () => { try { // Esta función crea una función global que retorna la variable si existe const variable = Function( `"use strict"; try { return ${nombreVariable}; } catch { return undefined; }` )(); if (variable !== undefined && variable !== null) { resolve(variable); return; } } catch { // ignoramos errores de referencia } if (Date.now() - startTime > timeout) { reject( new Error( `Timeout: ${nombreVariable} no disponible después de ${timeout}ms` ) ); return; } setTimeout(checkVariable, 50); }; checkVariable(); }); } /** * * @param {*} idProduct * @param {*} idProject * @param {*} Token */ Update(idProduct, idProject, token) { if (!this.#IsLoadSupport) return; if (!idProduct && !idProject && !token) return; this.#setSupportData(idProduct, idProject, token); if (this.#shouldUseNewOnlineSupport()) { edeskNewSupport.onUpdate( this.#ObjectSupport.IdProduct, this.#ObjectSupport.IdProject, this.#ObjectSupport.Token ); return; } this.#handleSupportType(); } // ------------------ Helper Methods ------------------ #setSupportData(idProduct, idProject, token) { this.#ObjectSupport.IdProduct = idProduct; this.#ObjectSupport.IdProject = idProject; this.#ObjectSupport.Token = token; localStorage.setItem('CONNECT Producto', idProduct); localStorage.setItem('CONNECT Proyecto', idProject); localStorage.setItem( 'CONNECT Cliente', sessionStorage.getItem('tagCliente') ); localStorage.setItem('connect_token', token); } #shouldUseNewOnlineSupport() { return this.#properties?.new_online_support == 1 && this.#TypeSupport == 1; } #handleSupportType() { if (this.#TypeSupport === 1) { this.#handleType1Support(); } else if (this.#TypeSupport === 2) { updateConnect( this.#ObjectSupport.IdProduct, this.#ObjectSupport.IdProject, this.#ObjectSupport.Token ); } } #handleType1Support() { try { if (sngConnect?.isConnected === true) return; } catch { // safely ignore } this.#boxSupport.remove(); this.#CreateContainerSupport(); this.#ShowSupport(); if (this.#IsOpen) { this.ShowContainerSupport(); } } #ShowSupport() { if (this.#IsLoadSupport) { try { if (this.#TypeSupport === 1) { creaSoporteConnect( 'init', this.#ObjectSupport.IdProduct, this.#boxSupport, this.#ObjectSupport.IdProject, this.#ObjectSupport.Token, this.#ObjectSupport.IdApplication, this.#ObjectSupport.TokenMain, this.#ObjectSupport.tagClient, this.#colorConnect ); } else if ( this.#ObjectSupport.IsAuthenticated && (this.#TypeSupport === 2 || this.#TypeSupport === 3 || this.#TypeSupport === 4) ) { creaEspera('login', '', this.#boxSupport); loginConnect( sessionStorage.getItem('tuMfBhBP'), sessionStorage.getItem('hrTm4Ch2'), sessionStorage.getItem('kses') ); } else { creaSoporteConnect( 'init', this.#ObjectSupport.IdProduct, this.#boxSupport, this.#ObjectSupport.IdProject, this.#ObjectSupport.Token, this.#ObjectSupport.IdApplication, this.#ObjectSupport.TokenMain, this.#colorConnect ); } this.#IsLoadQuestion = true; } catch { this.#IsLoadQuestion = false; } } } ShowContainerSupport(params = {}) { if (this.#isNewOnlineSupportActive()) return edeskNewSupport.showNewChat(); const areaRightVisible = $('.areaRight').hasClass('visible'); this.#hideLoginIfNeeded(areaRightVisible); const isContainerVisible = $('#boxSupportEdesk').hasClass('showContainer'); isContainerVisible ? this.#closeSupportContainer() : this.#openSupportContainer(); if (!this.#IsLoadQuestion && !params.openSupport) { this.#ShowSupport(); } } /* -------------------- 🔹 Métodos privados auxiliares -------------------- */ #isNewOnlineSupportActive() { return this.#properties.new_online_support == 1 && this.#TypeSupport == 1; } #hideLoginIfNeeded(areaRightVisible) { if ( areaRightVisible && !sessionStorage.getItem('id_usu_bpm') && !this.#ObjectSupport.IsFloat ) { try { if (typeof ocultaLogin === 'function') ocultaLogin(); } catch {} } } #closeSupportContainer() { this.#IsOpen = false; $('.areaRight').removeClass('visible'); $('#boxSupportEdesk').removeClass('showContainer'); if (this.#ObjectSupport.IsFloat) { this.#animateFloatBoxClose(); } else { this.#animateFixedBoxClose(); } } #openSupportContainer() { this.#IsOpen = true; $('.areaRight').addClass('visible'); $('#boxSupportEdesk').addClass('showContainer'); if (this.#ObjectSupport.IsFloat) { this.#removeEmptyRightAreaIfNeeded(); this.#animateFloatBoxOpen(); } else { this.#animateFixedBoxOpen(); } } /* -------------------- 🔹 Animaciones separadas -------------------- */ #animateFloatBoxClose() { const distance = this.isMobileSupport ? '-675px' : '-375px'; $('#boxSupportEdesk').animate( { right: distance }, this.isMobileSupport ? 900 : 400 ); } #animateFixedBoxClose() { $('.areaCentral').animate({ right: '0px' }, 400); $('.areaRight').animate({ right: '-295px', width: '295px' }, 400); } #removeEmptyRightAreaIfNeeded() { if (sessionStorage.getItem('id_usu_bpm')) { const contentRight = document.querySelector('.contentRight'); if (contentRight && contentRight.children.length === 0) { document.querySelector('.areaRight')?.remove(); } } } #animateFloatBoxOpen() { if (this.isMobileSupport) { $('#boxSupportEdesk').animate( { right: '0px', height: '100%', width: '100%', top: '40px' }, 400 ); } else { $('#boxSupportEdesk').animate({ right: '15px' }, 400); } } #animateFixedBoxOpen() { $('.areaCentral').animate({ right: '295px' }, 400); const areaRightProps = this.isMobileSupport ? { width: '100%', right: '0px' } : { width: '295px', right: '0px' }; $('.areaRight').animate(areaRightProps, 400); $('#boxSupportEdesk').animate({ right: '0px' }, 400); } HideContainerSupport(opt = false) { $('.iconConnectON').text('Soporte en Línea'); $('#boxSupportEdesk').removeClass('showContainer'); if (!this.#IsOpen) return; if (this.#ObjectSupport.IsFloat == true) { if (this.isMobileSupport) { $('#boxSupportEdesk').animate( { right: '-675px', }, 900 ); } else { $('#boxSupportEdesk').animate( { right: '-375px', }, 400 ); if ($('#boxSupportEdesk').hasClass('showContainer')) { $('#boxSupportEdesk').removeClass('showContainer'); } } } else { $('#boxSupportEdesk').animate( { right: '-295px', with: '0px', }, 400 ); if (opt) { $('.areaCentral').animate( { right: '0px', }, 400 ); $('.areaRight').animate( { right: '-295px', with: '295px', }, 400 ); } } this.#IsOpen = false; } async #getProperties() { return await this.getFetch(`${this.#UrlSupport}connect/api/GetProperties`, { id_prod: this.#encodeDataForGet(this.#ObjectSupport.IdProduct), id_proy: this.#encodeDataForGet(this.#ObjectSupport.IdProject), tkn: this.#encodeDataForGet(this.#ObjectSupport.Token), }); } async GetFrequentQuestions(params) { const DataRequest = { IdProd: params.IdProduct, IdProy: params.IdProject, Token: params.Token, Signed: params.Signed, IdApp: params.IdApplication ?? this.#ObjectSupport.IdApplication, TokenMain: this.#ObjectSupport.TokenMain, TagClient: sessionStorage.getItem('tagCliente'), }; try { let resultQuestions = await $.ajax({ url: `${this.#UrlSupport}connect/api/frequent_questions/get`, type: 'POST', data: DataRequest, headers: { Authorization: 'Bearer ' + this.#TokenConnect, }, }); return resultQuestions; } catch (error) { console.error(error); throw error; } } async AuthenticatedConnect(params) { const DataRequest = { UserName: params.UserName, Password: params.Password, Application: params.Application, Encrypt: true, }; try { let data = await $.ajax({ url: `${this.#UrlSupport}connect/api/login`, type: 'POST', data: DataRequest, }); if (Number.parseInt(data.code) == 1) { this.#TokenConnect = data.data.Token; return this.#TokenConnect; } else { return false; } } catch (error) { console.error(error); throw error; } } #boxConnectClassic() { let boxCon = document.createElement('div'); boxCon.setAttribute('class', 'containConnect'); boxCon.setAttribute('id', 'boxSupportEdesk'); $(boxCon).css('right', '-375px'); document.getElementsByClassName('contentRight')[0].appendChild(boxCon); this.#boxSupport = boxCon; this.#detectSwipe('boxSupportEdesk', this.#endTouch); } #CreateContainerSupport(params) { if (this.#ObjectSupport.IsFloat === true) { let boxSupport = document.createElement('div'); boxSupport.setAttribute('class', 'boxSupport'); boxSupport.setAttribute('id', 'boxSupportEdesk'); $('body').append(boxSupport); this.#boxSupport = boxSupport; this.#detectSwipe('boxSupportEdesk', this.#endTouch); document.addEventListener( 'focusin', function (e) { const openModal = document.querySelector('.modal.show'); if (openModal && !openModal.contains(e.target)) { e.stopImmediatePropagation(); } }, true ); } else { this.#boxConnectClassic(); } } initDrag(e) { this.startX = e.clientX; this.startY = e.clientY; this.startWidth = Number.parseInt( document.defaultView.getComputedStyle(p).width, 10 ); this.startHeight = Number.parseInt( document.defaultView.getComputedStyle(p).height, 10 ); document.documentElement.addEventListener('mousemove', this.doDrag, false); document.documentElement.addEventListener('mouseup', this.stopDrag, false); } doDrag(e) { p.style.width = this.startWidth + e.clientX - startX + 'px'; p.style.height = this.startHeight + e.clientY - startY + 'px'; } stopDrag(e) { document.documentElement.removeEventListener( 'mousemove', this.doDrag, false ); document.documentElement.removeEventListener( 'mouseup', this.stopDrag, false ); } // Función para cargar un script loadScriptNew(url, callback) { let script = document.createElement('script'); script.type = 'text/javascript'; if (script.readyState) { // IE script.onreadystatechange = function () { if ( script.readyState === 'loaded' || script.readyState === 'complete' ) { script.onreadystatechange = null; callback(); } }; } else { // Otros navegadores script.onload = function () { callback(); }; } script.src = url; document.getElementsByTagName('head')[0].appendChild(script); } // Función recursiva para cargar los scripts uno por uno loadScriptsNew(scripts, index, callback) { if (index < scripts.length) { this.loadScriptNew(scripts[index], () => { // Llamada recursiva para cargar el siguiente script this.loadScriptsNew(scripts, index + 1, callback); }); } if (index == scripts.length - 1) { callback(index); } if (scripts.length === 0) { callback(0); } } #GenerateVersion() { let date = new Date(); let dateStr = ('00' + (date.getMonth() + 1)).slice(-2) + '_' + ('00' + date.getDate()).slice(-2) + '_' + date.getFullYear(); return dateStr; } #loadDynamicCss(_css) { let head = document.getElementsByTagName('head')[0]; _css.forEach((href) => { if ($('link[href="' + href + '"]').length == 0) { let link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = href + '?v=' + this.#GenerateVersion(); head.appendChild(link); } }); } #getRoutesJs(TypeSupport) { let RoutesScripts = []; let Folder = 'connect'; let vers = '?v=' + this.#GenerateVersion(); if (TypeSupport === 1) { RoutesScripts = [ `${this.#UrlSupport}${Folder}/js/jquery.signalR-2.2.2.min.js${vers}`, `${this.#UrlSupport}${Folder}/js/usermedia.js${vers}`, `${this.#UrlSupport}${Folder}/js/jquery.textarea_autosize.js${vers}`, `${this.#UrlSupport}${Folder}/js/connectSignaling.js${vers}`, `${this.#UrlSupport}${Folder}/js/soporte.js${vers}`, `${ this.#UrlSupport }${Folder}/js/satisfaction/js/satisfaccion.js${vers}`, `${this.#UrlSupport}${Folder}/js/getScreenId.js${vers}`, // `${this.#UrlSupport}${Folder}/js/new-support/index.js`, ]; } else if (TypeSupport === 2 && this.#ObjectSupport.IsAuthenticated) { RoutesScripts = [ `${this.#UrlSupport}${Folder}/js/jquery.signalR-2.2.2.min.js${vers}`, `${this.#UrlSupport}${Folder}/js/usermedia.js${vers}`, `${this.#UrlSupport}${Folder}/js/jquery.textarea_autosize.js${vers}`, `${this.#UrlSupport}${Folder}/js/connectSignaling.js${vers}`, `${this.#UrlSupport}${Folder}/js/connect.js${vers}`, `${ this.#UrlSupport }${Folder}/js/satisfaction/js/satisfaccion.js${vers}`, `${this.#UrlSupport}${Folder}/js/getScreenId.js${vers}`, ]; } else if (TypeSupport === 3 && this.#ObjectSupport.IsAuthenticated) { RoutesScripts = [ `${this.#UrlSupport}${Folder}/js/jquery.signalR-2.2.2.min.js${vers}`, `${this.#UrlSupport}${Folder}/js/usermedia.js${vers}`, `${this.#UrlSupport}${Folder}/js/getScreenId.js${vers}`, `${this.#UrlSupport}${Folder}/js/jquery.textarea_autosize.js${vers}`, `${this.#UrlSupport}${Folder}/js/edoc/connectSignaling.js${vers}`, `${this.#UrlSupport}${Folder}/js/edoc/connectSignalingEDOC.js${vers}`, `${this.#UrlSupport}${Folder}/js/edoc/connectEDOC_1.0.0.js${vers}`, `${this.#UrlSupport}${Folder}/js/edoc/connect.js${vers}`, ]; } else if (TypeSupport === 4 && this.#ObjectSupport.IsAuthenticated) { RoutesScripts = [ `${this.#UrlSupport}${Folder}/js/usermedia.js${vers}`, `${this.#UrlSupport}${Folder}/js/jquery.signalR-2.2.2.min.js${vers}`, `${this.#UrlSupport}${Folder}/js/getScreenId.js${vers}`, `${this.#UrlSupport}${Folder}/js/jquery.textarea_autosize.js${vers}`, `${this.#UrlSupport}${Folder}/js/edoc/dekin/connectSignaling.js${vers}`, `${ this.#UrlSupport }${Folder}/js/edoc/dekin/connectSignalingEDOC.js${vers}`, `${ this.#UrlSupport }${Folder}/js/edoc/dekin/connectEDOC_1.0.0.js${vers}`, `${this.#UrlSupport}${Folder}/js/edoc/dekin/connect.js${vers}`, ]; } else { RoutesScripts = [ `${this.#UrlSupport}${Folder}/js/jquery.signalR-2.2.2.min.js${vers}`, `${this.#UrlSupport}${Folder}/js/usermedia.js${vers}`, `${this.#UrlSupport}${Folder}/js/jquery.textarea_autosize.js${vers}`, `${this.#UrlSupport}${Folder}/js/connectSignaling.js${vers}`, `${this.#UrlSupport}${Folder}/js/soporte.js${vers}`, `${this.#UrlSupport}${Folder}/js/getScreenId.js${vers}`, `${ this.#UrlSupport }${Folder}/js/satisfaction/js/satisfaccion.js${vers}`, ]; } return RoutesScripts; } #getRoutesCss(TypeSupport) { let Folder = 'connect'; let RoutesCss = [ `${this.#UrlSupport}${Folder}/css/InitSupport.css`, `${this.#UrlSupport}${Folder}/css/satisfaccion.css`, ]; if (TypeSupport === 1) { RoutesCss.push(`${this.#UrlSupport}${Folder}/css/connect.css`); } else if (TypeSupport === 2 && this.#ObjectSupport.IsAuthenticated) { RoutesCss.push(`${this.#UrlSupport}${Folder}/css/connect.css`); } else if (TypeSupport === 3 && this.#ObjectSupport.IsAuthenticated) { RoutesCss.push(`${this.#UrlSupport}${Folder}/css/edoc/connect.css`); } else if (TypeSupport === 4 && this.#ObjectSupport.IsAuthenticated) { RoutesCss.push(`${this.#UrlSupport}${Folder}/css/edoc/connect.css`); } else { RoutesCss.push(`${this.#UrlSupport}${Folder}/css/connect.css`); } return RoutesCss; } #ValidateParams(params) { const obj = this.#ObjectSupport; const setIfEmpty = (key, sessionKey) => { if (!obj[key]) obj[key] = sessionStorage.getItem(sessionKey); }; params.TypeSupport = params.TypeSupport || 1; if (!params.UrlSupport) return 'Dominio del soporte obligatorio'; obj.TypeUser = obj.TypeUser || sessionStorage.getItem('tipoUsu') || 'EXTERNO'; obj.IsAuthenticated = !!sessionStorage.getItem('id_usu_bpm'); setIfEmpty('IdProduct', 'id_prod'); setIfEmpty('IdProject', 'id_proy'); setIfEmpty('IdApplication', 'id_apl'); setIfEmpty('Token', 'kses'); setIfEmpty('TokenMain', 'kses'); setIfEmpty('tagClient', 'tagCliente'); const requiredFields = { IdProduct: 'Producto obligatorio', IdProject: 'Proyecto obligatorio', IdApplication: 'Aplicación obligatoria', Token: 'Token obligatorio', }; for (const [key, message] of Object.entries(requiredFields)) { if (!obj[key]) return message; } return ''; } #setMobilePlatform() { let navegador = navigator.userAgent; if ( navegador.match(/Android/i) || navegador.match(/webOS/i) || navegador.match(/iPhone/i) || navegador.match(/iPad/i) || navegador.match(/iPod/i) || navegador.match(/BlackBerry/i) || navegador.match(/Windows Phone/i) ) { this.isMobileSupport = true; } } #detectSwipe(el, func) { let swipe_det = new Object(); swipe_det.initX = 0; swipe_det.initY = 0; swipe_det.finX = 0; swipe_det.finY = 0; let min_x = 20; //min x swipe for horizontal swipe let max_x = 40; //max x difference for vertical swipe let min_y = 40; //min y swipe for vertical swipe let max_y = 50; //max y difference for horizontal swipe let direc = ''; let ele = document.getElementById(el); ele.addEventListener( 'touchstart', function (e) { let t = e.touches[0]; swipe_det.finX = t.screenX; swipe_det.initX = t.screenX; swipe_det.initY = t.screenY; }, { passive: false } ); ele.addEventListener( 'touchmove', function (e) { let t = e.touches[0]; swipe_det.finX = t.screenX; swipe_det.finY = t.screenY; }, { passive: false } ); ele.addEventListener( 'touchend', function (e) { const { initX, initY, finX, finY } = swipe_det; let direc = ''; const isHorizontal = Math.abs(finX - initX) > min_x && Math.abs(finY - initY) < max_y; const isVertical = Math.abs(finY - initY) > min_y && Math.abs(finX - initX) < max_x; if (isHorizontal) { const total = finX - initX; if (total > 150) direc = 'r'; else if (total < 0) direc = 'l'; } else if (isVertical) { direc = finY > initY ? 'd' : 'u'; } if (direc && typeof func === 'function') { func(el, direc); } }, false ); } #endTouch(el, d) { if (d == 'r') { edeskSupports.HideContainerSupport(); } } #extraerDominioBase(url) { // Eliminar espacios en blanco al inicio y final let urlLimpia = url.trim(); // Verificar si la URL contiene "/connect" o "/connect/" const indexConnect = urlLimpia.indexOf('/connect'); if (indexConnect !== -1) { // Extraer solo la parte antes de "/connect" urlLimpia = urlLimpia.substring(0, indexConnect); } // Asegurar que no termine en "/" if (urlLimpia.endsWith('/')) { return urlLimpia; } else { return urlLimpia + '/'; } } /** * Performs a fetch request with timeout capability * @param {string} resource - URL to fetch * @param {Object} options - Fetch options * @param {number} [options.timeout=8000] - Timeout in milliseconds * @returns {Promise} - Fetch response */ async fetchWithTimeout(resource, options = {}) { const { timeout = 8000 } = options; // Create abort controller for timeout handling const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeout); try { // Execute fetch with abort signal const response = await fetch(resource, { ...options, signal: controller.signal, }); // Check if response is ok if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response; } catch (error) { // Enhance error messages if (error.name === 'AbortError') { throw new Error(`Request timeout after ${timeout}ms: ${resource}`); } throw error; } finally { clearTimeout(timeoutId); } } /** * Performs a GET request with proper URL parameter handling * @param {string} url - Base URL for the request * @param {Object} params - URL parameters as key-value pairs * @param {Object} [options={}] - Additional fetch options * @returns {Promise} - Parsed JSON response */ async getFetch(url, params = {}, options = {}) { try { // Properly handle URL parameters const queryParams = new URLSearchParams(); Object.entries(params).forEach(([key, value]) => { queryParams.append(key, value); }); // Append parameters to URL if they exist const requestUrl = Object.keys(params).length > 0 ? `${url}?${queryParams.toString()}` : url; const response = await this.fetchWithTimeout(requestUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, timeout: options.timeout || 6000, ...options, }); return await response.json(); } catch (error) { console.error('GET request failed:', error.message); throw error; } } /** * Performs a POST request with proper JSON handling * @param {string} url - URL for the request * @param {Object} body - Request payload (will be JSON stringified) * @param {Object} [options={}] - Additional fetch options * @returns {Promise} - Parsed JSON response */ async postFetch(url, body = {}, options = {}) { try { console.log('POST request payload:', body); const response = await fetchWithTimeout(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify(body), timeout: options.timeout || 6000, ...options, }); return await response.json(); } catch (error) { console.error('POST request failed:', error.message); throw error; } } #encodeDataForGet(value) { return value != null && value !== undefined ? encodeURIComponent(value) : null; } #loadOldSupport(params) { const scripts = this.#getRoutesJs(params.TypeSupport); const css = this.#getRoutesCss(params.TypeSupport); this.#loadDynamicCss(css); this.loadScriptsNew(scripts, 0, (res) => { this.#IsLoadSupport = true; if (2 === this.#TypeSupport) { updateConnect( this.#ObjectSupport.IdProduct, this.#ObjectSupport.IdProject, this.#ObjectSupport.Token ); } const { search } = window.location; const urlParam = new URLSearchParams(search); let tokenSupport = urlParam.get('token_support'); const params = new URLSearchParams(window.location.search); const support = params.get('openSupport'); if (tokenSupport && 1 === this.#TypeSupport) { setTimeout(() => { this.ShowContainerSupport({ openSupport: true }); setTimeout(() => { ValidateProdProy(); openSupportExternal(this.#boxSupport, tokenSupport); }, 500); }, 1000); } else if (support) { setTimeout(() => { this.ShowContainerSupport({ openSupport: true }); setTimeout(() => { ValidateProdProy(); openSupportDirect(this.#boxSupport); }, 500); }, 1000); } }); } #loadNewSupport(obj = {}) { let versionAds = '?v=' + this.#GenerateVersion(); this.#cargarScript( `${ this.#UrlSupport }connect/js/clientApp/bundleSupportAds.js${versionAds}`, 'edeskNewSupport' ) .then(() => { if (window.edeskNewSupport?.onMounted) { window.edeskNewSupport.onMounted({ properties: this.#properties, position: obj.position, }); this.#IsLoadSupport = true; } else { console.error('edeskNewSupport.onMounted no está disponible.'); } }) .catch((err) => console.error('Error cargando script:', err)); } } window.edeskSupports = new EdeskSupports();