report_puchases.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. function report_puchases (reporting){
  2. "use strict";
  3. var instance = openerp;
  4. reporting.AllPurchasesWidget = reporting.Base.extend({
  5. template: 'AllPurchases',
  6. invoice: [],
  7. Currency:[],
  8. resCurrency :[],
  9. resCompany:[],
  10. accountJournal:[],
  11. supplier:[],
  12. newInvoice:[],
  13. rowsData :[],
  14. // event
  15. events:{
  16. 'click #toolbar > button' : 'clickOnAction',
  17. 'change #current-journal' : 'factSearch',
  18. 'change #current-currency' : 'factSearch',
  19. 'change #from' : 'factSearch',
  20. 'change #to' : 'factSearch',
  21. 'click #volver_btn' : 'volver',
  22. 'click-row.bs.table #table ' : 'ckickAnalysisDetail',
  23. },
  24. // Initil
  25. init : function(parent){
  26. this._super(parent);
  27. },
  28. // start
  29. start: function () {
  30. var self = this;
  31. var table = this.$el.find('#table');
  32. table.bootstrapTable({data : self.rowsData});
  33. this.fecthFecha();
  34. this.submitForm();
  35. },
  36. // Analisis Detallado
  37. ckickAnalysisDetail: function(e, row, $element, field){
  38. if (field == 'number'){
  39. this.do_action({
  40. name:"Factura de proveedor",
  41. type: 'ir.actions.act_window',
  42. res_model: "account.invoice",
  43. views: [[false,'form']],
  44. target: 'new',
  45. domain: [['type', '=', 'in_invoice'],['id','=', row.id]],
  46. context: {},
  47. flags: {'form': {'action_buttons': false, 'options': {'mode': 'view'}}},
  48. res_id: row.id,
  49. });
  50. }
  51. e.stopImmediatePropagation();
  52. },
  53. // volver
  54. volver: function(){
  55. this.$el.find('#volver').empty();
  56. this.$el.find('.bootstrap-table').show({
  57. effect: 'drop',
  58. direction: 'down',
  59. duration: 200,
  60. });
  61. },
  62. // Consultar
  63. submitForm: function () {
  64. var self = this;
  65. self.fetchResCurency().then(function(resCurrency) {
  66. return resCurrency;
  67. }).then(function (resCurrency) {
  68. self.resCurrency = resCurrency;
  69. self.$el.find('#current-currency').append('<option value="9999999">Todas las monedas</option>');
  70. _.each(resCurrency, function (item) {
  71. self.$el.find('#current-currency').append('<option value="' + item.id + '">' + item.name + '</option>');
  72. });
  73. return self.fetchCurency(resCurrency);
  74. }).then(function(Currency){
  75. self.Currency = Currency;
  76. return self.fetchJournal();
  77. }).then(function (journal) {
  78. self.accountJournal =journal;
  79. self.$el.find('#current-journal').append('<option value="9999999">TODAS LAS SUC.</option>');
  80. _.each(journal, function (item) {
  81. self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
  82. });
  83. return self.fetchInvoiceP2();
  84. }).then(function (invoice){
  85. self.invoice = invoice;
  86. return self.fetchSupplier(invoice);
  87. }).then(function(supplier){
  88. self.supplier=supplier;
  89. return self.fecthComanyCurrency();
  90. }).then(function(resCompany){
  91. self.resCompany = resCompany;
  92. self.inicializarBuscadorsup();
  93. return self.fect_generar(self.invoice);
  94. });
  95. },
  96. // Fecha
  97. fecthFecha: function() {
  98. var to;
  99. var dateFormat1 = "mm/dd/yy",
  100. from = $( "#from" )
  101. .datepicker({
  102. dateFormat: "dd/mm/yy",
  103. changeMonth: true,
  104. numberOfMonths: 1,
  105. })
  106. .on( "change", function() {
  107. to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
  108. });
  109. to = $( "#to" ).datepicker({
  110. dateFormat: "dd/mm/yy",
  111. defaultDate: "+7d",
  112. changeMonth: true,
  113. numberOfMonths: 1,
  114. })
  115. .on( "change", function() {
  116. from.datepicker( "option", "maxDate", getDate(this));
  117. });
  118. function getDate( element ) {
  119. var fechaSel =element.value.split('/');
  120. var date;
  121. try {
  122. date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
  123. } catch( error ) {
  124. date = null;
  125. }
  126. return date;
  127. }
  128. },
  129. // Buscar Diario
  130. fetchJournal: function () {
  131. var self = this;
  132. var defer = $.Deferred();
  133. var Journal = new instance.web.Model('account.journal');
  134. Journal.query(['id', 'name']).filter([['type', '=', 'purchase']]).all().then(function(results){
  135. defer.resolve(results);
  136. });
  137. return defer;
  138. },
  139. // Buscar Cambio de Monedas USD,PYG,ARG,BRL
  140. fetchCurency: function (currency) {
  141. var defer = $.Deferred();
  142. var currency_id = _.flatten(_.map(currency,function(map){
  143. return map.id;
  144. }))
  145. var currency_Rate = new instance.web.Model('res.currency.rate');
  146. var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
  147. var domain = [['currency_id', 'in', currency_id]];
  148. currency_Rate.query(fields).filter(domain).all().then(function (results) {
  149. defer.resolve(results);
  150. });
  151. return defer;
  152. },
  153. // Moneda
  154. fetchResCurency: function () {
  155. var defer = $.Deferred();
  156. var currency = new instance.web.Model('res.currency');
  157. var fields = ['id', 'name'];
  158. var domain = [['active', '=', true]];
  159. currency.query(fields).filter(domain).all().then(function (results) {
  160. defer.resolve(results);
  161. });
  162. return defer;
  163. },
  164. // Invoice (FACTURAS)
  165. fetchInvoiceP2: function () {
  166. var journal_ids = _.flatten(_.map(this.accountJournal, function (item) {
  167. return item.id;
  168. }));
  169. var filter =[['state', 'in',['open','paid']],['type', '=', 'in_invoice'],['origin', '!=', false],['journal_id', 'in',journal_ids]];
  170. var field =['id', 'type', 'number', 'origin', 'state', 'journal_id', 'currency_id', 'supplier_invoice_number','date_invoice','partner_id','amount_total','user_id'];
  171. var defer = $.Deferred();
  172. var Invoice = new instance.web.Model('account.invoice');
  173. Invoice.query(field).filter(filter).all().then(function (results) {
  174. defer.resolve(results);
  175. });
  176. return defer;
  177. },
  178. // company_curency
  179. fecthComanyCurrency: function(){
  180. var self = this;
  181. var defer = $.Deferred();
  182. var currency = new instance.web.Model('res.company');
  183. var field=['id', 'currency_id'];
  184. var domain=[['id','=',1]];
  185. currency.query(field).filter(domain).all().then(function(results){
  186. defer.resolve(results);
  187. });
  188. return defer;
  189. },
  190. // Partner (Proveeedor)
  191. fetchSupplier: function() {
  192. var self = this;
  193. var defer = $.Deferred();
  194. var supplier = new instance.web.Model('res.partner');
  195. supplier.query(['id', 'name', 'ruc', 'active', 'supplier']).filter([['active', '=', true], ['supplier', '=', true]]).all().then(function (results) {
  196. defer.resolve(results);
  197. });
  198. return defer;
  199. },
  200. // Obtener el Cambio de la Moneda
  201. getCurrency: function (id){
  202. return _.find(this.Currency,function (curr) {
  203. return _.contains(curr.currency_id,id);
  204. });
  205. },
  206. // Verificar si los Valores no son nulos
  207. valorNull:function(dato){
  208. var valor ="";
  209. if (dato){
  210. valor=dato;
  211. }
  212. return valor;
  213. },
  214. // Buscador
  215. inicializarBuscadorsup: function () {
  216. var self = this;
  217. var results = self.supplier;
  218. results = _.map(results, function (item) {
  219. return {
  220. label: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc),
  221. value: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc)
  222. }
  223. });
  224. self.$('#customer').autocomplete({
  225. source: results,
  226. minLength:0,
  227. search: function(event, ui) {
  228. if (!(self.$('#customer').val())){
  229. self.factSearch();
  230. }
  231. },
  232. close: function( event, ui ) {
  233. self.factSearch();
  234. },
  235. select: function(event, ui) {
  236. self.factSearch();
  237. }
  238. });
  239. },
  240. // unir los objetos
  241. fect_generar: function(invoices){
  242. var self = this;
  243. var data = [];
  244. _.each(invoices, function(invoice){
  245. data.push({
  246. id : invoice.id,
  247. number: invoice.number,
  248. supplier_invoice_number: self.valorNull(invoice.supplier_invoice_number),
  249. partner: invoice.partner_id[1],
  250. date: moment(invoice.date_invoice).format("DD/MM/YYYY"),
  251. date_invoice: invoice.date_invoice,
  252. user: invoice.user_id[1],
  253. currency: invoice.currency_id[1],
  254. amount_total: accounting.formatNumber(invoice.amount_total,2,".",","),
  255. amount: invoice.amount_total,
  256. journal_id : invoice.journal_id[0],
  257. currency_id : invoice.currency_id[0],
  258. partner_id : invoice.partner_id[0],
  259. origin: invoice.origin
  260. });
  261. });
  262. self.newInvoice = data;
  263. this.loadTable(data);
  264. },
  265. // Buscar
  266. factSearch: function(){
  267. var self = this;
  268. var desde =this.$el.find('#from').val();
  269. var hasta =this.$el.find('#to').val();
  270. var suc =this.$el.find('#current-journal').val();
  271. var currency =this.$el.find('#current-currency').val();
  272. var prov= this.$el.find('#customer').val().split('-');
  273. var newInvoice = self.newInvoice;
  274. // Buscar por Sucursales
  275. if (suc != 9999999){
  276. newInvoice=_.filter(newInvoice, function (inv){
  277. return inv.journal_id == suc;
  278. });
  279. }
  280. // Buscar por fecha Desde
  281. if (desde.length > 0){
  282. var date= desde.split('/');
  283. newInvoice = _.filter(newInvoice, function (inv){
  284. return inv.date_invoice >= (date[2]+"-"+date[1]+"-"+date[0]);
  285. });
  286. }
  287. // Buscar por Fechas Hasta
  288. if (hasta.length > 0){
  289. var date= hasta.split('/');
  290. newInvoice = _.filter(newInvoice, function (inv){
  291. return inv.date_invoice <= (date[2]+"-"+date[1]+"-"+date[0]);
  292. });
  293. }
  294. // Busacar por moneda
  295. if(currency != 9999999){
  296. newInvoice = _.filter(newInvoice,function(inv){
  297. return inv.currency_id == currency;
  298. });
  299. }
  300. // Buscar por proveedor
  301. if (prov != ""){
  302. newInvoice = _.filter(newInvoice, function(inv){
  303. return inv.partner_id == prov[0];
  304. });
  305. }
  306. self.loadTable(newInvoice)
  307. },
  308. // cargara la tabla
  309. loadTable:function(rowsTable){
  310. var self = this;
  311. self.rowsData = rowsTable;
  312. var table = this.$el.find('#table');
  313. table.bootstrapTable('load',rowsTable);
  314. },
  315. // Obtener Invoice por Monedad
  316. getInvoice : function(currency_id){
  317. var self = this;
  318. return _.filter(self.rowsData, function(item){
  319. return item.currency_id === currency_id;
  320. });
  321. },
  322. // Crear Objete PDF
  323. getObjetPdf: function(rowsTable){
  324. var self = this;
  325. var rowsPdf=[];
  326. var rows=[];
  327. var itemCurrecy;
  328. var itenRow;
  329. var item;
  330. var curreRate;
  331. var amount_total=0;
  332. var amount=0;
  333. var company = _.map(self.resCompany,function(map){return map.currency_id[1]});
  334. for (var i = 0; i < self.resCurrency.length; i++) {
  335. itemCurrecy = self.resCurrency[i];
  336. itenRow = self.getInvoice(itemCurrecy.id);
  337. rowsPdf=[];
  338. if (itenRow.length > 0){
  339. rowsPdf.push({number: itemCurrecy.name, supplier_invoice_number: "", partner: "", date: "", date_invoice: "", user: "", currency: "", amount_total: "", journal_id : "", currency_id : "", partner_id : ""});
  340. _.each(itenRow, function(item){
  341. rowsPdf.push({
  342. number: item.number,
  343. supplier_invoice_number: self.valorNull(item.supplier_invoice_number),
  344. partner: item.partner,
  345. date: moment(item.date_invoice).format("DD/MM/YYYY"),
  346. date_invoice: item.date_invoice,
  347. user: item.user,
  348. currency: item.currency,
  349. amount_total: accounting.formatNumber((item.amount),2,".",","),
  350. amount: item.amount,
  351. journal_id : item.journal_id,
  352. currency_id : item.currency_id,
  353. partner_id : item.partner_id
  354. });
  355. });
  356. curreRate = self.getCurrency(itemCurrecy.id);
  357. if (!curreRate){
  358. curreRate={};
  359. curreRate.rate=1;
  360. }
  361. amount_total= _.reduce(_.map(itenRow,function(map){
  362. return(map.amount);
  363. }),function(memo, num){
  364. return memo + num;
  365. },0);
  366. amount = amount+(amount_total/curreRate.rate);
  367. rowsPdf.push({
  368. number: "Sub - Total "+itemCurrecy.name,
  369. supplier_invoice_number: "",
  370. partner: "",
  371. date: "",
  372. date_invoice: "",
  373. user: "",
  374. currency: "",
  375. amount_total: accounting.formatNumber((amount_total),2,".",","),
  376. journal_id : "",
  377. currency_id : "",
  378. partner_id : ""
  379. });
  380. }
  381. if (rowsPdf.length >0){
  382. rows = rows.concat(rowsPdf);
  383. }
  384. }
  385. if (rows.length > 0){
  386. rows.push({
  387. number: "Total en "+company,
  388. supplier_invoice_number: "",
  389. partner: "",
  390. date: "",
  391. date_invoice: "",
  392. user: "",
  393. currency: "",
  394. amount_total: accounting.formatNumber((amount),2,".",","),
  395. journal_id : "",
  396. currency_id : "",
  397. partner_id : ""
  398. });
  399. }
  400. return rows;
  401. },
  402. // imprimir PDF
  403. clickOnAction: function (e) {
  404. var self = this;
  405. var rowsNew;
  406. var action = self.$el.find(e.target).val();
  407. var table = self.$el.find("#table");
  408. var data2 = table.bootstrapTable('getVisibleColumns');
  409. var getColumns=[];
  410. var rows=[];
  411. rowsNew = self.getObjetPdf();
  412. if (action === 'pdf') {
  413. var dataNEW = _.map(data2, function (val){
  414. return val.field;
  415. });
  416. _.each(rowsNew,function (item){
  417. rows.push(_.pick(item, dataNEW));
  418. });
  419. // Obtener los nombre de la Cabezera
  420. _.each(_.map(data2,function(val){
  421. return val;
  422. }), function(item){
  423. getColumns.push([{
  424. title: item.title,
  425. dataKey: item.field
  426. }]);
  427. });
  428. this.drawPDF(_.flatten(getColumns),rows);
  429. }
  430. },
  431. // Generar pdfDoc
  432. drawPDF: function (getColumns,rows) {
  433. var self = this;
  434. var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
  435. var desde =(this.$el.find('#from').val());
  436. var hasta =(this.$el.find('#to').val());
  437. var totalPagesExp = "{total_pages_count_string}";
  438. var pdfDoc = new jsPDF();
  439. pdfDoc.autoTable(getColumns, rows, {
  440. styles: { overflow: 'linebreak', fontSize: 8, columnWidth: 'wrap'},
  441. columnStyles: {
  442. number : {columnWidth: '8px'},
  443. supplier_invoice_number : {columnWidth: '8px'},
  444. partner : {columnWidth: '8px'},
  445. date : {columnWidth: '8px'},
  446. user : {columnWidth: '8px'},
  447. currency : {columnWidth: '8px'},
  448. amount_total: {halign:'right',columnWidth: '8px'},
  449. },
  450. margin: { top: 16, horizontal: 7},
  451. addPageContent: function (data) {
  452. pdfDoc.setFontSize(12);
  453. pdfDoc.setFontStyle('bold');
  454. pdfDoc.setTextColor(40);
  455. pdfDoc.text('Histórico de compras de '+ sucusal, data.settings.margin.left, 10);
  456. if(desde.length > 0 || hasta.length > 0){
  457. var fecha='';
  458. if(desde){
  459. fecha=fecha.concat(' Desde '+desde);
  460. }
  461. if (hasta){
  462. fecha=fecha.concat(' Hasta '+hasta);
  463. }
  464. pdfDoc.setFontSize(10);
  465. pdfDoc.setFontStyle('bold');
  466. pdfDoc.setTextColor(40)
  467. pdfDoc.text(fecha, data.settings.margin.left,14);
  468. }
  469. // FOOTER
  470. var str = "Pagina " + data.pageCount;
  471. // Total page number plugin only available in jspdf v1.0+
  472. if (typeof pdfDoc.putTotalPages === 'function') {
  473. str = str + " de " + totalPagesExp;
  474. }
  475. pdfDoc.setFontSize(9);
  476. pdfDoc.setFontStyle('bold');
  477. pdfDoc.setTextColor(40);
  478. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  479. }
  480. });
  481. if (typeof pdfDoc.putTotalPages === 'function') {
  482. pdfDoc.putTotalPages(totalPagesExp);
  483. }
  484. pdfDoc.save('Histórico de compras.pdf')
  485. },
  486. });
  487. }