var GlobElmentos = false;
var GlobGetSession = false;
var PageStart = false;
var PageAtual = false;
var loaders = {};
var scripts = [];
function loadProgressElement(id, show) {
const container = document.getElementById(id);
if (!container) return;
const progressBar = container.querySelector("progress");
if (!progressBar) return;
if (!loaders[id]) {
loaders[id] = {
progress: 0,
animating: false,
frameId: null,
};
}
const loader = loaders[id];
if (show) {
loader.progress = 0;
loader.animating = true;
progressBar.value = loader.progress;
container.classList.remove("hidden");
const animate = () => {
if (!loader.animating) return;
if (loader.progress < 90) {
loader.progress += 0.5;
progressBar.value = loader.progress;
loader.frameId = requestAnimationFrame(animate);
} else {
cancelAnimationFrame(loader.frameId);
}
};
loader.frameId = requestAnimationFrame(animate);
} else {
loader.animating = false;
const animateToEnd = () => {
if (loader.progress < 100) {
loader.progress += 2;
progressBar.value = loader.progress;
requestAnimationFrame(animateToEnd);
} else {
setTimeout(() => {
container.classList.add("hidden");
progressBar.value = 0;
// Limpa o estado se quiser que seja resetado para próximas execuções
delete loaders[id];
}, 300);
}
};
animateToEnd();
}
}
function formatarMensagem(texto) {
// chat
if (!texto) return "";
// Processa listas de opções (para mensagens de bot)
if (
texto.includes("Selecione uma opção") ||
texto.includes("Por favor, escolha")
) {
const lines = texto.split("\n");
return lines
.map((line) => {
if (line.match(/^\d+\.\s/) || line.match(/^-\s/)) {
return `
${line}
`;
}
return line + "
";
})
.join("");
}
// Formatação geral
return texto
.replace(/\*\*(.*?)\*\*/g, "$1") // Negrito
.replace(/\*(.*?)\*/g, "$1") // Itálico
.replace(/\n/g, "
") // Quebras de linha
.replace(
/(https?:\/\/[^\s]+)/g,
'$1'
); // Links
}
function loadElement(target, bl) {
let $element;
// Identifica se é jQuery, HTML ou string (id)
if (typeof target === "string") {
$element = $(`#${target}`);
} else if (isJqueryElement(target)) {
$element = target;
} else if (isHtmlElement(target)) {
$element = $(target);
} else {
console.warn("Elemento inválido passado para loadElement");
return;
}
if (!$element.length) return;
const id = $element.attr("id");
if (!id) {
console.warn("Elemento precisa ter um ID para usar loadElement");
return;
}
const spinnerId = `${id}Load`;
if (bl) {
// Adiciona spinner se não existir
if (!$(`#${spinnerId}`).length) {
$element.append(`
`);
}
$element.prop("disabled", true);
} else {
$(`#${spinnerId}`).remove();
$element.prop("disabled", false);
}
}
function avisos(titulo, mensagem, tipo = "primary") {
const toastContainer = document.getElementById("liveToast");
// Mapeamento de cores com valores hexadecimais
const colorMap = {
primary: {
bg: "#DBEAFE", // blue-100
border: "#BFDBFE", // blue-200
dot: "#3B82F6" // blue-500
},
success: {
bg: "#D1FAE5", // green-100
border: "#A7F3D0", // green-200
dot: "#10B981" // green-500
},
warning: {
bg: "#FEF3C7", // yellow-100
border: "#FDE68A", // yellow-200
dot: "#F59E0B" // yellow-500
},
error: {
bg: "#FEE2E2", // red-100
border: "#FECACA", // red-200
dot: "#EF4444" // red-500
},
info: {
bg: "#E0F2FE", // sky-100
border: "#BAE6FD", // sky-200
dot: "#0EA5E9" // sky-500
}
};
// Usar tipo padrão se não for válido
const colors = colorMap[tipo] || colorMap.primary;
// Criar elemento toast
const toast = document.createElement("div");
toast.style.cssText = `
max-width: 24rem;
width: 100%;
background-color: white;
border-radius: 0.5rem;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
margin-bottom: 0.5rem;
overflow: hidden;
border: 1px solid ${colors.border};
animation: fadeInToast 0.3s ease-in-out;
`;
// Conteúdo do toast
toast.innerHTML = `
${mensagem}
`;
// Adicionar ao container
toastContainer.appendChild(toast);
// Remover automaticamente após 5 segundos com animação
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transition = 'opacity 0.3s ease';
setTimeout(() => toast.remove(), 300);
}, 5000);
}
function primeiroCaracterMaiusculo(variavel) {
variavel = manipula(variavel);
if (variavel != " - ") {
variavel = variavel.toLowerCase().replace(/(?:^|\s)\S/g, function (a) {
return a.toUpperCase();
});
}
return variavel;
}
function manipula(item) {
if (
item == null ||
item == "undefined" ||
item == "" ||
item == 0 ||
item == "NaN"
) {
return " - ";
} else {
return item;
}
}
function formatarData(data) {
// Se estiver vindo como string ISO, transforma em objeto Date
const dateObj = new Date(data);
// Verifica se a data é válida
if (isNaN(dateObj.getTime())) {
return " - ";
}
// Extrai os dados
const dia = String(dateObj.getDate()).padStart(2, "0");
const mes = String(dateObj.getMonth() + 1).padStart(2, "0"); // meses são base 0
const ano = dateObj.getFullYear();
const horas = String(dateObj.getHours()).padStart(2, "0");
const minutos = String(dateObj.getMinutes()).padStart(2, "0");
const segundos = String(dateObj.getSeconds()).padStart(2, "0");
// Retorna no formato desejado
return `${dia}/${mes}/${ano} ${horas}:${minutos}:${segundos}`;
}
function formatDate(date) {
return date.toISOString().split("T")[0]; // Retorna YYYY-MM-DD
}
function formatTimestampToDuration(timestamp) {
if (!timestamp) return "00:00:00";
const diff = (Date.now() - timestamp * (timestamp < 1e12 ? 1000 : 1)) / 1000;
if (diff < 0) return "00:00:00";
const pad = (n) => n.toString().padStart(2, "0");
return [
pad(Math.floor(diff / 3600)),
pad(Math.floor((diff % 3600) / 60)),
pad(Math.floor(diff % 60)),
].join(":");
}
function formatSegToDuration(segundos) {
if (typeof segundos !== "number" || isNaN(segundos)) return "00:00:00";
const horas = Math.floor(segundos / 3600);
const minutos = Math.floor((segundos % 3600) / 60);
const segundosRestantes = segundos % 60;
const pad = (n) => String(n).padStart(2, "0");
return `${pad(horas)}:${pad(minutos)}:${pad(segundosRestantes)}`;
}
function formatarHora(dateTimeString) {
if (!dateTimeString) return "";
const [datePart, timePart] = dateTimeString.split(" ");
if (!timePart) return "";
return timePart.substring(0, 5); // Retorna apenas HH:MM
}
function formatarTelefone(numero) {
if (!numero) return "--";
// Remove todos os caracteres não numéricos
const apenasNumeros = numero.toString().replace(/\D/g, "");
// Verifica se tem código de país (55) e remove
let numerosFormatados = apenasNumeros;
if (apenasNumeros.length > 11 && apenasNumeros.startsWith("55")) {
numerosFormatados = apenasNumeros.substring(2);
}
// Aplica a formatação de acordo com o tamanho
if (numerosFormatados.length === 11) {
// Com 9º dígito: (47) 99286-9383
return numerosFormatados.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
} else if (numerosFormatados.length === 10) {
// Sem 9º dígito: (47) 9286-9383
return numerosFormatados.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
} else if (numerosFormatados.length === 9) {
// Apenas número com 9º dígito: 99286-9383
return numerosFormatados.replace(/(\d{5})(\d{4})/, "$1-$2");
} else if (numerosFormatados.length === 8) {
// Apenas número sem 9º dígito: 9286-9383
return numerosFormatados.replace(/(\d{4})(\d{4})/, "$1-$2");
}
// Se não se encaixar em nenhum padrão, retorna o original
return numero;
}
function escapeHtml(unsafe) {
if (!unsafe) return "";
return unsafe
.toString()
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function carregarGlobais() {
// Carrega os elementos globais
if (GlobElmentos) return;
GlobElmentos = {
NomePage: $("#nomePage"),
Conteudo: $("#conteudoPage"),
LoadSessao: $("#loadSessao"),
PageCarregada: $(".NloadSessao"),
MenuPrincipal: $("#menu-principal"),
NotificarUsuario: $("#bash-notification-icon"),
};
}
function getUserSession() {
if (!localStorage.getItem("usuario")) return;
return JSON.parse(localStorage.getItem("usuario"));
}
var gestaoList = [];
function carregarMenu() {
carregarGlobais();
GlobElmentos.MenuPrincipal.empty();
let html = "";
let controleGestao = false;
GlobGetSession.sort((a, b) => a.peso - b.peso).forEach((e) => {
if (e.url.split("/").length == 1 && e.bl_menu) {
html += ``;
} else if (e.url.split("/").length < 4 && e.url.split("/")[0] == "gestao") {
if (!controleGestao) {
controleGestao = [];
}
controleGestao.push(e);
}
});
token = localStorage.getItem("token");
html += ` Monitoria`;
if (controleGestao) {
html += '';
html += 'Gestão';
controleGestao.forEach((e) => {
if (e.bl_menu) {
html += ``;
} else {
splitE = e.url.split("/");
pos = splitE[0] + "/" + splitE[1];
if (!gestaoList[pos]) {
gestaoList[pos] = [];
}
gestaoList[pos].push(e);
}
});
}
GlobElmentos.MenuPrincipal.append(html);
}
function carregarPage(page) {
const overlay = document.getElementById("offcanvas-overlay");
const offcanvas = document.getElementById("offcanvas-menu");
if (page == PageAtual) return false;
PageAtual = page;
localStorage.setItem("PageAtual", PageAtual);
$(`.menu-item a`).removeClass("bg-primary");
$("#menu-" + page.replaceAll("/", "-")).addClass("bg-primary");
GlobElmentos.Conteudo.empty();
let pageName = false;
GlobGetSession.forEach((e) => {
if (e.url == page) {
pageName = e.nome;
}
});
if (!pageName) {
avisos("Sessão", "Usuário não possui acesso a esta tela", "error");
carregarPage(PageStart);
return false;
}
if (typeof window.destroySessao === "function") {
try {
window.destroySessao();
delete window.destroySessao;
} catch (e) {
console.warn("Erro ao destruir a sessão anterior:", e);
}
}
GlobElmentos.NomePage.text(pageName);
// GlobElmentos.Conteudo.load(`/sessao/${page}/index.html`);
if (
page == "atendimentos" &&
localStorage.getItem("limparAtendimento") == "false" &&
localStorage.getItem("oldPage") != "atendimentos"
) {
localStorage.setItem("limparAtendimento", true);
window.location.reload(true);
} else {
if (typeof window.bashAtendimentoOmni != "undefined") {
window.bashAtendimentoOmni.destroy();
}
if (typeof window.bashAtendimento != "undefined") {
window.bashAtendimento.destroy();
}
localStorage.setItem("limparAtendimento", false);
}
GlobElmentos.Conteudo.load(
`/sessao/${page}/index.html?_=${new Date().getTime()}`
);
// GlobElmentos.LoadSessao.hide(500);
// GlobElmentos.PageCarregada.show(1500);
GlobElmentos.LoadSessao.fadeOut(1000, function () {
GlobElmentos.PageCarregada.fadeIn(1000);
$("body").removeClass("overflow-hidden");
const chat = wbCreateApp();
$("body").append(chat);
});
offcanvas.classList.add("translate-x-full");
overlay.classList.add("hidden");
localStorage.setItem("oldPage", PageAtual);
}
function temaSystem(tema) {
if (tema) {
localStorage.setItem("tema", tema);
} else {
tema = localStorage.getItem("tema");
}
const html = document.documentElement;
html.setAttribute("data-theme", tema);
}
function preLoadTela() {
const objTela =
GlobGetSession[GlobGetSession.findIndex((item) => item.url === PageAtual)]
.ferramentas;
return objTela;
}
function filterTable(tableId, filter) {
let table = document.getElementById(tableId);
let rows = table.querySelectorAll("tbody tr");
let hasVisibleRows = false;
if (!filter || filter.trim() === "") {
rows.forEach((row) => {
row.style.display = "";
});
return;
}
let filterText = filter.toLowerCase();
rows.forEach((row) => {
// Verifica se a linha é a linha vazia (quando não há itens)
if (row.querySelector("td[colspan]")) {
row.style.display = "none";
return;
}
// Obtém todo o texto da linha em minúsculas
let rowText = row.textContent.toLowerCase();
// Mostra ou esconde a linha baseado no filtro
if (rowText.includes(filterText)) {
row.style.display = "";
hasVisibleRows = true;
} else {
row.style.display = "none";
}
});
if (!hasVisibleRows) {
let emptyRow = document.createElement("tr");
emptyRow.className = "border-b border-gray-800";
emptyRow.innerHTML = `
Nenhum item encontrado
|
`;
// Remove a mensagem anterior se existir
let existingEmptyRow = table.querySelector(
"tbody tr[style*='display: none']"
);
if (existingEmptyRow && existingEmptyRow.querySelector("td[colspan]")) {
existingEmptyRow.remove();
}
table.querySelector("tbody").appendChild(emptyRow);
} else {
// Remove a mensagem de "Nenhum item encontrado" se existir
let emptyRow = table.querySelector("tbody tr td[colspan='7']");
if (emptyRow && emptyRow.textContent.includes("Nenhum item encontrado")) {
emptyRow.closest("tr").remove();
}
}
}
temaSystem();
function carregarFiltroDataHora(id_ini, id_fim, tipo) {
const today = new Date();
const yyyy = today.getFullYear();
const mm = String(today.getMonth() + 1).padStart(2, "0");
const dd = String(today.getDate()).padStart(2, "0");
let dIni, dFim;
if (tipo == "hoje" || tipo == 1) {
dIni = new Date(today.setHours(0, 0, 0, 0));
dFim = new Date(today.setHours(23, 59, 0, 0));
} else if (tipo == "semana" || tipo == 2) {
const dayOfWeek = today.getDay();
const diffToMonday = (dayOfWeek === 0 ? -6 : 1) - dayOfWeek;
dIni = new Date(today);
dIni.setDate(today.getDate() + diffToMonday);
dIni.setHours(0, 0, 0, 0);
dFim = new Date(today);
dFim.setHours(23, 59, 0, 0);
} else if (tipo == "mes" || tipo == 3) {
dIni = new Date(today.getFullYear(), today.getMonth(), 1, 0, 0, 0, 0);
dFim = new Date(today.setHours(23, 59, 0, 0));
} else if (tipo == "30" || tipo == 4) {
dIni = new Date(today);
dIni.setDate(today.getDate() - 30);
dIni.setHours(0, 0, 0, 0);
dFim = new Date(today.setHours(23, 59, 0, 0));
}
if (dIni && dFim) {
const format = (d) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
d.getDate()
).padStart(2, "0")}T${String(d.getHours()).padStart(2, "0")}:${String(
d.getMinutes()
).padStart(2, "0")}`;
document.getElementById(id_ini).value = format(dIni);
document.getElementById(id_fim).value = format(dFim);
}
}
function carregarFiltroData(id_ini, id_fim, tipo) {
tipo = parseInt(tipo);
let today = new Date();
let dIni = new Date();
let dFim = new Date();
switch (tipo) {
case 1: // Hoje
dIni = new Date(today);
dFim = new Date(today);
break;
case 2: // Semana
dIni.setDate(today.getDate() - today.getDay()); // Domingo da semana atual
dFim = new Date(today); // Hoje
break;
case 3: // Mês
dIni = new Date(today.getFullYear(), today.getMonth(), 1); // Primeiro dia do mês
dFim = new Date(today); // Hoje
break;
case 4: // Últimos 30 dias
dIni.setDate(today.getDate() - 30);
dFim = new Date(today); // Hoje
break;
case 0: // Limpar
default:
dIni = "";
dFim = "";
break;
}
$(`#${id_ini}`).val(dIni ? formatDate(dIni) : "");
$(`#${id_fim}`).val(dFim ? formatDate(dFim) : "");
}
function exportarPDFComMultiplasTabelas(
htmlString,
nomeArquivo,
idElementLoad
) {
const { jsPDF } = window.jspdf;
const doc = new jsPDF({ orientation: "landscape" });
let y = 10;
const container = document.getElementById("html2pdfDownload");
container.innerHTML = htmlString;
const elementos = container.childNodes;
elementos.forEach((el) => {
if (el.tagName === "H6") {
const titulo = el.innerText || el.textContent;
doc.setFontSize(12);
if (y > 260) {
doc.addPage();
y = 10;
}
doc.text(titulo, 14, y);
y += 6;
}
if (el.tagName === "TABLE") {
doc.autoTable({
html: el,
startY: y,
theme: "grid",
styles: { fontSize: 8 },
headStyles: { fillColor: [41, 128, 185] },
});
y = doc.lastAutoTable.finalY + 10;
}
});
doc.save(nomeArquivo + ".pdf");
loadElement(idElementLoad, 0);
}
function exportarPDFfromHtml(htmlString, nomeArquivo, idElementLoad) {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
let y = 10;
const container = document.createElement("div");
container.innerHTML = htmlString;
document.body.appendChild(container);
// Processar seções principais
const sections = container.querySelectorAll(".bg-base-200.rounded-lg");
sections.forEach((section) => {
// Adicionar título da seção
const sectionTitle = section.querySelector("h3");
if (sectionTitle) {
if (y > 260) {
doc.addPage();
y = 10;
}
doc.setFontSize(14);
doc.setTextColor(0, 0, 0);
doc.setFont("helvetica", "bold");
doc.text(sectionTitle.textContent.trim(), 14, y);
y += 10;
}
// Processar cards de cada seção
const cards = section.querySelectorAll(".card");
if (cards.length > 0) {
cards.forEach((card) => {
if (y > 260) {
doc.addPage();
y = 10;
}
// Título do card
const cardTitle = card.querySelector(".card-title");
if (cardTitle) {
doc.setFontSize(12);
doc.setTextColor(41, 128, 185);
doc.setFont("helvetica", "bold");
doc.text(cardTitle.textContent.trim(), 14, y);
y += 7;
}
// Conteúdo do card
const contentElements = card.querySelectorAll("div:not(.rating)");
contentElements.forEach((el) => {
if (el.textContent.trim() && !el.classList.contains("rating")) {
if (y > 260) {
doc.addPage();
y = 10;
}
doc.setFontSize(10);
doc.setTextColor(0, 0, 0);
doc.setFont("helvetica", "normal");
doc.text(el.textContent.trim(), 14, y);
y += 5;
}
});
y += 5; // Espaço entre cards
});
} else {
// Se não houver cards, verifica se há mensagem de informação
const alert = section.querySelector(".alert");
if (alert) {
if (y > 260) {
doc.addPage();
y = 10;
}
doc.setFontSize(10);
doc.setTextColor(100, 100, 100);
doc.setFont("helvetica", "italic");
doc.text(alert.textContent.trim(), 14, y);
y += 10;
}
}
y += 10; // Espaço entre seções
});
// Remover container temporário
document.body.removeChild(container);
doc.save(nomeArquivo + ".pdf");
loadElement(idElementLoad, 0);
}
function getFilter(formId) {
const filtro = {};
const form = document.getElementById(formId);
form.querySelectorAll("input, select, textarea").forEach((element) => {
const nome = element.name;
const valor = element.value;
if (nome) filtro[nome] = valor;
});
return filtro;
}
function popularSelect(selectIdOrName, dados, campoLabel, campoValue = null) {
const select =
document.getElementById(selectIdOrName) ||
document.querySelector(`select[name="${selectIdOrName}"]`);
if (!select) {
console.warn(
`Elemento