window.onload = function () { $(".loader").fadeOut("slow"); $("#body").fadeIn(1000); } //Função que carrega conteúdo sem refresh function Conteudo(url, div) { ShowLoader(); $.ajax({ url: url, success: function (data) { $('#' + div).html(data); HideLoader(); }, error: function () { HideLoader(); } }); } function ShowToast(aTitle, aHeader) { $('#title_toast').html(aTitle); $('#body_toast').html(aHeader); $('#base_toast').removeClass('d-none'); //console.log(aHeader); $(".toast").addClass('show-toast'); setTimeout(function () { CloseToast(); }, 3500); } function CloseToast() { $(".toast").removeClass('show-toast'); $('#base_toast').addClass('d-none'); } function ShowModal(titulo, texto) { $('#modal_titulo').html(titulo); $('#modal_texto').html(texto); CloseModal(); $('#modal').modal('show'); } function ShowModalPage(url) { CloseModal(); $('#modalPage').modal('show'); Conteudo(url, 'corpo-modal-page'); //$('#corpo-modal-page').load(url); //console.log(url); } function CloseModal() { $('#modal').modal('hide'); } function CloseModalEdit2() { $('#modalEdit2').modal('hide'); } function CloseModalPage() { $('#modalPage').modal('hide'); } function ShowLoader() { $("#progressbar").removeClass('invisible'); } function HideLoader() { $("#progressbar").addClass('invisible'); } function SelectOptionText(idcombo, valor) { $("#" + idcombo).val($('option:contains("' + valor + '")').val()); } function SelectOptionValue(idcombo, valor) { $('#' + idcombo + ' option[value="' + valor + '"]').attr({ selected: "selected" }); } function GetConfig() { //console.log('entrou get config'); var dados = $(this).serialize(); $.ajax({ url: "pages/ajax/get_config.php", cache: false, data: dados, success: function (data) { if (data == true) { //console.log('Configurado com sucesso !!!'); } else { //console.log('Ops config', data); } }, error: function (erro) { //console.log('Erro Config !!', 'Ocorreu um erro ao tentar gravar o cadastro. Erro: ' + erro); } }); } /* function LimpaForm() { $('#ajax_form').each(function () { this.reset(); console.log('pssou aqui'); }); } */ function SetTitle(NamePage) { if (NamePage.trim() !== '') { document.title = NamePage + ' - ' + document.title; } } function SetLS(nome, valor) { localStorage.setItem(nome, valor); } function GetLS(nome) { var LS; LS = localStorage.getItem(nome); if (LS == null) { return ""; } else { return LS; } } function ClearLS(nome) { localStorage.setItem(nome, ''); } function SetSS(nome, valor) { sessionStorage.setItem(nome, valor); } function GetSS(nome) { var SS; SS = sessionStorage.getItem(nome); if (SS == null) { return ""; } else { return SS; } } function ClearSS(nome) { sessionStorage.setItem(nome, ''); } function SaveMenu(ItemMenu) { SetLS('open_menu', ItemMenu); } function OpenMenu() { var NomeMenu = GetLS('open_menu'); $('#' + NomeMenu).click(); } function OpenPage(link) { window.open(link, "_self"); } function UpperPrime(text) { if (text !== '') { var words = text.toLowerCase().split(" "); for (var a = 0; a < words.length; a++) { var w = words[a]; words[a] = w[0].toUpperCase() + w.slice(1); } return words.join(" "); } } function Deleta(id, ref, opt = '') { var rConfirma; bootbox.confirm({ message: "Deseja mesmo prosseguir com a exclusão do cadastro ?", buttons: { confirm: { label: ' Confirmar', className: 'btn-success' }, cancel: { label: ' Cancelar', className: 'btn-danger' } }, callback: function (result) { if (result) { $.ajax({ cache: false, url: "Source/App/delete.php", type: 'POST', data: { "id": id, "referencia": ref, "parametro": opt }, success: function (data) { if (data == '') { ShowModal('Ops', 'Esta ação não teve o retorno esperado. Contate um administrador.'); } else { var obj = JSON.parse(data); if (obj.erro == 1) { ShowModal('Ops', obj.msg); } else { // console.log(obj + ' - id:' + id + ' - ref:' + ref); // return false; if ($("#ajax_form").length && ref !== 'propriedade_talhao' && ref !== 'servico_prestado_talhao' && ref !== 'produto_exame' && ref !== 'atividade_talhao_equipamento' && ref !== 'atividade_talhao_prestadores' && ref !== 'atividade_talhao_produto' && ref !== 'servico_assistencial_procedimentos' && ref !== 'entrada_cana_talhao' && ref !== 'associado_conta_corrente' && ref !== 'arquivo' && ref !== 'anexo_destino' && ref !== 'associado_propriedade_matricula' && ref !== 'atividade_talhao_talhao' && ref !== 'conta_corrente_cobranca') { if (ref == 'associado_dependente' || ref == 'associado_propriedade' || ref == 'propriedade_colheita') { if (ref == 'associado_dependente') location.reload(); $('#back').click(); } else { var AtualPage = location.href.substring(location.href.lastIndexOf('/') + 1); AtualPage = AtualPage.split('?')[0]; var url_atual = window.location.href; if ((AtualPage == 'cad_contas_receber_edit')) { url_atual = url_atual.replace('?' + GetParamURL('edit'), ''); url_atual = url_atual.replace('cad_contas_receber_edit', 'contas_receber'); window.location.href = url_atual; } else if (AtualPage == 'cad_contas_pagar_edit') { url_atual = url_atual.replace('?' + GetParamURL('edit'), ''); url_atual = url_atual.replace('cad_contas_pagar_edit', 'contas_pagar'); window.location.href = url_atual; } else { window.location.href = url_atual.replace('?' + GetParamURL('edit'), ''); } return false; } } else { var lg = 'row_'; if (ref == 'atividade_talhao_equipamento') lg = 'row_ate_'; if (ref == 'atividade_talhao_prestadores') lg = 'row_atp_'; if (ref == 'atividade_talhao_produto') lg = 'row_atprod_'; if (ref == 'atividade_talhao_talhao' || ref == 'entrada_cana_talhao') lg = 'row_talh_'; if (ref == 'associado_conta_corrente') lg = 'row_cc_'; if (ref == 'arquivo') lg = 'row_anexo_'; if (ref == 'anexo_destino') lg = 'row_dest_anexo_'; if (ref == 'movimento_financeiro_transferencia') lg = 'row_transf_'; if (ref == 'associado_propriedade_matricula') lg = 'row_matricula_'; if (ref == 'conta_corrente_cobranca') lg = 'row_cobranca_'; if (ref == 'propriedade_talhao') { var aUrlAtual = window.location.href; if (aUrlAtual.indexOf("cad_propriedade") > -1) { aIdsafra = $('#form_safra #selectAnoSafra').val(); aIdPropriedade = $('#ajax_form #inputId').val(); } else if (aUrlAtual.indexOf("cad_colheita_propriedade") > -1) { aIdsafra = $('#ajax_form #inputId').val(); aIdPropriedade = $('#ajax_form #inputIdPropriedade').val(); } GetTalhoes(aIdsafra, aIdPropriedade); } ShowToast('', obj.msg); setTimeout(() => { $('#' + lg + id).remove(); }, 200); } } } }, error: function (erro) { ShowModal("Ops", 'Ocorreu um erro durante a exclusão do item. Erro: ' + erro); } }); document.preventDefault; } } }); } function formatReal(int) { var tmp = int + ''; tmp = tmp.toString().replaceAll('.', ''); tmp = tmp.toString().replaceAll(',', ''); tmp = tmp.replace(/([0-9]{2})$/g, ",$1"); if (tmp.length > 6) tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2"); return tmp; } function keypressed(obj, e) { var tecla = (window.event) ? e.keyCode : e.which; if (tecla == 8 || tecla == 0) return true; if (tecla != 44 && tecla < 48 || tecla > 57) return false; } function openCloseLeftMenu() { if (document.getElementById("mySidenav").style.width == "278px") { closeLeftMenu(); SetLS('openleftmenu', false); $('#selectModulo').removeClass('position-fixed'); $('.controle-geral').css('top', '0px'); } else { openLeftMenu(); SetLS('openleftmenu', true); setTimeout(() => { $('#selectModulo').addClass('position-fixed'); $('.controle-geral').css('top', '37px'); }, 300); } } function ativarInativar(text, id, tabela) { bootbox.confirm({ message: `Deseja mesmo ${text} o cadastro?`, buttons: { confirm: { label: ' Confirmar', className: 'btn-success' }, cancel: { label: ' Cancelar', className: 'btn-danger' } }, callback: function (result) { if (result) { $.ajax({ cache: false, url: "Source/App/ativar_reativar.php", type: 'POST', data: { "id": id, "referencia": tabela, "inativo": text }, success: function (data) { //console.log(obj); if (data == '') { ShowModal('Ops', 'Esta ação não teve o retorno esperado. Contate um administrador.'); } else { var obj = JSON.parse(data); if (obj.erro == 1) { ShowModal('Ops', obj.msg); } else { var lg = 'row_'; if (text == "inativar") { $('#' + lg + id).css({ 'color': '#d06b86' }); $(`#btn_ativar_${id}`).html(' Ativar'); $(`#btn_ativar_${id}`).attr('onclick', `ativarInativar('ativar', ${id}, '${tabela}')`); } else { $('#' + lg + id).css({ 'color': '#212529' }); $(`#btn_ativar_${id}`).html(' Inativar'); $(`#btn_ativar_${id}`).attr('onclick', `ativarInativar('inativar', ${id}, '${tabela}')`); } ShowToast('', obj.msg); } } } }); }; } }) } function openLeftMenu() { $('#mySidenav').css('width', '278px'); $('#corpo').css('margin-left', '278px'); $('.nav-tools').css('left', '308px'); //document.getElementById("mySidenav").style.width = "278px"; //document.getElementById("corpo").style.marginLeft = "278px"; } function closeLeftMenu() { $('#mySidenav').css('width', '0'); $('#corpo').css('margin-left', '0'); $('.nav-tools').css('left', '30px'); //document.getElementById("mySidenav").style.width = "0"; //document.getElementById("corpo").style.marginLeft = "0"; } function Tip(data) { $("#tip-text").text($(data).attr('data-tip')); } function NoTip() { $("#tip-text").text(''); } function ShowHideFilters() { var visivel = $('#nav-filter').is(':visible'); if (visivel) SetLS('filter', 'none'); else SetLS('filter', 'block'); $('#nav-filter').toggle('fast'); } function ChekUnchek(id) { $('#' + id).each(function () { if (this.checked) this.checked = false; else this.checked = true; }); } function marcarTodos(marcardesmarcar) { var dataTable = $('#rel-table').dataTable(); $(dataTable.fnGetNodes()).each(function () { // https://legacy.datatables.net/ref $(this).find('input[type="checkbox"]').each(function () { this.checked = marcardesmarcar; }); }); } function ValidaForm(aForm) { //$('#modalEdit2').modal('hide'); var Campos = ''; if (aForm == '' || isUndefined(aForm)) aForm = 'ajax_form'; $("#" + aForm + " input[valida='true']").each(function (index) { if ($.trim($(this).val()) == '') { //Adicionado condição force-valida para validar também campos específicos que contenham o readonly ou disable if (!$(this).attr("disabled") && (!$(this).attr("readonly") || ($(this).attr("readonly") && $(this).attr("force-valida")))) { $(this).addClass('border-invalid'); if ($(this).attr("text-valid") !== '') { Campos += '
* ' + $(this).attr("text-valid"); } } else { $(this).removeClass('border-invalid'); } } else { $(this).removeClass('border-invalid'); } }); $("#" + aForm + " select[valida='true']").each(function (index) { if (!$(this).val()) { if (!$(this).attr("disabled") && !$(this).attr("readonly")) { $(this).addClass('border-invalid'); if ($(this).attr("text-valid") !== '') { Campos += '
* ' + $(this).attr("text-valid"); } } } else { $(this).removeClass('border-invalid'); } }); $("#" + aForm + " textarea[valida='true']").each(function (index) { if (!$(this).val()) { if (!$(this).attr("disabled") && !$(this).attr("readonly")) { $(this).addClass('border-invalid'); if ($(this).attr("text-valid") !== '') { Campos += '
* ' + $(this).attr("text-valid"); } } } else { $(this).removeClass('border-invalid'); } }); $("#" + aForm + " input[doc='cpfcnpj']").each(function (index) { if ($.trim($(this).val()) !== '') { if (!$(this).attr("disabled") && !$(this).attr("readonly")) { if (!validaCpfCnpj($.trim($(this).val()))) { $(this).addClass('border-invalid'); Campos += '
* Informar CPF ou CNPJ Válido'; } } else { $(this).removeClass('border-invalid'); } } }); $("#" + aForm + " input[tp='data']").each(function (index) { if ($.trim($(this).val()) !== '') { if (!$(this).attr("disabled") && !$(this).attr("readonly")) { if ($.trim($(this).val()) !== '00/00/0000') { if (!validateDate($.trim($(this).val()))) { //$(this).addClass('border-invalid'); var legenda = $("label[for='" + $(this).attr('name') + "']").html(); if (legenda !== '') { Campos += '
* Informe uma ' + legenda + ' válida'; } else { Campos += '
* Data Válida'; } } } } } }); if (Campos !== '') { ShowModal(' Campos Obrigatórios', 'Os campos abaixo devem ser preenchidos !!!
' + Campos) return false; } else { return true; } } function LimpaForm(aForm) { if (aForm == '') { aForm = 'ajax_form'; } $('#' + aForm).each(function () { this.reset(); }); } function GetParam(aurlParams, aParam) { //coonsole.log('aaa'); // Verifica se o parâmetro existe aurlParams.has(aParam); // true // Imprime todos os parâmetros como na forma original, sem o "?" na frente return aurlParams.toString(); // page=1 } function GetParamURL(aParam) { // Exemplo: https://website.com/blog?page=1 var urlParams = new URLSearchParams(location.search); // Verifica se o parâmetro existe urlParams.has(aParam); // true // Imprime todos os parâmetros como na forma original, sem o "?" na frente return urlParams.toString(); // page=1 // Adiciona um parâmetro com chave e valor especificados //urlParams.append('key', 'val'); // Resultado: page=1&key=val // Remove um parâmetro //urlParams.delete('key'); // Resultado: page=1 } function GetParamsURL() { var query = location.search.slice(1); var partes = query.split('&'); var data = {}; partes.forEach(function (parte) { var chaveValor = parte.split('='); var chave = chaveValor[0]; var valor = chaveValor[1]; data[chave] = valor; }); return data; } function isUndefined(aVal) { return (typeof aVal === "undefined"); } function onlynumber(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(); } } function validaCpfCnpj(val) { if (val.length == 11) { var cpf = val.trim(); cpf = cpf.replace(/\./g, ''); cpf = cpf.replace('-', ''); cpf = cpf.split(''); var v1 = 0; var v2 = 0; var aux = false; for (var i = 1; cpf.length > i; i++) { if (cpf[i - 1] != cpf[i]) { aux = true; } } if (aux == false) { return false; } for (var i = 0, p = 10; (cpf.length - 2) > i; i++, p--) { v1 += cpf[i] * p; } v1 = ((v1 * 10) % 11); if (v1 == 10) { v1 = 0; } if (v1 != cpf[9]) { return false; } for (var i = 0, p = 11; (cpf.length - 1) > i; i++, p--) { v2 += cpf[i] * p; } v2 = ((v2 * 10) % 11); if (v2 == 10) { v2 = 0; } if (v2 != cpf[10]) { return false; } else { return true; } } else if (val.length == 14) { var cnpj = val.trim(); cnpj = cnpj.replace(/\./g, ''); cnpj = cnpj.replace('-', ''); cnpj = cnpj.replace('/', ''); cnpj = cnpj.split(''); var v1 = 0; var v2 = 0; var aux = false; for (var i = 1; cnpj.length > i; i++) { if (cnpj[i - 1] != cnpj[i]) { aux = true; } } if (aux == false) { return false; } for (var i = 0, p1 = 5, p2 = 13; (cnpj.length - 2) > i; i++, p1--, p2--) { if (p1 >= 2) { v1 += cnpj[i] * p1; } else { v1 += cnpj[i] * p2; } } v1 = (v1 % 11); if (v1 < 2) { v1 = 0; } else { v1 = (11 - v1); } if (v1 != cnpj[12]) { return false; } for (var i = 0, p1 = 6, p2 = 14; (cnpj.length - 1) > i; i++, p1--, p2--) { if (p1 >= 2) { v2 += cnpj[i] * p1; } else { v2 += cnpj[i] * p2; } } v2 = (v2 % 11); if (v2 < 2) { v2 = 0; } else { v2 = (11 - v2); } if (v2 != cnpj[13]) { return false; } else { return true; } } else { return false; } } function validateDate_old(aData) { var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02]) [\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/; if (!((aData.match(RegExPattern)) && (aData.value != ''))) { return false; } else { return true; } } 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 ValidaData(aData) { var dia = aData.split("/")[0]; var mes = aData.split("/")[1]; var ano = aData.split("/")[2]; var MyData = new Date(ano, mes - 1, dia); if ((MyData.getMonth() + 1 !== mes) || (MyData.getDate() !== dia) || (MyData.getFullYear() !== ano)) { return false; } else { return true; } } function RemoveParams() { var url_atual = window.location.href; //window.location.href = url_atual.substr(0, url_atual.indexOf('?')); //window.history.replaceState(data, title, url_atual.substr(0, url_atual.indexOf('?'))); window.history.replaceState('', '', url_atual.substr(0, url_atual.indexOf('?'))); //console.log(url_atual); } function apenasNumeros(string) { var numsStr = string.replace(/[^0-9]/g, ''); return numsStr; } function apenasMoeda(string) { //var numsStr = string.replaceAll(/[^0-9+,]/g, ''); //var numsStr = string.replaceAll(/\,|[^0-9]/g, ''); var numsStr = string.replaceAll(/^\d+,\d{2}$/g, ''); //numsStr = numsStr.replace(/\d|,/g, ''); return (numsStr); } function MoedaCalculo(aValor) { //aValor = aValor.replaceAll('.', ''); //aValor = aValor.replaceAll(',', '.'); aValor = aValor.replaceAll('.', ''); aValor = aValor.replace(',', '.'); return parseFloat(aValor); } function FormataValorMoeda(aValor) { if ((typeof aValor) === "number") { aValor = aValor.toString(); } aValor = aValor.replaceAll(',', '.'); aValor = parseFloat(aValor); //aValor = aValor.ToFixed(2); //aValor = aValor.replaceAll('.', ','); return aValor.toLocaleString('pt-br', { minimumFractionDigits: 2 }); } function MoedaPrint(aValor) { /* aValor = aValor.toString().replaceAll('.', ''); aValor = aValor.toString().replaceAll(',', ''); aValor = formatReal(aValor); aValor = aValor.toString().replaceAll('.', ''); */ aValor = aValor.toLocaleString('pt-br', { minimumFractionDigits: 2 }); /* if (aValor !== null) { aValor = aValor.toString().replaceAll('.', ','); } else { aValor = '0,00'; } */ return aValor; } function FormataMoeda(aVal) { if (aVal == '') { return '0,00'; } else { return aVal.toLocaleString('pt-br', { minimumFractionDigits: 2 }); } } function OpenCloseMenu(aMenu) { var vs = $('#' + aMenu).is(':visible'); if (vs) { $('#' + aMenu).slideUp(); SetLS(aMenu, 'false'); } else { $('#' + aMenu).slideDown(); SetLS(aMenu, 'true'); } } function FormataCPFCNPJ(aDoc) { var NumCarac = aDoc.length; var Doc; if (NumCarac == 11) { Doc = aDoc.substring(0, 3) + '.' + aDoc.substring(3, 6) + '.' + aDoc.substring(6, 9) + '-' + aDoc.substring(9, 11); } else if (NumCarac == 14) { Doc = aDoc.substring(0, 2) + '.' + aDoc.substring(2, 5) + '.' + aDoc.substring(5, 8) + '/' + aDoc.substring(8, 12) + '-' + aDoc.substring(12, 14); } else { Doc = aDoc; } return Doc; } $(document).ajaxStart(function () { ShowLoader(); }); $(document).ajaxComplete(function () { HideLoader(); }); $(document).ajaxSuccess(function () { HideLoader(); }); $(document).ajaxError(function () { HideLoader(); }); $(document).ajaxStop(function () { HideLoader(); }); function CallBackValue(aCampoSemaforo, aCampoValue, aValue) { /* PARA QUE O CAMPO "aCampoValue" POSSA SER PREENCHIDO, O CAMPO "aCampoSemaforo" PRECISA ESTAR PREENCHIDO, BASICAMENETE É ISSO QUE A ROTINA FAZ... ELE CONSIDERA 120 CHECAGENS ANTES DE IGNORAR A AÇÃO */ if (aValue !== 0 && aValue !== '') { var i = 0; $(aCampoValue).addClass('input-load'); var Start = setInterval(function () { //console.log('CallBackValue: ' + i); if ($(aCampoSemaforo).val() || i == 120) { $(aCampoValue).val(aValue); if ($(aCampoValue).val() || i == 120) { $(aCampoValue).removeClass('input-load'); $(aCampoValue).change(); clearInterval(Start); } } i++; }, 50); } } function DataDia() { var dt = new Date(); var d = dt.getDate(); var m = dt.getMonth(); m++; var y = dt.getFullYear(); if (String(d).length == 1) { d = '0' + d; } if (String(m).length == 1) { m = '0' + (m); } return d + '/' + m + '/' + y; } function SalvaFiltro(aForm) { $("#" + aForm + " input[save='true']").each(function (index) { SetLS($(this).attr('name'), $(this).val()); }); $("#" + aForm + " select[save='true']").each(function (index) { SetLS($(this).attr('name'), $(this).val()); }); return true; } function LoadFiltro(aForm) { $("#" + aForm + " input[save='true']").each(function (index) { $(this).val(GetLS($(this).attr('name'))); }); $("#" + aForm + " select[save='true']").each(function (index) { $(this).val(GetLS($(this).attr('name'))); }); } function getTotalTable(aNameTable, aPosColumn) { let result = 0; let columns = $("#" + aNameTable + " tr td:nth-child(" + aPosColumn + ")"); columns.each(i => { result += parseFloat(MoedaCalculo($(columns[i]).html())); }); return result; } function convertToReal(number, options = {}) { const { moneySign = true } = options; if (Number.isNaN(number) || !number) return "need a number as the first parameter"; if (typeof number === "string") { // n1 number = Number(number); } let res; const config = moneySign ? { style: 'currency', currency: 'BRL' } : { minimumFractionDigits: 2 }; moneySign ? res = number.toLocaleString('pt-BR', config) : res = number.toLocaleString('pt-BR', config) const needComma = number => number <= 1000; if (needComma(number)) { res = res.toString().replace(".", ","); } return res; // n2 } function IsEmail(email) { var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/); if (!er.test(email)) { return false; } else { return true; } } function setCookie(aName, aValue) { document.cookie = aName + "=" + aValue; } function getCookie(name) { var cookies = document.cookie; var prefix = name + "="; var begin = cookies.indexOf("; " + prefix); if (begin == -1) { begin = cookies.indexOf(prefix); if (begin != 0) { return null; } } else { begin += 2; } var end = cookies.indexOf(";", begin); if (end == -1) { end = cookies.length; } return unescape(cookies.substring(begin + prefix.length, end)); } function GetSession() { return $.ajax({ url: "Source/Get/Usuario/get_session.php", cache: false, type: 'POST' }); /*COMO UTILIZAR GetSession() .done(function (data) { //done code }) .fail(function () { //fail code }) .always(function () { //some code }); */ } // Função criada pois o SHowModal fica por trás da tela na exibição de erros, então foi criada essa função para auxiliar em cadastros modal function ModalRejeicao(local, msg) { $('#' + local).html(''); $('#tip-text').html(''); } function OrdenaCombo(aId) { var itens = $('#' + aId + ' option').sort(function (a, b) { return a.text < b.text ? -1 : 1; }); $('#' + aId).html(itens); } /** REMOVE OPTIONS*/ function CleanOptionsSelect(aSelectID, aValueNotDelete) { $('#' + aSelectID + ' > option').each(function () { if ($(this).val() !== aValueNotDelete) $(this).remove(); }); } /**MOSTRA/OCULTA CAMPO TYPE="PASSWORD"*/ $('button[vps="true"]').on('click', function () { let aP = $(this).attr('vps-data'); if (!isUndefined(aP)) if ($(aP).prop('type') == 'text') $(aP).prop('type', 'password'); else $(aP).prop('type', 'text'); }); function Cript(aText, aTp = 'c') { return $.ajax({ type: "POST", url: 'Source/App/cript.php', cache: false, data: { aText: aText, aTp: aTp } }); } function FilePreview(aFilePath) { $('#bodyModalFiles').html('
'); $('#modalFiles').fadeIn(); $.ajax({ url: `Source/Get/Anexo/file_preview.php?path=${aFilePath}`, cache: false, success: function (data) { $('#bodyModalFiles').html(data); }, error: function (erro) { console.log('Erro Config !!', 'Ocorreu um erro ao tentar gravar o cadastro. Erro: ' + erro); } }); } /***********************************************************************************/ function DownloadFile(fileType, filename, referencia) { var URL = `Source/Get/Anexo/get_anexo_download.php?file_name=${filename}&file_type=${fileType}&referencia=${referencia}`; var link = document.createElement("a"); link.setAttribute('target', '_blank'); link.href = URL; /* case 'jpg': case 'jpeg': case 'png': case 'gif': case 'pdf': case 'xls': case 'xlsx': case 'txt': case 'xml': case 'doc': case 'docx': */ var eImg = ["jpg", "jpeg", "png", "gif"]; var eDoc = ["xls", "xlsx", "txt", "xml", "doc", "docx"]; var ext = filename.split('/').pop(); ext = ext.indexOf('.') < 1 ? '' : ext.split('.').pop(); if ((eDoc.indexOf(ext) !== -1)) { link.click(); } else { $('#bodyModalFiles').html('
'); $('#modalFiles').fadeIn(); $.ajax(document).done(function (response) { var req = new XMLHttpRequest(); req.open("GET", URL, true); req.responseType = "blob"; req.onload = function (event) { var blob = req.response; var html = ''; var reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function () { var base64data = reader.result; if (filename.indexOf('.pdf') !== -1) { html += ''; html += '
'; html += ' '; html += '
'; html += '
'; } else if (eImg.indexOf(ext) !== -1) { //html += '
'; html += `
`; } $('.title-modal-files').html(''); $('#bodyModalFiles').html(html); } }; req.send(); }); } } function GravaMensagem(idDest, tipoMSG = 0, MSG = '', anexos = undefined) { /* tipoMSG 0 = Mensagem recebida via js 1 = Serviço assistencial gerar conta 2 = Serviço assistencial atualizar conta 3 = Serviço prestado novo 4 = Mudança de status da atualiuzação */ /* Se tipo mensagem 0, enviar mensagem por parametro para o parametro MSG Se != 0, enviar o tipo mensagem corretamente de acordo com as constantes criadas no PHP e mandar os dados da mensagem em um objeto no parâmetro MSG retornaMensagemWPP() é a função do php que monta as mensagens */ $.ajax({ type: "POST", url: "Source/Get/Mensagem/grava_mensagem.php", cache: false, data: { id_destinatario: idDest, tipoMSG: tipoMSG, mensagem: MSG }, success: function(data) { console.log(data); } }); }