let aClickMenu = 1; window.onload = function () { $(".loader").fadeOut("slow"); $("#body").fadeIn(1000); } $(document).ready(() => { // MENU GRÁFICO NÃO ESTAVA PARANDO ABERTO // ESTE CÓDIGO FOI IMPLEMENTADO PARA CORRIGIR ESPECIFICAMENTE ESTE MENU, // O RESTO DOS MENU FUNCIONAM NORMALMENTE if (GetLS('lm_grafico') == 'true') { $('#lm_grafico').slideDown(); SetLS('lm_grafico', 'true'); } //Se não tiver Local Storage, seta o controle de campo para o LocalStorage if (localStorage.getItem('menuAberto') == null) { localStorage.setItem('menuAberto', 1); } //Busca Menu selecionado no Local Storage e seleciona if (localStorage.getItem('menuAberto') !== null) { id = localStorage.getItem('menuAberto'); OpenModulo(id); } }) // FUNÇÃO PARA ALTERAR ENTRE OS MÓDULOS FINANCEIROS E CONTROLE DE CAMPO function OpenModulo(id) { localStorage.setItem('menuAberto', id); if (id == 1) { $(`#controle-1`).css({ 'display': 'block' }); $(`#controle-2`).css({ 'display': 'none' }); $('#mod_controle_campo').html(" Controle de Campo"); $('#mod_controle_financeiro').html(" Controle Financeiro"); } else if (id == 2) { $(`#controle-2`).css({ 'display': 'block' }); $(`#controle-1`).css({ 'display': 'none' }); $('#mod_controle_financeiro').html(" Controle Financeiro"); $('#mod_controle_campo').html(" Controle de Campo"); } } //Função que carrega conteúdo sem refresh function _GETDATATABLE(url, aDestino = 'data-table') { ShowLoader(); $.ajax({ type: "GET", url: url, success: function (data) { try { $('#' + aDestino).html(data); if (aDestino == 'data-table') { LoadDataTable(); } HideLoader(); } catch (err) { console.error(err); if (resolve) { resolve() } } }, error: function () { HideLoader(); } }); } function _GETDATATABLEFILTER(aUrl, aDestino = 'data-table') { ShowLoader(); let data = {}; // MONTA UM OBJETO COM OS FILTROS PARA CARREGAR A LISTAGEM $("#form_filtro input[save='true']").each(function (index) { // $(this).val(GetLS($(this).attr('name'))); data[$(this).attr('name')] = GetLS($(this).attr('name')); }); $("#form_filtro select[save='true']").each(function (index) { // $(this).val(GetLS($(this).attr('name'))); const valueLS = GetLS($(this).attr('name')); const value = $(this).val(); if (valueLS !== '') { data[$(this).attr('name')] = valueLS; } else if (value !== '') { data[$(this).attr('name')] = value; } }); $.ajax({ type: "POST", url: aUrl, data: data, success: function (data) { try { $('#' + aDestino).html(data); LoadDataTable(); HideLoader(); } catch (err) { console.error(err); if (resolve) { resolve() } } }, 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 ShowModalCallback(titulo, texto) { $('#modal_titulo').html(titulo); $('#modal_texto').html(texto); CloseModal(); $('#modal').modal('show'); } function ShowModalPage(url) { CloseModal(); $('#modalPage').modal('show'); _GETDATATABLE(url, 'corpo-modal-page'); } 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: 'bg-verde-btn' }, cancel: { label: ' Cancelar', className: 'btn-danger' } }, callback: function (result) { if (result) { document.preventDefault; _EXECDELETA(id, ref, opt) } } }); } // O AJAX QUE FICAVA DENTRO DA FUNÇÃO Deleta() FOI EXTRAIDO PARA UMA NOVA FUNÇÃO, POIS SERIA NECESSÁRIO UTILIZAR-LO // SEM A MODAL DE CONFIRMAÇÃO function _EXECDELETA(id, ref, opt = '') { $.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 { 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 !== 'atividade_talhao_arquivo' && ref !== 'conta_corrente_cobranca' && ref !== 'usinas_zonas') { 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 { if (ref == 'associado_equipamento') { $('#row_' + id).remove(); return; } 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 == 'consumo_energia') lg = 'row_ce_'; 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); setTimeout(() => { // ATUALIZA OS CAMPOS DE COMBUSTIVEL NA ATIVIDADE TALHÃO AO REMOVER UM EQUIPAMENTO if (ref == "atividade_talhao_equipamento") atualizarCamposCombustivel(); }, 300); } } } }, error: function (erro) { ShowModal("Ops", 'Ocorreu um erro durante a exclusão do item. Erro: ' + erro); } }); } 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 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 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) { if (!aValor) { return 0; // Retorne 0 ou outro valor padrão caso `aValor` seja nulo ou indefinido } 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, qtdCheca = 120) { /* 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 PARA ALTERAR A QUANTIDADE DE CHECAGEM, PASSE COMO PARÂMETRO */ if (aValue !== 0 && aValue !== '') { var i = 0; $(aCampoValue).addClass('input-load'); var Start = setInterval(function () { if ($(aCampoSemaforo).val() || i == qtdCheca) { $(aCampoValue).val(aValue); if ($(aCampoValue).val() || i == qtdCheca) { $(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) { // inputs normais $("#" + aForm + " input[save='true']").each(function () { const value = GetLS($(this).attr('name')); if (value !== '') { $(this).val(value); } }); // select múltiplo Safra $("#" + aForm + " #selectSafra[save='true']").each(function () { const value = GetLS($(this).attr('name')); if (value !== '') { var safraIds = value.split(','); $(this).selectpicker('val', safraIds); } }); // selects genéricos (inclusive inputAssociadoFiltro) $("#" + aForm + " select[save='true']").each(function () { const value = GetLS($(this).attr('name')); if (value !== '') { // seta valor $(this).val(value); // se for bootstrap-select, atualiza visual if ($(this).hasClass("cboBootstrapSelect")) { $(this).selectpicker('val', value); } } }); // força refresh em todos os cboBootstrapSelect $("#" + aForm + " .cboBootstrapSelect").selectpicker('refresh'); } // function LoadFiltro(aForm) { // $("#" + aForm + " input[save='true']").each(function (index) { // const value = GetLS($(this).attr('name')); // if (value !== '') { // $(this).val(value); // } // }); // $("#" + aForm + " #selectSafra[save='true']").each(function (index) { // const value = GetLS($(this).attr('name')); // if (value !== '') { // var safraIds = value.split(','); // $('#selectSafra').selectpicker('val', safraIds); // $('#selectSafra').selectpicker('refresh'); // } // }); // $("#" + aForm + " select[save='true']").each(function (index) { // const value = GetLS($(this).attr('name')); // if (value !== '') { // $(this).val(value); // } // }); // $('#inputIdAssociadoFiltro').selectpicker('refresh'); // } 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 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function Cript(aText, aTp = 'c') { return $.ajax({ type: "POST", url: 'Source/App/cript.php', cache: false, data: { aText: aText, aTp: aTp } }); } function FilePreview(aFilePath, nomeAnexo = null) { $('#bodyModalFiles').html('
'); $('#modalFiles').fadeIn(); $.ajax({ url: `Source/Get/Anexo/file_preview.php?path=${aFilePath}`, cache: false, success: function (data) { var ex = aFilePath.split('.').pop().toLowerCase(); var exImages = ["jpg", "jpeg", "png", "gif"]; var locked = ['php', 'html', 'htm', 'asp']; if ($.inArray(ex, locked) !== -1) { ShowToast('Extensão não permitida', 'Permitidas: jpg, jpeg, png, gif, xlsx, txt, xml, docx, pdf'); } else if ($.inArray(ex, exImages) !== -1) { $('#bodyModalFiles').html('
'); } else if (ex === 'pdf') { $('#bodyModalFiles').html( '' + '
' + ' ' + '
' + '
' ); } else { fetch(aFilePath).then(response => response.blob()).then(blob => { var url = window.URL.createObjectURL(blob); // Cria um URL Blob para o arquivo var link = document.createElement('a'); // Cria o elemento de link link.href = url; // Define o URL Blob link.download = (nomeAnexo != null) ? nomeAnexo : aFilePath.split("/").pop(); // Define o nome do arquivo para download document.body.appendChild(link); // Adiciona o link ao documento link.click(); // Simula o clique no link document.body.removeChild(link); // Remove o link do documento window.URL.revokeObjectURL(url); // Libera o URL Blob }).catch(err => OpenToast('Não foi possível realizar o download do arquivo !', true)); $('#modalFiles').fadeOut(); } }, 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 += `
`; } $('.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); } }); } function toggleLeftMenu() { const width = window.innerWidth; if (width >= 1260) { if (aClickMenu % 2 == 0) { $('#LeftMenu > ul').css({ 'display': 'block' }); $('.a-container').css({ 'margin-left': '310px', 'transition': '0.5s' }) $('.dataTables_info').css({ 'width': '70%' }) localStorage.setItem('statusMenu', 0); // menu aberto $('.dataTables_scrollHeadInner').css({ 'width': '100%' }) // tira evento hover $('.icon-menu').off('hover'); $('#LeftMenu').off('mouseleave'); } else { $('#LeftMenu').css({ 'display': 'none' }); $('.a-container').css({ 'margin-left': '30px', 'transition': '0.5s' }) $('.dataTables_info').css({ 'width': '90%' }) localStorage.setItem('statusMenu', 1) // menu fechado $('.dataTables_scrollHeadInner').css({ 'width': '100%' }) $('.icon-menu').hover(() => $('#LeftMenu').css({ 'display': 'block' })); $('#LeftMenu').mouseleave(() => $('#LeftMenu').css({ 'display': 'none' })); } aClickMenu++; } else { if (aClickMenu % 2 == 0) { $('#LeftMenu > ul').css({ 'display': 'block', 'z-index': 1 }); $('.a-container').css({ 'margin-left': '310px', 'transition': '0.5s' }) $('.dataTables_info').css({ 'width': '40%' }) localStorage.setItem('statusMenu', 0); // menu aberto } else { $('#LeftMenu > ul').css({ 'display': 'none' }); $('.a-container').css({ 'margin-left': '30px', 'transition': '0.5s' }) $('.dataTables_info').css({ 'width': '35%' }) localStorage.setItem('statusMenu', 1) // menu fechado } aClickMenu++; } } // ## FUNÇÃO PARA FORMATAR XML ====== function formatXml(xml) { var formatted = ''; var reg = /(>)(<)(\/*)/g; xml = xml.replace(reg, '$1\r\n$2$3'); var pad = 0; jQuery.each(xml.split('\r\n'), function (index, node) { var indent = 0; if (node.match(/.+<\/\w[^>]*>$/)) { indent = 0; } else if (node.match(/^<\/\w/)) { if (pad != 0) { pad -= 1; } } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) { indent = 1; } else { indent = 0; } var padding = ''; for (var i = 0; i < pad; i++) { padding += ' '; } formatted += padding + node + '\r\n'; pad += indent; }); return formatted; } // ## === FUNÇÃO GETDATASESSION PARA PEGAR OS DADOS DA SESSION function getDataSession() { let session = sessionStorage.getItem('SESSION_DATA'); if (!session || session == '[]') { $.ajax({ url: "Source/Get/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; } } // ## === FUNÇÃO PARA RENDERIZAR/ABRIR MODAIS PERSONALIZADAS function OpenModalCustom(url, div) { ShowLoader(); $.ajax({ url: url, success: function (data) { $('#' + div).html(data); HideLoader(); }, error: function () { HideLoader(); } }); } function formatarMoeda(valor) { // Remove qualquer caractere não numérico, exceto ponto e vírgula valor = valor.replace(/[^\d,.]/g, ''); // Substitui a vírgula por ponto, caso exista valor = valor.replace(',', '.'); // Converte o valor para float const valorFloat = parseFloat(valor); // Verifica se a conversão para float resultou em NaN if (isNaN(valorFloat)) { return "Valor inválido"; } // Formata o valor para o formato brasileiro const valorFormatado = valorFloat.toFixed(2).replace('.', ','); // Adiciona o prefixo "R$" e retorna return "R$ " + valorFormatado.replace(/\B(?=(\d{3})+(?!\d))/g, '.'); } function formataCPFCNPJ(aDoc) { const numCarac = aDoc.length; let doc = ''; if (numCarac === 11) { // Formata CPF doc = aDoc.slice(0, 3) + '.' + aDoc.slice(3, 6) + '.' + aDoc.slice(6, 9) + '-' + aDoc.slice(9); } else if (numCarac === 14) { // Formata CNPJ doc = aDoc.slice(0, 2) + '.' + aDoc.slice(2, 5) + '.' + aDoc.slice(5, 8) + '/' + aDoc.slice(8, 12) + '-' + aDoc.slice(12); } else { // Retorna o valor original se não for CPF nem CNPJ doc = aDoc; } return doc; } function formatNumerosDecimais(valor) { // Se o valor for vazio, retorna a tag if (!valor || valor == '') { return '0,00'; } // Remove qualquer caractere não numérico, exceto o ponto e a vírgula valor = valor.replace(/[^\d,.]/g, ''); // Se houver mais de um ponto ou vírgula, mantém apenas o último como separador decimal const partes = valor.split(/[,\.]/); const inteiro = partes[0]; const decimal = partes.slice(1).join(''); // Concatena as partes decimais // Formata o número com vírgula como separador decimal const valorFormatado = inteiro + ',' + (decimal.padEnd(2, '0').slice(0, 2)); return valorFormatado; } // === # ESSAS FUNÇÕES FORAM CRIADAS PARA ATUALIZAR OS CAMPOS (LTRS COMBUSTIVEL, CONSUMO COMBUSTIVEL E TOTAL COMBUSTIVEL R$) // === # INICIALMENTE ESTAVAM NO ARQUIVO ATIVIDADETALHOA.JS MAS COMO ERA NECESSÁRIO UTILIZAR-LA NA FUNÇÃO DELETA, FOI TRANSFERIDO PARA CÁ function atualizarCamposCombustivel() { verificarAtualizarLtrsCombustivel(); verificarAtualizarConsumoCombustivel(); verificarAtualizarTotalCombustivel(); // GRAVAR AS INFORMAÇÕES PARA EVITAR ERROS $('#btnGrava').click(); } function verificarAtualizarLtrsCombustivel() { let totalLitrosConsumidos = 0; let totalAreaTrabalhadaEquipamento = 0; $('tr[id^="row_ate_"]').each(function () { let areaTrabalhada = parseFloat($(this).find('td:eq(6)').text().replace(',', '.')); let litrosConsumidos = parseFloat($(this).find('td:eq(7)').text().replace(',', '.')); if (!isNaN(areaTrabalhada)) { totalAreaTrabalhadaEquipamento += areaTrabalhada; } if (!isNaN(litrosConsumidos)) { totalLitrosConsumidos += litrosConsumidos; } }); let litrosPorHATrabalhado = (totalLitrosConsumidos / totalAreaTrabalhadaEquipamento); if (totalLitrosConsumidos == 0 || totalAreaTrabalhadaEquipamento == 0) { $('#inputLitrosHectare').val(cortarParaTresDecimais(0)); } else { $('#inputLitrosHectare').val(cortarParaTresDecimais(litrosPorHATrabalhado)); } } function verificarAtualizarConsumoCombustivel() { let totalLitrosConsumidos = 0; $('tr[id^="row_ate_"]').each(function () { let litrosConsumidos = parseFloat($(this).find('td:eq(7)').text().replace(',', '.')); if (!isNaN(litrosConsumidos)) { totalLitrosConsumidos += litrosConsumidos } }); $('#inputConsumoDiesel').val(cortarParaTresDecimais(totalLitrosConsumidos)); } function verificarAtualizarTotalCombustivel() { let valorTotalCombustivel = 0; $('tr[id^="row_ate_"]').each(function () { let totalCombustivelLinha = parseFloat($(this).find('td:eq(8)').text().replace(',', '.')); valorTotalCombustivel += totalCombustivelLinha; }); $('#inputValorDiesel').val(cortarParaTresDecimais(valorTotalCombustivel)); } function cortarParaTresDecimais(valor) { let valorStr = valor.toString(); let partes = valorStr.split('.'); if (partes[1]) { partes[1] = partes[1].substring(0, 3); } return partes.join('.'); } // ===@ ESSA FUNÇÃO TRANSFORMA QUALQUER VALOR PARA FICAR COM 3 CASAS DECIMAIS. function formatarParaTresCasasDecimais(value) { var formattedValue = parseFloat(value).toFixed(3); return formattedValue; } function formatarDataParaMySQL(data) { const partes = data.split('/'); const dataFormatada = `${partes[2]}-${partes[1]}-${partes[0]}`; return dataFormatada; } function FullModalVideo(aURL, aTitulo) { ShowLoader(); $.ajax({ url: `View/Pages/PgModal/fullVIdeoModal.php?url=${encodeURIComponent(aURL)}&titulo=${aTitulo}`, success: function (data) { console.log('🔥 Requisição Efetuada: ' + data); $('#aModalFullVideo').html(data); HideLoader(); // EXIBE A MODAL $('#modalFullVideo').modal({ backdrop: 'static', keyboard: true }); }, error: function () { HideLoader(); } }); } // ========================== MOVIMENTO ESTOQUE ========================== function OpenModalMovimentoEstoque() { ShowLoader(); $.ajax({ url: `View/Pages/PgModal/movimento_estoque.php`, success: function (data) { $('#modalGlobalMovimentoEstoque').html(data); HideLoader(); // EXIBE A MODAL $('#modalMovimentoEstoque').modal({ backdrop: 'static', keyboard: true }); // ATIVA O SELECT PICKER $('.cboBootstrapSelect').selectpicker({ noneResultsText: 'Nenhum registro encontrado', }); $('input, select').bind("keypress", function (e) { var k = e.which || e.keyCode; if (k == 13) { e.preventDefault(); campo = $('input, select, textarea, button'); indice = campo.index(this); if (campo.eq(indice + 1).attr('readonly')) { for (i = 1; i < 100; i++) { if (!campo.eq(indice + i).attr('readonly')) { if (campo[indice + i] != null) { proximo = campo[indice + i]; proximo.focus(); } break; } } } else { if (campo[indice + 1] != null) { proximo = campo[indice + 1]; proximo.focus(); } } } }); /**MANIPULA OS DADOS PARA USUÁRIO ASSOCIADO OPERADOR*/ GetSession() .done(function (data) { let OBJ = JSON.parse(data); if (OBJ.nome_associado) { $('#inputAssociadoSearch').val(OBJ.id_associado).trigger('change'); $('button[data-id="inputAssociadoSearch"]').attr({ "readonly": true, "disabled": true, 'style': 'background-color: #ecf0f1 !important; color: #000 !important; opacity: 1;', }); } }); /***/ }, error: function () { HideLoader(); } }); } // === # Essa função carrega os lotes no combobox passado como parâmetro, por padrão // === # irá carregar no combobox da modal, mas é possível alterar para utilizar no apontamento. function getComboLotes(idProduto, idAssociado, idSelect = 'selectLoteMovEstoque', idLabelSelect = 'lblLote') { $(`#${idSelect}`).html(''); if (idProduto !== '' && idProduto !== '0' && idAssociado !== '' && idAssociado !== '0') { $.ajax({ type: "POST", url: "Source/Get/MovimentoEstoque/get_lote_movimento_estoque.php", cache: false, data: { id_produto: idProduto, id_associado: idAssociado, }, success: function (data) { if (data !== '' && data !== '[]' && data !== null && data !== 'null') { var obj = JSON.parse(data); var row = ''; var controla_estoque_lote = obj[0].controla_estoque_lote row += ''; obj.forEach(function (o, index) { let selected = (index == 0) ? 'selected' : ''; let txtOption = (o.controla_estoque_lote == 1) ? `LOTE: ${o.lote} - ${o.data_movimento} - SALDO: ${formatarNumeroVisualmente(o.qtd)}` : `SALDO: ${formatarNumeroVisualmente(o.qtd)}` row += ``; }); if (controla_estoque_lote == 1) { $(`#${idLabelSelect}`).text('Lote/Num. Nota'); $(`#${idSelect}`).attr('disabled', false); } else if (controla_estoque_lote == 0) { $(`#${idLabelSelect}`).text('Saldo Restante'); $(`#${idSelect}`).attr('disabled', true); } if (row == '') { $(`#${idSelect}`).html(''); $(`#${idSelect}`).attr('disabled', true); } else { $(`#${idSelect}`).html(row); // $(`#${idSelect}`).attr('disabled', false); } } else { $(`#${idSelect}`).html(''); $(`#${idSelect}`).attr('disabled', true); } }, error: function (erro) { $(`#${idSelect}`).html(''); $(`#${idSelect}`).attr('disabled', true); } }); } else { $(`#${idSelect}`).html(''); $(`#${idSelect}`).attr('disabled', true); } } // === ## Essa função verifica se a quantidade inserida é maior do que o saldo restante no estoque. // === ## Esta função foi criada exclusivamente pensando no tipo de movimento (saída) function verificarQuantidadeInserida(idInputQtd = 'inputQtdMovEstoque', idSelectLote = 'selectLoteMovEstoque') { // SÓ VERIFICA SE O SELECT DE LOTE E INPUT DE QUANTIDADE ESTIVER PREENCHIDO if ($(`#${idSelectLote}`).val() && $(`#${idInputQtd}`).val()) { let qtd = $(`#${idInputQtd}`).val().replace(/\./g, '').replace(/,/g, '.'); // ESSE VALOR VEM ALGO ASSIM: 1.235,54 (PRECISO TIRAR O PONTO E DEPOIS TROCAR A VIRGULA PELO PONTO) let saldoEstoque = $(`#${idSelectLote} option:selected`).attr("saldo"); // ESSE VALOR JÁ VEM FORMATADO CORRETO DO BANCO DE DADOS 0000.000 (COM PONTO EM VEZ DE ,) // SE A QUANTIDADE FOR MAIOR QUE O SALDO DE ESTOQUE, NÃO DEIXA INSERIR if (parseFloat(qtd) > parseFloat(saldoEstoque)) { ShowModal(' Saldo Insuficiente', `O produto selecionado não possui saldo suficiente no estoque.

Saldo Estoque: ${saldoEstoque}
Qtd Requisitada: ${formatarParaTresCasasDecimais(qtd)}`); $(`#${idInputQtd}`).val(''); // LIMPA O CAMPO INPUT DE QUANTIDADE // SE A FUNÇÃO FOR CHAMADA DO APONTAMENTO, LIMPA O CAMPO QUANTIDADE POR HA TAMBÉM if (idInputQtd == 'inputQtdHAAdd') { $('#inputQtdAplicAdd').val(''); $('#inputValorTotalAdd').val(''); $('#inputQtdAplicAdd').focus(); } else { $(`#${idInputQtd}`).focus(); } } } } // ================================================================================================================== // ====================================== FUNÇÃO GENÉRICA PARA MOVITAR ESTOQUE ====================================== // ================================================================================================================== async function MovimentarEstoque(arrayProduto, confirmarMovimentacao = true, callback, baixaAutomaticaCombustivel = false) { if (arrayProduto.length == 0) { ShowModal(' Atenção', 'Você precisa ter ao menos UM (1) item produto para realizar uma movimentação de estoque ! Insira um item e tente novamente.'); } else { if (confirmarMovimentacao) { bootbox.confirm({ message: "Deseja confirmar essa movimentação de estoque?", buttons: { confirm: { label: ' Confirmar', className: 'btn-success' }, cancel: { label: ' Cancelar', className: 'btn-danger' } }, callback: function (result) { if (result) { _EXECMOVIMENTOESTOQUE(arrayProduto, callback, baixaAutomaticaCombustivel); } } }); } else { _EXECMOVIMENTOESTOQUE(arrayProduto, callback, baixaAutomaticaCombustivel); } } } function _EXECMOVIMENTOESTOQUE(arrayProduto, callback, baixaAutomaticaCombustivel = false) { $.ajax({ type: "POST", url: "Source/Get/MovimentoEstoque/grava_movimento_estoque.php", cache: false, data: { movEstoqueItens: arrayProduto, }, success: function (data) { if (data == '') { ShowModal(' Atenção', 'A gravação dos dados retornou vazia. Contate um Administrador !!'); } else { var obj = JSON.parse(data); if (obj.erro == 1) { ShowModal(' Atenção', obj.msg); } else if (obj.erro == 2) { sobrescreverEntradaEstoque(obj.msg, obj.idsMovEstoque, arrayProduto); } else { if (callback && typeof callback === 'function') { if (baixaAutomaticaCombustivel) { callback(obj.total_combustivel); } else { callback(); } } ShowToast('Sucesso', obj.msg); } } }, error: function (erro) { ShowModal('Erro !!', 'Ocorreu um erro ao tentar concluir a movimentação de estoque. Erro: ' + erro); } }); } function sobrescreverEntradaEstoque(mgsBody, arrIdsMovEstoque, arrayProduto) { bootbox.confirm({ message: mgsBody, size: 'large', title: ' Aviso de Duplicidade no Estoque', buttons: { confirm: { label: ' Sobrescrever', className: 'btn-success' }, cancel: { label: ' Cancelar', className: 'btn-danger' } }, callback: function (result) { if (result) { // PERCORRE O ARRAY DELETANDO AS MOVIMENTAÇÕES arrIdsMovEstoque.forEach(function (value, index) { _EXECDELETA(value, 'movimento_estoque'); }); // ESPERA 2 ms APÓS "DELETAR" TODOS AS MOVIMENTAÇÕES ANTIGAS setTimeout(() => { _EXECMOVIMENTOESTOQUE(arrayProduto, function () { $('#btnNovaMovEstoque').click(); }); }, 200); } } }); } // ================================================================================================================== // FUNÇÃO PARA ALTERAR/INSERIR UMA ÁREA QUEIMADA NO TALHÃO ========================================================== function insereAlteraAreaQueimada(iptAreaQueimada, areaTotal, idEntradaCanaTalhao, valorAnteriorAreaQueimada) { let areaQueimada = parseFloat($(iptAreaQueimada).val().replace(',', '.')); if (isNaN(areaQueimada) || isNaN(areaTotal)) { ShowToast('Erro', 'Porfavor, insira um valor númerico válido.'); return; } if (areaQueimada > areaTotal) { ShowToast('Erro', 'Área Queimada é maior que Área Total.'); $(iptAreaQueimada).val(valorAnteriorAreaQueimada); $(iptAreaQueimada).focus(); } else { $.ajax({ type: "POST", url: "Source/Get/EntradaCana/grava_area_queimada.php", cache: false, data: { id_entradacana: idEntradaCanaTalhao, area_queimada: areaQueimada, }, success: function (data) { if (data == '') { ShowModal('Ops', 'A gravação dos dados retornou vazia. Contate um Administrador !!'); } else { var obj = JSON.parse(data); if (obj.erro == 1) { ShowModal('Ops', obj.msg); } else { ShowToast('Sucesso', 'Área Queimada atualizada com Sucesso !!'); } } } }); } } // ===@ FUNÇÃO SOMENTE LETRAS ============================================================== function SomenteLetras(string) { return string.replace(/[0-9.-]/g, ""); } // ===@ FUNÇÃO CRIADA PARA DESATIVAR OS INPUTS DO TIPO SELECT COMBOBOX // ===@ PARÂMETRO ID DO ELEMENTO SEM A #, POR EXEMPLO inputIdAssociado function desativarSelectCombobox(idElementoInput = 'inputIdAssociado') { $(`button[data-id="${idElementoInput}"]`).attr({ "readonly": true, "disabled": true, 'style': 'background-color: #ecf0f1 !important; color: #000 !important; opacity: 1;', }); } // ===@ MANIPULA OS DADOS PARA USUÁRIO ASSOCIADO OPERADOR ================================== function manipularCamposAssociadoOperador(elementoInputAssociado = 'inputIdAssociado', insereIdAssociado = true) { GetSession().done(function (data) { let OBJ = JSON.parse(data); if (OBJ.id_associado > 0) { if (insereIdAssociado) { $(`#${elementoInputAssociado}`).val(OBJ.id_associado).trigger('change'); } desativarSelectCombobox(elementoInputAssociado); } }); } function saldoEstoque(idAssociado, idProduto) { return new Promise((resolve, reject) => { $.ajax({ type: "POST", url: "Source/Get/MovimentoEstoque/get_saldo_atual_estoque.php", cache: false, data: { id_produto: idProduto, id_associado: idAssociado, }, success: function (data) { if (data == '') { ShowModal('Ops', 'A gravação dos dados retornou vazia. Contate um Administrador !!'); resolve(0); } else { var obj = JSON.parse(data); if (obj.erro == 1) { ShowModal('Ops', obj.msg); resolve(0); } else { resolve(parseFloat(obj[0].saldo_restante_estoque)); } } }, error: function () { reject('Erro na requisição'); } }); }); } // ===@ ESSA FUNÇÃO LIMPA O TEXTO DAS OPTIONS E DEIXA APENAS 0000/0000 function limparTextoOptions(idElementoSelect = '#selectSafra') { $(`${idElementoSelect} option`).each(function () { if ($(this).val() != '') { let valor = $(this).text(); valor = valor.replace(/[a-zA-Z\s-]/g, ''); $(this).text(valor); } }); } function validaCNPJ(val) { 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; } } } function trocarPontoPorVirgula(aIdElemento) { $(`#${aIdElemento}`).on('input', function () { $(this).val($(this).val().replace(/\./g, ',')); }); } function tratarNumerosDecimais(e, casasDecimais = 2) { let valor = $(e).val(); // Remove tudo que não seja número valor = valor.replace(/[^\d]/g, ''); // mantém só números if (valor === '') { $(e).val(''); return; } // Converte para número real considerando as casas decimais let divisor = Math.pow(10, casasDecimais); let numero = (parseInt(valor, 10) / divisor).toFixed(casasDecimais); // Formata com separador de milhar e vírgula decimal numero = numero.replace('.', ','); numero = numero.replace(/\B(?=(\d{3})+(?!\d))/g, '.'); $(e).val(numero); } function tratarNumerosParaDB(valorFormatado) { if (!valorFormatado) return null; // Remove pontos (milhar) let valorSemPonto = valorFormatado.replace(/\./g, ''); // Substitui vírgula por ponto (decimal) let valorDecimal = valorSemPonto.replace(',', '.'); // Converte para número float let numero = parseFloat(valorDecimal); // Retorna null se não for número válido if (isNaN(numero)) return null; return numero; } function formatarNumeroVisualmente(numero) { // Garante que é string numero = String(numero); // Separa parte inteira e decimal let partes = numero.split('.'); let inteiro = partes[0]; let decimal = partes[1] || ''; // Formata a parte inteira com separador de milhar usando regex let inteiro_formatado = inteiro.replace(/\B(?=(\d{3})+(?!\d))/g, "."); // Junta novamente return decimal !== '' ? inteiro_formatado + ',' + decimal : inteiro_formatado; } // ==================================================================== // ============== CONSTANTES PARA O MOVIMENTO DE ESTOQUE ============== // ==================================================================== const MOVIMENTO_ESTOQUE_SAIDA = 0; const MOVIMENTO_ESTOQUE_ENTRADA = 1; const ORIGEM_MANUAL_MOVIMENTO_ESTOQUE = 0; const ORIGEM_APONTAMENTO_MOVIMENTO_ESTOQUE = 1; const TIPO_ORIGEM_MANUAL_MOVIMENTO_ESTOQUE = 0 const TIPO_ORIGEM_PRODUTO_MOVIMENTO_ESTOQUE = 1; const TIPO_ORIGEM_COMBUSTIVEL_MOVIMENTO_ESTOQUE = 2; const ID_ORIGEM_MANUAL_MOVIMENTO_ESTOQUE = 0; const ID_ORIGEM_FILHO_MANUAL_MOVIMENTO_ESTOQUE = 0; // ==================================================================== // ============== CONSTANTES PARA CATEGORIA DE PRODUTOS =============== // ==================================================================== const FERTILIZANTE = 3; const CALCARIO = 4; const HERBICIDA = 5; const INSETICIDA = 6; const BIOLOGICO = 7; const GESSO = 8; const ADUBO_ORGANICO = 9; const FUNGICIDA = 10; const NEMATICIDA = 11; const COMBUSTIVEL = 13; const ENERGIA = 12;