Explorar o código

[ADD] Resumen de Egreso

Rodney Enciso Arias %!s(int64=7) %!d(string=hai) anos
pai
achega
3f992185d5
Modificáronse 2 ficheiros con 543 adicións e 1 borrados
  1. 467 1
      static/src/js/eiru_reporting.js
  2. 76 0
      static/src/reports/report_resumen_egresos.xml

+ 467 - 1
static/src/js/eiru_reporting.js

@@ -16,9 +16,14 @@ openerp.eiru_reporting = function (instance, local) {
             // },
             {
                 title: 'Resumen de Ingreso',
-                description: 'Resumen de Ingreso(Pagos de  Clientes) ',
+                description: 'Resumen de Ingreso(Pagos de Clientes) ',
                 action: 'ReportResumenIngreso'
             },
+            {
+                title: 'Resumen de Engreso',
+                description: 'Resumen de Engreso(Pagos a Proveedores) ',
+                action: 'ReportResumenEngreso'
+            },
             {
                 title: 'Análisis de Utilidad',
                 description: 'Breve descripción del reporte',
@@ -992,6 +997,461 @@ openerp.eiru_reporting = function (instance, local) {
 
     });
 
+
+    // comienza mi codigo ***************************************************************
+
+    local.ReportResumenEngresoWidget = instance.Widget.extend({
+        template :'ReportResumenEngreso',
+        accountVoucher:[],
+        resCurrency:[],
+        accountJournal:[],
+        dataVoucher:[],
+        currencyRate:[],
+        companyCurrency:[],
+
+        events:{
+          'click td > button' : 'clickOnAction',
+          'change #current-journal': 'fectSearch',
+          'change #current-currency': 'fectSearch',
+          'change #from' : 'fectSearch',
+          'change #to': 'fectSearch',
+          'click #volver_btn': 'volver',
+        },
+
+        init:function(parent){
+            this._super(parent);
+        },
+        start: function(){
+            var self = this;
+            self.fecthFecha();
+            self.fecthInitial();
+        },
+        // Fecha
+        fecthFecha: function() {
+            var to;
+            var dateFormat1 = "mm/dd/yy",
+                from = $( "#from" ).datepicker({
+                    dateFormat: "dd/mm/yy",
+                    changeMonth: true,
+                    numberOfMonths: 1,
+                })
+                .on( "change", function() {
+                    to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
+                });
+                to = $( "#to" ).datepicker({
+                    dateFormat: "dd/mm/yy",
+                    defaultDate: "+7d",
+                    changeMonth: true,
+                    numberOfMonths: 1,
+                })
+                .on( "change", function() {
+                    from.datepicker( "option", "maxDate", getDate(this));
+                });
+            function getDate( element ) {
+                var fechaSel =element.value.split('/');
+                var date;
+                try {
+                    date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
+                } catch( error ) {
+                    date = null;
+                }
+              return date;
+            }
+         },
+        //  Metodo inicial
+        fecthInitial: function(){
+            var self = this;
+            self.fecthJournalStore().then(function(accountJournal){
+                self.accountJournal=accountJournal;
+                return accountJournal;
+            }).then(function(accountJournal){
+                self.$el.find('#current-journal').append('<option value="9999999">Todas las SUC.</option>');
+                _.each(accountJournal,function(item){
+                    self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
+                });
+                return self.fecthCurrency();
+            }).then(function(resCurrency){
+                self.$el.find('#current-currency').append('<option value="999">Todas las Monedas</option>');
+                _.each(resCurrency,function(item){
+                    self.$el.find('#current-currency').append('<option value="'+item.id+'">'+item.name +' '+item.symbol+'</option>');
+                });
+                self.resCurrency =resCurrency;
+                return self.fecthCurrencyRate();
+            }).then(function(currencyRate){
+                self.currencyRate =currencyRate;
+                return self.fecthVoucher();
+            }).then(function(accountVoucher){
+                self.accountVoucher =accountVoucher;
+                return self.fecthComanyCurrency();
+            }).then(function(companyCurrency){
+                self.companyCurrency = companyCurrency;
+                return self.fecthDataVoucher(self.accountVoucher,self.accountJournal);
+            });
+
+            return false;
+        },
+        // Journal
+        fecthJournalStore: function(){
+            var self = this;
+            var defer = $.Deferred();
+            var journal = new instance.web.Model('res.store');
+            var field=['id', 'name','out_invoice_id','journal_ids'];
+            journal.query(field).order_by('id').all().then(function(results){
+                defer.resolve(results);
+            });
+            return defer;
+        },
+        // company_curency
+        fecthComanyCurrency: function(){
+            var self = this;
+            var defer = $.Deferred();
+            var currency = new instance.web.Model('res.company');
+            var field=['id', 'currency_id'];
+            var domain=[['id','=',1]];
+            currency.query(field).filter(domain).all().then(function(results){
+                defer.resolve(results);
+            });
+            return defer;
+        },
+        // Moneda
+        fecthCurrency:function(){
+            var self = this;
+            var defer = $.Deferred();
+            var currency = new instance.web.Model('res.currency');
+            var field = ['id', 'name', 'symbol'];
+            var domain = [['active','=', true]];
+            currency.query(field).filter(domain).order_by('id').all().then(function(results){
+                defer.resolve(results);
+            });
+            return defer;
+        },
+        // Cambio de la moneda
+        fecthCurrencyRate:function(){
+            var defer = $.Deferred();
+            var currency_Rate = new instance.web.Model('res.currency.rate');
+            var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
+            var domain = [['currency_id', '=', [166 , 20, 7, 3]]];
+            currency_Rate.query(fields).filter(domain).all().then(function (results) {
+              defer.resolve(results);
+            });
+            return defer;
+        },
+        // Voucher -
+        fecthVoucher:function(){
+            var self= this;
+            var defer = $.Deferred();
+            var voucher = new instance.web.Model('account.voucher');
+            var field = ['id', 'reference', 'number', 'partner_id', 'payment_rate_currency_id', 'currency_id', 'company_id',' state',' pre_line', 'payment_rate', 'type', 'date', 'name', 'journal_id', 'amount'];
+            var domain =[['type', '=', 'payment']];
+            voucher.query(field).filter(domain).order_by('id').all().then(function(results){
+                defer.resolve(results);
+            });
+            return defer;
+        },
+        // Verificar Valor null
+        valorNull:function(dato){
+            var valor ="";
+            if (dato){
+                if(dato == true && typeof dato == 'boolean'){
+                    valor="X";
+                }else{
+                    valor=dato;
+                }
+            }
+            return valor;
+        },
+        // Join object
+        fecthDataVoucher:function(objVoucher,objJournal){
+            var self=this;
+            var item;
+            var journal;
+            var voucherLine;
+            var voucherItem;//Contenido del voucher
+            var sumaAmount; //Guardar la suma de los pagos
+            var voucherObject=[];
+            var voucherObjectItem=[];
+            var cutrrencyRate; //Valor del cambio
+            var total=0;
+            var sumaAmountTot=0;
+            var  itemVoucher;
+            for (var i = 0; i < objJournal.length; i++) {
+                voucherObjectItem=[];
+                journal=objJournal[i];
+                //Generar la Cabezera con el nombre de la sucursal
+                for (var f = 0; f < journal.journal_ids.length; f++) {
+                    voucherLine = journal.journal_ids[f];
+                    voucherItem = self.getVoucherjournal(objVoucher,voucherLine)
+                    if (voucherItem.length > 0){
+                        sumaAmount=_.reduce(_.map(voucherItem,function(item){return item.amount}), function(memo, num){ return memo + num; },0);
+                        itemVoucher = voucherItem.shift();
+                        cutrrencyRate=self.getCutrrencyRate(itemVoucher.currency_id[0]);
+                        if (!cutrrencyRate){
+                            cutrrencyRate={};
+                            cutrrencyRate.rate=1;
+                        }
+                        // Guardar item
+                        voucherObjectItem.push({    journal : " ",
+                                                method  :self.valorNull(itemVoucher.journal_id[1]),
+                                                amount  : accounting.formatNumber(self.valorNull(sumaAmount),2, ".", ","),
+                                                currency_name : self.valorNull(itemVoucher.currency_id[0]),
+                                                currency_id : self.valorNull(itemVoucher.currency_id[1]),
+                                                rate : cutrrencyRate.rate,
+                                                amountBase : self.valorNull(sumaAmount / cutrrencyRate.rate),
+                                                journal_id: journal.id,
+                                                journal_name: journal.name,
+                                                graficar: false
+                                        })
+                    }
+                }
+                var company = _.map(self.companyCurrency, function (map) {
+                    return map.currency_id[1];
+                });
+
+                sumaAmountTot=_.reduce(_.map(voucherObjectItem,function(item){return (item.amountBase)}), function(memo, num){ return memo + num; },0);
+                total=total+sumaAmountTot;
+                voucherObjectItem.push({journal : " ",
+                                        method  :"Total " + company,
+                                        amount  : accounting.formatNumber(self.valorNull(sumaAmountTot),2, ".", ","),
+                                        currency_name : "",
+                                        currency_id : "",
+                                        rate : "cutrrencyRate.rate",
+                                        amountBase:"",
+                                        journal_id: journal.id,
+                                        journal_name: journal.name,
+                                        graficar: true
+                                });
+                // Generarl la Cabezera
+                voucherObjectItem.unshift({ journal : journal.name, method  :"", amount  :"", voucherLine_name :"", voucherLine_id :"",rate :"",amountBase :"",journal_id:journal.id, journal_name:journal.name, graficar:false});
+                // Generar Objeto Principal
+                voucherObject=voucherObject.concat(voucherObjectItem);
+            }
+            voucherObject.push({journal : " Total de Egreso",
+                                    method  :"",
+                                    amount  : accounting.formatNumber(self.valorNull(total),2, ".", ","),
+                                    currency_name : "",
+                                    currency_id : "",
+                                    rate : "",
+                                    amountBase:"",
+                                    journal_id: journal.id,
+                                    journal_name: journal.name,
+                                    graficar: false
+                            });
+            self.loadTable(voucherObject);
+        },
+        // Obtener Voucher
+        getVoucherjournal:function(objVoucher,journal_id){
+            return _.map(_.filter(objVoucher, function (inv){return inv.journal_id[0] === journal_id}),function(item){return item});
+        },
+        // Obtener Cambio
+        getCutrrencyRate: function(currency_id){
+            return _.filter(this.currencyRate, function(rate){return rate.currency_id[0] === currency_id}).shift();
+        },
+        // Generar la tabla
+        loadTable:function(rowsTable){
+            this.dataVoucher=rowsTable;
+            var table = this.$el.find('#table');
+            if( table.bootstrapTable('getData').length <= 1){
+                table.bootstrapTable({data : rowsTable});
+            }else{
+                table.bootstrapTable('load' ,rowsTable);
+            }
+        },
+        // Buscar
+        fectSearch: function(){
+            var self = this;
+            var desde =this.$el.find('#from').val();
+            var hasta =this.$el.find('#to').val();
+            var journal =this.$el.find('#current-journal').val();
+            var currency =this.$el.find('#current-currency').val();
+            var newJournal= self.accountJournal; //copia del Diario
+            var newVoucher= self.accountVoucher; //copia del Vouacher
+
+            if (journal != 9999999){
+                var botonChart =this.$el.find('#chart').attr("disabled", true);
+                 newJournal=_.filter(newJournal, function (inv){ return inv.id == journal});
+            }else {
+                var botonChart =this.$el.find('#chart').attr("disabled", false);
+            }
+
+            if(currency != 999){
+                 newVoucher=_.filter(newVoucher, function (inv){ return inv.currency_id[0] == currency});
+            }
+
+            if (desde){
+                 var date= desde.split('/')
+                 newVoucher=_.filter(newVoucher, function (inv){return inv.date >= (date[2]+"-"+date[1]+"-"+date[0])});
+            }
+
+            if (hasta){
+                var date= hasta.split('/')
+                newVoucher=_.filter(newVoucher, function (inv){return inv.date <= (date[2]+"-"+date[1]+"-"+date[0])});
+           }
+            self.fecthDataVoucher(newVoucher,newJournal);
+        },
+        // volver
+        volver: function(){
+          this.$el.find('#volver').empty();
+          this.$el.find('#grafico').empty();
+        //   this.$el.find('canvas').empty()
+          this.$el.find('.bootstrap-table').show({
+              effect: 'drop',
+              direction: 'down',
+              duration: 200,
+          });
+          this.$el.find('#toolbar').show({
+              effect: 'drop',
+              direction: 'down',
+              duration: 200,
+          });
+        },
+        // Click pdf -Grafic
+        clickOnAction: function (e) {
+            var action = this.$el.find(e.target).val();
+            var self = this;
+            var getColumns=[];
+            var rows=[];
+            var table = this.$el.find("#table");
+            var data2 = table.bootstrapTable('getVisibleColumns');
+            if (action === 'pdf') {
+              var dataNEW = _.map(data2, function (val){ return val.field});
+              _.each(this.dataVoucher,function (item){
+                        rows.push(_.pick(item, dataNEW));
+              });
+              // Obtener los nombre de la Cabezera
+              _.each(_.map(data2,function(val){return val}), function(item){
+                 getColumns.push([{title: item.title, dataKey: item.field}]);
+              });
+              // Llamar al pdf
+              this.drawPDF(_.flatten(getColumns),rows)
+            }
+            if (action === 'chart'){
+                var self = this;
+                var objetChar;
+                objetChar = _.filter(self.dataVoucher,function(item){return item.graficar === true});
+                self.fectCharFilter(objetChar);
+            }
+        },
+        // pdfDoc
+        drawPDF:function(getColumns,rows){
+            var self = this;
+            var fechaActu= new Date();
+            var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
+            var desde =(this.$el.find('#from').val());
+            var hasta =(this.$el.find('#to').val());
+            var totalPagesExp = "{total_pages_count_string}";
+            var pdfDoc = new window.jsPDF();
+
+            pdfDoc.autoTable(getColumns, rows, {
+                    styles: { overflow: 'linebreak', fontSize:10 , columnWidth: 'wrap'},
+                   columnStyles:{ journal: {fontStyle: 'bold'},
+                                  method :{columnWidth: '10px'},
+                                  amount : {halign:'right'},
+                                },
+                   margin: { top: 16, horizontal: 7},
+                addPageContent: function (data) {
+                    pdfDoc.setFontSize(12);
+                    pdfDoc.setFontStyle('bold');
+                    pdfDoc.setTextColor(40);
+                    pdfDoc.text('Resumen de Egreso de '+ sucusal, data.settings.margin.left, 10);
+                    if(desde.length > 0 || hasta.length > 0){
+                        var fecha='';
+                        if(desde){
+                            fecha=fecha.concat(' Desde '+desde);
+                        }
+                        if (hasta){
+                            fecha=fecha.concat(' Hasta '+hasta);
+                        }
+                        pdfDoc.setFontSize(10);
+                        pdfDoc.setFontStyle('bold');
+                        pdfDoc.setTextColor(40)
+                        pdfDoc.text(fecha, data.settings.margin.left,14);
+                    }
+                    // FOOTER
+                    var str = "Pagina  " + data.pageCount;
+                    // Total page number plugin only available in jspdf v1.0+
+                    if (typeof pdfDoc.putTotalPages === 'function') {
+                        str = str + " de " + totalPagesExp +"\n  Día de Expedición  "+fechaActu.getDate()+"/"+fechaActu.getMonth()+"/"+fechaActu.getFullYear();
+                    }
+                    pdfDoc.setFontSize(9);
+                    pdfDoc.setFontStyle('bold');
+                    pdfDoc.setTextColor(40);
+                    pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
+                }
+            });
+            if (typeof pdfDoc.putTotalPages === 'function') {
+                pdfDoc.putTotalPages(totalPagesExp);
+            }
+           pdfDoc.save('Resumen de Egreso.pdf');
+        },
+        // Char filter
+        fectCharFilter: function(objetChar){
+            var self = this;
+            var dataBody=[];
+            var dataHeader=[];
+            // objetChar
+            var canvas="<canvas id='graf_resume'></canvas>";
+              this.$el.find('#grafico').append(canvas);
+            _.each(objetChar,function(voucher){
+                dataHeader.push(voucher.journal_name);
+                dataBody.push(parseFloat(((voucher.amount.replace(".","")).replace(",","."))));
+            });
+          var selector ="<button type='button' class='oe_button oe_form_button oe_highlight' id='volver_btn' name='volver_btn'><span>Atras</span></button>";
+          this.$el.find('#volver').append(selector);
+          this.$el.find('.bootstrap-table').hide({
+              effect: 'drop',
+              direction: 'up',
+              duration: 200,
+              complete: function () {
+                self.drawChart(dataHeader,dataBody);
+              }
+          });
+          this.$el.find('#toolbar').hide({
+              effect: 'drop',
+              direction: 'up',
+              duration: 200,
+              complete: function () {
+                self.drawChart(dataHeader,dataBody);
+              }
+          });
+        },
+        //Chart
+        drawChart: function (dataHeader,dataBody) {
+            var barChart = new Chart(this.$el.find('#graf_resume'), {
+                type: 'doughnut',//bar, doughnut
+                data: {
+                    labels: dataHeader,
+                    datasets: [
+                        {
+                            labels: dataHeader,
+                            backgroundColor: [
+                                'rgba(255, 99, 132, 0.2)',
+                                'rgba(54, 162, 235, 0.2)',
+                                'rgba(255, 206, 86, 0.2)',
+                                'rgba(75, 192, 192, 0.2)',
+                                'rgba(153, 102, 255, 0.2)',
+                            ],
+                            borderColor: [
+                                'rgba(255,99,132,1)',
+                                'rgba(54, 162, 235, 1)',
+                                'rgba(255, 206, 86, 1)',
+                                'rgba(75, 192, 192, 1)',
+                                'rgba(153, 102, 255, 1)',
+                            ],
+                            borderWidth: 1,
+                            data: dataBody,
+                        }
+                    ]
+                },
+                options: {
+                    maintainAspectRatio: false,
+                    layout: {
+                        padding: 30
+                    }
+                },
+            });
+        },
+    });
+
     local.ReportResumenIngresoWidget = instance.Widget.extend({
         template :'ReportResumenIngreso',
         accountVoucher:[],
@@ -1410,6 +1870,12 @@ openerp.eiru_reporting = function (instance, local) {
         },
     });
 
+
+
+
+
+
+
     local.ReportStockLocationWidget = instance.Widget.extend({
         template : 'ReportStockLocation',
         stockLocation : [],

+ 76 - 0
static/src/reports/report_resumen_egresos.xml

@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<template xml:space="preserve">
+    <t t-name="ReportResumenEngreso">
+        <div class="report_view">
+            <div class="reporting_page_header">
+                <h1>Resumen de Egreso</h1>
+                <div id="volver"></div>
+            </div>
+            <div id="toolbar">
+                <div class="panel panel-default">
+                    <table class="table">
+                        <tbody>
+                            <tr>
+                                <td>
+                                    <div class="form-group">
+                                        <label for="current-journal">Sucursal: </label>
+                                        <select id="current-journal" class="form-control ui-autocomplete-input"  name="journal"></select>    
+                                    </div>
+                                </td>
+                                <td>
+                                    <div class="form-group">
+                                        <label for="current-currency">Moneda: </label>
+                                        <select id="current-currency" class="form-control ui-autocomplete-input"  name="currency"></select>    
+                                    </div>     
+                                </td>
+                                <td>
+                                    <div class="form-group">
+                                        <label for="from">Desde: </label>
+                                        <input type="text" class="form-control" id="from" name="from"/>
+                                    </div>
+                                </td>
+                                <td>
+                                    <div class="form-group">
+                                        <label for="to" >Hasta: </label>
+                                        <input type="text" class="form-control" id="to" name="to" />  
+                                    </div>  
+                                </td>
+                            </tr>
+                            <tr>
+                                <td></td>
+                                <td></td>
+                                <td>
+                                    <button class="oe_button oe_form_button oe_highlight btn-block" value="pdf" id="pdf">Exportar a PDF</button>
+                                </td>
+                                <td>
+                                    <button class="oe_button oe_form_button oe_highlight btn-block" value="chart" id="chart">Graficar</button>
+                                </td>
+                            </tr>
+                        </tbody>
+                    </table>
+                </div>
+            </div>
+            <table id="table"
+                data-classes="table table-hover table-condensed"
+                data-buttons-class="oe_button oe_form_button oe_highlight"
+                data-reorderable-columns="true"
+                data-height="auto"
+                data-pagination="false"
+                data-show-columns="true"
+                data-id-field="number"
+                data-row-style="rowStyle">
+                <thead >
+                    <tr>
+                        <th data-field="journal" class="sucursal" >Sucursal</th>
+                        <th data-field="method" >Método de Pago</th>
+                        <th data-field="amount" data-align="right" >Pagos a Proveedores</th>
+                    </tr>
+                </thead>
+            </table>
+
+            <div class="widget-content" id="grafico">
+            </div>
+            <div id="dialog"></div>
+        </div>
+    </t>
+</template>