function report_purchases (reporting){ "use strict"; var instance = openerp; reporting.ReportPurchasesWidget = reporting.Base.extend({ template: 'ReportPurchases', invoice: [], Currency:[], resCurrency :[], resCompany:[], accountJournal:[], supplier:[], newInvoice:[], newCabecera:[], rowsData :[], events:{ 'change #current-period' : 'factSearch', 'click #txt' : 'generarTxt', 'click .download' : 'downloadAttachment', 'click .preview' : 'previewAttachment' }, // Init init : function(parent){ this._super(parent); }, // start start: function () { var self = this; var table = this.$el.find('#table'); table.bootstrapTable( {data : self.rowsData} ); this.submitForm(); }, // Consultar submitForm: function () { var self = this; self.fetchPeriod().then(function(period) { return period; }).then(function (period) { self.period = period; self.$el.find('#current-period').append('<option value="9999999">Todos los períodos</option>'); _.each(period, function (item) { self.$el.find('#current-period').append('<option value="' + item.id + '">' + item.name + '</option>'); }); return self.fetchJournal(); }).then(function (journal) { self.accountJournal =journal; return self.fetchInvoiceP2(); }).then(function (invoice){ self.invoice = invoice; return self.fetchSupplier(invoice); }).then(function (supplier){ self.supplier=supplier; return self.fetchPaymentTerm(); }).then(function (paymentTerm){ self.paymentTerm=paymentTerm; return self.fetchAttachment(); }).then(function(attachment){ self.attachment=attachment; return self.fecthComanyCurrency(); }).then(function(resCompany){ self.resCompany = resCompany; self.inicializarBuscadorsup(); return self.fect_generar(self.invoice); }).then(function(currency){ self.currency = currency; // return self.fect_cabecera(self.resCompany, self.newInvoice); }); }, // Buscar Diario fetchJournal: function () { var self = this; var defer = $.Deferred(); var Journal = new instance.web.Model('account.journal'); Journal.query(['id', 'name']).filter([['type', '=', ['purchase','purchase_refund']]]).all().then(function(results){ defer.resolve(results); }); return defer; }, // Periodo fetchPeriod: function () { var defer = $.Deferred(); var period = new instance.web.Model('account.period'); var fields = ['id', 'name']; var domain = [['special', '!=', true]]; period.query(fields).filter(domain).all().then(function (results) { defer.resolve(results); }); return defer; }, // Invoice (FACTURAS) fetchInvoiceP2: function () { var journal_ids = _.flatten(_.map(this.accountJournal, function (item) { return item.id; })); var filter =[['state', 'in',['open','paid']],['type', '=', ['in_invoice','in_refund']],['journal_id', 'in',journal_ids]]; var field =['id', 'type', 'number', 'origin', 'state', 'journal_id', 'currency_id', 'supplier_invoice_number','date_invoice','partner_id','amount_total','user_id','contado','credito','payment_term','period_id','amount_untaxed','amount_tax','attachment_ids','timbrado']; var defer = $.Deferred(); var Invoice = new instance.web.Model('account.invoice'); Invoice.query(field).filter(filter).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','exportador','agent_ruc','legal_agent','company_ruc','name','juridico']; var domain=[['id','=',1]]; currency.query(field).filter(domain).all().then(function(results){ defer.resolve(results); }); return defer; }, // Partner (Proveeedor) fetchSupplier: function() { var self = this; var defer = $.Deferred(); var supplier = new instance.web.Model('res.partner'); supplier.query(['id', 'name', 'ruc', 'active', 'supplier']).filter([['active', '=', true], ['supplier', '=', true]]).all().then(function (results) { defer.resolve(results); }); return defer; }, // Archivos Adjuntos fetchAttachment: function() { var self = this; var defer = $.Deferred(); var id = _.flatten(_.map(self.invoice,function(map){ return id; })); var attachment = new instance.web.Model('ir.attachment'); attachment.query(['id','res_id', 'datas', 'res_model','file_type','name']).filter([['res_model', '=','account.invoice']]).all().then(function (results) { defer.resolve(results); }); return defer; }, // Plazos de pagos fetchPaymentTerm: function () { var self = this; var defer = $.Deferred(); var payment_term = _.flatten(_.map(self.invoice,function(map){ return map.payment_term[0]; })); var paymentTerm = new instance.web.Model('account.payment.term'); paymentTerm.query(['id','name','line_ids']).filter([['id', '=', payment_term]]).all().then(function(results){ defer.resolve(results); }); return defer; }, // Verificar si los Valores no son nulos valorNull:function(dato){ var valor =""; if (dato){ valor=dato; } return valor; }, // Buscador inicializarBuscadorsup: function () { var self = this; var results = self.supplier; results = _.map(results, function (item) { return { label: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc), value: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc) } }); self.$('#customer').autocomplete({ source: results, minLength:0, search: function(event, ui) { if (!(self.$('#customer').val())){ self.factSearch(); } }, close: function( event, ui ) { self.factSearch(); }, select: function(event, ui) { self.factSearch(); } }); }, getSupplier : function(partner_id){ var self = this; return _.filter(self.supplier,function(item){ return item.id === partner_id; }).shift(); }, getPaymentTerm : function(id){ var self = this; return _.filter(self.paymentTerm,function(item){ return item.id === id; }).shift(); }, getAttachment : function(attachment_ids){ var self = this; return _.filter(self.attachment,function(item){ return item.id === attachment_ids; }).shift(); }, // Detalle del registro fect_generar: function(invoices){ var self = this; var data = []; var supplier_ruc; var ruc; var cuota; var tipo; var tasa_10 = 0; var tasa_5 = 0; var iva_5 = 0; var iva_10 = 0; var IVA = 0; var TAX = 0; var adjunto; var untaxed; var condicion; var contador = 0; var icons = 0; var imagen; var img; _.each(invoices, function(invoice){ // Obtener el ruc y el DV del proveedor supplier_ruc = self.getSupplier(invoice.partner_id[0]); ruc = supplier_ruc.ruc.split("-"); // Determinar si la factura es a credito o al contado. condicion = 1; if (invoice.credito == true){ condicion = 2; } // Determinar la cantidad de cuotas. cuota = _.flatten(self.getPaymentTerm(invoice.payment_term[0])).length - 2; // Validar. Si la factura es al contado, la cuota debe ser cero. if (condicion == 1 || cuota < 1){ cuota = 0; } // Determinar el tipo de factura. if(invoice.type == 'in_invoice'){ tipo = 1; }else{ tipo = 2; } // Manejo de impuestos IVA = accounting.formatNumber(((invoice.amount_untaxed * 10)/100),"",""); TAX = accounting.formatNumber(invoice.amount_tax,"",""); untaxed = 0; iva_5 = 0; iva_10 = 0; tasa_10 = 0; tasa_5 = 0; // Determinar si fue aplicado algun impuesto a la factura. if(invoice.amount_total == invoice.amount_untaxed){ untaxed = accounting.formatNumber(invoice.amount_untaxed,"",""); }else{ // Si fue aplicado impuesto, determina si fue de 10% o 5%. if(IVA == TAX){ iva_10 = accounting.formatNumber(invoice.amount_tax,"","");; tasa_10 = accounting.formatNumber(invoice.amount_untaxed,"",""); }else{ iva_5 = accounting.formatNumber(invoice.amount_tax,"","");; tasa_5 = accounting.formatNumber(invoice.amount_untaxed,"",""); } } // Obtener binario del archivo adjunto adjunto = self.getAttachment(invoice.attachment_ids[0]); imagen = _.flatten(adjunto); // Obtener el tipo de adjunto if(adjunto == undefined){ icons = '<a class="" href="javascript:void(0)" title="Descarga no disponible"><i class="fa fa-file fa-lg" aria-hidden="true"></i></a> <a class="" href="javascript:void(0)" title="Vista previa no disponible"><i class="fa fa-eye-slash fa-lg" aria-hidden="true"></i></a>'; }else{ if(imagen[1]=='image/png' || imagen[1]=='image/jpeg'){ icons = '<a class="download" href="javascript:void(0)" title="Descargar"><i class="fa fa-download fa-lg" aria-hidden="true"></i></a> <a class="preview" title="Vista previa"><i class="fa fa-eye fa-lg" aria-hidden="true"></i></a>'; }else{ icons = '<a class="download" href="javascript:void(0)" title="Descargar"><i class="fa fa-download fa-lg" aria-hidden="true"></i></a> <a class="" href="javascript:void(0)" title="Vista previa no disponible"><i class="fa fa-eye-slash fa-lg" aria-hidden="true"></i></a>'; } } // Indice de la tabla contador += 1; // Crear el objeto que se muestra en la tabla data.push({ linea: contador, tipo_registro: 2, ruc_proveedor: ruc[0], dv: ruc[1], partner : invoice.partner_id[1], supplier_invoice_number: self.valorNull(invoice.timbrado), tipo_documento : tipo, number: self.valorNull(invoice.supplier_invoice_number), date: moment(invoice.date_invoice).format("DD/MM/YYYY"), tasa_10 : tasa_10, iva_10 : iva_10, tasa_5 : tasa_5, iva_5 : iva_5, amount_untaxed: untaxed, tipo_operacion : 8, condicion_compra : condicion, cantidad_cuotas : cuota, period_id : invoice.period_id[0], period_name : invoice.period_id[1], attachment_ids : adjunto, download_icon : icons, }); }); self.newInvoice = data; this.loadTable(data); }, // Informacion para el txt. fect_cabecera: function(resCompanys, invoices){ var self = this; // Cabecera var datos = []; var company_ruc; var agent_ruc; var version = 2; var total = 0; var cantidad = 0; var valor = 0; var periodo; var ruc_agente = 0; var dv_agente = 0; var nombre_agente = 0; var period =this.$el.find('#current-period').val(); _.each(resCompanys, function(resCompany){ // Obtener el RUC y el DV de la compania company_ruc = resCompany.company_ruc.split("-"); // Determinar si la persona es fisica o juridica if(resCompany.juridico == true){ agent = resCompany.agent_ruc.split("-"); ruc_agente = agent[0]; dv_agente = agent[1]; nombre_agente = resCompany.legal_agent; } // Tipo de registro datos.push(1); datos.push('\t'); // Periodo datos.push(201708); // moment(periodo).format("YYYYMM") datos.push('\t'); // Tipo de reporte datos.push(1); datos.push('\t'); // Codigo Obligacion datos.push(911); datos.push('\t'); // Codigo Formulario datos.push(211); datos.push('\t'); // Ruc agente de informacion datos.push(company_ruc[0]); datos.push('\t'); // DV agente de informacion datos.push(company_ruc[1]); datos.push('\t'); // Nombre o denominacion del agente de informacion datos.push(resCompany.name); datos.push('\t'); // Ruc representante legal datos.push(ruc_agente); datos.push('\t'); // DV representante legal datos.push(dv_agente); datos.push('\t'); // Nombre y apellido de representante legal datos.push(nombre_agente); datos.push('\t'); // Cantidad de registros datos.push(50); datos.push('\t'); // Monto total datos.push(2654122); datos.push('\t'); // Exportador datos.push(resCompany.exportador); datos.push('\t'); // Version datos.push(version); datos.push('\r\n'); }); // detalles _.each(invoices, function(newInvoice){ if(newInvoice.period_id == period){ // tipo de registro datos.push(newInvoice.tipo_registro); datos.push('\t'); // ruc del proveedor datos.push(newInvoice.ruc_proveedor); datos.push('\t'); // dv del proveedor datos.push(newInvoice.dv); datos.push('\t'); // Nombre o denominacion del proveedor datos.push(newInvoice.partner); datos.push('\t'); // Numero de timbrado datos.push(newInvoice.supplier_invoice_number); datos.push('\t'); // Tipo de documento datos.push(newInvoice.tipo_documento); datos.push('\t'); // Numero de documento datos.push(newInvoice.number); datos.push('\t'); // Fecha de documento datos.push(newInvoice.date); datos.push('\t'); // Monto de la compra a la tasa 10% datos.push(newInvoice.tasa_10); datos.push('\t'); // IVA credito 10% datos.push(newInvoice.iva_10); datos.push('\t'); // Monto de la compra a la tasa 5% datos.push(newInvoice.tasa_5); datos.push('\t'); // IVA credito 5% datos.push(newInvoice.iva_5); datos.push('\t'); // Monto de la compra no gravada o exenta datos.push(newInvoice.amount_untaxed); datos.push('\t'); // Tipo de operacion datos.push(newInvoice.tipo_operacion); datos.push('\t'); // Condicion de compra datos.push(newInvoice.condicion_compra); datos.push('\t'); // Cantidad de cuotas datos.push(newInvoice.cantidad_cuotas); datos.push('\r\n'); // Catidad de registros cantidad += 1; valor = parseInt(newInvoice.amount_untaxed) + parseInt(newInvoice.tasa_5) + parseInt(newInvoice.tasa_10); total += valor; periodo = newInvoice.period_name.split("/"); } }); datos.splice(2,0); datos[2] = periodo[1] + periodo[0]; datos.splice(22,0); datos[22] = cantidad; datos.splice(24,0); datos[24] = accounting.formatNumber(total,"",""); self.newCabecera = new Blob(datos, {type: 'text/plain'}); }, // Buscar factSearch: function(){ var self = this; var period =this.$el.find('#current-period').val(); var newInvoice = self.newInvoice; // Buscar por Periodo if (period != 9999999){ newInvoice=_.filter(newInvoice, function (inv){ return inv.period_id == period; }); } self.loadTable(newInvoice) }, // cargara la tabla loadTable:function(rowsTable){ var self = this; self.rowsData = rowsTable; var table = this.$el.find('#table'); table.bootstrapTable('load',rowsTable); }, // Generar el txt con el nombre correspondiente generarTxt: function () { var self = this; var newInvoice = self.newInvoice; var period =this.$el.find('#current-period').val(); if (period != 9999999){ newInvoice=_.filter(newInvoice, function (inv){ return inv.period_id == period; }); if(newInvoice.length != 0){ var periodo = newInvoice[0].period_name.split("/"); var fileName = "Compras " + periodo[1] + periodo[0]; self.fect_cabecera(self.resCompany, self.newInvoice); download(self.newCabecera, fileName, "text/plain"); }else{ self.showMensajeRegistro(); } }else{ self.showMensaje(); } }, // Descargar el archivo adjunto downloadAttachment: function (e) { var self = this; var newInvoice = self.newInvoice; var fila = $(e.target).closest('tr'); var columnas = fila.children(); var orden = parseInt(columnas[0].textContent); var dato = newInvoice[orden - 1].attachment_ids; download("data:"+dato.file_type+";base64,"+dato.datas+"",dato.name,dato.file_type); }, // Vista previa del archivo previewAttachment: function (e) { var self = this; var newInvoice = self.newInvoice; var fila = $(e.target).closest('tr'); var columnas = fila.children(); var orden = parseInt(columnas[0].textContent); var dato = newInvoice[orden -1].attachment_ids; var img = 'data:'+dato.file_type+';base64,'+dato.datas; lightbox.option({ 'showImageNumberLabel': false }); $(".preview").attr("data-lightbox",dato.name); $(".preview").attr("href",img); }, // Lanzar el mensaje de pediodo showMensaje : function(modelos){ var self = this; $("#dialog" ).dialog({ autoOpen: true, resizable: false, modal: true, title: 'Atención', width: 500, open: function() { $(this).html('Debe elegir un periodo'); }, show: { effect: "fade", duration: 200 }, hide: { effect: "fade", duration: 200 }, buttons: { Aceptar: function() { $(this).dialog('close'); } } }); return }, // Lanzar mensaje de registros showMensajeRegistro : function(modelos){ var self = this; $("#dialog" ).dialog({ autoOpen: true, resizable: false, modal: true, title: 'Atención', width: 500, open: function() { $(this).html('No hay registros que exportar'); }, show: { effect: "fade", duration: 200 }, hide: { effect: "fade", duration: 200 }, buttons: { Aceptar: function() { $(this).dialog('close'); } } }); return }, }); }