AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.80
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/public_html/lrsys_apps/gasch/ui/lib/orders/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/public_html/lrsys_apps/gasch/ui/lib/orders/add.js
/* global optionsProducts */

$(document).ready(function () {
    var optionsProducts='';
    var editProduct=false;
     var rowNum = 0;
    loadProducts();
    $(".progress").hide();
    $("#emsg").hide();
    var ind_decimal = $("#_dec_point").val();
    var ind_mil = $("#_mil_point").val();
    var curr_code = $("#_curr_code").val();

    var _url = $("#_url").val();
    var _msg_add_new_segment = $("#_msg_add_new_nature_operation").val();

    var address_tax_address = '';
    var address_billing_address = '';

  
    var $submit = $("#submit");
    var $ibox_form = $('#ibox_form');

    $submit.on('click', function (e) {
        e.preventDefault();
        $ibox_form.block({message: block_msg});
        $.post(_url + "orders/post/", $("#ib_form").serialize())
                .done(function (data) {
                    if ($.isNumeric(data)) {
                        window.location = _url + 'orders/view/' + data;
                    } else {
                        $ibox_form.unblock();
                        var body = $("html, body");
                        body.animate({scrollTop:0}, '1000', 'swing');
                        $("#emsgbody").html(data);
                        $("#emsg").show("slow");
                    }
                });
    });



/////////////ADD NATURE OPERATION
    var ib_form_bootbox = "<form class=\"form-horizontal push-10\" method=\"post\" onsubmit=\"return false;\">\n    <div class=\"form-group\">\n        <div class=\"col-xs-12\">\n            <div class=\"form-material floating\">\n                <input class=\"form-control\" type=\"text\" id=\"nature_name\" name=\"nature_name\">\n                <label for=\"envato_api_key\">" + _L['Name'] + "</label>\n                           </div>\n        </div>\n    </div>\n\n</form>";
    $("#add_new_nature").click(function (e) {
        e.preventDefault();
        var box = bootbox.dialog({
            title: _L['Add New Nature Of Operation'],
            message: ib_form_bootbox,
            buttons: {
                success: {
                    label: _L['Save'],
                    className: "btn-primary",
                    callback: function () {
                        var name_val = $('#nature_name').val();
                        $.post(_url + "nature_operation/add-post/", {name: name_val})
                                .done(function (data) {
                                    if ($.isNumeric(data)) {
                                        loadNatureOperation('');
                                    } else {
                                        bootbox.alert(data);
                                    }
                                });
                    }
                }
            },
            show: false
        }
        );

        box.modal('show');
    });


    loadNatureOperation(1);


    /////////////////////ADD CONTACT

    ///////////////////////////////////////////
//////aciona o modal para adicionar o contato, evento de abertura do modal
    var $modal = $('#ajax-modal');
    $("#contact_add").click(function (e) {
        e.preventDefault();
        // create the backdrop and wait for next modal to be triggered
        $('body').modalmanager('loading');
        setTimeout(function () {
            $modal.load(_url + 'contacts/modal_add/', '', function () {
                $modal.modal();
                initModalAddContact();
            });

        }, 1000);
    });
    //////////////////////Acao de Salvar do Modal////////////////////////////
    $modal.on('click', '#modal_contact_submit', function (e) {
        e.preventDefault();
        // $('#ibox_form').block({message: block_msg});
        var _url = $("#_url").val();
        $.post(_url + 'contacts/add-post/', $("#modal_rform").serialize())
                .done(function (data) {
                    var _url = $("#_url").val();
                    if ($.isNumeric(data)) {
                        // location.reload();
//                    var is_recurring = $('#is_recurring').val();
//                    if(is_recurring == 'yes'){
//                        window.location = _url + 'invoices/add/recurring/' + data + '/';
//                    }
//                    else{
//                        window.location = _url + 'invoices/add/1/' + data + '/';
//                    }
                        $modal.modal('hide');
                        loadContacts();
                    } else {
                        //$('#ibox_form').unblock();
                        $("#modal_emsgbody").html(data);
                        $("#modal_emsg").show("slow");
                        document.location.href = "#modal_rform";
                    }
                });
    });
    loadContacts();


    /////////////////////////EDIT CONTACT//////////////////
//////aciona o modal para adicionar o contato, evento de abertura do modal
    var $modal = $('#ajax-modal');
    $("#contact_edit").click(function (e) {
        e.preventDefault();
        // create the backdrop and wait for next modal to be triggered
        $('body').modalmanager('loading');
        setTimeout(function () {
            $modal.load(_url + 'contacts/modal_edit_contact_address/', {cid: $("#client").val()}, function () {
                $modal.modal();
                initModalEditContact();
            });
        }, 1000);
    });
    //////////////////////Acao de Salvar do Modal////////////////////////////
    $modal.on('click', '#modal_edit_address_contact_submit', function (e) {
        e.preventDefault();
        // $('#ibox_form').block({message: block_msg});
        var _url = $("#_url").val();
        $.post(_url + 'contacts/edit-address-post/', $("#modal_edit_address_rform").serialize())
                .done(function (data) {
                    if ($.isNumeric(data)) {
                        //esconde a modal, e recarrega os valores dos selects, que podem ter sido adicionados
                        $modal.modal('hide');
                        update_address();
                    } else {
                        //$('#ibox_form').unblock();
                        $("#modal_edit_address_emsgbody").html(data);
                        $("#modal_edit_address_emsg").show("slow");
                        document.location.href = "#modal_rform";

                    }
                });
    });


    function update_address() {
        address_tax_address = '';
        address_billing_address = '';
        var adrs = $("#ta_address");
        adrs.html("");
        var _url = $("#_url").val();
        var cid = $('#client').val();
        if (cid != '') {
            $.post(_url + 'contacts/all-address/', {
                cid: cid

            })
                    .done(function (data) {
                        if (data[0].status == 'OK' || data[1].status == 'OK') {
                            address_tax_address = data[0];
                            address_billing_address = data[1];

                            adrs.html(data[0].address + " " + data[0].number + " " + data[0].complement +
                                    "\n" + data[0].city + " " + data[0].zip + "\n" + data[0].state + "\n" + data[0].country
                                    );
                            $("#type_address").removeClass('hide');
                            if (address_tax_address.billing_address == 'Y' || address_billing_address.billing_address == 'Y') {

                                $(".type_address_billing").removeClass('hide');
                            } else {
                                $(".type_address_billing").removeClass('hide');
                                $(".type_address_billing").addClass('hide');
                            }
                            //remove a classe, para garantir que possui somente uma classe hide no spam
                            $("#spam-edit-client").removeClass('hide');
                            $("#spam-edit-client").addClass('hide');
                        } else {
                            $("#spam-edit-client").removeClass('hide');
                            adrs.html("");
                            $("#type_address").removeClass('hide');
                            $("#type_address").addClass('hide');
                        }
                    });
        }

    }

    $('#client').on("change", function (e) {
        if($(this).val()!=''){
            update_address();
        }else{
            $("#type_address").removeClass('hide');
            $("#type_address").addClass('hide');
            $("#spam-edit-client").removeClass('hide');
            $("#spam-edit-client").addClass('hide');
           
           
        }
        
        checkPrice();
    });
    
    $('#delivery_type').on("change", function (e) {
        checkPrice();
    });


    ////////////////////////////////////////////////////////////////
    $('.exchange_address').on("change", function (e) {
        if ($(this).val() === 'other') {
            $("#div_zip").show();
            $("#ta_address").hide();
        }else{
            $("#div_zip").hide();
            $("#ta_address").show();
            var data = "";
            if ($(this).val() == 'billing_address') {
                data = address_billing_address;
            } else {
                data = address_tax_address;
            }
            $("#ta_address").html(data.address + " " + data.number + " " + data.complement +
                    "\n" + data.city + " " + data.zip + "\n" + data.state + "\n" + data.country
                    );
        }
    });
    $("#div_zip").hide();

    
    ////////////////cidade endereço////////////////////////////////
    $('#city').html('<option value="state" selected>' +  _L['Select State']  + '</option>');
    //função para listar cidades do estado selecionado
    $('#state').on('change', function () {
            buscaCity($(this).val(),"city");  
    });


    function buscaCity(state,valor){
        if(state){ 
            $.getJSON($("#_url").val() + 'ajax/city', {state_id: state}, function (j) {
                    var options = '<option value="city">' + _L['Select City'] + '</option>';
                    for (var i = 0; i < j.length; i++) {
                        options += '<option value="' + j[i].id + '">' + j[i].city_name + '</option>';
                    }

                    $('#city').html(options);
                    $('#city').select2("val",valor);
                });
        } else {
                //select_state contem o texto padrão campo hidden na page
                $('#city').html('<option value="state">' + _L['Select State'] + '</option>');
                $('#city').select2("val","state");
            }
    }

    ///////////////////////BUSCA CEP////////////
    $('#zip').blur(function (e) {
       e.preventDefault();
       //esmaece a div e coloca o loading
       //vai esse block_msg nao sei da onde, mas fica o  loading
       $("#div_zip").block({message: block_msg});
       //cria o bootbox para cadastrar novo grupo
       $.post(_url + "ajax/zip", {zip: $("#zip").val()})
           .done(function (data) {
               if(data[0].status=='OK'){
                   $('#state').select2("val",data[0].state_id);
                   $("#address").val(data[0].address);
                   $("#neighborhood").val(data[0].neighborhood);  
                   //necessário chamar aqui para garantir a busca das cidade pelo estado
                   //e atribuir a cidade selecionada
                   buscaCity(data[0].state_id,data[0].city_id);
               }else{
                   alert(data[0].status);
               }
               $('#div_zip').unblock();
    });
       
                                        
    });

    
    ///////////////////FIM TRATAMENTO CLIENTE
    loadSalesman();
    loadConveyor();


    //tratamento dos itens
    $('.amount').autoNumeric('init');
    var _url = $("#_url").val();
    var $invoice_items = $('#invoice_items');
    var item_remove = $('#item-remove');
    item_remove.hide();
    var $modal = $('#ajax-modal');

    function loadOptions(id){
           var options='';
           var products = document.getElementsByName('product[]');

           for (var i = 0; i <optionsProducts.length; i++) {
               var registrado=false;
               for (j = 0; j < products.length; j++) {
                    if(i==products[j].value && products[j].value!=""){
                        registrado=true;
                    }
               }

               if(optionsProducts[i].id==id || !registrado){
                   options += '<option value="'+i+'" data-product-id="'+optionsProducts[i].id+'">' + optionsProducts[i].description + '</option>';
               }
            }
            return options;

    }
    
    $('#item-add').on('click', function () {  
        
        
        var optionsProduct= loadOptions("");
        if(!editProduct && optionsProduct.length>0 ){
                $(".qtyl").attr("readonly","readonly");
                $(".product_select").attr("disabled","disabled");
                $(".edit_product").removeClass('hide');
                $(".ok_product").addClass('hide');

                $invoice_items.find('tbody')
                .append(
                       '<tr class="itm_nm_ftura "><td class="middle"><span id="product_code'+rowNum+'"></td>\n\
                       <td class="middle"><input type="hidden" class="id_product" id="id_product_'+rowNum+'" name="id_product[]"><input type="hidden" id="i_' + rowNum + '" name="desc[]"><select data-row="'+rowNum+'"  id="select_product_'+rowNum+'" name="product[]"  class="form-control product_select"><select>\n\
                       <span class="text-red hide" id="msg_stock_'+rowNum+'"></spam></td>  \n\
                       <td class="middle"><input class="itm_nm_ftura" type="hidden"  id="unit_itm' + rowNum + '">\n\
                       <input type="text" data-net-weight="0.00" data-gross-weight="0.00" readonly class="form-control qtyl qtyVal' + rowNum + '"  value="1' + ind_decimal + '000" name="qty[]" id="' + rowNum + '">\n\
                       <input type="hidden" name="qtdBe[]" id="qtdBe' + rowNum + '" value="1' + ind_decimal + '000"></td><td class="middle">\n\
                       <input type="text" id="item_price' + rowNum + '"  value="'+curr_code+' 0' + ind_decimal + '00" class="form-control item_price' + rowNum + ' am" name="amount[]"  readonly></td> \n\\n\
                       <td class="middle">\n\
                       <input type="text" id="item_discount' + rowNum + '"  value="'+curr_code+' 0' + ind_decimal + '00" class="form-control item_discount item_discount' + rowNum + ' am" name="item_discount[]"></td> \n\
                       <td class="ltotal middle"><input type="text" value="'+curr_code+' 0' + ind_decimal + '00"  id="lvtotal' + rowNum + '" class="form-control lvtotal lvtotal' + rowNum + ' am" readonly ></td>  <td class="middle col-xs-1">  <span class="btn btn-success btn-xs ok_product" id="ok_product'+rowNum+'" data-row="'+rowNum+'" ><i class="fa fa-check"></i> </span>   <span class="btn btn-success btn-xs edit_product hide" id="edit_product'+rowNum+'"  data-row="'+rowNum+'" ><i class="fa fa-edit"></i> </span> <span class="btn btn-danger btn-xs delete_product" data-row="'+rowNum+'" ><i class="fa fa-trash"></i> </span></td></tr>'
                    );
                $('[data-toggle="tooltip"]').tooltip();
                $(".product_select").select2({ theme: "bootstrap"});
                editProduct=true;   

                $("#select_product_"+rowNum).html( '<option disabled="disabled" selected>'+_L['Select']+'</option>'+optionsProduct);
                $("#select_product_"+rowNum).focus();
                $('#'+rowNum).autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 0, aSign:''});


                $("#select_product_"+rowNum).on('change', function () 
                {      
                    $('#msg_stock_' +$(this).attr("data-row")).removeClass('hide');
                    $('#msg_stock_' +$(this).attr("data-row")).addClass('hide');

                    $("#select_product_"+rowNum).html('<option disabled="disabled" selected>'+_L['Select']+'</option>'+ loadOptions($(this).val()));
                    $('#id_product_' +$(this).attr("data-row") + '').val(optionsProducts[$(this).val()].id);

                    var qtd_itn = $('#' +$(this).attr("data-row") + '').val().replace(" " + optionsProducts[$(this).val()].item_sifr, "").replace(ind_mil,"").replace(ind_decimal,'.');     
                    editProduct=false;                         
                    //remove os dados do produto da soma, caso o usuário esteja trocando o produto selecionadao
                    subTotalGeral = subTotalGeral- parseFloat($("#lvtotal"+$(this).attr("data-row")).val().replace(curr_code + " ", "").replace(ind_mil,"").replace(ind_decimal,'.'));
                    $('#total_product').val((subTotalGeral+"").replace('.',ind_decimal));

                    updateTotais();  

                    var valorTotalProduct = parseFloat(qtd_itn) * parseFloat((optionsProducts[$(this).val()].price+"").replace(ind_mil,"").replace(ind_decimal,'.'));                    
                    $("#product_img"+$(this).attr("data-row")).attr('src',optionsProducts[$(this).val()].image);
                    $("#product_code"+$(this).attr("data-row")).html(optionsProducts[$(this).val()].id);
                    $("#unit_itm"+$(this).attr("data-row")).val(optionsProducts[$(this).val()].item_sifr);
                    $("#item_price"+$(this).attr("data-row")).val(optionsProducts[$(this).val()].price);
                    $("#lvtotal"+$(this).attr("data-row")).val((valorTotalProduct+"").replace('.',ind_decimal));
                    $("#i_"+$(this).attr("data-row")).val(optionsProducts[$(this).val()].description);


                    $('.am').autoNumeric('init', {aSep: ind_mil, aDec: ind_decimal, mDec: 2, aSign: curr_code + ' '});
                    $('.am').trigger('blur');
                    //acrecenta o peso do produto no total de pesos

                    updateWeight($(this).attr("data-row") ,qtd_itn);


                    //remove o disable do campo de quantidade após selecionar um produto
                    $("#"+$(this).attr("data-row")).removeAttr('readonly');

                    if (optionsProducts[$(this).val()].item_unit == 0){
                        $('#' +$(this).attr("data-row") + '').autoNumeric('update', {aSep: ind_mil, aDec: ind_decimal, mDec: 3, aSign: ' ' + optionsProducts[$(this).val()].item_sifr, pSign: 's'});
                    }else{
                        $('#' +$(this).attr("data-row") + '').autoNumeric('update', {aSep: ind_mil, aDec: ind_decimal, mDec: 0, aSign: ' ' + optionsProducts[$(this).val()].item_sifr, pSign: 's'});
                    }

                    admItens(rowNum, valorTotalProduct);

                    var  stock_av="";
                     if (optionsProducts[$(this).val()].item_unit == 1){
                         stock_av= _L['stock available:'] +parseFloat(optionsProducts[$(this).val()].current_stock).toFixed(0)+ " " + optionsProducts[$(this).val()].item_sifr;
                     }else{
                         stock_av=_L['stock available:'] + optionsProducts[$(this).val()].current_stock + " " + optionsProducts[$(this).val()].item_sifr;
                     }
                    $('#msg_stock_' +$(this).attr("data-row") ).html(stock_av);

                    if(parseFloat(optionsProducts[$(this).val()].current_stock)<parseFloat((qtd_itn+"").replace(ind_mil,"").replace(ind_decimal,'.'))){    
                        $('#msg_stock_' +$(this).attr("data-row")).removeClass('hide');
                    }
                    checkPrice();
                });

                rowNum++;
            
            }else if(optionsProduct.length==0){
                bootbox.alert(_L['There are no items to add']);
            }else{
                bootbox.alert(_L['Select the item first.']);
            }
    });


       
    $invoice_items.on("click", ".edit_product", function (e) {
        $("#"+$(this).attr("data-row")).removeAttr('readonly');
        $("#select_product_"+$(this).attr("data-row")).removeAttr('disabled');
        $("#ok_product"+$(this).attr("data-row")).removeClass('hide');
        $("#edit_product"+$(this).attr("data-row")).addClass('hide');
    });

    $invoice_items.on("click", ".ok_product", function (e) {
        if( $("#select_product_"+$(this).attr("data-row")).val()!=null){
            $("#"+$(this).attr("data-row")).attr('readonly','readonly');
            $("#select_product_"+$(this).attr("data-row")).attr('disabled','disabled');
            $("#edit_product"+$(this).attr("data-row")).removeClass('hide');
            $("#ok_product"+$(this).attr("data-row")).addClass('hide');
        }else{
            bootbox.alert(_L['Select the item first.']);
        }
    });

    $invoice_items.on("click", ".delete_product", function (e) {

            var net_weight = $("#net_weight").val().replace(ind_mil,"").replace(ind_decimal,'.');
            var gross_weight =$("#gross_weight").val().replace(ind_mil,"").replace(ind_decimal,'.');
            if(net_weight.length==0){
                net_weight=0;
            }
            if(gross_weight.length==0){
                gross_weight=0;
            }
            gross_weight=parseFloat(gross_weight)- parseFloat($("#"+$(this).attr("data-row")).attr("data-gross-weight"));
            if(gross_weight<0){
                gross_weight=0;
            }
            $("#gross_weight").val((gross_weight+"").replace('.',ind_decimal));

            net_weight=parseFloat(net_weight)- parseFloat($("#"+$(this).attr("data-row")).attr("data-net-weight"));
            if(net_weight<0){
                net_weight=0;
            }
            $("#net_weight").val((net_weight+"").replace('.',ind_decimal));



            var val = $('.lvtotal' + $(this).attr("data-row")).val().replace(curr_code, "").replace(ind_mil,"").replace(ind_decimal,'.');
            $(this).closest('tr').remove();
            subTotalGeral = subTotalGeral-parseFloat(val);
            //  retornaDesconto();
            $('#total_product').val((subTotalGeral+"").replace('.',ind_decimal));
            updateTotais();  
            //atualiza pesos
            $('.amount').autoNumeric('update', {});     
            $('.am').autoNumeric('update', {});     
    });


    var subTotalGeral = "0.00";
    var totalFinal = "0.00";
    var qtdAnterior = ["1.000"];
    var qtdCorrente = 1;
    var validaDecimal;


    $invoice_items.on('blur', '.qtyl', function () {
        // verifico o preço do produto
        checkPrice();
    });
    
    $invoice_items.on('blur', '.item_discount', function () {
        // verifico o preço do produto
        checkPrice();
    });
    
    function updateTotalValue(id)
    {
        this.id = id;
        if ($('.qtyVal' + this.id).val() == "")
            return;
        var unit = $("#unit_itm" + this.id).val();
        var qtd_itn = parseFloat($('.qtyVal' + this.id).val().replace(" " + unit, "").replace(ind_mil,"").replace(ind_decimal,'.'));

        ///TRATAMENTO CONTROLE DO ESTOQUE
        if ((qtd_itn) > parseFloat(optionsProducts[ $("#select_product_"+this.id).val()].current_stock)) {
            $('#msg_stock_' + this.id).removeClass('hide');
        }else{
            $('#msg_stock_' + this.id).removeClass('hide');
            $('#msg_stock_' + this.id).addClass('hide');
        }
        $('#qtdBe' + this.id).val(qtd_itn);
        var preco_itn = parseFloat($('.item_price' + this.id).val().replace(curr_code + " ", "").replace(ind_mil,"").replace(ind_decimal,'.'));
        var discount_itn = parseFloat($('.item_discount' + this.id).val().replace(curr_code + " ", "").replace(ind_mil,"").replace(ind_decimal,'.'));
        
        var valorTotal = qtd_itn* (preco_itn - discount_itn);
        
        $('.lvtotal' + this.id).val((valorTotal+"").replace('.',ind_decimal));
        var id = parseInt(this.id);
        (qtdAnterior[id]) ? qtdAnterior[id] = qtdAnterior[id] : qtdAnterior[id] = "1.000";
        var valorAnterior = parseFloat(qtdAnterior[id])* preco_itn;

        var subTotalCorrente = "0.000";
        subTotalCorrente = parseFloat(subTotalGeral-valorAnterior).toFixed(2);
        subTotalGeral = parseFloat((parseFloat(subTotalCorrente)+  parseFloat(valorTotal))).toFixed(2);
        $('#total_product').val((subTotalGeral+"").replace('.',ind_decimal));

        qtdAnterior[id] = qtd_itn;
        updateTotais();
        updateWeight(id,qtd_itn);


        editProduct=false;
        $('.amount').autoNumeric('update', {});     
        $('.am').autoNumeric('update', {});   
    }
  

   
    function updateWeight(row,qtd_itn){
        var net_weight = $("#net_weight").val().replace(ind_mil,"").replace(ind_decimal,'.');
        var gross_weight =$("#gross_weight").val().replace(ind_mil,"").replace(ind_decimal,'.');
        if(net_weight.length==0){
            net_weight=0;
        }
        if(gross_weight.length==0){
            gross_weight=0;
        }
        gross_weight=parseFloat(gross_weight)-parseFloat($("#"+row).attr("data-gross-weight"));
        if(gross_weight<0){
            gross_weight=0;
        }
        $("#gross_weight").val((gross_weight+"").replace('.',ind_decimal));
        net_weight=parseFloat(net_weight)-parseFloat($("#"+row).attr("data-net-weight"));
        if(net_weight<0){
            net_weight=0;
        }
        $("#net_weight").val((net_weight+"").replace('.',ind_decimal));

        var gross_weight_product=parseFloat(qtd_itn) * parseFloat(optionsProducts[ $("#select_product_"+row).val()].gross_weight);
        $("#gross_weight").val(((parseFloat(gross_weight)+ gross_weight_product)+"").replace('.',ind_decimal));
        $("#"+row).attr("data-gross-weight",gross_weight_product);

        var net_weight_product=parseFloat(qtd_itn) * parseFloat(optionsProducts[ $("#select_product_"+row).val()].net_weight);
        $("#net_weight").val(((parseFloat(net_weight)+ net_weight_product)+"").replace('.',ind_decimal));
        $("#"+row).attr("data-net-weight",net_weight_product);
        //update na formatação do campo
        $('.amount').autoNumeric('update', {});
        $('.am').autoNumeric('update', {});
    }
   
    function admItens(item_id, item_price) {

        var unit = $("#unit_itm" + item_id).val();
        var preco_itn = (""+item_price).replace(curr_code + " ", "");
     //   (idsItnsSlcd == "") ? idsItnsSlcd += item_id : idsItnsSlcd += "," + item_id;
        subTotalGeral = parseFloat(subTotalGeral) + parseFloat(preco_itn);
        $('#total_product').val((subTotalGeral+'').replace('.',ind_decimal));
       
        
        //  retornaDesconto();
        updateTotais();
    }
    
    function updateTotais() {
        var elemento = document.getElementsByName('id_product[]');
        $('#number_itens').val(elemento.length);
        $('#qtd_volumes').val(elemento.length);
        
        
        var qtds = document.getElementsByName('qty[]');
        var qtd = 0;
        for (i = 0; i < qtds.length; i++) {
            var unit = $("#unit_itm" + qtds[i].id).val();
            var qtd_itn = $('.qtyVal' + qtds[i].id).val().replace(" " + unit, "").replace(ind_mil,"").replace(ind_decimal,'.');
          
            qtd = parseFloat(qtd_itn)+ parseFloat(qtd);
        }
        $('#qtd_itens').val(qtd);
        
        var discount=$("#discount").val().replace(curr_code, "").replace(ind_mil,"").replace(ind_decimal,'.');
        if (discount.length === 0) {
            discount=0;
        }
      
        var freight=$("#freight").val().replace(curr_code, "").replace(ind_mil,"").replace(ind_decimal,'.');
        if (freight.length === 0) {
            freight=0;
        } 
        //pega o tipo d edesconto pelo valor do span, ao lado do componente
        if($('#span_type_disc').html()==='%'){  
           discount=(parseFloat(discount)* parseFloat($("#total_product").val().replace(curr_code, "").replace(' ',"").replace(ind_mil,"").replace(ind_decimal,'.')))/100;
        }
        
        $("#total").val((parseFloat(($("#total_product").val().replace(curr_code, "").replace(ind_mil,"").replace(ind_decimal,'.'))-parseFloat(discount)+parseFloat(freight)).toFixed(2)+"").replace('.',ind_decimal));
        $('.amount').autoNumeric('update', {});
    }
    
    $('.exchange_type_discount').on("change", function (e) {
       if($(this).val()==='p'){
            $('#span_type_disc').html("%");
       }else{
            $('#span_type_disc').html(curr_code);
       }
        updateTotais();

    });
   
    
    $('.updateTotais').on("blur", function (e) {
        updateTotais();
    });

    ///fim do tratamento dos itens

    /// Transportador / Volumes tratamento de acordo com a forma de envio

    $('#shipping_method').on("change", function (e) {
         if($(this).val()==='1'){
              $(".not_ship_method_3").show();
              $(".not_ship_method_1").hide();
         }else if($(this).val()==='3'){
              $(".not_ship_method_1").show();
              $(".not_ship_method_3").hide();
         }else{
             $(".not_ship_method_1").show();
             $(".not_ship_method_3").show();
         }
    });
    
    //começa sem frete selecionado    
    $(".not_ship_method_3").hide();    
    
    ///////////////////TAG/////////////////////////

    //adicionando o memsa ação de grupo para tag

    var ib_form_bootbox_tag = "<form class=\"form-horizontal push-10\" method=\"post\" onsubmit=\"return false;\">\n    <div class=\"form-group\">\n        <div class=\"col-xs-12\">\n            <div class=\"form-material floating\">\n                <input class=\"form-control\" type=\"text\" id=\"tag_name\" name=\"tag_name\">\n                <label>" + _L['Tags'] + "</label>\n                           </div>\n        </div>\n    </div>\n\n</form>";

    $("#add_new_tag").click(function (e) {
        e.preventDefault();
        //cria o bootbox para cadastrar novo grupo
            bootbox.dialog({
            title: _L['Add New Tag'],
            message: ib_form_bootbox_tag,
            buttons: {
                success: {
                    label: "Save",
                    className: "btn-primary",
                    callback: function () {
                        var tag_name_val = $('#tag_name').val();
                        if (tag_name_val != '') {
                            $.post(_url + "tags/add-post-orders/", {tag: tag_name_val})
                                    .done(function (data) {
                                        if ($.isNumeric(data)) {
                                            loadTags();
                                            $('#tag_name').val("");
                                        } else {
                                            bootbox.alert(data);
                                            $('#tag_name').val("");
                                        }
                                    });
                        }
                    }
                }
            },
            show: true
        });
    });

    //aciona o método ao inciar
    loadTags();

    ///////////////////
    function loadProducts() {
        //carrega os segmentos
        $.getJSON($("#_url").val() + 'ps/ajax-list', function (j) {
           optionsProducts=j;
        });
    };
    
    // Função para atualizar os preços customizados dos produtos
    function changePrice(price, e, margin_discount) 
    {
        // altero o valor do produto
        $('#item_price'+e).val((price.replace('.',',')));
        
        // verifico se o desconto oferecido é permitido
        var discount_itn = parseFloat($('.item_discount' + e).val().replace(curr_code + " ", "").replace(ind_mil,"").replace(ind_decimal,'.'));
        price = parseFloat(price.replace(',','.'));
        
        if(discount_itn > (margin_discount/100)*price)
        {
            $('.item_discount' + e).val(0);
            if(margin_discount > 0)
            {
                alert ('O desconto não pode ser maior do que '+margin_discount+'% do valor do produto.');
            }
            else
            {
                alert ('Para este produto não é permitido dar desconto.');
            }
        }
        
        return true;
    };
    
    function checkPrice() 
    {
        var product_id          = null;
        var produts_details     = null;
        var price               = null;
        var account_id          = $('#client').val();
        var delivery_type       = $('#delivery_type').val();
        
        $('.id_product').each(function(e){
            product_id = $( this ).val();
            var qtd = $('.qtyVal'+e).val();
            var unit = $("#unit_itm" + e).val();
            var qtd = parseFloat(qtd.replace(" " + unit, "").replace(ind_mil,"").replace(ind_decimal,'.'));
            var custom_price = false;
            var margin_discount = 0;
            if(product_id > 0)
            {
                //carrega os dados do produto
                $.getJSON($("#_url").val() + 'ps/ajax-list/'+product_id, function (p) {
                    produts_details=p;
                    produts_details=produts_details[0];
                    
                    for (var j = 0; j < produts_details.custom_prices.length; j++) 
                    {
                        price = produts_details.custom_prices[j].sales_price;
                        margin_discount = produts_details.custom_prices[j].margin_discount;
                        
                        // Verifico o tipo de entrega
                        if(delivery_type === produts_details.custom_prices[j].type_delivery || 
                            produts_details.custom_prices[j].type_delivery === 'All' && custom_price == false)
                        {
                            
                            // verifico se o account_id do cliente bate com o do preço
                            for (var k = 0; k < produts_details.custom_prices[j].account_ids.length; k++) 
                            {
                                if(account_id > 0 && account_id == produts_details.custom_prices[j].account_ids[k])
                                {
                                    // ATUALIZAR O VALOR DO PRODUTO NO GRID
                                    changePrice(price, e, margin_discount);
                                    custom_price = true;
                                }
                            }
                            
                            if(custom_price == false)
                            {
                                // verifico se o Segmento do cliente bate com o do preço
                                var segment_id = $('#client').find(":selected").attr('data-segment');
                                for (var k = 0; k < produts_details.custom_prices[j].segment_ids.length; k++) 
                                {
                                    if(segment_id > 0 && segment_id == produts_details.custom_prices[j].segment_ids[k])
                                    {
                                        // ATUALIZAR O VALOR DO PRODUTO NO GRID
                                        changePrice(price, e, margin_discount);
                                        custom_price = true;
                                    }
                                }
                            }
                            
                            if(custom_price == false)
                            {
                                //verifco a quantidade
                                if(qtd >= produts_details.custom_prices[j].quantity)
                                {
                                    // ATUALIZAR O VALOR DO PRODUTO NO GRID
                                    changePrice(price, e, margin_discount);
                                    custom_price = true;
                                }
                            }
                        }
                    }
                    
                    // se não tem preço especial, coloco o preço default
                    if(custom_price == false)
                    {
                        // se não bater com nenhum custom price, coloca o preço defaul
                        margin_discount = produts_details.margin_discount;
                        changePrice(produts_details.price, e, margin_discount);
                    }
                    
                    // atualizo os valores dos produtos
                    updateTotalValue(e);
                    return true;
                });
            }
        });
        return true;
    };
    
    $('#delivery_type').on("change", function (e) {
        console.log($(this).val());
        if ($(this).val() === 'Withdrawal') 
        {
            $(".delivery-type-delivery").hide();
        }
        else
        {
            $(".delivery-type-delivery").show();
        }
    });
});
// FIM DO DOCUMENT.READY


function loadNatureOperation(select) {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'nature_operation/ajax-list', function (j) {
        //options = '<option value="">' + _L['Select Nature Of Operation'] + '</option>';
        options='';
        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '" >' + j[i].name + '</option>';
        }
        $('#nature_operation').html(options);
     
        if(select!==''){
            $("#nature_operation").select2('val',select); 
        }
        
    });
}

function loadContacts() {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'contacts/ajax-list', function (j) {
        options = '<option value="">' + _L['Select Client'];
        +'</option>';
        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '" data-segment="' + j[i].segment_id + '">' + j[i].name_email + '</option>';
        }
        $('#client').html(options);
        
        
    });
}



function loadSalesman() {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'contacts/ajax-listbygroup/Salesman', function (j) {
        options = '<option value="">' + _L['Select Salesman'];
        +'</option>';

        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '">' + j[i].account + '</option>';
        }
        $('#salesman').html(options);
    });
}

function loadTags(){
        //carrega os dados das tags ao iniciar
     $.getJSON($("#_url").val()+'tags/orders',function (j) {
        var options = '';
        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].text + '">' + j[i].text + '</option>';
        }
        $('#tags').html(options);
    });
}

function loadConveyor() {
    //carrega os segmentos
    $.getJSON($("#_url").val() + 'contacts/ajax-listbygroup/Conveyor', function (j) {
        options = '<option value="">' + _L['Select Conveyor'];
        +'</option>';

        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '">' + j[i].account + '</option>';
        }
        $('#conveyor_id').html(options);
    });
}

Anon7 - 2022
AnonSec Team