`;
$("body").append(md);
if (hasAddButton && typeof addFunction == 'function') {
$(`#${btnNovoCadastroModal}`).off('click').on('click', () => {
addFunction(); // Aqui sim, ela é executada no clique
});
}
if (overflowHidden) {
$(`.modal_${key}`).css({ 'overflow-y': 'auto' });
}
else {
$(`.modal_${key}`).css({ 'overflow-y': 'initial' });
}
$(`.modal_${key}`).css({ 'max-height': '700px' });
if (!paddingInterno) {
$(`.modal_${key}`).css({ 'padding': '0px' });
}
else {
$(`.modal_${key}`).css({ 'padding': '1rem' });
}
$('.loading').remove();
/**AQUI ELE RENDERIZA O JS DEFINIDO EM READY.JS PARA O CONTEÚDO DA MODAL*/
$(document).trigger('ready');
response = true;
},
error: function (e) {
OpenModal('Ops, Ocorreu um problema durante a requisição. Erro:
');
}
});
return response;
}
function PageModalSemHeader(aURL, title, aModalLarger = true, aModalCustomWidth = null, paddingInterno = true, overflowHidden = true) {
$('body').append('
');
let response = false;
let md = '';
let randID = `aBodyPageModal_${Math.floor(Math.random() * 9999) + 1}`;
$.ajax({
url: aURL,
cache: false,
async: false,
success: function (data) {
const key = (Math.random() + 1).toString(36).substring(2);
md += `
`;
if (aModalLarger)
md += `
`;
else
md += `
`;
md += `
`;
md += `
`;
md += `
${title}
`;
md += `
`;
md += `
`;
md += `
`;
$("body").append(md);
if (overflowHidden) {
$(`.modal_${key}`).css({ 'overflow-y': 'auto' });
}
else {
$(`.modal_${key}`).css({ 'overflow-y': 'initial' });
}
$(`.modal_${key}`).css({ 'max-height': '700px' });
if (!paddingInterno) {
$(`.modal_${key}`).css({ 'padding': '0px' });
}
else {
$(`.modal_${key}`).css({ 'padding': '0px 1rem 1rem 1rem' });
}
$('.loading').remove();
/**AQUI ELE RENDERIZA O JS DEFINIDO EM READY.JS PARA O CONTEÚDO DA MODAL*/
$(document).trigger('ready');
response = true;
},
error: function (e) {
OpenModal('Ops, Ocorreu um problema durante a requisição. Erro:
');
}
});
return response;
}
function changeModalSize() {
if ($('.modal-dialog').hasClass('modal-xl')) {
$('.modal-dialog').addClass('d-modal-fullscreen');
$('.modal-dialog').removeClass('modal-xl');
}
else {
$('.modal-dialog').removeClass('d-modal-fullscreen');
$('.modal-dialog').addClass('modal-xl');
}
}
const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
function FileModal(aFileSRC, nomeAnexo = null, base64 = false) {
const ext = getFileExtension(aFileSRC);
const extImage = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
let FinalFile;
if (base64) {
const blob = b64toBlob(aFileSRC, 'application/pdf')
const blobUrl = URL.createObjectURL(blob);
aFileSRC = blobUrl;
}
if (extImage.includes(ext)) {
// FinalFile = '
';
FinalFile = '

';
} else if (ext == 'pdf' || ext == 'PDF' || base64) {
if (nomeAnexo == null || base64) {
FinalFile = '
';
} else {
FinalFile = `
`;
}
} else {
fetch(aFileSRC)
.then(response => response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let link = document.createElement('a');
// Tenta obter a extensão do tipo MIME
const mimeToExt = {
'application/json': '.json',
'application/pdf': '.pdf',
'image/jpeg': '.jpg',
'image/png': '.png',
'application/zip': '.zip',
'application/x-rar-compressed': '.rar',
'text/plain': '.txt',
'application/msword': '.doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
'application/vnd.ms-excel': '.xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
'application/vnd.ms-powerpoint': '.ppt',
'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx'
};
let extension = mimeToExt[blob.type] || '';
let fallbackName = aFileSRC.split("/").pop().split("?")[0]; // Remove query string
if (!fallbackName.includes('.')) fallbackName += extension;
link.href = url;
link.download = nomeAnexo ? (nomeAnexo.includes('.') ? nomeAnexo : nomeAnexo + extension) : fallbackName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
})).catch(err => OpenToast('Não foi possível realizar o download do arquivo!', true));
return false;
}
let md = '';
md += '
';
md += '
';
md += '
';
md += ' ';
md += '
';
md += '
' + FinalFile + '
';
md += '
';
md += '
';
md += '
';
md += '
';
$("body").append(md);
// $('.filemodal-body').css({ 'max-height': 'calc(100vh - 130px)', 'overflow-y': 'scroll' });
$('.filemodal-body').css({ 'overflow-y': 'scroll', 'height': 'calc(100vh)' });
}
function FileModalPDF(aFileSRC, nomeAnexo = null) {
let FinalFile = '
';
let md = '';
md += '
';
md += '
';
md += '
';
md += ' ';
md += '
';
md += '
' + FinalFile + '
';
md += '
';
md += '
';
md += '
';
md += '
';
$("body").append(md);
// $('.filemodal-body').css({ 'max-height': 'calc(100vh - 130px)', 'overflow-y': 'scroll' });
$('.filemodal-body').css({ 'overflow-y': 'scroll' });
}
function showXML(xml) {
let md = '';
md += '
';
md += '
';
md += '
';
md += ' ';
md += '
';
md += '
' + xml + '
';
md += '
';
md += '
';
md += '
';
md += '
';
$("body").append(md);
$('.filemodal-body').css({ 'overflow-y': 'scroll' });
}
function modalHide(id) {
$(`#${id}`).modal('hide');
}
/**CRIPT */
function Cript(aText, aAction = 'C') {
return $.ajax({
url: '/' + URL_BASE + 'App/Conf/Cript.php',
data: { 'action': aAction, 'text': aText },
cache: false,
type: 'POST'
});
/**COMO UTILIZAR
Cript('URL', 'DADOS')
.done(function (data) {
//done code
})
.fail(function () {
//fail code
})
.always(function () {
//some code
});
*/
preventDefault();
}
function getRegistroPonto(id) {
const time = fnCurrentTime();
let ponto = {};
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'colaborador_registro_ponto',
condition: `AND id_colaborador = ${id} AND data = '${time.year}-${time.month}-${time.date}'`
})
.done(data => ponto = JSON.parse(data));
return ponto;
}
function fnCurrentTime() {
const time = new Date();
const day = time.getDay();
const date = time.getUTCDate().toString().padStart(2, '0');
const month = (time.getUTCMonth() + 1).toString().padStart(2, '0');
const year = time.getUTCFullYear();
const hours = time.getHours().toString().padStart(2, '0');
const minutes = time.getUTCMinutes().toString().padStart(2, '0');
const seconds = time.getUTCSeconds().toString().padStart(2, '0');
return {
date,
day,
month,
year,
hours,
minutes,
seconds
}
}
function getDataSession() {
let session = sessionStorage.getItem('SESSION_DATA');
if (!session || session == '[]') {
$.ajax({
url: '/' + URL_BASE + '/App/Controller/Session/get_session.php',
cache: false,
async: false,
success: function (data) {
session = JSON.parse(data);
sessionStorage.setItem('SESSION_DATA', JSON.stringify(session));
return session;
},
error: function (erro) {
console.error(erro);
}
});
} else {
session = JSON.parse(session);
return session;
}
}
function updateGetDataSession() {
let session;
$.ajax({
url: '/' + URL_BASE + '/App/Controller/Session/get_session.php',
cache: false,
async: false,
success: function (data) {
session = JSON.parse(data);
sessionStorage.setItem('SESSION_DATA', JSON.stringify(session));
return session;
},
error: function (erro) {
console.error(erro);
}
});
}
function getUserData(id) {
let user = {};
if (id == undefined) return [];
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'usuario',
condition: ' AND id = ' + id
})
.done(data => {
user = JSON.parse(data)
});
return user;
}
function getDepartamentData(id) {
let departament = {}
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'departamento',
condition: ' AND id = ' + id
})
.done(data => departament = JSON.parse(data));
return departament;
}
function getAllUsers() {
let user = {};
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'usuario',
condition: ' AND data_exclusao IS NULL AND id_tipo_colaborador < 4 AND inativo = 0'
})
.done(data => {
user = JSON.parse(data)
});
return user;
}
const converterMinutosHoras = (minutos) => {
const horas = Math.floor(minutos / 60);
const min = minutos % 60;
const textoHoras = (`00${horas}`).slice(-2);
const textoMinutos = (`00${min}`).slice(-2);
return `${textoHoras}:${textoMinutos}`;
};
const converterMinutosHorasGrafico = (minutos) => {
const horas = Math.floor(minutos / 60);
const min = minutos % 60;
if (horas > 1000) {
const textoHoras = (`0000${horas}`).slice(-4);
const textoMinutos = (`00${min}`).slice(-2);
return `${textoHoras}h${textoMinutos}`;
}
else if (horas >= 100) {
const textoHoras = (`000${horas}`).slice(-3);
const textoMinutos = (`00${min}`).slice(-2);
return `${textoHoras}h${textoMinutos}`;
} else {
const textoHoras = (`00${horas}`).slice(-2);
const textoMinutos = (`00${min}`).slice(-2);
return `${textoHoras}h${textoMinutos}`;
}
};
function getEmpresas() {
let empresas = {};
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'empresa',
})
.done(data => empresas = JSON.parse(data));
return empresas;
};
function getEmpresasNome() {
const empresas = [];
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'empresa',
})
.done(data => {
const response = JSON.parse(data);
response.forEach(el => el.nome && empresas.push(el.nome.toUpperCase()))
});
return empresas;
};
function formatText(nome) {
return nome.toLowerCase() // Converte tudo para minúsculas
.split(' ') // Separa por espaços
.map(palavra => palavra.charAt(0).toUpperCase() + palavra.slice(1)) // Capitaliza a primeira letra
.join(' '); // Junta as palavras novamente
}
function fnGetTituloProjeto() {
const titulo = [];
$.ajax({
type: "GET",
url: `/${URL_BASE}App/Controller/TitulosProjeto/TitulosProjeto.controller.php?action=get`,
success: function (data) {
const response = JSON.parse(data);
response.forEach(el => titulo.push(el.nome_titulo));
// titulo.push('Todos');
}
});
return titulo;
}
function fnGetProjeto() {
const projeto = [];
$.ajax({
type: "GET",
url: `/${URL_BASE}App/Controller/Projetos/Projetos.controller.php?filter=true`,
success: function (data) {
const response = JSON.parse(data);
response.forEach(el => projeto.push(el.nome_titulo));
projeto.push('Todos');
}
});
return projeto;
};
function fnGetCliente() {
const cliente = [];
$.ajax({
type: "GET",
url: `/${URL_BASE}App/Controller/Cliente/Cliente.controller.php?action=filter`,
success: function (data) {
const response = JSON.parse(data);
response.forEach(el => cliente.push(el.nome));
cliente.push('Todos');
}
});
return cliente;
};
function fnGetColaborador() {
const colaborador = [];
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'usuario',
condition: ` AND id_tipo_colaborador < 4 AND data_exclusao IS NULL` // Condição para trazer apenas usuários que são Colaboradores
})
.done(data => {
const response = JSON.parse(data);
response.forEach(el => colaborador.push(el.nome));
colaborador.push('Todos');
});
return colaborador;
};
function fnGetColaboradorData() {
let colaborador = [];
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'usuario',
})
.done(data => {
colaborador = JSON.parse(data);
});
return colaborador;
};
function validateDate(aData) {
var date = aData;
var ardt = new Array;
var ExpReg = new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
ardt = date.split("/");
erro = false;
if (date.search(ExpReg) == -1) {
erro = true;
} else if (((ardt[1] == 4) || (ardt[1] == 6) || (ardt[1] == 9) || (ardt[1] == 11)) && (ardt[0] > 30))
erro = true;
else if (ardt[1] == 2) {
if ((ardt[0] > 28) && ((ardt[2] % 4) != 0))
erro = true;
if ((ardt[0] > 29) && ((ardt[2] % 4) == 0))
erro = true;
}
if (erro) {
return false;
} else {
return true;
}
}
function RemoveIdURL() {
let aURL = $(location).attr('href').split("/");
if ($.isNumeric(aURL[aURL.length - 1]))
window.history.replaceState('', document.title, document.URL.replace('/' + aURL[aURL.length - 1], ''));
}
/**VERIFICA SE FOR EDIÇÃO*/
function pageEdit() {
let aURL = $(location).attr('href').split("/");
return $.isNumeric(aURL[aURL.length - 1]);
}
function getProprietarioGerente() {
let colaborador = {};
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'usuario',
condition: ' AND id_tipo_colaborador > 1'
})
.done(data => colaborador = JSON.parse(data));
return colaborador;
}
/** KEY EVENT
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);
*
*/
function hasDuplicates(arr) {
return new Set(arr).size !== arr.length;
}
function visualizarAnexo(anexo, nomeAnexo = null) {
const file = anexo.replace("{", "").replace("}", "");
const url_format = URL_BASE.replace("/client", "");
const host = window.location.origin;
const path_anexo = file.replace("../../", "");
const url = anexo
const ext = getFileExtension(file);
const extFile = ['png', 'jpg', 'jpeg', 'pdf'];
const extImage = ['png', 'jpg', 'jpeg', 'gif'];
FileModal(url, nomeAnexo);
// if (extImage.includes(ext)) {
// FileModal(url);
// }
// if (extFile.includes(ext)) {
// window.open(url, "", "popup");
// } else {
// console.log(url)
// window.location.href = url;
// }
}
function isFeriado(dateValue = null) {
let isFeriado = false;
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'feriados',
condition: ' AND data_exclusao IS NULL'
})
.done(data => {
const response = JSON.parse(data);
const date = dateValue != null ? new Date(`${dateValue}T12:00:00`) : new Date();
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
response.forEach(el => {
if (el.dia == day && el.mes == month && el.ano == year) {
isFeriado = true;
}
});
const session = getDataSession();
const id = $('#selectFiltroColaborador').val() ? $('#selectFiltroColaborador').val() : session.id;
_GET('/App/Controller/Query/get.controller.php', {
table_name: 'usuario',
condition: ' AND id = ' + id
})
.done(data => {
const response = JSON.parse(data);
if (response[0].arr_config_adicionais != null && response[0].arr_config_adicionais.includes('1')) isFeriado = false;
});
})
return isFeriado;
}
function excluirAnexoEmail(statusEmail) {
$('.a_modal').css('z-index', 99);
bootbox.confirm({
title: "Exclusão",
message: "Deseja realmente excluir o anexo?",
closeButton: false,
buttons: {
cancel: {
label: '
Cancelar'
},
confirm: {
label: '
Confirmar'
}
},
callback: result => {
if (result) {
$('#inputAnexoPost').val('');
$('.richText-editor').click();
$('#inputEmailEnviado').val(statusEmail);
_EXEC('formEmail', 'Anexo removido com sucesso')
.done(data => {
$('#divVisualizarAnexoEmail').remove();
_GETDATATABLE(`/${URL_BASE}App/View/Pages/email/saida/include/lista_ajax.php`);
})
}
}
});
}
function DivZero(Valor1, Valor2) {
let divisao = Valor1 / Valor2;
return (divisao == Infinity) ? 0 : divisao;
}
function copiarTexto(id) {
let textoCopiado = document.getElementById(id);
navigator.clipboard.writeText(textoCopiado.value);
// navigator.clipboard.writeText(textoCopiado.textContent);
OpenToast("Informação copiada");
}
function getFileExtension(filename) {
return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2)
}
function chatOnline(idUser, logout = false) {
let form = "";
form += `
`;
$('body').append(form);
_EXEC('formUsuarioLogin', null, false).done(res => {
$('#formUsuarioLogin').remove();
});
}
function adicionaProtocolo(url) {
const cleanUrl = url.replace(/[.,);!?]+$/, '');
return cleanUrl.startsWith('http://') || cleanUrl.startsWith('https://')
? cleanUrl
: `http://${cleanUrl}`;
}
function getHostName(url) {
try {
return new URL(url).hostname;
} catch {
return url;
}
}
// Função para verificar se o texto contém apenas links
function contemApenasLinks(texto) {
// Regex para verificar se é um link sem texto antes ou depois
const urlRegex = /(\b(https?:\/\/|www\.)[\w\-\.]+\.\w{2,}(\/[\w\-\.~:\/?#[\]@!$&'()*+,;=%]*)?)/gi;
const links = texto.match(urlRegex);
// Verifica se todo o texto é composto por links
return links && links.join(' ') === texto.trim();
}
function identificaLink(texto) {
if (texto.includes('
![]()
{
const href = adicionaProtocolo(match);
linksEncontrados.push(href);
return `
${match}`;
});
// Etapa 2: destaca #hashtags e @menções (mas ignora dentro de tags)
textoProcessado = textoProcessado.replace(/(^|\s)(#[\w\d_]+)/g, '$1
$2');
// Etapa 3: se for só links, retorna cards ou players
if (contemApenasLinks(texto.trim())) {
let cardsHTML = '';
linksEncontrados.forEach(href => {
// verifica se é um link do YouTube
const youtubeMatch = href.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
if (youtubeMatch) {
const videoId = youtubeMatch[1];
cardsHTML += `
`;
} else {
const host = getHostName(href);
cardsHTML += `
`;
}
});
return cardsHTML;
}
return textoProcessado;
}
//FUNÇÃO NOVA SEM O CARD DOS LINKS
// function identificaLink(text) {
// if (text.includes('
![]()
{
// const href = adicionaProtocolo(match);
// return `
${match}`;
// });
// }
//DESCONTINUEI ESSA FUNÇÃO E FIZ A DE CIMA, POIS É MAIS PRECISA
// function identificaLink(text) {
// if (!text.includes('
![]()
{
// if (el.includes('.com') || el.includes('.com.br') || el.includes('.net') || el.includes('.app') || el.includes('.org') || el.includes('.br')) {
// if (el.includes('http://') || el.includes('https://')) mensagem[key] = `
${el}`;
// else mensagem[key] = `
${el}`;
// }
// })
// return mensagem.join(' ');
// } else {
// return text;
// }
// }
function removerTags(aHTML) {
if (aHTML.includes('
![]()
req.text())
.then(cabecalho => {
const conteudoRelatorio = $('.container-relatorio').html();
let content = "";
content += "";
content += " ";
content += "
"
content += '
';
content += ` ${cabecalho}`;
content += ` ${conteudoRelatorio}`;
content += " ";
content += "";
win.document.write(content);
setTimeout(() => {
win.print();
win.close();
}, 500);
})
}
function dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];
for (var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1]) - 1 : 0;
for (var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j + 1) {
var month = j + 1;
var displayMonth = month < 10 ? '0' + month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}
function desabilitaHabilitaBotao(id) {
$(`#${id}`).attr('disabled', true);
setTimeout(() => $(`#${id}`).attr('disabled', false), 1000);
}
function verificaSeExisteNotificacao() {
// const session = getDataSession();
// const idUsuario = session.id;
// const tipoColaborador = session.id_tipo_colaborador;
// const listaLidos = 1;
// fetch(`/${URL_BASE}App/DAO/CentralMensagens/CentralMensagens.class.php?mensagensNaoLidas=true&idUsuario=${idUsuario}&tipoColaborador=${tipoColaborador}&listaLidos=${listaLidos}`)
// .then(req => req.json())
// .then(res => {
// // existe notificação nova
// if (res.length > 0) {
// $('#navbarNotificacao').append('
');
// }
// })
}
if (localStorage.getItem('idUser')) {
verificaSeExisteNotificacao();
//buscaNoticiasWiki();
//setTimeout(() => buscaNoticiasWiki(), 3600000) // 1 hora
}
function buscaNoticiasWiki() {
fetch(`/${URL_BASE}App/Controller/CentralMensagens/CentralMensagens.controller.php?executarCentral=true`)
.then(req => req.text())
.then(res => {
verificaSeExisteNotificacao();
fetch(`/${URL_BASE}App/View/Pages/Notificacoes/lista_notificacao.php?listaLidos=1`)
.then(req => req.text())
.then(res => {
$('.body-msg').html(res);
})
});
}
function utf8Decode(utf8String) {
if (typeof utf8String != 'string')
throw new TypeError('parameter ‘utf8String’ is not a string');
const unicodeString = utf8String
.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, (c) => {
return String.fromCharCode(((c.charCodeAt(0) & 0x0f) << 12)
| ((c.charCodeAt(1) & 0x3f) << 6)
| (c.charCodeAt(2) & 0x3f));
})
.replace(/[\u00c0-\u00df][\u0080-\u00bf]/g, (c) => {
return String.fromCharCode((c.charCodeAt(0) & 0x1f) << 6
| c.charCodeAt(1) & 0x3f);
});
return unicodeString;
}
function saveLog(dados) {
const formData = new FormData();
formData.append('cnpjCliente', dados.cnpjCliente);
formData.append('idServico', dados.idServico);
formData.append('status', dados.status);
formData.append('idUsuario', dados.idUsuario);
fetch(`/${URL_BASE}App/DAO/API/API.class.php?log=true`, {
method: 'POST',
body: formData
})
.then(req => req.text())
.then(res => console.log(res))
}
function uploadArquivo(image) {
let url;
_GET(`App/Controller/Query/upload_image.php?image=${image}`)
.done(data => {
const response = JSON.parse(data);
url = response.fileUrl;
});
return url;
}
function lancarAviso(titulo, mensagem, nivelAcesso = 0) {
// let form = "";
// form += `
`;
// $('body').append(form);
// _EXEC('formDEC', null, null)
// .done(data => {
// verificaSeExisteNotificacao();
// listaAviso();
// $('#formDEC').remove();
// })
}
function listaAviso() {
fetch(`/${URL_BASE}App/View/Pages/Notificacoes/lista_notificacao.php?listaLidos=1`)
.then(req => req.text())
.then(res => {
$('.body-msg').html(res);
const height = document.querySelectorAll('.body-msg > div').length;
$('.body-msg').scrollTop(100 * height);
})
}
let qtdArtigosBuscaWiki = 0;
function buscaAjudaWiki() {
const url = URL_BASE.split('/client');
const currentURL = window.location.href.split('/client');
const urlRelacionada = currentURL[1].split('/lista');
$('#buscaAjudaLoading').css({ 'display': 'flex' });
fetch(`/${url[0]}/API/Wiki/ajudaWiki.php?url=client${currentURL[1]}&urlRelacionado=${urlRelacionada[0]}`)
.then(req => req.json())
.then(artigos => {
qtdArtigosBuscaWiki = artigos.wiki.length;
// nenhuma noticia
if (artigos.wiki.length == 0) {
fetch(`/${URL_BASE}App/View/Pages/wiki/ajudaWikiSemArtigo.php`)
.then(req => req.text())
.then(res => {
$('#buscaAjudaLoading').css({ 'display': 'none' });
$('#containerWiki').html(res)
})
}
// tem artigo
else {
const data = JSON.stringify(artigos.wiki[countBuscaAjudaWiki]);
const artigoRelacionado = JSON.stringify(artigos.artigoRelacionado);
fetch(`/${URL_BASE}App/View/Pages/wiki/ajudaWikiComArtigo.php?&qtdArtigos=${artigos.wiki.length}&artigoAtual=${countBuscaAjudaWiki}`, {
method: 'post',
body: JSON.stringify({ data: data, artigoRelacionado: artigoRelacionado })
})
.then(req => req.text())
.then(res => {
$('#buscaAjudaLoading').css({ 'display': 'none' });
$('#containerWiki').html(res)
})
}
})
}
let countBuscaAjudaWiki = 0;
$('document').ready(() => {
$('body').on('click', '#nextBuscaAjudaWiki', e => {
if ((countBuscaAjudaWiki + 2) <= qtdArtigosBuscaWiki) {
countBuscaAjudaWiki++;
buscaAjudaWiki();
}
e.stopPropagation();
})
$('body').on('click', '#backBuscaAjudaWiki', e => {
if (countBuscaAjudaWiki > 0) {
countBuscaAjudaWiki--;
buscaAjudaWiki();
}
e.stopPropagation();
})
})
function loadtable(table, idColaborador, resolve = () => { }) {
let div = '
';
div += '';
div += '
';
$('#conteudo').html(div);
fetch(`/${URL_BASE}App/View/Pages/Obrigacoes/include/${table}.php?ajax=true&id_colaborador=${idColaborador || 'null'}`)
.then(req => req.text())
.then(res => {
$('.data-table').html(res);
LoadDataTable(false, 'Obrigacoes a Entregar');
//if($('.dataTables_empty')) $('#conteudo').html('
| NENHUMA INFORMAÇÃO ENCONTRADA |
';
div += '';
$('#conteudo').html(div);
fetch(`/${URL_BASE}App/View/Pages/Obrigacoes/include/modal_obrigacao_entregues/${table}.php?ajax=true&id_colaborador=${idColaborador || 'null'}`)
.then(req => req.text())
.then(res => {
$('.data-table').html(res);
LoadDataTable();
//if($('.dataTables_empty')) $('#conteudo').html('