viernes, 5 de abril de 2013

Jqgrid Codigo que permite recorrer todas las filas del grid y sumar el contenido de las celdas con cifras numéricas dependiendo si son positivas o negativas.



Jqgrid Codigo que permite recorrer todas las filas del grid y sumar el contenido de las celdas con cifras numéricas dependiendo si son positivas o negativas.

 



<?php
extract($_POST);
extract($_GET);
if (!isset($_SESSION["mapa"])){
    include('msj_inicio_session.php');
}else{       
    if ($_SESSION["mapa"] == -1 || $_SESSION["mapa"] == 2 || $_SESSION["mapa"] == 3){       
    //Includes Necesarios
        include('funciones/Conectar.php');//Conexion a la Base de datos
        include('funciones/Funciones_Contabilidad.php');//Conexion a la Base de datos
?>
<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.8.16.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
function formafecha(fecha)
 {
 Anio =fecha.substr(0,4);
 mes=fecha.substr(5,2);
 dia=fecha.substr(8,2);
 fecha=dia+"/"+mes+"/"+Anio;
 return (fecha);
 }



$(function(){
 var Identifica_accion =<?php echo $_GET['rp'];?>;
       // $.jgrid.formatter.integer.thousandsSeparator = ',';
        $.jgrid.formatter.number.thousandsSeparator = '.';
         $.jgrid.formatter.number.decimalSeparator = ',';
         $.jgrid.formatter.number.decimalPlaces = 2;
      //  $.jgrid.formatter.currency.thousandsSeparator = ',';

$.getJSON('Funciones_Contabilidad.php',{Id_Proceso:2},function(solicitud){$('#Debe_Original').val(solicitud.Total_Monto);});// cierra getJSON
$.getJSON('Funciones_Contabilidad.php',{Id_Proceso:1},function(solicitud){$('#Haber_Original').val(solicitud.Total_Monto);});// cierra getJSON

   
   
     if(Identifica_accion!=0)
 {


 $.getJSON('Busca_Data.php',{Num_Comprobante:Identifica_accion},function(solicitud){   
       
             //var plantilla=(solicitud.Plantilla_Id);
            //$('select[id="Tipo_solicitud_Id"] option:selected').val(solicitud.Tipo_solicitud_Id);
            $('#Id_Comprobante').val(solicitud.Id_Registro);
            $('#Num_Comprobante').val(solicitud.Numero_Comprobante);
            $('#fecha_Cambio').val(formafecha(solicitud.Fecha_Comprobante));
            $('#Comentario').val(solicitud.Descripcion);
            $('#Tipo_Asiento').val(solicitud.Tipo_Comprobante);
            $('#Estatus_Asiento').val(solicitud.Estatus_Actualizado);
           
           

   
        });// cierra getJSON
       

 }// cierra el if identifica_accion


$("#enlace").click(function() {
     location.href = this.href; // ir al link
});   
   
// ESTA RUTINA PERMITE RECORRER EL GRID Y SUMAR EL CONTENIDO DE LAS CELDAS DEPENDIENDO SI SON CIFRAS POSITIVAS O NEGATIVAS
function Totaliza () {
 var total_haber=0,total_debe=0;
 var rows= jQuery("#grps").jqGrid('getRowData');
                for(var i=0;i<rows.length;i++){
                      var row=rows[i];
                      if(Number(row['Monto'])>0)
                        {
                         total_haber +=Number(row['Monto']);
                        }else{
                         total_debe +=Number(row['Monto']);
                        }
                     
                  }
                 
                  total_haber=Number(total_haber)+Number($('#Haber_Original').val());
                  total_debe=Number(total_debe)+Number($('#Debe_Original').val());
                $('#Haber').val(total_haber);
                $('#Debe').val(total_debe);
                 
      return true;
};


    var ccosto = (function () {
            var list = null;

            $.ajax({
                async: false,
                global: false,
                url: 'Centro_Costo.php',
                dataType: 'json',
                success: function (data) {
                    list = data;
                }
            });

            return list;
        })();
   
   
    var dasocia = (function () {
            var list = null;

            $.ajax({
                async: false,
                global: false,
                url: 'Doc_Asociado.php',
                dataType: 'json',
                success: function (data) {
                    list = data;
                }
            });

            return list;
        })();   


    var dtipo = (function () {
            var list = null;

            $.ajax({
                async: false,
                global: false,
                url: 'Doc_Tipo.php',
                dataType: 'json',
                success: function (data) {
                    list = data;
                }
            });

            return list;
        })();   
       
$("#grps").jqGrid({
url:'Carga_Datos.php?filtro='+<?php echo $_GET['rp'];?>,
datatype: 'json',
mtype: 'GET',
  colNames: ['Id_Registro','Codigo_Cuenta','Centro_Costo', 'Doc_Asoc','Tipo', 'Descripcion', 'Monto'],
          colModel: [
      { name: 'Id_Registro', index: 'Id_Registro', width: 100, align: 'left',editable: false},
     { name: 'Codigo_Cuenta', index: 'Codigo_Cuenta', width: 100, align: 'left',editable: true,editrules:{required:true},edittype:"select",editoptions:{dataUrl:'Plan_Cuentas.php'} ,sortable: true, resizable: false},
      { name: 'Centro_Costo', index: 'Centro_Costo', width: 100, align: 'left',editable: true,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: ccosto},sortable: true, resizable: false},
      { name: 'Doc_Asoc', index: 'Doc_Asoc', width: 100, align: 'left',editable: true,editrules:{required:true},edittype:'text'},
      { name: 'Tipo', index: 'Tipo', width: 100, align: 'left',editable: true,editrules:{required:true},edittype:"select",formatter:'select',editoptions: { value: dasocia},sortable: true, resizable: false},
      { name: 'Descripcion', index: 'Descripcion', width: 200, align: 'left',editable: true,editrules:{required:true},edittype:'text'},
      { name: 'Monto', index: 'Monto', width: 200, align: 'left',editable: true,editrules:{number:true},formatter: 'number',edittype:'text'},
      ],
   
   

    rownumbers:true,
    pager: '#pgrps',
    rowNum:15,
    rowList:[10,25,50,100],
    autowidth: true,
  //  sortname: 'Id_Registro',
  //  sortorder: 'desc',
    viewrecords: true,
    width: "98%",
    height: "100%",
    editurl: "inlineEdit.php",
    caption: 'Carga Asientos Contables',
    footerrow: true,
    cellEdit: true,
    cellurl:"otro.php",
   


afterSaveCell: function (rowid, cellname, value) {
                    if (cellname === 'Monto') {
                        var sum = jQuery("#grps").jqGrid('getCol', 'Monto', false, 'sum');
                    

                     var total_registros =jQuery("#grps").jqGrid('getGridParam', 'records');// lee el numero total de filas a recorrer
                     jQuery("#grps").setGridParam({ rowNum: total_registros }).trigger('reloadGrid');// cambia el numero de filas  que tiene el grid al numero de total_registros 
   

                        var z=Totaliza();
                        jQuery("#grps").jqGrid('footerData','set', {Id_Registro: 'Total:', Monto: sum});
                       }
                },
               
ondblClickRow: function(rowid,iRow,iCol,e){
                   var myCellData = $('#grps').jqGrid('getCell', rowid, 'Codigo_Cuenta');
                   $.post('Funciones.php',{Codigo:myCellData},Busca_Texto);
                    function Busca_Texto(datos)
                    {
                    $("#Cuenta").val(datos);
                    }
                },


afterInsertRow:function(rowid,rowdata,rowelem) {
             var sum =  jQuery("#grps").jqGrid('getCol', 'Monto', false, 'sum');



                     var total_registros =jQuery("#grps").jqGrid('getGridParam', 'records');// lee el numero total de filas a recorrer
                     jQuery("#grps").setGridParam({ rowNum: total_registros }).trigger('reloadGrid');// cambia el numero de filas  que tiene el grid al numero de total_registros 
          

  var z=Totaliza();
             jQuery("#grps").jqGrid('footerData','set', {Id_Registro: 'Total:', Monto: sum});
           
  
        },
 
gridComplete: function(){
             var sum = jQuery("#grps").jqGrid('getCol', 'Monto', false, 'sum');
             jQuery("#grps").jqGrid('footerData','set', {Id_Registro: 'Total:', Monto: sum});
        },

  });




jQuery("#grps").jqGrid('navGrid','#pgrps',{}, //options
{height:280,width:600,reloadAfterSubmit:false,closeAfterEdit:true},// edit
{height:280,width:600,reloadAfterSubmit:false,closeAfterAdd:true}, // add options
{reloadAfterSubmit:false}, // del options
{multipleSearch:true,closeAfterSearch: true, closeOnEscape: true}
);






jQuery("#grps").jqGrid('navButtonAdd','#pgrps',{
       caption:"Cuenta",
       title:"Cuenta",
       onClickButton : function () {
          var prueba=0;
          var id = jQuery("#grps").jqGrid('getGridParam','selrow');
          if (id)
          {
             var ret = jQuery("#grps").jqGrid('getRowData',id);
             var prueba=ret.Codigo_Cuenta;
            }
       
               $.getJSON('Funciones.php',{Codigo:prueba},Busca_Texto);
               function Busca_Texto(datos)
               {
                 alert(datos);
                 $("#Cuenta1").html(datos);
                }
       
       
       } ,
      
});   


$("#bedata").click(function()
        {
                             // CODIGO MUY IMPORTANTE SIN EL CUAL NO SE GRABARAN TODAS LAS FILAS DEL GRID
                     var total_registros =jQuery("#grps").jqGrid('getGridParam', 'records');// lee el numero total de filas a recorrer
                     jQuery("#grps").setGridParam({ rowNum: total_registros }).trigger('reloadGrid');// cambia el numero de filas  que tiene el grid al numero de total_registros


                if(!confirm(" Esta seguro  de Grabar los asientos?"))  {return false;}
                else {
               
                     var Identifica_Usuario=$('#Id_Usuario').val();
                     var busca_error =0;
                     var mensaje ="";
                     var fecha_Cambio = $('#fecha_Cambio').val();
                     var Num_Comprobante =$('#Num_Comprobante').val();
                     var Comentario =$('#Comentario').val();
                     var cantidad = $("#grps tbody").find("tr").length;
                     var Tipo_Asiento =$('#Tipo_Asiento option:selected').val();
                     var Estatus_Asiento =$('#Estatus_Asiento option:selected').val();
                   
                     if ($("#Estatus_Asiento option:selected").text()=="Seleccione"){busca_error=1;mensaje="Estatus_Asiento";}
                     if ($("#Tipo_Asiento option:selected").text()=="Seleccione"){busca_error=1;mensaje="Tipo_Asiento";}
                     if (cantidad==1){busca_error=2;mensaje="No Puede Grabar Registros en blanco";}
                     if (fecha_Cambio==""){busca_error=1;mensaje="Fecha";}
                     if (Num_Comprobante==""){busca_error=1;mensaje="Numero de Comprobante";}
                     if (Comentario==""){busca_error=1;mensaje="Comentario";}

                   
               
               
                        var z=0;
                     var texto ="";
                     var columns = new Array ();
                     var lista = jQuery("#grps").getDataIDs();
                     for(i=0;i<lista.length;i++)
                        {
                            rowData=jQuery("#grps").getRowData(lista[i]);
                            columns[z]=rowData.Codigo_Cuenta+';'+rowData.Centro_Costo+';'+rowData.Doc_Asoc+';'+rowData.Tipo+';'+rowData.Descripcion+';'+rowData.Monto;
                            z++;
                       }// cierra el for
       
 if(busca_error==0)
{     
          
    var jObject={};
    for(i in columns)
    {
        jObject[i] = columns[i];
    }
   
           
                      $.post("pruebaz.php",{jObject:  jObject,fecha_Cambio:fecha_Cambio,Num_Comprobante:Num_Comprobante,Comentario:Comentario,Tipo_Asiento:Tipo_Asiento,Identifica_Usuario:Identifica_Usuario,Estatus_Asiento:Estatus_Asiento,Identifica_accion:Identifica_accion},function(result){alert(result);$("#enlace").click();});
                         // return false;
                       

}else{

if (busca_error==1){alert('Ingrese un Valor para el Campo '+mensaje);}
if (busca_error==2){alert(mensaje);}
}
                      
                           
                        
                     }   // cierra el confirm       
        });  // cierra la funcion clic
});
</script>



<table width="900" border="0" align="center" cellpadding="5" cellspacing="0">
  <tr>
    <td><a href="index.php?m=1&amp;p=0" id='enlace' name='enlace'>Volver al listado</a></td>
  </tr>
</table>
<br />

<form action="?m=82" method="post" enctype="application/x-www-form-urlencoded" name="rp" id="rp" onSubmit="return ValidaRP1(this)">
  <table width="900" border="0" align="center" cellpadding="3" cellspacing="0" class="srcTabla">
    <tr>
      <th scope="col" style="text-align:center" >Carga de Asientos </th>
    </tr>
    <tr>
      <td align="center" valign="middle" nowrap="nowrap" bgcolor="#ECECEC">
        <table width="100%" border="1" cellspacing="0" cellpadding="6" class="srcTabla">
            <tr>

              <th scope="col" width="140">Id Comprobante  </th>
              <th scope="col" width="140">Tipo de Asiento  </th>
              <th scope="col" width="85">Numero</th>
              <th scope="col" width="125">Fecha</th>
              <th width="492" scope="col">Comentario</th>
              <th width="492" scope="col">Estatus</th>
            </tr>
             <tr>
           
   
               <td valign="middle" nowrap="nowrap"><input type="text" name="Id_Comprobante" Id="Id_Comprobante" readonly="True" /></td>
       
              <td height="50" valign="middle" nowrap="nowrap"><div id="Combo_Asiento" style=" float:left">
                <select name="Tipo_Asiento" id="Tipo_Asiento">
            <option value="Seleccione"      title="Seleccione">Seleccione</option>
            <option value="ad"      title="ad">ad</option>
            <option value="b"       title="b">b</option>
            <option value="cierre"  title="cierre">cierre</option>
            <option value="n"  title="n">n</option>
            <option value="p"  title="p">p</option>
               </select>
                </div>
              </td>
             
              <td valign="middle" nowrap="nowrap"><input type="text" name="Num_Comprobante" Id="Num_Comprobante" /></td>
             
                <td valign="middle" nowrap="nowrap"><input name="fecha_Cambio" type="text" id="fecha_Cambio" size="12" maxlength="10" value="" onkeyup = "this.value=formateafecha(this.value);"/>
      <img src="images/calendar.png" alt="Elija una fecha" name="cal_x_fecha_reg" width="16" height="16" align="bottom" id="cal_x_fecha_reg" style="cursor:pointer;cursor:hand;" onMouseOver="crearcalendar();" />                    </td>
           
             <td valign="middle" nowrap="nowrap"><input name="Comentario" type="text" Id="Comentario" size="70" /></td>
             <td valign="middle" nowrap="nowrap"><div id="Combo_Estatus_Asiento" style=" float:left">
                <select name="Estatus_Asiento" id="Estatus_Asiento">
            <option value="Seleccione"      title="Seleccione">Seleccione</option>
            <option value="S"      title="Actualizado">Actualizado</option>
            <option value="N"       title="No Actualizado">No Actualizado</option>
               </select>
                </div>
              </td>
            </tr>
           
           
      </table></td>
    </tr>
   
   
    <tr>
   
      <td height="63" bgcolor="#ECECEC"><table width="100%" border="1" cellspacing="0" cellpadding="5">
      
      
      </table>
        <table width="1111" border="1" cellspacing="0" cellpadding="0">
          <tr>
            <td width="471" height="30">DEBE:
            <input type="text" name="Debe"   Id="Debe"  readonly="True" value="0"/>
       
            <input type="hidden" name="Debe_Original" Id="Debe_Original" value="" /></td>
           
            <td width="634">HABER:
              <input type="text" name="Haber" Id="Haber" readonly="True" value="0"/>
             
              <input type="hidden" name="Haber_Original" Id="Haber_Original" value=""/></td>
             
          </tr>
        </table>
      </td>
    </tr>
   
   
   
   
   
   
   
   
  </table>
  <br />
 
  <br />
 

  <table id="grps"></table>
  <div id="pgrps"></div>

   <p>&nbsp;</p>
   <p>
     <label id="Cuenta1">     </label>

  </p>
<div id="boton" align="center">
<input type="BUTTON" id="bedata" value="Grabar Comprobante y Asientos Cargados" />
</div>
</form>
<br/><br/><br/>


<?php

    }//Cierra if de Nivel de Acceso
        else{
            include ('msj_nivel_acceso.php');
        }
}//Cierra Nivel de Seguridad
?>

<p>
    <input type="hidden" name="Id_Usuario"  Id="Id_Usuario" value="<?php echo $_SESSION["nombres"].' '.$_SESSION["apellidos"]?>"/>
  </p>

No hay comentarios:

Publicar un comentario