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

Asked

Viewed 72 times

0

On the site I took over from a previous developer, the investor registration is done one by one after a search in the system called CM. The function is called cadastralInvestidor:

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 as complex as it is different for the registration of individuals as legal.

As the function works perfectly, it is possible to create a button with a function to register several investors of the search performed at the same time?

  • 2

    The function is really great.. But did I have the need to post it all here? It could perhaps simplify and put only what is important, for example the name of the functions and etc.

  • Really... https://image-pd.s3.envato.com/files/38522860/_MG_1248.jpg

  • But now, seriously... if this call $.ajax initial registration was already complete, it would be very simple to create a button to register all, but - apparently - after making the call, it opens other dialogs, which in turn, make other calls and so on, so I don’t think I can automate this, since it requires more user input. Or am I mistaken?

  • Okay, I’m sorry. I know it’s too much to post the whole function. Normally the registrationInvestidor results in opening a dialog box to confirm that the data to be registered are correct. Then come choose between save (that makes the registration) and cancel. And in some cases it does not open this dialog box if the investor is already registered. The idea of automation would be to simply activate the register in order to save and so on. If they do not know how, no problem. It did not cost to try, hehehe

1 answer

1

The way it is, nay it seems possible to reuse the function for multiple simultaneous registrations.

Some problems I can identify:

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

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

I suggest a solution in the following terms:

  1. Refactor the code. This means changing without affecting behavior. However, do this so that each part of the registration is done in separate routines. The search should be in one routine, date validation in another, small entries in other, etc. Each routine should have well defined its input and output parameters, that is to say, do not use global variables. These routines should not read or affect the status of the page. All orchestration of visual components should continue in a central logic.

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

  3. Change the main logic which, after step 1, should be well lean, to read the various items being imported and call the subroutines for each of them.

Anyway, I know these are abstract steps, but I really don’t see a simple way to solve the problem other than redo virtually everything.

If you think that none of this is worth it, a simpler alternative would be to open each import in a different tab and so the processing will be done in isolation in each tab. It’s not the best user experience, but it works (provided, of course, there are no competition issues on the server).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.