123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328 |
- openerp.report_invoice_utility = function (instance, local) {
- local.ReportWidget = instance.Widget.extend({
- template: 'ReportContainerTemplate1',
- invoices: [],
- invoiceLines: [],
- productProduct:[],
- Currency:[],
- start: function () {
- this.fetchJournal();
- this.fecthFecha();
- this.$el.find('#report_form').submit(_.bind(this.submitForm, this));
- },
- 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;
- }
- },
- // Buscar Diario
- fetchJournal: function () {
- var self = this;
- var Journal = new instance.web.Model('account.journal');
- Journal.query(['id', 'type', 'code', 'currency', 'name', 'company_id', 'active']).filter([['type', '=', 'sale'], ['active', '=', true]]).all().then(function (results) {
- self.journal = results;
- _.each(results, function (item) {
- self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
- });
- self.$el.find('#current-journal').append('<option value="9999999">TODAS LAS SUC.</option>');
- });
- },
- // Buscar Cambio de Monedas USD,PYG,ARG,BRL
- fetchCurency: 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;
- },
- // Invoice (FACTURAS)
- fetchInvoiceV2: function (journalId) {
- var desde =(this.$el.find('#from').val());
- var hasta =(this.$el.find('#to').val());
- var domain ="[['state', '=',['open','paid']],['type', '=', 'out_invoice']";
- if( journalId != 9999999){
- domain += ",['journal_id.id', '=', "+journalId+"]";
- }
- if (desde.length > 0 ){
- domain += ",['date_invoice','>=', '"+desde+"'], ['date_invoice', '<=', '"+hasta+"']";
- }
- domain += "]";
- var defer = $.Deferred();
- var Invoice = new instance.web.Model('account.invoice');
- Invoice.query(['id', 'type', 'number', 'origin', 'state', 'journal_id', 'currency_id', 'invoice_line','date_invoice']).filter(domain).all().then(function (results) {
- defer.resolve(results);
- });
- return defer;
- },
- // Invoice line (Linea de Factura)
- fetchInvoiceLine: function (invoices) {
- var defer = $.Deferred();
- var linesIds = _.flatten(_.map(invoices, function (item) {
- return item.invoice_line;
- }));
- var InvoiceLine = new instance.web.Model('account.invoice.line');
- InvoiceLine.query(['id', 'quantity', 'price_unit', 'discount', 'name', 'product_id', 'origin','invoice_id']).filter([['id', 'in', linesIds]]).all().then(function (results) {
- defer.resolve(results)
- });
- return defer;
- },
- // Product Product
- fecthProduct: function(invoiceLines){
- var defer = $.Deferred();
- var porductIDS = _.flatten(_.map(invoiceLines, function (item) {
- return item.product_id[0];
- }));
- var ProductProdcut = new instance.web.Model('product.product');
- var fields = ['id', 'default_code', 'name_template', 'factory_code', 'factory_reference', 'factory_barcode', 'standard_price','type'];
- ProductProdcut.query(fields).filter([['id', 'in', porductIDS]]).all().then(function (results) {
- defer.resolve(results)
- });
- return defer;
- },
- // Cansultar
- submitForm: function (e) {
- var desde =this.$el.find('#from').val();
- var hasta =this.$el.find('#to').val();
- e.preventDefault();
- var formData = this.$(e.currentTarget).serializeJSON();
- if ((formData.journal == 0) || (((desde.length == 0) && (hasta.length > 0)) || ((desde.length > 0) && (hasta.length == 0)))){
- $("#dialog" ).dialog({
- autoOpen: true,
- resizable: false,
- modal: true,
- title: 'Atención',
- open: function() {
- $(this).html('Complete el formulario para generar el reporte');
- },
- show: {
- effect: "shake",
- duration: 300
- },
- hide: {
- effect: "fade",
- duration: 300
- },
- buttons: {
- Aceptar: function() {
- $(this).dialog('close');
- }
- }
- });
- return;
- }
- var self = this;
- this.fetchCurency().then(function(currency) {
- self.Currency = currency;
- });
- this.fetchInvoiceV2(formData.journal).then(function (invoices) {
- self.invoices = invoices;
- return invoices;
- }).then(function (invoices) {
- return self.fetchInvoiceLine(invoices);
- }).then(function (invoiceLines) {
- self.invoiceLines = invoiceLines;
- return self.fecthProduct(invoiceLines);
- }).then(function(productProduct){
- self.productProduct = productProduct;
- return self.invoice_Currency();
- });
- return false;
- },
- // Obtener Monedas de la Factura
- getCutrrency: function (id){
- return _.find(this.Currency,function (curr) {
- return _.contains(curr.currency_id,id);
- });
- },
- // Actualizar cambio de las moneda de Factura
- invoice_Currency: function(){
- for (var i = 0; i < this.invoices.length; i++) {
- var currency_new;
- var item = this.invoices[i];
- var id = item.currency_id[0];
- currency_new = this.getCutrrency(id)
- if (!currency_new){
- currency_new={};
- currency_new.rate=1;
- }
- this.invoices[i].rate=(currency_new.rate);
- }
- return this.fectUtility();
- },
- // Obtener la Detalles de la Factura
- getInvoice: function (id_line){
- return _.find(this.invoices, function (inv) {
- return _.contains(inv.invoice_line, id_line);
- });
- },
- // Obtener las lineas de las Facturas
- getProduct: function(pro_id){
- return _.find(this.productProduct, function(prod){
- return _.contains(pro_id, prod.id);
- });
- },
- // unir los objetos
- fectUtility: function(){
- var data=[];
- var item;
- var invoice;
- var producto;
- for (var i = 0; i < this.invoiceLines.length; i++) {
- item = this.invoiceLines[i];
- invoice = this.getInvoice(item.id)
- producto =this.getProduct(item.product_id)
- if (!producto){
- producto={};
- producto.standard_price=0;
- }
- if (producto.type =="product"){
- data.push({number : (invoice.number),
- name : (item.name),
- quantity : (item.quantity),
- price_unity : (item.price_unit.toFixed(2) / invoice.rate.toFixed(2)),
- standar_price : (producto.standard_price.toFixed(2)),
- price_tot : (item.quantity * (item.price_unit.toFixed(2) / invoice.rate.toFixed(2))),
- standar_tot : (item.quantity * producto.standard_price.toFixed(2)),
- utility : ((item.quantity * (item.price_unit.toFixed(2) / invoice.rate.toFixed(2))) - (item.quantity * producto.standard_price)).toFixed(2)});
- }
- }
- this.drawPDF(data);
- },
- // Generar el pdfDoc
- drawPDF: function (rows) {
- var rows2=[];
- 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 getColumns = [
- {title: "Factura", dataKey: "number"},
- {title: "Producto", dataKey: "name"},
- {title: "Cantidad", dataKey: "quantity"},
- {title: "Precio Unitario", dataKey: "price_unity"},
- {title: "Precio Costo", dataKey: "standar_price"},
- {title: "Total Venta", dataKey: "price_tot"},
- {title: "Total Costo", dataKey: "standar_tot"},
- {title: "Utilidad", dataKey: "utility"}
- ];
- var pdfDoc = new window.jsPDF();
- var quantity=0,precio_cost=0,precio_unit=0,tol_cost=0,tot_unit=0,utility=0;
- _.each(rows, function (datos) {
- quantity += datos.quantity;
- precio_unit += datos.price_unity;
- precio_cost += parseFloat(datos.standar_price);
- tot_unit += datos.price_tot;
- tol_cost += datos.standar_tot;
- utility += parseFloat(datos.utility);
- });
- rows.push({ number : " ",
- name : "TOTAL USD ",
- quantity: quantity,
- price_unity : precio_unit.toFixed(2),
- standar_price : precio_cost.toFixed(2),
- price_tot : tot_unit.toFixed(2),
- standar_tot : tol_cost.toFixed(2),
- utility : utility.toFixed(2)});
- rows.unshift({ number : " ",
- name : "TOTAL USD ",
- quantity: quantity,
- price_unity : precio_unit.toFixed(2),
- standar_price : precio_cost.toFixed(2),
- price_tot : tot_unit.toFixed(2),
- standar_tot : tol_cost.toFixed(2),
- utility : utility.toFixed(2)});
- _.each(rows, function (rows1) {
- rows2.push({ number : rows1.number,
- name : rows1.name,
- quantity: accounting.formatNumber(rows1.quantity,0, ".", ","),
- price_unity : accounting.formatNumber(rows1.price_unity, 2, ".", ","),
- standar_price : accounting.formatNumber(rows1.standar_price, 2, ".", ","),
- price_tot : accounting.formatNumber(rows1.price_tot, 2, ".", ","),
- standar_tot : accounting.formatNumber(rows1.standar_tot, 2, ".", ","),
- utility : accounting.formatNumber(rows1.utility, 2, ".", ",")});
- });
- pdfDoc.autoTable(getColumns, rows2, {
- styles: { overflow: 'linebreak', fontSize: 8, columnWidth: 'wrap'},
- columnStyles: {number: {fontStyle: 'bold'},
- name :{columnWidth: '10px'},
- quantity :{halign:'right' },
- price_unity : {halign:'right' },
- standar_price : {halign:'right' },
- price_tot : {halign:'right' },
- standar_tot : {halign:'right' },
- utility : {halign:'right'},},
- margin: { top: 16, horizontal: 7},
- addPageContent: function (data) {
- pdfDoc.setFontSize(12);
- pdfDoc.setFontStyle('bold');
- pdfDoc.setTextColor(40);
- pdfDoc.text('Análisis de Utilidad '+ sucusal, data.settings.margin.left, 10);
- if(desde.length > 0 ){
- pdfDoc.setFontSize(10);
- pdfDoc.setFontStyle('bold');
- pdfDoc.setTextColor(40)
- pdfDoc.text('Desde: '+desde+' Hasta: '+hasta, 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;
- }
- 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('Analisis de utilidad.pdf')
- }
- });
- instance.web.client_actions.add('report_invoice_utility.action_report', 'instance.report_invoice_utility.ReportWidget');
- }
|