Is it possible to reuse this complex function for multiple entries at the same time?

0

In the site that I assumed from a previous developer, one registers investors one by one after a system search called CM. The function is called cadastraInvestidor:

function cadastraInvestidor(codigoCM){ // TODO 2/4/2015 - Cadastro de investidor com código CM
$.ajax({
      async: true, cache:false, 
      url: '[:raiz]cadAdmin/getDetalhesInvestidorCM',
      data: {
          codigoCM: codigoCM
      },
      dataType: 'json',
      success: function(data) {
          if (data == 'erro'){
                 $("#erroInvestidorJaCadastrado").dialog( {
                    buttons : {
                        Ok : function() {
                            $(this).dialog('close');
                        }
                    },
                    modal : true,
                    autoOpen : false,
                    resizable : false,
                    closeOnEscape : false,
                    open : function(event, ui) {
                        $(".ui-dialog-titlebar-close").hide();
                    }
                 });    
                 $("#erroInvestidorJaCadastrado").dialog('open');
          } else {
                var arrayContatos = new Array();
                var close = $('#lblCancelar').val();
                var save = $('#lblSalvar').val();
                var dialog_buttons = {};  

                dialog_buttons[close] = function(){
                    $( this ).dialog( "close" );
                };
                dialog_buttons[save] = function(){

                    $.ajax({
                          async: true, cache:false, 
                          url: '[:raiz]cadAdmin/validaEmailInvestidorCM',
                          data: {
                              codigoCM: codigoCM
                          },
                          dataType: 'json',
                          success: function(dt) {

                              var info = new Array();
                              info[0] = $('#lblInfo0').val();
                              info[1] = $('#lblInfoConfDadosCM1').val();
                              info[2] = $('#lblInfoSalvaInvest2').val();
                              info[3] = $('#lblInfoSalvaInvest3').val();
                              info[4] = $('#lblInfoSalvaInvest4').val();
                              info[5] = $('#lblInfoSalvaInvest5').val();
                              info[6] = $('#lblInfoSalvaInvest6').val();
                              info[7] = $('#lblInfoSalvaInvest7').val();
                              info[8] = $('#lblInfoSalvaInvest8').val();
                              info[9] = $('#lblInfoSalvaInvest9').val();
                              info[10] = $('#lblInfo9').val();
                              info[11] = $('#lblInfoCom7').val();
                              info[12] = $('#lblInfo11').val();
                              info[13] = $('#lblInfoCom8').val();
                              info[14] = $('#lblInfoConfDadosCM25').val();
                              info[15] = $('#lblInfo12').val();

                              data['info']=info;

                              if(dt=='1'){  //VALIDAÇÃO EMAIL DT=0 CERTO DT=1 ERRADO DT=2 E-MAIL EM BRANCO
                                  $("#erroEmail").dialog( {
                                        buttons : {
                                            Ok : function() {
                                                $(this).dialog('close');
                                            }
                                        },
                                        modal : true,
                                        autoOpen : false,
                                        resizable : false,
                                        closeOnEscape : false,
                                        width: 500,
                                        height: 120,
                                        open : function(event, ui) {
                                            $(".ui-dialog-titlebar-close").hide();
                                        }
                                     });                                      
                                  $('#erroEmail').dialog('open');
                              }
                                else if(dt=='0') {
                                    $.ajax({
                                          async: true, cache:false, 
                                          url: '[:raiz]cadAdmin/cadastraInvestidorCM',
                                        //  data: ({
                                             data : data,
                                        //}),
                                          type: "POST",
                                          dataType: 'json',
                                          success: function(dados) {

                                             $("#erroUhSemUnidade,#sucessoSalvaCM,#erroEmailInvestidor,#erroLoginInvestidor").dialog( {
                                                buttons : {
                                                    Ok : function() {
                                                        $(this).dialog('close');
                                                    }
                                                },
                                                modal : true,
                                                autoOpen : false,
                                                resizable : false,
                                                closeOnEscape : false,
                                                width: 500,
                                                open : function(event, ui) {
                                                    $(".ui-dialog-titlebar-close").hide();
                                                }
                                             });    

                                              $.ajax({
                                                  cache:false, 
                                                  data: ({
                                                          codigoCM: codigoCM,
                                                          preferencias: (data['tipo'] == 'F' ? $('#txtPreferenciasF').val() : $('#txtPreferenciasJ').val()),
                                                          comportamento: (data['tipo'] == 'F' ? $('#txtComportamentoF').val() : $('#txtComportamentoJ').val()) 
                                                  }),
                                                  url: '[:raiz]cadAdmin/salvaInfoInvestidorCodigoCM',
                                                  dataType: 'json',
                                                  success: function(dt) {                   
                                                        //$('#modalDadosSalvos').dialog('open');
                                                      $.ajax({
                                                          cache:false, 
                                                          data: ({
                                                                  codigoCM: codigoCM,
                                                                  arrayContatos : arrayContatos,
                                                          }),
                                                          type: "POST",
                                                          url: '[:raiz]cadAdmin/salvaContatoInvestidor',
                                                          dataType: 'json',
                                                      });
                                                  }
                                              });
                                              if(dados != null && dados != ""){
                                                  if (dados == '2'){
                                                      $("#erroEmailInvestidor").dialog('open');
                                                  } 
                                                  else if (dados == '3') {
                                                      $("#erroLoginInvestidor").dialog('open');
                                                  }
                                                  else {
                                                      if(dados.split("|")[1] != ''){
                                                          var dadosSplit = dados.split("|");
                                                          var tam = dadosSplit.length;
                                                          var erros ='';
                                                          for ( var int = 0; int < (tam-1); int++) {
                                                              erros+=' '+dadosSplit[int];
                                                              if (int != (tam-2)){
                                                                  erros+=',';
                                                              }
                                                          }
                                                          $("#erroUhSemUnidade").html($('#errosalva').val()+erros);
                                                          $("#erroUhSemUnidade").dialog('open');
                                                      }else{

                                                          $("#erroUhSemUnidade").html($('#errosalva').val()+dados.split("|")[0]);
                                                          $("#erroUhSemUnidade").dialog('open');
                                                      }
                                                  }
                                              }else{
                                                  $("#sucessoSalvaCM").dialog('open');
                                              }
                                              $( "#modalDetalhes" ).dialog( "close" );
                                          }
                                    });
                                }else if(dt=='2'){
                                    $("#emailEmBranco").dialog( {
                                        buttons : {
                                            Ok : function() {
                                                $(this).dialog('close');
                                            }
                                        },
                                        modal : true,
                                        autoOpen : false,
                                        resizable : false,
                                        closeOnEscape : false,
                                        width: 500,
                                        open : function(event, ui) {
                                            $(".ui-dialog-titlebar-close").hide();
                                        }
                                     });                                        
                                    $("#emailEmBranco").dialog('open');
                                }
                          }
                    });
                };
                $('#bodyInvestidoresUh').html("");
                $('#bodyInvestidoresUhJ').html("");
                if(data['dataNascimento'] != 'NULL'){
                      var nasc = data['dataNascimento'].split("-");
                      nasc = nasc[2]+"/"+nasc[1]+"/"+nasc[0];
                  }else{
                    var nasc = 'NULL';
                  }

                if (data['tipo'] == 'F'){
                      var checkBox = "";
                      var tamanhoModal = 670 + (50 * parseInt(data['uhs'].length));
                      $('#detalhesFisica').show();
                      $('#detalhesJuridica').hide();
                      $('#modalDetalhes').attr('title',$('#lblDetalhesInvestidor').val());
                      $('#modalDetalhes').dialog({
                            width: 625,
                            height: tamanhoModal,
                            modal: true,
                            buttons: dialog_buttons,
                            autoOpen: true,
                            resizable: false,
                            closeOnEscape: true,
                            position: 'top',
                            close: function(){

                            }
                      });

                      $('#txtPreferenciasF').val("");
                      $('#txtComportamentoF').val("");

                      $('#lblFisicaNome').html(data['nome'].toString().toUpperCase() == 'NULL' ? '' : data['nome'].toString());                   
                      $('#lblFisicaCPF').html(data['documento'].toString().toUpperCase() == 'NULL' ? '' : data['documento'].toString());
                      $('.lblFisicaDataNascimento').html(nasc.toUpperCase() == 'NULL' ? '' : nasc.toString());
                      $('#lblFisicaEmail').html(data['email'].toString().toUpperCase() == 'NULL' ? '' : data['email'].toString());
                      $('#lblFisicaTelefone').html(data['telefone'].toString().toUpperCase() == 'NULL' ? '' : data['telefone'].toString());
                      $('#lblFisicaLogradouro').html(data['logradouro'].toString().toUpperCase() == 'NULL' ? '' : data['logradouro'].toString());
                      $('#lblFisicaBairro').html(data['bairro'].toString().toUpperCase() == 'NULL' ? '' : data['bairro'].toString());                     
                      $('#lblFisicaCidade').html(data['cidade'].toString().toUpperCase() == 'NULL' ? '' : data['cidade'].toString());
                      $('#lblFisicaEstado').html(data['estado'].toString().toUpperCase() == 'NULL' ? '' : data['estado'].toString());
                      $('#lblFisicaPais').html(data['pais'].toString().toUpperCase() == 'NULL' ? '' : data['pais'].toString());
                      $('#lblFisicaCargo').html(data['cargo'].toString().toUpperCase() == 'NULL' ? '' : data['cargo'].toString());
                      $('#lblFisicaCC').html(data['contaCorrente'].toString().toUpperCase() == 'NULL' ? '' : data['contaCorrente'].toString());
                      $('#lblFisicaAgencia').html(data['agencia'].toString().toUpperCase() == 'NULL' ? '' : data['agencia'].toString());
                      $('#lblFisicaBanco').html(data['banco'].toString().toUpperCase() == 'NULL' ? '' : data['banco'].toString());

                      $('#tableInvestidoresUh').show();
                      var retorno = "";
                      //$('#bodyInvestidoresUh').html(retorno);

                      for ( var int = 0; int < data['uhs'].length; int++) {
                            retorno += "<tr>";
                            if((data['uhs'][int]['numero']).match(/^S.*$/)){
                                retorno += "<td>"+ 'Office' +"</td>";
                            } else if ((data['uhs'][int]['numero']).match(/^L.*$/) || (data['uhs'][int]['numero']).match(/^B.*$/)){
                                retorno += "<td>"+ 'Outros' + "</td>";
                            } else {
                            retorno += "<td>"+ (data['uhs'][int]['tipoinvestidor'] == 'P' ? 'Pool' : 'Condomínio') +"</td>";
                            }
                            retorno += "<td>"+data['uhs'][int]['numero']+" - "+data['uhs'][int]['desctipo']+"</td>";
                            retorno += "<td>"+data['uhs'][int]['unidade']+"</td>";
                            retorno += "<td>"+data['uhs'][int]['descricao']+"</td>";
                            retorno += "<td>"+data['uhs'][int]['participacao']+"</td>";
                            retorno += "</tr>";
                      }
                     $('#bodyInvestidoresUh').html(retorno);

                     var contato =0;
                     $.ajax({
                            async: false, cache:false, 
                            url: '[:raiz]cadAdmin/getContatoInvestidorCm',
                            data: {
                                codCm: codigoCM
                            },
                            dataType: 'json',
                            success: function(dt) {
                                var contactTable = "";
                                if (dt[0]!=undefined && dt[0]['COUNT'] > 0){
                                    contato = dt[0]['COUNT'];
                                    $('#txt0DadosContato').show();
                                    contactTable+="<table class='tables' style='width:565px;float:left;font-size: 11px;'><tr><td>"+$('#lblNome').val()+"</td>" +
                                            "<td>"+$('#lblTel').val()+"</td><td>"+$('#lblEmail').val()+"</td></tr>";
                                    for(var i=0;i<dt.length;i++){
                                        arrayContatos[i] = dt[i]['NOME']+"|"+dt[i]['TELEFONE'] +"|"+ dt[i]['EMAIL']+";";
                                        var nome = (dt[i]['NOME']!=undefined ? dt[i]['NOME'] : "");
                                        var telefone = (dt[i]['TELEFONE']!=undefined ? dt[i]['TELEFONE'] : "");
                                        var email = (dt[i]['EMAIL']!=undefined ? dt[i]['EMAIL'] : "");
                                        contactTable+=("<tr><td>" + nome + " </td><td> " + telefone + " </td><td> " + email +"</td></tr>");
                                    }
                                    contactTable+="</table>";
                                    $('#txt1DadosContato').show();
                                }else{
                                    $('#txt1DadosContato').hide();
                                }
                                $('.dadosContato').html(contactTable);
                            }
                        }); 
                     var tamanhoModal = (670 + (45 * ((parseInt(data['uhs'].length)>0 ?parseInt(data['uhs'].length)+2 : 0 ))
                             + ((contato>0 ? contato+2 : 0)*20))*1.22); 
                     $('#detalhesFisica').show();
                     $('#detalhesJuridica').hide();
                     $('#modalDetalhes').attr('title',$('#lblDetalhesInvestidor').val());
                     $('#modalDetalhes').dialog({
                            width: 625,
                            height: tamanhoModal,
                            modal: true,
                            buttons: dialog_buttons,
                            autoOpen: true,
                            resizable: false,
                            closeOnEscape: true,
                            position: 'top',
                            close: function(){

                            }
                        });
                } else {
                      var checkBox = "";

                      $('#txtPreferenciasJ').val("");
                      $('#txtComportamentoJ').val("");                          

                      $('#lblJuridicaNome').html(data['nome'].toString().toUpperCase() == 'NULL' ? '' : data['nome'].toString());
                      $('.lblFisicaDataNascimento').html(nasc.toUpperCase() == 'NULL' ? '' : nasc.toString());
                      $('#lblJuridicaCNPJ').html(data['documento'].toString().toUpperCase() == 'NULL' ? '' : data['documento'].toString());
                      $('#lblJuridicaRazaoSocial').html(data['razaoSocial'].toString().toUpperCase() == 'NULL' ? '' : data['razaoSocial'].toString());
                      $('#lblJuridicaTipo').html(data['tipo'].toString().toUpperCase() == 'NULL' ? '' : (data['tipo'].toString().localeCompare('F') == 0 ? "Física" : "Jurídica"));
                      $('#lblJuridicaEmpresa').html(data['empresa'].toString().toUpperCase() == 'NULL' ? '' : data['empresa'].toString());
                      $('#lblJuridicaEmail').html(data['email'].toString().toUpperCase() == 'NULL' ? '' : data['email'].toString());
                      $('#lblJuridicaTelefone').html(data['telefone'].toString().toUpperCase() == 'NULL' ? '' : data['telefone'].toString());                 
                      $('#lblJuridicaLogradouro').html(data['logradouro'].toString().toUpperCase() == 'NULL' ? '' : data['logradouro'].toString());
                      $('#lblJuridicaBairro').html(data['bairro'].toString().toUpperCase() == 'NULL' ? '' : data['bairro'].toString());         
                      $('#lblJuridicaCidade').html(data['cidade'].toString().toUpperCase() == 'NULL' ? '' : data['cidade'].toString());
                      $('#lblJuridicaEstado').html(data['estado'].toString().toUpperCase() == 'NULL' ? '' : data['estado'].toString());
                      $('#lblJuridicaPais').html(data['pais'].toString().toUpperCase() == 'NULL' ? '' : data['pais'].toString());
                      $('#lblJuridicaCargo').html(data['cargo'].toString().toUpperCase() == 'NULL' ? '' : data['cargo'].toString());
                      $('#lblJuridicaCC').html(data['contaCorrente'].toString().toUpperCase() == 'NULL' ? '' : data['contaCorrente'].toString());
                      $('#lblJuridicaAgencia').html(data['agencia'].toString().toUpperCase() == 'NULL' ? '' : data['agencia'].toString());
                      $('#lblJuridicaBanco').html(data['banco'].toString().toUpperCase() == 'NULL' ? '' : data['banco'].toString());

                      $('#tableInvestidoresUhJ').show();
                      var retorno = "";
                      //$('#bodyInvestidoresUhJ').html(retorno);
                      for ( var int = 0; int < data['uhs'].length; int++) {
                        retorno += "<tr>";
                        if ((data['uhs'][int]['desctipo']).match(/^S.*$/)){
                            retorno += "<td>"+ 'Office' +"</td>";
                        } else if ((data['uhs'][int]['desctipo']).match(/^L.*$/) || (data['uhs'][int]['desctipo']).match(/^B.*$/)){
                            retorno += "<td>"+ 'Outros' + "</td>";
                        } else {
                            retorno += "<td>"+ (data['uhs'][int]['tipoinvestidor'] == 'P' ? 'Pool' : 'Condomínio') +"</td>";
                        }
                        retorno += "<td>"+data['uhs'][int]['desctipo']+"</td>";
                        retorno += "<td>"+data['uhs'][int]['unidade']+"</td>";
                        retorno += "<td>"+data['uhs'][int]['descricao']+"</td>";
                        retorno += "<td>"+data['uhs'][int]['participacao']+"</td>";
                        retorno += "</tr>";
                      }
                     $('#bodyInvestidoresUhJ').html(retorno);
                     //iniciaDataTableUH("tableInvestidoresUhJ", 1, "desc");

                        var contato = 0;
                        $.ajax({
                            async: false, cache:false, 
                            url: '[:raiz]cadAdmin/getContatoInvestidor',
                            data: {
                                codCm: codigoCM
                            },
                            dataType: 'json',
                            success: function(dt) {
                                var contactTable = "";
                                if (dt[0]!=undefined && dt[0]['COUNT'] > 0){
                                    contato = dt[0]['COUNT'];
                                    $('#txt0DadosContato').show();
                                    contactTable+="<table class='tables' style='width:565px;float:left;font-size: 11px;'><tr><td>"+$('#lblNome').val()+"</td>" +
                                            "<td>"+$('#lblTel').val()+"</td><td>"+$('#lblEmail').val()+"</td></tr>";
                                    for(var i=0;i<dt.length;i++){
                                        arrayContatos[i] = dt[i]['NOME']+"|"+dt[i]['TELEFONE'] +"|"+ dt[i]['EMAIL']+";";
                                        var nome = (dt[i]['NOME']!=undefined ? dt[i]['NOME'] : "");
                                        var telefone = (dt[i]['TELEFONE']!=undefined ? dt[i]['TELEFONE'] : "");
                                        var email = (dt[i]['EMAIL']!=undefined ? dt[i]['EMAIL'] : "");
                                        contactTable+=("<tr><td>" + nome + " </td><td> " + telefone + " </td><td> " + email +"</td></tr>");
                                    }
                                    contactTable+="</table>";
                                    $('#txt0DadosContato').show();
                                }else{
                                    //dar um hide no contato caso o investidor seja pessoa f�sica
                                    $('#txt0DadosContato').hide();
                                }                                   
                                $('.dadosContato').html(contactTable);
                            }
                        }); 

                    //var tamanhoModal = (690 + (50 * parseInt(data['uhs'].length) + (contato*20))*1.22);
                    var tamanhoModal = (670 + (45 * ((parseInt(data['uhs'].length)>0 ?parseInt(data['uhs'].length)+2 : 0 ))
                             + ((contato>0 ? contato+2 : 0)*20))*1.22); 
                    $('#detalhesJuridica').show();
                    $('#detalhesFisica').hide();    
                    $('#modalDetalhes').attr('title',$('#lblDetalhesInvestidor').val());
                    $('#modalDetalhes').dialog({
                        width: 625,
                        height: tamanhoModal,
                        modal: true,
                        buttons: dialog_buttons,
                        autoOpen: true,
                        resizable: false,
                        closeOnEscape: true,
                        position: 'top',
                        close: function(){

                        }
                    });                         
                }
            }
      }
});
}

I know that the function is both complex and complex, since it is different for the registration of individuals and legal entities.

Since the function works perfectly, is it possible to create a button with a function to register multiple investors from the search performed at the same time?

    
asked by anonymous 07.10.2015 / 16:06

1 answer

1

As it is, no it seems to me possible to reuse the function for multiple concurrent entries.

Some issues I can identify:

  • Interface dependency for logic : the most serious problem from my point of view. There is no logical separation of the processed data and the components of the page, which makes it very difficult to reuse any portion.
  • Almost no modularity : Although the code works, there does not seem to be any splitting of the process into distinguishable subroutines or "steps."
  • Poorly defined data flow : It is difficult to identify which data is used in each step of the routine, ie what are the inputs and outputs of each phase of the search and the registration.

Based on the above items, I would say that without a reworking of the routine it is not feasible to perform several simultaneously.

I suggest a solution in the following terms:

  • Refactor the code . That means changing without affecting the behavior. However, do this so that each part of the record is done in separate routines. The search must be in a routine, the validation of date in another, the small registers in others, etc. Each routine must have well defined its input and output parameters, that is, do not use global variables . These routines should not read or affect the state of the page. All visual component orchestration should continue in a central logic.

  • Get rid of dialogs . Now think about how you can present the information without using dialogues. Dialogs are practical, however for parallel or sequential processing are a big problem, after all only one information can be displayed at a time. A simple solution is to generate some type of log or table of errors, or, in case there is a table with the search results, show the errors in a column for each row that is selected. One idea is to show a success or error image for each line and show details about the error when the user clicks the image.

  • Change the main logic that, after step 1, should be very lean, to read the various items being imported and call the subroutines for each one. >

  • Anyway, I know they are abstract steps, but I really do not see a simple way to solve the problem other than redo practically everything.

    If you find that none of this is worth it, a somewhat simpler alternative would be to open each import on a different tab and so the rendering will be done in isolation on each tab. This is not the best experience for the user, but it works (since, of course, there are no competition issues on the server).

        
    13.10.2015 / 07:16