const VeryService = { GET: function (url, token) { showLoadingScreen(); const tk = token ? token : localStorage.accessToken; return fetch(url, { headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: `Bearer ${tk}` } }).then(r => { hideLoadingScreen(); const contentType = r.headers.get("content-type"); if (r.ok) { try { if (contentType === 'application/json') return r.json(); return r.text(); } catch (e) { console.error("Erro inesperado ", e); throw "Erro inesperado: " + e; } } else { if (r.status === 500) { throw "Servidor não responde apropriadamente."; } if (r.status === 404) { throw "API não encontrada no servidor: " + url; } if (r.status === 401) { console.log("localStorage.accessToken: ", localStorage.accessToken) if (localStorage.accessToken) { r.json().then(erro => { console.error("Erro da requisicao: ", erro); // localStorage.setItem("page", window.location.pathname); // setTimeout(function () { window.location.replace("/login"); }, 1000); return; }); } throw "Acesso não permitido: " + url; } if (r.status === 403) { //window.location.replace("/"); throw "Acesso não permitido: " + url; } return r.json().then(erro => { console.error("Erro da requisicao: ", erro); if (erro.status === 500) { if (erro.message.includes("signature does not match") || erro.message.includes("JWT expired") ) { throw "Problema ao verificar credenciais do usuário. Efetue novo login."; } else { throw (erro && erro.message) ? erro.message : ""; } } else { throw erro; } }); } }).catch(erro =>{ console.error("---->", erro); hideLoadingScreen(); return { success: false, msg: erro } }); }, POST: function (url, dado) { showLoadingScreen(); return fetch(url, { method: "POST", body: JSON.stringify(dado), headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: `Bearer ${localStorage.accessToken}` } }).then(r => { hideLoadingScreen(); if (r.ok) { return r.json(); } else { if (r.status === 500) { throw "Servidor não responde apropriadamente."; } if (r.status === 401) { console.error("Erro da requisicao: ", r); throw r; //"Usuário não atenticado"; } if (r.status === 403) { //window.location.replace("/"); throw "Acesso não permitido: " + url; } return r.json().then(erro => { console.error("Erro da requisicao: ", erro); if (erro.status === 500) { if (erro.message.includes("signature does not match") || erro.message.includes("JWT expired") ) { throw "Problema ao verificar credenciais do usuário. Efetue novo login."; } else { throw (erro && erro.message) ? erro.message : ""; } } else { throw erro; } }); } }); }, GETHML: function (url, token) { showLoadingScreen(); const tk = token ? token : localStorage.accessToken; return fetch(url, { headers: { Authorization: `Bearer ${tk}` } }).then(r => { hideLoadingScreen(); if (r.ok) { try { return r.text(); } catch (e) { console.error("Erro inesperado ", e); throw "Erro inesperado: " + e; } } else { if (r.status === 500) { throw "Servidor não responde apropriadamente."; } if (r.status === 404) { throw "API não encontrada no servidor: " + url; } if (r.status === 401) { console.log("localStorage.accessToken: ", localStorage.accessToken) if (localStorage.accessToken) { r.json().then(erro => { console.error("Erro da requisicao: ", erro); // localStorage.setItem("page", window.location.pathname); // setTimeout(function () { window.location.replace("/login"); }, 1000); return; }); } throw "Acesso não permitido: " + url; } if (r.status === 403) { //window.location.replace("/"); throw "Acesso não permitido: " + url; } return r.json().then(erro => { console.error("Erro da requisicao: ", erro); if (erro.status === 500) { if (erro.message.includes("signature does not match") || erro.message.includes("JWT expired") ) { throw "Problema ao verificar credenciais do usuário. Efetue novo login."; } else { throw (erro && erro.message) ? erro.message : ""; } } else { throw erro; } }); } }); }, GETTXT: function (url, token) { showLoadingScreen(); const tk = token ? token : localStorage.accessToken; return fetch(url, { headers: { Authorization: `Bearer ${tk}` } }).then(r => { hideLoadingScreen(); if (r.ok) { try { return r.text(); } catch (e) { console.error("Erro inesperado ", e); throw "Erro inesperado: " + e; } } else { if (r.status === 500) { throw "Servidor não responde apropriadamente."; } if (r.status === 404) { throw "API não encontrada no servidor: " + url; } if (r.status === 401) { console.log("localStorage.accessToken: ", localStorage.accessToken) if (localStorage.accessToken) { r.json().then(erro => { console.error("Erro da requisicao: ", erro); // localStorage.setItem("page", window.location.pathname); // setTimeout(function () { window.location.replace("/login"); }, 1000); return; }); } throw "Acesso não permitido: " + url; } if (r.status === 403) { //window.location.replace("/"); throw "Acesso não permitido: " + url; } return r.json().then(erro => { console.error("Erro da requisicao: ", erro); if (erro.status === 500) { if (erro.message.includes("signature does not match") || erro.message.includes("JWT expired") ) { throw "Problema ao verificar credenciais do usuário. Efetue novo login."; } else { throw (erro && erro.message) ? erro.message : ""; } } else { throw erro; } }); } }); }, } class VeryPage { constructor(idHidden) { this.idHidden = idHidden; } trataTipo(dado, tipo) { if (!dado) return ''; if (tipo === 'String') { if (typeof dado === "object") { return JSON.stringify(dado); } if (typeof dado === 'string') { if (dado.indexOf("data:image/") >= 0) { const el = document.createElement("img") el.src = dado; return el; } } return dado; } } gerar(callBackFunction) { console.log('>>>>gerar<<<<') const el = document.getElementById(this.idHidden); const input = document.querySelector('[nome="pagina"]'); const val = input.value; const js = JSON.parse(val); VeryService.POST("/api/security/model/montaPaginaDinamica", js).then(r => { if (r.success) { console.log('==========') console.log(r) console.log('==========') if (js.tpPagina === 'table') { const tbody = el.querySelector("tbody"); tbody.innerHTML = r.html } else if (js.tpPagina === 'fields') { const conteudo = el.querySelector('[name="conteudoField"]'); const modelo = conteudo.querySelector('[name="modelo"]');//.cloneNode(); console.log(modelo); const header = js.header; modelo.setAttribute("style", "display:none;") if (Array.isArray(r.js)) { for (let x in r.js) { const obj = r.js[x]; const div = document.createElement("div"); const clone = modelo.cloneNode(true); let style = clone.getAttribute("style"); console.log(style); if (style.indexOf('display:none') >= 0) { style = style.replace('display:none', 'display:inline') clone.setAttribute("style", style); } for (let h of header) { if (!h.mostrar) continue; const key = h.key; let val = obj[key]; val = this.trataTipo(val, h.tipo); const span = document.createElement('span'); if (typeof val === 'object') span.appendChild(val); else span.innerHTML = val; const p = clone.querySelector('[name="' + key + '"]'); if (!p) continue; p.appendChild(span); } div.appendChild(clone); conteudo.append(div) } } else { const div = document.createElement("div"); for (let h of header) { if (!h.mostrar) continue; const key = h.key; const clone = modelo.cloneNode(true); const val = this.trataTipo(r.js[key], h.tipo); const p = clone.querySelector('[name="' + key + '"]'); const span = document.createElement('span'); span.innerHTML = val; p.appendChild(span); div.appendChild(p); } conteudo.append(div) } } else { const newDiv = document.createElement('div'); newDiv.innerHTML = r.html el.appendChild(newDiv); } if (callBackFunction) callBackFunction(); } else { alert(r.msg) } }) } } function showLoadingScreen() { document.getElementById('very-loading-overlay').style.display = 'flex'; } function hideLoadingScreen() { document.getElementById('very-loading-overlay').style.display = 'none'; } function fecharDialog(param) { const dialog = document.querySelector(".vy-dialog"); if (dialog) { dialog.close(); dialog.classList.add("hidden"); dialog.classList.remove("vy-dialog"); } if (param) { if (typeof param === 'function') param(); } if (rootCallBack) rootCallBack(param); } function handleMascaraTelefone(e) { var value = e.value; var r = value.replace(/\D/g, ""); r = r.replace(/^0/, ""); if (r.length > 10) { r = r.replace(/^(\d\d)(\d{5})(\d{4}).*/, "($1) $2-$3"); } else if (r.length > 5) { r = r.replace(/^(\d\d)(\d{4})(\d{0,4}).*/, "($1) $2-$3"); } else if (r.length > 2) { r = r.replace(/^(\d\d)(\d{0,5})/, "($1) $2"); } else { r = r.replace(/^(\d*)/, "($1"); } e.value = r; } function handleMascaraCPF(e) { var value = e.value; // Remove tudo que não for dígito value = value.replace(/\D/g, ""); // Limita a 11 dígitos para o CPF value = value.slice(0, 11); // Aplica a máscara: 3 dígitos.3 dígitos.3 dígitos-2 dígitos if (value.length > 3) { value = value.replace(/(\d{3})(\d)/, "$1.$2"); } if (value.length > 7) { value = value.replace(/(\d{3})(\d)/, "$1.$2"); } if (value.length > 11) { value = value.replace(/(\d{3})(\d{2})$/, "$1-$2"); } e.value = value; } function validaCPF(cpf) { var Soma = 0; var Resto; var strCPF = String(cpf).replace(/[^\d]/g, ''); if (strCPF.length !== 11) return false if ([ '00000000000', '11111111111', '22222222222', '33333333333', '44444444444', '55555555555', '66666666666', '77777777777', '88888888888', '99999999999', ].indexOf(strCPF) !== -1) return false for (i = 1; i <= 9; i++) Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (11 - i); Resto = (Soma * 10) % 11 if ((Resto == 10) || (Resto == 11)) Resto = 0 if (Resto != parseInt(strCPF.substring(9, 10))) return false Soma = 0; for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (12 - i) Resto = (Soma * 10) % 11 if ((Resto == 10) || (Resto == 11)) Resto = 0 if (Resto != parseInt(strCPF.substring(10, 11))) return false return true } function formataMesAno(time) { if (!time) return ''; const dt = new Date(time); const formatter = new Intl.DateTimeFormat('pt-BR', { month: 'long', year: 'numeric' }); return formatter.format(dt); } let rootCallBack; function showDialog(titulo, corpo, btOk, btFecha, callback) { // const dialog = document.querySelector("dialog"); let dialog = document.getElementById("dialog") if (!dialog) { dialog = document.querySelector("dialog"); } rootCallBack = callback; if (dialog) { const body = dialog.querySelector(".vy-dialog-body"); const footer = dialog.querySelector(".vy-dialog-footer") if (titulo) { const header = dialog.querySelector(".vy-dialog-header").querySelector("h2"); header.innerHTML = titulo; } if (footer) { const btnOk = footer.querySelector(".vy-action-button"); const btnCancel = footer.querySelector(".vy-cancel-button"); if (btOk) { if (btnOk) btnOk.classList.remove("hidden"); if (btnOk) btnOk.innerHTML = btOk; } else { if (btnOk) btnOk.classList.add("hidden"); } if (btFecha) { if (btnCancel) btnCancel.innerHTML = btFecha; } } if (corpo) { if (typeof corpo === 'string') { body.innerHTML = corpo; } else { body.innerHTML = ""; body.appendChild(corpo); } } dialog.classList.remove("hidden"); dialog.classList.add("vy-dialog"); // dialog.showModal(); } } class Paginacao { constructor(idPage, dados, pageSize, callback) { this.idPage = idPage; this.pageSize = pageSize ? pageSize : 5; this.page = 0; this.dados = dados; this.callback = callback; this.field = null; this.order = null; } handleRowPerPage(e) { console.log('>>handleBackPage<<', e.target.value); this.pageSize = e.target.value; console.log(this.dados); this.update(); } setDados(d) { this.dados = d; this.update(); } setCallBack(cal) { this.callback = cal; } handleBackPage() { console.log('>>handleBackPage<<') this.page = this.page - 1;//(this.page +1)* this.pageSize; console.log(this.getDadoPaginado()); this.update(); } handleNextPage() { console.log('>>handleNextPage<<') this.page = this.page + 1;//(this.page +1)* this.pageSize; console.log(this.getDadoPaginado()); this.update(); } getDadoPaginado() { return this.dados.slice( this.page * this.pageSize, (this.page + 1) * this.pageSize ); } setSort(e, key) { const cel = e.target; const nodes = cel.parentNode.children; for (const el of nodes) { el.classList.remove("th-sort-asc", "th-sort-desc"); } if (this.order === null) { cel.classList.add("th-sort-asc"); this.order = 'asc' this.field = key; } else { if (this.order === 'asc') { cel.classList.add("th-sort-desc"); this.order = 'desc' this.field = key; } else { cel.classList.add("th-sort-asc"); this.order = 'asc' this.field = key; } } this.sort() } sort() { const arr = this.dados.sort((a, b) => { const key = this.field if (this.order === 'asc') { return a[key].localeCompare(b[key]); } else { return b[key].localeCompare(a[key]); } }); this.dados = arr; this.update(); } update() { let pg = null; if (this.idPage) { pg = document.getElementById("pg-" + this.idPage) } else { pg = document.querySelector(".vy-pagination"); } const title = pg.querySelector('[name="title"]'); const btnNext = pg.querySelector('[name="btnNext"]'); const btnBack = pg.querySelector('[name="btnBack"]'); btnBack.disabled = false; btnNext.disabled = false; let init = (this.page * this.pageSize); let fim = (this.page + 1) * this.pageSize; if (init <= 0) { btnBack.disabled = true; } if (fim >= this.dados.length) { fim = this.dados.length; btnNext.disabled = true; } title.textContent = init + "-" + fim + " de " + this.dados.length; this.callback(); } } var selectedRow = null function toggleVyMenuClick (event, element){ event.stopPropagation(); const menu = document.getElementById('vy-menu'); if( !menu)return; selectedRow = element.getAttribute('data-item-id'); event.preventDefault(); let mouseX = event.clientX; const mouseY = event.clientY; const w = menu.offsetWidth===0?100:menu.offsetWidth; const ww = window.innerWidth; if( mouseX + w > ww) mouseX = mouseX - w; menu.style.top = `${mouseY}px`; menu.style.left = `${mouseX}px`; menu.style.display = 'block'; } function hideVyMenuMenu() { const menu = document.getElementById('vy-menu'); if( menu) menu.style.display = 'none'; } window.addEventListener('click', hideVyMenuMenu);