123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495 |
- function report_puchases (reporting){
- "use strict";
- var instance = openerp;
- reporting.AllPurchasesWidget = reporting.Base.extend({
- template: 'AllPurchases',
- invoice: [],
- Currency:[],
- resCurrency :[],
- resCompany:[],
- accountJournal:[],
- supplier:[],
- newInvoice:[],
- rowsData :[],
- // event
- events:{
- 'click #toolbar > button' : 'clickOnAction',
- 'change #current-journal' : 'factSearch',
- 'change #current-currency' : 'factSearch',
- 'change #from' : 'factSearch',
- 'change #to' : 'factSearch',
- 'click #volver_btn' : 'volver',
- 'click-row.bs.table #table ' : 'ckickAnalysisDetail',
- },
- // Initil
- init : function(parent){
- this._super(parent);
- },
- // start
- start: function () {
- var self = this;
- var table = this.$el.find('#table');
- table.bootstrapTable({data : self.rowsData});
- this.fecthFecha();
- this.submitForm();
- },
- // Analisis Detallado
- ckickAnalysisDetail: function(e, row, $element, field){
- if (field == 'number'){
- this.do_action({
- name:"Factura de proveedor",
- type: 'ir.actions.act_window',
- res_model: "account.invoice",
- views: [[false,'form']],
- target: 'new',
- domain: [['type', '=', 'in_invoice'],['id','=', row.id]],
- context: {},
- flags: {'form': {'action_buttons': false, 'options': {'mode': 'view'}}},
- res_id: row.id,
- });
- }
- e.stopImmediatePropagation();
- },
- // volver
- volver: function(){
- this.$el.find('#volver').empty();
- this.$el.find('.bootstrap-table').show({
- effect: 'drop',
- direction: 'down',
- duration: 200,
- });
- },
- // Consultar
- submitForm: function () {
- var self = this;
- self.fetchResCurency().then(function(resCurrency) {
- return resCurrency;
- }).then(function (resCurrency) {
- self.resCurrency = resCurrency;
- self.$el.find('#current-currency').append('<option value="9999999">Todas las monedas</option>');
- _.each(resCurrency, function (item) {
- self.$el.find('#current-currency').append('<option value="' + item.id + '">' + item.name + '</option>');
- });
- return self.fetchCurency(resCurrency);
- }).then(function(Currency){
- self.Currency = Currency;
- return self.fetchJournal();
- }).then(function (journal) {
- self.accountJournal =journal;
- self.$el.find('#current-journal').append('<option value="9999999">TODAS LAS SUC.</option>');
- _.each(journal, function (item) {
- self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
- });
- return self.fetchInvoiceP2();
- }).then(function (invoice){
- self.invoice = invoice;
- return self.fetchSupplier(invoice);
- }).then(function(supplier){
- self.supplier=supplier;
- return self.fecthComanyCurrency();
- }).then(function(resCompany){
- self.resCompany = resCompany;
- self.inicializarBuscadorsup();
- return self.fect_generar(self.invoice);
- });
- },
- // 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;
- }
- },
- // 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']]).all().then(function(results){
- defer.resolve(results);
- });
- return defer;
- },
- // Buscar Cambio de Monedas USD,PYG,ARG,BRL
- fetchCurency: function (currency) {
- var defer = $.Deferred();
- var currency_id = _.flatten(_.map(currency,function(map){
- return map.id;
- }))
- var currency_Rate = new instance.web.Model('res.currency.rate');
- var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
- var domain = [['currency_id', 'in', currency_id]];
- currency_Rate.query(fields).filter(domain).all().then(function (results) {
- defer.resolve(results);
- });
- return defer;
- },
- // Moneda
- fetchResCurency: function () {
- var defer = $.Deferred();
- var currency = new instance.web.Model('res.currency');
- var fields = ['id', 'name'];
- var domain = [['active', '=', true]];
- currency.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'],['origin', '!=', false],['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'];
- 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'];
- 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;
- },
- // Obtener el Cambio de la Moneda
- getCurrency: function (id){
- return _.find(this.Currency,function (curr) {
- return _.contains(curr.currency_id,id);
- });
- },
- // 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();
- }
- });
- },
- // unir los objetos
- fect_generar: function(invoices){
- var self = this;
- var data = [];
- _.each(invoices, function(invoice){
- data.push({
- id : invoice.id,
- number: invoice.number,
- supplier_invoice_number: self.valorNull(invoice.supplier_invoice_number),
- partner: invoice.partner_id[1],
- date: moment(invoice.date_invoice).format("DD/MM/YYYY"),
- date_invoice: invoice.date_invoice,
- user: invoice.user_id[1],
- currency: invoice.currency_id[1],
- amount_total: accounting.formatNumber(invoice.amount_total,2,".",","),
- amount: invoice.amount_total,
- journal_id : invoice.journal_id[0],
- currency_id : invoice.currency_id[0],
- partner_id : invoice.partner_id[0],
- origin: invoice.origin
- });
- });
- self.newInvoice = data;
- this.loadTable(data);
- },
- // Buscar
- factSearch: function(){
- var self = this;
- var desde =this.$el.find('#from').val();
- var hasta =this.$el.find('#to').val();
- var suc =this.$el.find('#current-journal').val();
- var currency =this.$el.find('#current-currency').val();
- var prov= this.$el.find('#customer').val().split('-');
- var newInvoice = self.newInvoice;
- // Buscar por Sucursales
- if (suc != 9999999){
- newInvoice=_.filter(newInvoice, function (inv){
- return inv.journal_id == suc;
- });
- }
- // Buscar por fecha Desde
- if (desde.length > 0){
- var date= desde.split('/');
- newInvoice = _.filter(newInvoice, function (inv){
- return inv.date_invoice >= (date[2]+"-"+date[1]+"-"+date[0]);
- });
- }
- // Buscar por Fechas Hasta
- if (hasta.length > 0){
- var date= hasta.split('/');
- newInvoice = _.filter(newInvoice, function (inv){
- return inv.date_invoice <= (date[2]+"-"+date[1]+"-"+date[0]);
- });
- }
- // Busacar por moneda
- if(currency != 9999999){
- newInvoice = _.filter(newInvoice,function(inv){
- return inv.currency_id == currency;
- });
- }
- // Buscar por proveedor
- if (prov != ""){
- newInvoice = _.filter(newInvoice, function(inv){
- return inv.partner_id == prov[0];
- });
- }
- 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);
- },
- // Obtener Invoice por Monedad
- getInvoice : function(currency_id){
- var self = this;
- return _.filter(self.rowsData, function(item){
- return item.currency_id === currency_id;
- });
- },
- // Crear Objete PDF
- getObjetPdf: function(rowsTable){
- var self = this;
- var rowsPdf=[];
- var rows=[];
- var itemCurrecy;
- var itenRow;
- var item;
- var curreRate;
- var amount_total=0;
- var amount=0;
- var company = _.map(self.resCompany,function(map){return map.currency_id[1]});
- for (var i = 0; i < self.resCurrency.length; i++) {
- itemCurrecy = self.resCurrency[i];
- itenRow = self.getInvoice(itemCurrecy.id);
- rowsPdf=[];
- if (itenRow.length > 0){
- rowsPdf.push({number: itemCurrecy.name, supplier_invoice_number: "", partner: "", date: "", date_invoice: "", user: "", currency: "", amount_total: "", journal_id : "", currency_id : "", partner_id : ""});
- _.each(itenRow, function(item){
- rowsPdf.push({
- number: item.number,
- supplier_invoice_number: self.valorNull(item.supplier_invoice_number),
- partner: item.partner,
- date: moment(item.date_invoice).format("DD/MM/YYYY"),
- date_invoice: item.date_invoice,
- user: item.user,
- currency: item.currency,
- amount_total: accounting.formatNumber((item.amount),2,".",","),
- amount: item.amount,
- journal_id : item.journal_id,
- currency_id : item.currency_id,
- partner_id : item.partner_id
- });
- });
- curreRate = self.getCurrency(itemCurrecy.id);
- if (!curreRate){
- curreRate={};
- curreRate.rate=1;
- }
- amount_total= _.reduce(_.map(itenRow,function(map){
- return(map.amount);
- }),function(memo, num){
- return memo + num;
- },0);
- amount = amount+(amount_total/curreRate.rate);
- rowsPdf.push({
- number: "Sub - Total "+itemCurrecy.name,
- supplier_invoice_number: "",
- partner: "",
- date: "",
- date_invoice: "",
- user: "",
- currency: "",
- amount_total: accounting.formatNumber((amount_total),2,".",","),
- journal_id : "",
- currency_id : "",
- partner_id : ""
- });
- }
- if (rowsPdf.length >0){
- rows = rows.concat(rowsPdf);
- }
- }
- if (rows.length > 0){
- rows.push({
- number: "Total en "+company,
- supplier_invoice_number: "",
- partner: "",
- date: "",
- date_invoice: "",
- user: "",
- currency: "",
- amount_total: accounting.formatNumber((amount),2,".",","),
- journal_id : "",
- currency_id : "",
- partner_id : ""
- });
- }
- return rows;
- },
- // imprimir PDF
- clickOnAction: function (e) {
- var self = this;
- var rowsNew;
- var action = self.$el.find(e.target).val();
- var table = self.$el.find("#table");
- var data2 = table.bootstrapTable('getVisibleColumns');
- var getColumns=[];
- var rows=[];
- rowsNew = self.getObjetPdf();
- if (action === 'pdf') {
- var dataNEW = _.map(data2, function (val){
- return val.field;
- });
- _.each(rowsNew,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
- }]);
- });
- this.drawPDF(_.flatten(getColumns),rows);
- }
- },
- // Generar pdfDoc
- drawPDF: function (getColumns,rows) {
- var self = this;
- 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 jsPDF();
- pdfDoc.autoTable(getColumns, rows, {
- styles: { overflow: 'linebreak', fontSize: 8, columnWidth: 'wrap'},
- columnStyles: {
- number : {columnWidth: '8px'},
- supplier_invoice_number : {columnWidth: '8px'},
- partner : {columnWidth: '8px'},
- date : {columnWidth: '8px'},
- user : {columnWidth: '8px'},
- currency : {columnWidth: '8px'},
- amount_total: {halign:'right',columnWidth: '8px'},
- },
- margin: { top: 16, horizontal: 7},
- addPageContent: function (data) {
- pdfDoc.setFontSize(12);
- pdfDoc.setFontStyle('bold');
- pdfDoc.setTextColor(40);
- pdfDoc.text('Histórico de compras 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;
- }
- 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('Histórico de compras.pdf')
- },
- });
- }
|