Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Variáveis globais */
- var novoObjeto = []; // Armazena dados do XML tratados
- var novoObjetoCorrigido = []; // Armazena dados do XML tratados e com correção de chapa
- var depurarObjeto = []; // Armazena dados puros do XML
- var contadorDeLinhas = 0; // Armazena a quantidade de linhas do XML
- var variavelGlobal; // Para tratamento do arquivo
- var retornoFuncinarios = new Array(0); // Retorna os dados do funcionários encontrados no RM
- var retornoFuncinariosRM = new Array(0); // Retorna os dados do funcionários encontrados no RM
- var retornoFuncinariosUA = new Array(0); // Retorna os dados do funcionários encontrados no RM com Centro de Custo
- var retornoFuncionariosComErro = new Array(0); // Armazena as chapas não encontradas no RM
- var retornoFuncionariosComErroENome = new Array(0); // Armazena as chapas não encontradas no RM e o nome
- var listaCentroDeCusto = new Array(0); // Centro de custo
- var listaCentroDeCustoDesc = new Array(0); // Centro de custo com descrição
- var listaDeChapas;
- var novaListaCC = new Array(0);
- var retornoDataTableCC = new Array(0);
- var totalPorChapa = new Array(0); // Recebera o total geral por chapa
- var valorAgrupadosPorFunc = new Array(0); // Recebera os valores agrupados por chapa para calculo
- var totalPorChapaV = new Array(0); // Recebera a soma dos valores agrupados por chapa
- var somaTotalPorChapa = totalPorChapaV.reduce((totalGeral, total) => totalGeral + total.total, 0); // Apenas para testar a variável anterior
- var somaTotalGeral = 0;
- var rateioPorCCSemAgrupar = new Array(0);
- var rateioPorCCAgrupado = new Array(0);
- var rateioPorCCSomado = new Array(0);
- var rateioPorCCSomadoGeral = rateioPorCCSomado.reduce((totalGeral, total) => totalGeral + total.total, 0); // Apenas para validar a variavel anterior - Se houver erro em alguma das chapas o valor devera ser abaixo do total somando do espelho
- var CSVcompletoSemTratamento; // Irá armazera um JSON com os dados do espelho
- var objetoTratado; // Irá armazera um JSON com os dados tratados do espelho
- var objetoCorrigido; // Irá armazera um JSON com os dados corrigidos do espelho
- /* Funções globais */
- var novaChapa = function (chapaAntiga) {
- var novaChapa = ("000000" + chapaAntiga).slice(-6);
- return novaChapa;
- }
- var separar = (itens, maximo) => {
- return itens.reduce((acumulador, item, indice) => {
- var grupo = Math.floor(indice / maximo);
- acumulador[grupo] = [...(acumulador[grupo] || []), item];
- return acumulador;
- }, []);
- };
- function procuraNoArray(chave, conteudoChave, meuArray, campoRetorno) {
- var novoArray = new Array();
- for (var i = 0; i < meuArray.length; i++) {
- if (meuArray[i][chave] === conteudoChave) {
- novoArray.push({
- encontrou: meuArray[i][chave],
- retorno: meuArray[i][campoRetorno]
- });
- //return "Encontrou";
- } else {
- // Não faz nada... por enquanto
- }
- }
- novoArray.push({
- encontrou: "FIM",
- retorno: "FIM"
- });
- return novoArray;
- }
- function inicializarAutoComplete(nomeDoCampo) {
- var operacoesAutoComplete = [];
- if (operacoesAutoComplete[nomeDoCampo] !== undefined) {
- operacoesAutoComplete[nomeDoCampo].destroy();
- operacoesAutoComplete[nomeDoCampo] = undefined;
- }
- var campos = ["colleagueName", "colleaguePK.colleagueId"];
- var operacoes = DatasetFactory.getDataset("colleague", campos, null, null).values;
- funcTemp = [];
- for (i = 0; i < operacoes.length; i++) {
- funcTemp.push(operacoes[i]["colleaguePK.colleagueId"] + "-" + operacoes[i]["colleagueName"]);
- }
- operacoesAutoComplete[nomeDoCampo] = FLUIGC.autocomplete(nomeDoCampo, {
- source: substringMatcher(funcTemp),
- name: 'funcionarios',
- minLength: 5,
- displayKey: 'description',
- allowDuplicates: false,
- hint: true,
- tagClass: 'tag-gray',
- type: 'autocomplete'
- });
- }
- function substringMatcher(strs) {
- return function findMatches(q, cb) {
- var matches, substrRegex;
- matches = [];
- substrRegex = new RegExp(q, 'i');
- $.each(strs, function (i, str) { if (substrRegex.test(str)) { matches.push({ description: str }); } }); cb(matches);
- };
- }
- function mapeiaAlteracaoDeChapa() {
- listaDeIds = $("[id^='chapaNome']");
- listaDeIds.on("change", function () {
- for (i = 0; i < listaDeIds.length; i++) {
- if (listaDeIds[i].name != null) {
- var c1 = $("#" + listaDeIds[i].name).selector.replace('#chapaNome', '');
- var novaChapa1 = $("#chapaNome" + c1).val().split("-")[0];
- var novoFunc = $("#chapaNome" + c1).val().split("-")[1];
- if (novoFunc != undefined) {
- $("#novoFunc" + c1).text("Funcionário correto: " + novoFunc);
- $("#novoFunc" + c1).text();
- // Atribuí a chapa correta ao novoObjetoCorrigido
- for (var i = 0; i < novoObjetoCorrigido.length; i++) {
- if (novoObjetoCorrigido[i].chapa == c1) {
- novoObjetoCorrigido[i].chapa = novaChapa1;
- }
- }
- }
- }
- }
- });
- }
- function porcentagem(val1) {
- return (val1 / 100);
- }
- function calcPercet(valtotal, valUnit) {
- let previa = (valUnit * 100);
- let resultado = (previa / valtotal);
- let saida = Number(resultado).toFixed(2) + "%";
- return saida;
- }
- function buscaCC(params) {
- for (let i = 0; i < listaCentroDeCustoDesc.length; i++) {
- if (listaCentroDeCustoDesc[i].CODCCUSTO == params /* "020.030.050.002.006.003" teste */) {
- var retorno = listaCentroDeCustoDesc[i].NOME;
- }
- }
- var novoRetorno = retorno == undefined ? "CENTRO DE CUSTO NÃO IDENTIFICADO" : retorno;
- return novoRetorno;
- }
- const msgCarregamento = FLUIGC.loading(window, {
- textMessage: 'Aguarde, processando arquivo...'
- });
- const msgTxt = FLUIGC.loading(window, {
- textMessage: 'Carregando arquivo da operadora'
- });
- const consultaDadosFuncMsg = FLUIGC.loading(window, {
- textMessage: 'Processando dados dos funcionários'
- });
- const dataTableRateioMsg = FLUIGC.loading(window, {
- textMessage: 'Processando rateio'
- });
- const dataTableFalhasDeImportacaoMsg = FLUIGC.loading(window, {
- textMessage: 'Processando falhas de importação de funcionários'
- });
- const mudaChapaMsg = FLUIGC.loading(window, {
- textMessage: 'Criando campos para corrigir falhas de importação'
- });
- function mostraCarregamento(loading, anyFunction, ...anyParam) {
- loading.show();
- setTimeout(function () {
- anyFunction(...anyParam);
- loading.hide();
- }, 300);
- }
- function contaItensDeUmArray(contarEsse) {
- array_elements = contarEsse;
- array_elements.sort();
- retorno = new Array();
- var current = null;
- var cnt = 0;
- for (var i = 0; i < array_elements.length; i++) {
- if (array_elements[i] != current) {
- if (cnt > 0) {
- retorno.push({ "item": current, "contador": cnt });
- }
- current = array_elements[i];
- cnt = 1;
- } else {
- cnt++;
- }
- }
- if (cnt > 0) {
- retorno.push({ "item": current, "contador": cnt });
- }
- return retorno;
- }
- function removeRepetidosArray(arrayBusca, elemento) {
- var novoArray = new Array(0);
- verificaExistencia = function (arrayParaLimpar, itemBusca) {
- var chaves;
- chaves = arrayParaLimpar == undefined ? ['vazio', 'algo'] : arrayParaLimpar;
- var item = itemBusca;
- if (chaves.indexOf(item) > -1) {
- //console.log("Encontrou");
- var retornoVE = true;
- } else {
- //console.log("Não encontrou");
- var retornoVE = false;
- }
- return retornoVE;
- }
- for (var cont = 0; cont < arrayBusca.length; cont++) {
- var processando = arrayBusca[cont][elemento] == null ? '999999999' : arrayBusca[cont][elemento];
- if (verificaExistencia(novoArray, processando)) {
- // Se encontrar, não faz nada
- } else {
- // Se não encontrar, adiciona ao array
- novoArray.push(processando);
- //console.log(processando);
- }
- }
- return novoArray;
- }
- /* *****************************************
- Trabalhando o arquivo TXT */
- manipulaArquiv = function () {
- this.primeira = "primeira";
- variavelGlobal = this;
- }
- manipulaArquiv.prototype.lerArquivo = function (arquivo) {
- //console.log("lerArquivo");
- var reader = new FileReader();
- reader.readAsText(arquivo, 'windows-1252');
- reader.onload = function (event) {
- var csv = event.target.result;
- variavelGlobal.adicionaPrevs(csv);
- };
- return "Chamou a função para ler arquivo";
- }
- manipulaArquiv.prototype.adicionaPrevs = function (data) {
- var aLine = data.split(/\r?\n|\r/);
- aLine.forEach(function (element, index) {
- let cols = element.split(';');
- if (cols.length >= 10) {
- if (index == 0 && cols.length == 30) {
- // Não faz nada
- contadorDeLinhas++;
- }
- if (index == 1 && cols.length == 30) {
- // Não faz nada
- contadorDeLinhas++;
- }
- if (cols.length == 78 && index == 0) {
- // Não faz nada
- contadorDeLinhas++;
- }
- if (cols.length == 10 && cols[4].trim().toUpperCase() == "CENTRAL NACIONAL UNIMED") {
- // Não faz nada cols[4] == "CENTRAL NACIONAL UNIMED"
- console.log("%c" + "CENTRAL NACIONAL UNIMED", "color: lime;");
- contadorDeLinhas++;
- }
- if (cols[0].trim().toUpperCase() == "H") {
- // Não faz nada
- contadorDeLinhas++;
- }
- if (cols.length == 19) {
- // Layout criado
- variavelGlobal.getObjPrev(cols, "copartUnimedBH");
- console.log("%c" + "copartUnimedBH", "color: lime;");
- contadorDeLinhas++;
- }
- if (cols.length == 78 && index != 0) {
- // layout criado
- variavelGlobal.getObjPrev(cols, "copartCNU");
- console.log("%c" + "copartCNU", "color: lime;");
- contadorDeLinhas++;
- }
- if (cols.length == 34 || cols.length == 27) {
- // layout criado
- variavelGlobal.getObjPrev(cols, "mensalidadeUnimedBH");
- console.log("%c" + "mensalidadeUnimedBH", "color: lime;");
- contadorDeLinhas++;
- }
- if (cols.length == 30) {
- if (index == 0 || index == 1) {
- // Não faz nada
- } else {
- variavelGlobal.getObjPrev(cols, "mensalidadeCNU");
- console.log("%c" + "mensalidadeCNU", "color: lime;");
- contadorDeLinhas++;
- }
- }
- if (cols.length == 99) {
- variavelGlobal.getObjPrev(cols, "genericoGENTE");
- contadorDeLinhas++;
- }
- if (contadorDeLinhas == 0) {
- FLUIGC.message.alert({
- message: 'Layout não cadastrado para o arquivo importado ou arquivo com erro',
- title: 'Atenção',
- label: 'OK'
- }, function (el, ev) {
- console.log("------------------------");
- console.log("Linha que deu erro: " + index);
- console.log(cols);
- console.log(cols.length);
- console.log("------------------------");
- });
- }
- }
- else {
- //Não faz nada;
- }
- });
- }
- manipulaArquiv.prototype.adicionaPrevsDataset = function (data) {
- //var cs0 = DatasetFactory.createConstraint('FUNCIONAL', '00000000000139115', '00000000000139115', ConstraintType.MUST);
- var cs1 = DatasetFactory.createConstraint('COMPETENCIAPGTO', '12/2019', '12/2019', ConstraintType.MUST);
- var cs2 = DatasetFactory.createConstraint('TIPOCSV', 'MENSALIDADE', 'MENSALIDADE', ConstraintType.MUST);
- var cs3 = DatasetFactory.createConstraint('OPERADORA', 'CNU', 'CNU', ConstraintType.MUST);
- var constrr = new Array(cs1, cs2, cs3);
- var datasetDsFormCSVPlano = DatasetFactory.getDataset('dsFormCSVPlano', null, constrr, null);
- var aLine = datasetDsFormCSVPlano.values;
- aLine.forEach(function (element, index) {
- //console.log(element);
- variavelGlobal.getObjPrev(element, "dsFormCSVPlano");
- if (index == (aLine.length - 1)) {
- console.log("Acabou o processamento");
- }
- });
- }
- //variavelGlobal.adicionaPrevsDataset();
- manipulaArquiv.prototype.getObjPrev = function (colunas, layout) {
- let obj;
- depurarObjeto.push(colunas);
- console.log(JSON.parse(colunas.CCRATEIO));
- if (layout == "dsFormCSVPlano") {
- // Arquivo de coparticipação Unimed BH --- RelCO.txt
- obj = {
- beneficiario: colunas.NOME_ASSOCIADO.trim(),
- beneficiarioId: colunas.NUM_ASSOCIADO.trim(),
- prestador: null,
- prestadorId: null,
- dataAtendimento: null,
- codProcedimento: null,
- qtdProcedimento: null,
- valor: parseFloat(parseFloat(colunas.VL_FATURA.trim()) / 100), //deve ser divido por 100 para obter o valor correto
- titular: colunas.NOME_TITULAR.trim(),
- chapa: novaChapa(colunas.FUNCIONAL.trim()),
- CCRATEIO: JSON.parse(colunas.CCRATEIO)
- };
- }
- if (layout == "copartUnimedBH") {
- // Arquivo de coparticipação Unimed BH --- RelCO.txt
- obj = {
- beneficiario: colunas[3].trim(),
- beneficiarioId: colunas[4].trim(),
- prestador: colunas[5].trim(),
- prestadorId: colunas[6].trim(),
- dataAtendimento: colunas[8].trim(),
- codProcedimento: colunas[12].trim(),
- qtdProcedimento: colunas[13].trim(),
- valor: parseFloat(parseFloat(colunas[16].trim()) / 100), //deve ser divido por 100 para obter o valor correto
- titular: colunas[17].trim(),
- chapa: novaChapa(colunas[18].trim())
- };
- }
- if (layout == "mensalidadeUnimedBH") {
- obj = {
- beneficiario: colunas[2].trim(),
- beneficiarioId: colunas[1].trim(),
- prestador: colunas[17].trim(),
- prestadorId: colunas[17].trim(),
- dataAtendimento: null,
- codProcedimento: null,
- qtdProcedimento: null,
- valor: parseFloat(parseFloat(colunas[19] ? colunas[19].trim() : 0) / 100), //deve ser divido por 100 para obter o valor correto
- titular: colunas[2].trim(),
- chapa: novaChapa(colunas[25].trim())
- };
- }
- if (layout == "copartCNU") {
- obj = {
- beneficiario: colunas[19].trim(),
- beneficiarioId: colunas[16].trim(),
- prestador: colunas[64].trim(),
- prestadorId: colunas[63].trim(),
- dataAtendimento: colunas[27].trim(),
- codProcedimento: colunas[27] == undefined ? "null" : colunas[30].trim(),
- qtdProcedimento: colunas[37].trim(),
- valor: parseFloat(colunas[42].replace(",", ".") ? colunas[42].replace(",", ".") : 0),
- titular: colunas[17].trim(),
- chapa: novaChapa(colunas[13].trim())
- };
- }
- if (layout == "mensalidadeCNU") {
- obj = {
- beneficiario: colunas[8].trim(),
- beneficiarioId: colunas[11].trim(),
- prestador: null,
- prestadorId: null,
- dataAtendimento: null,
- codProcedimento: null,
- qtdProcedimento: null,
- valor: Number((colunas[21].trim()).replace(',', '.')).toFixed(2) / 100, //deve ser divido por 100 para obter o valor correto
- titular: colunas[14].trim(),
- chapa: novaChapa(colunas[6].trim())
- };
- }
- else {
- //console.log("layout não cadastrado " + new Date());
- }
- variavelGlobal.populaObjeto(obj);
- }
- manipulaArquiv.prototype.populaObjeto = function (obj) {
- novoObjeto.push(obj);
- }
- function validaInput(arquivo) {
- if (arquivo.length == 0) {
- FLUIGC.message.alert({
- message: 'Layout não cadastrado para o arquivo importado',
- title: 'Atenção',
- label: 'OK'
- }, function (el, ev) {
- console.log("Linha que deu erro");
- console.log(ev);
- });
- } else {
- console.log("Arquivo valido");
- }
- }
- // Soma os valores do novoObjeto
- manipulaArquiv.prototype.somaValoresNovoObjeto = function (nomeObjeto) {
- // Aqui realiza a soma dos valores da propriedade "valor" dentro do objeto
- var total2 = nomeObjeto.reduce((total, valor) => total + valor.valor, 0);
- // Resultado da soma
- return total2;
- }
- /* *****************************************
- Trabalhando com dados dos funcionários */
- /* A função cerraga os campos do input de chapas com erro e incializa a função inicializarAutoComplete
- passando o nome do campo que deverá ter atribuido o metodo autocomplete do Fluig */
- manipulaArquiv.prototype.mudaChapa = function () {
- var listaDeIds = $("[id^='chapaNome']");
- for (var ind = 0; ind < listaDeIds.length; ind++) {
- var mudou = listaDeIds[ind];
- var carragaCampo = "#" + $(mudou)[0].id;
- inicializarAutoComplete(carragaCampo);
- }
- }
- /* Verifica se a chapa existe e é cadastrada com colleagueId do Fluig */
- manipulaArquiv.prototype.consultaDadosFunc = function (chapa) {
- retornoFuncinarios = []; // Limpar novo objeto sempre que carregar um novo arquivo
- var constraintsUsuario = new Array();
- var chapasAConsultar = new Array();
- for (var iChapa = 0; iChapa < chapa.length; iChapa++) {
- chapasAConsultar.push(novaChapa(chapa[iChapa]));
- }
- //console.log('Chapas a consultar ' + chapasAConsultar);
- // monta constraints
- for (var func2 = 0; func2 < chapasAConsultar.length; func2++) {
- var buscar = DatasetFactory.createConstraint('colleaguePK.colleagueId', chapasAConsultar[func2], chapasAConsultar[func2], ConstraintType.SHOULD);
- constraintsUsuario.push(buscar);
- }
- var dataset = DatasetFactory.getDataset('colleague', null, constraintsUsuario, null);
- for (var i = 0; i < dataset.values.length; i++) {
- retornoFuncinarios.push(dataset.values[i]);
- }
- return dataset;
- }
- /* Consulta dados do funcionário direto no RM */
- manipulaArquiv.prototype.consultaDadosFuncRM = function (chapa) {
- // Não funcionou como deveria, a configuração da consulta no RM só permite a consulta de uma chapa por vez
- retornoFuncinariosRM = new Array(0); // Limpar novo objeto sempre que carregar um novo arquivo
- var constraintsUsuario = new Array();
- var chapasAConsultar = new Array();
- for (var iChapa = 0; iChapa < chapa.length; iChapa++) {
- chapasAConsultar.push(novaChapa(chapa[iChapa]));
- }
- //console.log('Chapas a consultar ' + chapasAConsultar);
- for (var func2 = 0; func2 < chapasAConsultar.length; func2++) {
- var buscar = DatasetFactory.createConstraint('CHAPA', chapasAConsultar[func2], chapasAConsultar[func2], ConstraintType.SHOULD);
- constraintsUsuario = new Array(buscar);
- var dataset = DatasetFactory.getDataset('dsBuscaDadosFuncionarioRM', null, constraintsUsuario, null);
- for (var i = 0; i < dataset.values.length; i++) {
- if (dataset.values[i]["NOME"] != null) {
- //console.log("Encontrado");
- retornoFuncinariosRM.push(dataset.values[i]);
- }
- if (dataset.values[i]["CHAPA"] == "Cannot find function has in object ." || dataset.values[i]["CHAPA"] == null || dataset.values[i]["CHAPA"] == undefined) {
- //console.log("Não encontrado");
- retornoFuncinariosRM.push({
- "CHAPA": chapasAConsultar[func2],
- "NOME": "Desconhecido"
- });
- }
- }
- }
- }
- /* Consulta dados do RM retornando o também o centro de custo e a fração de rateio */
- manipulaArquiv.prototype.consultaDadosFuncUA = function (chapa) {
- //console.log("==============================")
- console.log("%c" + "Carregando os dados dos funcionários", "color: pink;");
- retornoFuncinariosUA = null;
- var chapas = [];
- for (let j = 0; j < chapa.length; j++) {
- chapas.push(novaChapa(chapa[j]));
- }
- var lista = separar(chapas, 1000);
- var constraintsUsuario = [];
- var saida = [];
- for (let i = 0; i < lista.length; i++) {
- var buscar = DatasetFactory.createConstraint('CHAPA_IN', lista[i].join(), null, ConstraintType.SHOULD);
- constraintsUsuario = new Array(buscar);
- var datasetUA = DatasetFactory.getDataset('ds_BuscaFuncionarioComRateio', null, constraintsUsuario, null);
- saida.push(datasetUA.values);
- }
- var retorno = saida.flat();
- retornoFuncinariosUA = retorno;
- return retorno;
- }
- /* Monta o datable com falhas de importação */
- manipulaArquiv.prototype.dataTableFalhasDeImportacao = function (nomeObjeto) {
- console.log("%c" + "Montando o datatable com falhas de importação", "color: red;");
- var retornoDataTable = new Array(0);
- var funcionariosBuscar = new Array(0);
- var removerRepetido = new Array(0)
- novoObjetoCorrigido = novoObjeto;
- retornoFuncinariosUA;
- // Remove os repetidos para encontramos as chapas com erro
- var removerRepetido = new Array(0)
- for (var i = 0; i < nomeObjeto.length; i++) {
- if (removerRepetido.length == 0) {
- removerRepetido.push(nomeObjeto[i]);
- }
- if (removerRepetido.length > 0) {
- for (var j = 0; j < removerRepetido.length; j++) {
- var buscaChapaNoRepetido = removerRepetido.map(function (e) { return e.chapa; }).indexOf(nomeObjeto[i].chapa);
- var buscaChapaNoUA = retornoFuncinariosUA.map(function (e) { return e.CHAPA; }).indexOf(nomeObjeto[i].chapa);
- if (buscaChapaNoUA < 0 && buscaChapaNoRepetido < 0) {
- //console.log("Chapa não encontrada %c" + nomeObjeto[i].chapa, "color: red;");
- removerRepetido.push({
- naoEncontrado: "Sim",
- ...nomeObjeto[i]
- });
- }
- else if (buscaChapaNoRepetido < 0) {
- var element = removerRepetido[j].titular + " - " + nomeObjeto[i].titular;
- removerRepetido.push(nomeObjeto[i]);
- }
- //console.log(i + " - " + j);
- }
- }
- }
- //console.log(removerRepetido);
- var retornoDataTable = new Array(0);
- for (var iii = 0; iii < removerRepetido.length; iii++) {
- if (removerRepetido[iii].naoEncontrado == "Sim" && removerRepetido[iii].naoEncontrado) {
- retornoDataTable.push(new Array(
- removerRepetido[iii].chapa,
- removerRepetido[iii].titular,
- removerRepetido[iii].valor
- ));
- }
- }
- //console.log("%c" + "Chapas com erro", "color: red;");
- //console.log(retornoDataTable);
- var tabela = $('#tableFalhasDeImportacao').dataTable();
- tabela.fnDestroy();
- $('#tableFalhasDeImportacao').dataTable({
- data: retornoDataTable,
- "language": {
- "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/Portuguese-Brasil.json"
- },
- "pageLength": 50,
- columns: [
- {
- title: "Procurar chapa correta",
- "class": "novaChapa fs-txt-center col-md-1",
- "orderable": false,
- "render": function (data, type, full, meta) {
- var retornoBC = "<input type=\"text\" class=\"form-control\" id=\"chapaNome" + full[0] + "\" name=\"chapaNome" + full[0] + "\">";
- return retornoBC;
- },
- },
- {
- title: "Nome",
- "render": function (data, type, full, meta) {
- var retornoClass = "<span id='nomeFuncionario" + full[0] + "'>" + full[1] + "</span><label for='novoFunc" + full[0] + "' id='novoFunc" + full[0] + "'></label>";
- return retornoClass;
- }
- },
- { title: "Valor", "class": "moedaReal" }
- ]
- });
- }
- /* Remove chapas repetidas para agilizar as consultas */
- manipulaArquiv.prototype.removeChapasRepetidas = function (nomeObjeto) {
- var arrayDeChapas = [];
- verificaExistencia = function (array, itemBusca) {
- var chaves;
- chaves = array == undefined ? ['vazio', 'algo'] : array;
- var item = itemBusca;
- if (chaves.indexOf(item) > -1) {
- var retornoVE = true;
- } else {
- var retornoVE = false;
- }
- return retornoVE;
- }
- for (var rCI = 0; rCI < nomeObjeto.length; rCI++) {
- if (verificaExistencia(arrayDeChapas, parseInt(nomeObjeto[rCI]['chapa']))) {
- // Se encontrar, não faz nada
- } else {
- // Se não encontrar, adiciona ao array
- arrayDeChapas.push(parseInt(nomeObjeto[rCI]['chapa']));
- }
- }
- return arrayDeChapas;
- }
- /* Compara itens de arrys, porém, é necessário ter as chaves login e chapa */
- manipulaArquiv.prototype.compararArrays = function (array1, array2) {
- retornoFuncionariosComErro = new Array(0);
- retornoFuncionariosComErroENome = new Array(0);
- for (var ai1 = 0; ai1 < array1.length; ai1++) {
- for (var ai2 = 0; ai2 < array2.length; ai2++) {
- var retorno = procuraNoArray('login', array2[ai2]['chapa'], array1);
- //console.log("Chapa consultada: " + array2[ai2]['chapa']);
- var novoRetorno = retorno == undefined ? "Não encontrou nada" : retorno;
- //console.log(retorno);
- }
- }
- return novoRetorno;
- }
- /* *****************************************
- * Trabalhando os centro de custo
- **/
- /* Remove códigos de centro de custo repetidos e atribuí a uma array */
- manipulaArquiv.prototype.removeCCRepetidos = function (retornoFunc) {
- console.log("%c" + "Removendo centro de custo repetido", "color: #ffff00;");
- var arrayDeCC = [];
- verificaExistencia = function (array, itemBusca) {
- var chaves;
- chaves = array == undefined ? ['vazio', 'algo'] : array;
- var item = itemBusca;
- if (chaves.indexOf(item) > -1) {
- //console.log("Encontrou");
- var retornoVE = true;
- } else {
- //console.log("Não encontrou");
- var retornoVE = false;
- }
- return retornoVE;
- }
- for (var rCI = 0; rCI < retornoFunc.length; rCI++) {
- var centroDeCusto = retornoFunc[rCI]['CODCCUSTO'] == null ? '999999999' : retornoFunc[rCI]['CODCCUSTO'];
- if (verificaExistencia(arrayDeCC, centroDeCusto)) {
- // Se encontrar, não faz nada
- } else {
- // Se não encontrar, adiciona ao array
- arrayDeCC.push(centroDeCusto);
- //console.log(centroDeCusto);
- }
- }
- return arrayDeCC;
- }
- /* Consulta centro de custo a partir do novo array
- O dataset de funcionários já retorna o centro de custo com código e descrição, utilizar para para fazer essa lista.
- */
- manipulaArquiv.prototype.consultaCentroDeCusto = function (CODCCUSTO) {
- console.log("%c" + "Consultando centro de custo no RM", "color: #bfff00;");
- listaCentroDeCustoDesc = new Array(0);
- var pesquisarCC = separar(CODCCUSTO, 50);
- novaListaCC = new Array(0);
- for (let j = 0; j < pesquisarCC.length; j++) {
- let cccs = new Array(0);
- for (let ccc = 0; ccc < pesquisarCC[j].length; ccc++) {
- let c1 = DatasetFactory.createConstraint('CODCCUSTO', pesquisarCC[j][ccc], pesquisarCC[j][ccc], ConstraintType.SHOULD, true);
- cccs.push(c1);
- }
- let datasetDsCentroDeCusto = DatasetFactory.getDataset('dsBuscaCentroCusto', null, cccs, null);
- listaCentroDeCustoDesc.push(datasetDsCentroDeCusto.values);
- novaListaCC.push(datasetDsCentroDeCusto.values);
- }
- var saida = novaListaCC;
- return saida;
- }
- /* Cria um array com o número do centro de custo de todos os funcionários */
- manipulaArquiv.prototype.contaFuncCC = function () {
- console.log("%c" + "Alimento array de CC para o datatable", "color: #80ff00;");
- let arrayDeCCConta = new Array(0);
- for (let i = 0; i < retornoDataTableCC.length; i++) {
- arrayDeCCConta.push(retornoDataTableCC[i][0]);
- }
- return arrayDeCCConta;
- }
- /* Cria o datatable que lista o rateio por centro de custo */
- manipulaArquiv.prototype.dataTableRateio = function () {
- console.log("%c" + "Construindo o datatable de rateio por CC", "color: #40ff00;");
- retornoDataTableCC = new Array(0);
- // Prepara estrutura para o datatable
- for (var iii = 0; iii < rateioPorCCSomado.length; iii++) {
- retornoDataTableCC.push(new Array(
- rateioPorCCSomado[iii]["CODCCUSTO"],
- rateioPorCCSomado[iii]["NOME"],
- rateioPorCCSomado[iii]["TOTAL"],
- calcPercet(somaTotalGeral, rateioPorCCSomado[iii]["TOTAL"])
- ));
- }
- // Testar retorno
- //console.log(retornoDataTableCC);
- var tabela = $('#tableRadioCC').dataTable();
- tabela.fnDestroy();
- $('#tableRadioCC').dataTable({
- data: retornoDataTableCC,
- "language": {
- "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/Portuguese-Brasil.json"
- },
- "pageLength": 50,
- columns: [
- { title: "Centro de Custo" },
- { title: "Descrição" },
- { title: "Valor", "class": "moedaReal" },
- {
- title: "Percentual",
- "class": "anexoTable fs-txt-center col-md-1",
- "orderable": false,
- "render": function (data, type, full, meta) {
- return full[3];
- }
- }
- ]
- });
- }
- // Agrupa valores gastos por chapa
- manipulaArquiv.prototype.agrupaChapas = function (ArrayASerProcessado) {
- console.log("%c" + "Realizando agrupamento de chapas", "color: #00ffbf;");
- var variavel = ArrayASerProcessado;
- var chapas = variavel.reduce((obj, { chapa, valor }) => {
- //console.log(chapas);
- if (!obj[chapa]) obj[chapa] = [];
- obj[chapa].push(valor);
- return obj;
- }, {});
- var outraVariante = Object.keys(chapas).map(chapa => {
- return {
- chapa,
- valores: chapas[chapa]
- };
- });
- return outraVariante;
- }
- // Soma os valores do beneficio por agrupamento de chapa
- manipulaArquiv.prototype.somaValoresChapasAgrupadas = function (arraySomar) {
- console.log("%c" + "Somando valores por agrupamento de chapas", "color: #0080ff;");
- // Aqui realiza a soma dos valores da propriedade "valor" dentro do objeto
- var totalSomado = arraySomar.reduce((total, valores) => total + valores, 0);
- // Resultado da soma
- return totalSomado;
- }
- // Calcula o total geral por chapa e popula o array
- manipulaArquiv.prototype.totalPorChapa = function (agrupamentoValores) {
- console.log("%c" + "Total por chapa", "color: #ff00ff;");
- var totalSomado = new Array(0);
- for (i = 0; i < agrupamentoValores.length; i++) {
- var valorSomado = variavelGlobal.somaValoresChapasAgrupadas(agrupamentoValores[i]['valores']);
- totalSomado.push({
- chapa: agrupamentoValores[i]["chapa"],
- total: valorSomado
- });
- }
- return totalSomado;
- }
- // Calcula o total geral por chapa e popula o array
- manipulaArquiv.prototype.rateioPorCCFunc = function () {
- console.log("%c" + "Rateio por CC do funcionário", "color: #ff8000;");
- var output = retornoFuncinariosUA.map(s => ({ chapa: s.CHAPA, ...s }));
- rateioPorCCSemAgrupar = new Array(0);
- for (let i = 0; i < output.length; i++) {
- for (let j = 0; j < totalPorChapaV.length; j++) {
- if (totalPorChapaV[j].chapa == output[i].chapa) {
- rateioPorCCSemAgrupar.push({
- CHAPA: totalPorChapaV[j].chapa,
- CODCCUSTO: output[i].CODCCUSTO,
- DESCCC: buscaCC(output[i].CODCCUSTO),
- RATEIO: output[i].RATEIO,
- VTOTAL: totalPorChapaV[j].total,
- VRATEIO: totalPorChapaV[j].total * parseFloat(output[i].RATEIO / 100)
- });
- }
- }
- }
- return rateioPorCCSemAgrupar;
- }
- manipulaArquiv.prototype.agrupamentoCC = function (ArrayASerProcessado) {
- console.log("%c" + "Novo agrupamento por CC do funcionário", "color: #ffff00;");
- var variavel = ArrayASerProcessado;
- rateioPorCCAgrupado = new Array(0);
- var CCs = variavel.reduce((obj, { CODCCUSTO, VRATEIO }) => {
- if (!obj[CODCCUSTO]) obj[CODCCUSTO] = [];
- obj[CODCCUSTO].push(VRATEIO);
- return obj;
- }, {});
- var outraVariante = Object.keys(CCs).map(CODCCUSTO => {
- return {
- CODCCUSTO,
- valores: CCs[CODCCUSTO]
- };
- });
- rateioPorCCAgrupado = outraVariante;
- return outraVariante;
- }
- manipulaArquiv.prototype.totalPorCC = function (agrupamentoValores) {
- console.log("%c" + "Total por centro de custo", "color: #80ff00;");
- var totalSomado = new Array(0);
- rateioPorCCSomado = new Array(0);
- for (i = 0; i < agrupamentoValores.length; i++) {
- var valorSomado = variavelGlobal.somaValoresChapasAgrupadas(agrupamentoValores[i]['valores']);
- totalSomado.push({
- CODCCUSTO: agrupamentoValores[i]["CODCCUSTO"],
- NOME: buscaCC(agrupamentoValores[i]["CODCCUSTO"]),
- TOTAL: valorSomado
- });
- }
- rateioPorCCSomado = totalSomado;
- return totalSomado;
- }
- manipulaArquiv.prototype.init = function (objetoCarregado) {
- /* Pega lista de chapas únicas e cunsulta dos dados dos funcionários listados */
- setTimeout(() => {
- valorAgrupadosPorFunc = variavelGlobal.agrupaChapas(objetoCarregado);
- totalPorChapaV = variavelGlobal.totalPorChapa(valorAgrupadosPorFunc);
- somaTotalGeral = variavelGlobal.somaValoresNovoObjeto(objetoCarregado);
- $("#valorTotalEspelho").val(somaTotalGeral);
- setTimeout(() => {
- listaCentroDeCusto = variavelGlobal.removeCCRepetidos(retornoFuncinariosUA); /// retornoFuncinariosUA ou retornoFuncinarios
- mostraCarregamento(dataTableRateioMsg, variavelGlobal.consultaCentroDeCusto, listaCentroDeCusto); // Linha 773 Busca o nome do centro de custo no RM
- setTimeout(() => {
- mostraCarregamento(dataTableRateioMsg, variavelGlobal.rateioPorCCFunc); // 740
- setTimeout(() => {
- mostraCarregamento(dataTableRateioMsg, variavelGlobal.agrupamentoCC, rateioPorCCSemAgrupar); // aqui esta dando erro - gargalo aqui
- setTimeout(() => {
- mostraCarregamento(dataTableRateioMsg, variavelGlobal.totalPorCC, rateioPorCCAgrupado);
- setTimeout(() => {
- mostraCarregamento(dataTableRateioMsg, variavelGlobal.dataTableRateio);
- /* Carrega dos dataTables de rateio e falhas de importação */
- setTimeout(() => {
- mostraCarregamento(dataTableFalhasDeImportacaoMsg, variavelGlobal.dataTableFalhasDeImportacao, objetoCarregado);
- setTimeout(() => {
- mostraCarregamento(mudaChapaMsg, variavelGlobal.mudaChapa);
- setTimeout(() => {
- mapeiaAlteracaoDeChapa();
- setTimeout(() => {
- // JSON
- CSVcompletoSemTratamento = JSON.stringify(depurarObjeto); // Irá armazera um JSON com os dados do espelho
- objetoTratado = JSON.stringify(novoObjeto); // Irá armazera um JSON com os dados tratados do espelho
- objetoCorrigido = JSON.stringify(novoObjetoCorrigido) > 0 ? JSON.stringify(novoObjetoCorrigido) : JSON.stringify(novoObjeto); // Irá armazera um JSON com os dados corrigidos do espelho
- $("#CSVcompletoSemTratamento").val(CSVcompletoSemTratamento);
- $("#objetoTratado").val(objetoTratado);
- $("#objetoCorrigido").val(objetoCorrigido);
- }, 300);
- }, 300);
- }, 300);
- }, 300);
- }, 300);
- }, 300);
- }, 300);
- }, 300);
- }, 299);
- }, 500);
- }
- // Essa é a função que irá regerar o arquivo de imoprtação
- manipulaArquiv.prototype.correcaoDeDivergencias = function (params) {
- console.log("%c" + "Correção de divergências", "color: #80ff00;");
- variavelGlobal.init(novoObjetoCorrigido);
- }
- /* *****************************************
- Função mágica */
- manipulaArquiv.prototype.pegaArquivoDoInput = function (evt) {
- console.clear();
- clear();
- console.log("Mudou arquivo - pegaArquivoDoInput");
- novoObjeto = new Array(0); // Limpar novo objeto sempre que carregar um novo arquivo
- depurarObjeto = new Array(0); // Limpar novo objeto sempre que carregar um novo arquivo
- retornoFuncinarios = new Array(0); // Limpar novo objeto sempre que carregar um novo arquivo
- contadorDeLinhas = 0;
- var files = evt.target.files;
- var file = files[0];
- var r = /\.(TXT)$/;
- if (r.test(file.name.toUpperCase())) {
- var carregandoArquivoTXT = variavelGlobal.lerArquivo(file);
- mostraCarregamento(msgTxt, carregandoArquivoTXT);
- } else {
- FLUIGC.toast({ title: 'Por Favor:', message: 'Envie um arquivo no formato TXT (.txt)', type: 'warning' });
- }
- variavelGlobal.init(novoObjeto);
- }
- /* Inicialização do documento */
- var variavelGlobal = new manipulaArquiv(true);
- $(document).ready(function () {
- console.clear();
- /* Essa é a primeira chamanda; Quando o usuário solicitar o carregamento do TXT da operadora.
- as demais execuções serão feitas pela função pegaArquivoDoInput */
- $("#inputBotaoAnexoEspelho").on('change', variavelGlobal.pegaArquivoDoInput);
- // Para teste, o campo não estava limpando ao recarregar o formulário
- $("#valorTotalEspelho").val("");
- $("#regerarEspelho").on("click", variavelGlobal.correcaoDeDivergencias);
- });
- /* Fim fazer teste e remover */
- var logTitle = function (title) {
- console.log("%c--------------------------------", "color: red ;font-weight:bold;");
- console.log(title);
- return "--------------------------------";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement