report_invoice_utility.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. openerp.report_invoice_utility = function (instance, local) {
  2. local.ReportWidget = instance.Widget.extend({
  3. template: 'ReportContainerTemplate1',
  4. invoices: [],
  5. invoiceLines: [],
  6. productProduct:[],
  7. Currency:[],
  8. start: function () {
  9. this.fetchJournal();
  10. this.fecthFecha();
  11. this.$el.find('#report_form').submit(_.bind(this.submitForm, this));
  12. },
  13. fecthFecha: function() {
  14. var to;
  15. var dateFormat1 = "mm/dd/yy",
  16. from = $( "#from" )
  17. .datepicker({
  18. dateFormat: "dd/mm/yy",
  19. changeMonth: true,
  20. numberOfMonths: 1,
  21. })
  22. .on( "change", function() {
  23. to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
  24. });
  25. to = $( "#to" ).datepicker({
  26. dateFormat: "dd/mm/yy",
  27. defaultDate: "+7d",
  28. changeMonth: true,
  29. numberOfMonths: 1,
  30. })
  31. .on( "change", function() {
  32. from.datepicker( "option", "maxDate", getDate(this));
  33. });
  34. function getDate( element ) {
  35. var fechaSel =element.value.split('/');
  36. var date;
  37. try {
  38. date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
  39. } catch( error ) {
  40. date = null;
  41. }
  42. return date;
  43. }
  44. },
  45. // Buscar Diario
  46. fetchJournal: function () {
  47. var self = this;
  48. var Journal = new instance.web.Model('account.journal');
  49. Journal.query(['id', 'type', 'code', 'currency', 'name', 'company_id', 'active']).filter([['type', '=', 'sale'], ['active', '=', true]]).all().then(function (results) {
  50. self.journal = results;
  51. _.each(results, function (item) {
  52. self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
  53. });
  54. self.$el.find('#current-journal').append('<option value="9999999">TODAS LAS SUC.</option>');
  55. });
  56. },
  57. // Buscar Cambio de Monedas USD,PYG,ARG,BRL
  58. fetchCurency: function () {
  59. var defer = $.Deferred();
  60. var currency_Rate = new instance.web.Model('res.currency.rate');
  61. var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
  62. var domain = [['currency_id', '=', [166 , 20, 7, 3]]];
  63. currency_Rate.query(fields).filter(domain).all().then(function (results) {
  64. defer.resolve(results);
  65. });
  66. return defer;
  67. },
  68. // Invoice (FACTURAS)
  69. fetchInvoiceV2: function (journalId) {
  70. var desde =(this.$el.find('#from').val());
  71. var hasta =(this.$el.find('#to').val());
  72. var domain ="[['state', '=',['open','paid']],['type', '=', 'out_invoice']";
  73. if( journalId != 9999999){
  74. domain += ",['journal_id.id', '=', "+journalId+"]";
  75. }
  76. if (desde.length > 0 ){
  77. domain += ",['date_invoice','>=', '"+desde+"'], ['date_invoice', '<=', '"+hasta+"']";
  78. }
  79. domain += "]";
  80. var defer = $.Deferred();
  81. var Invoice = new instance.web.Model('account.invoice');
  82. Invoice.query(['id', 'type', 'number', 'origin', 'state', 'journal_id', 'currency_id', 'invoice_line','date_invoice']).filter(domain).all().then(function (results) {
  83. defer.resolve(results);
  84. });
  85. return defer;
  86. },
  87. // Invoice line (Linea de Factura)
  88. fetchInvoiceLine: function (invoices) {
  89. var defer = $.Deferred();
  90. var linesIds = _.flatten(_.map(invoices, function (item) {
  91. return item.invoice_line;
  92. }));
  93. var InvoiceLine = new instance.web.Model('account.invoice.line');
  94. InvoiceLine.query(['id', 'quantity', 'price_unit', 'discount', 'name', 'product_id', 'origin','invoice_id']).filter([['id', 'in', linesIds]]).all().then(function (results) {
  95. defer.resolve(results)
  96. });
  97. return defer;
  98. },
  99. // Product Product
  100. fecthProduct: function(invoiceLines){
  101. var defer = $.Deferred();
  102. var porductIDS = _.flatten(_.map(invoiceLines, function (item) {
  103. return item.product_id[0];
  104. }));
  105. var ProductProdcut = new instance.web.Model('product.product');
  106. var fields = ['id', 'default_code', 'name_template', 'factory_code', 'factory_reference', 'factory_barcode', 'standard_price','type'];
  107. ProductProdcut.query(fields).filter([['id', 'in', porductIDS]]).all().then(function (results) {
  108. defer.resolve(results)
  109. });
  110. return defer;
  111. },
  112. // Cansultar
  113. submitForm: function (e) {
  114. var desde =this.$el.find('#from').val();
  115. var hasta =this.$el.find('#to').val();
  116. e.preventDefault();
  117. var formData = this.$(e.currentTarget).serializeJSON();
  118. if ((formData.journal == 0) || (((desde.length == 0) && (hasta.length > 0)) || ((desde.length > 0) && (hasta.length == 0)))){
  119. $("#dialog" ).dialog({
  120. autoOpen: true,
  121. resizable: false,
  122. modal: true,
  123. title: 'Atención',
  124. open: function() {
  125. $(this).html('Complete el formulario para generar el reporte');
  126. },
  127. show: {
  128. effect: "shake",
  129. duration: 300
  130. },
  131. hide: {
  132. effect: "fade",
  133. duration: 300
  134. },
  135. buttons: {
  136. Aceptar: function() {
  137. $(this).dialog('close');
  138. }
  139. }
  140. });
  141. return;
  142. }
  143. var self = this;
  144. this.fetchCurency().then(function(currency) {
  145. self.Currency = currency;
  146. });
  147. this.fetchInvoiceV2(formData.journal).then(function (invoices) {
  148. self.invoices = invoices;
  149. return invoices;
  150. }).then(function (invoices) {
  151. return self.fetchInvoiceLine(invoices);
  152. }).then(function (invoiceLines) {
  153. self.invoiceLines = invoiceLines;
  154. return self.fecthProduct(invoiceLines);
  155. }).then(function(productProduct){
  156. self.productProduct = productProduct;
  157. return self.invoice_Currency();
  158. });
  159. return false;
  160. },
  161. // Obtener Monedas de la Factura
  162. getCutrrency: function (id){
  163. return _.find(this.Currency,function (curr) {
  164. return _.contains(curr.currency_id,id);
  165. });
  166. },
  167. // Actualizar cambio de las moneda de Factura
  168. invoice_Currency: function(){
  169. for (var i = 0; i < this.invoices.length; i++) {
  170. var currency_new;
  171. var item = this.invoices[i];
  172. var id = item.currency_id[0];
  173. currency_new = this.getCutrrency(id)
  174. if (!currency_new){
  175. currency_new={};
  176. currency_new.rate=1;
  177. }
  178. this.invoices[i].rate=(currency_new.rate);
  179. }
  180. return this.fectUtility();
  181. },
  182. // Obtener la Detalles de la Factura
  183. getInvoice: function (id_line){
  184. return _.find(this.invoices, function (inv) {
  185. return _.contains(inv.invoice_line, id_line);
  186. });
  187. },
  188. // Obtener las lineas de las Facturas
  189. getProduct: function(pro_id){
  190. return _.find(this.productProduct, function(prod){
  191. return _.contains(pro_id, prod.id);
  192. });
  193. },
  194. // unir los objetos
  195. fectUtility: function(){
  196. var data=[];
  197. var item;
  198. var invoice;
  199. var producto;
  200. for (var i = 0; i < this.invoiceLines.length; i++) {
  201. item = this.invoiceLines[i];
  202. invoice = this.getInvoice(item.id)
  203. producto =this.getProduct(item.product_id)
  204. if (!producto){
  205. producto={};
  206. producto.standard_price=0;
  207. }
  208. if (producto.type =="product"){
  209. data.push({number : (invoice.number),
  210. name : (item.name),
  211. quantity : (item.quantity),
  212. price_unity : (item.price_unit.toFixed(2) / invoice.rate.toFixed(2)),
  213. standar_price : (producto.standard_price.toFixed(2)),
  214. price_tot : (item.quantity * (item.price_unit.toFixed(2) / invoice.rate.toFixed(2))),
  215. standar_tot : (item.quantity * producto.standard_price.toFixed(2)),
  216. utility : ((item.quantity * (item.price_unit.toFixed(2) / invoice.rate.toFixed(2))) - (item.quantity * producto.standard_price)).toFixed(2)});
  217. }
  218. }
  219. this.drawPDF(data);
  220. },
  221. // Generar el pdfDoc
  222. drawPDF: function (rows) {
  223. var rows2=[];
  224. var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
  225. var desde =(this.$el.find('#from').val());
  226. var hasta =(this.$el.find('#to').val());
  227. var totalPagesExp = "{total_pages_count_string}";
  228. var getColumns = [
  229. {title: "Factura", dataKey: "number"},
  230. {title: "Producto", dataKey: "name"},
  231. {title: "Cantidad", dataKey: "quantity"},
  232. {title: "Precio Unitario", dataKey: "price_unity"},
  233. {title: "Precio Costo", dataKey: "standar_price"},
  234. {title: "Total Venta", dataKey: "price_tot"},
  235. {title: "Total Costo", dataKey: "standar_tot"},
  236. {title: "Utilidad", dataKey: "utility"}
  237. ];
  238. var pdfDoc = new window.jsPDF();
  239. var quantity=0,precio_cost=0,precio_unit=0,tol_cost=0,tot_unit=0,utility=0;
  240. _.each(rows, function (datos) {
  241. quantity += datos.quantity;
  242. precio_unit += datos.price_unity;
  243. precio_cost += parseFloat(datos.standar_price);
  244. tot_unit += datos.price_tot;
  245. tol_cost += datos.standar_tot;
  246. utility += parseFloat(datos.utility);
  247. });
  248. rows.push({ number : " ",
  249. name : "TOTAL USD ",
  250. quantity: quantity,
  251. price_unity : precio_unit.toFixed(2),
  252. standar_price : precio_cost.toFixed(2),
  253. price_tot : tot_unit.toFixed(2),
  254. standar_tot : tol_cost.toFixed(2),
  255. utility : utility.toFixed(2)});
  256. rows.unshift({ number : " ",
  257. name : "TOTAL USD ",
  258. quantity: quantity,
  259. price_unity : precio_unit.toFixed(2),
  260. standar_price : precio_cost.toFixed(2),
  261. price_tot : tot_unit.toFixed(2),
  262. standar_tot : tol_cost.toFixed(2),
  263. utility : utility.toFixed(2)});
  264. _.each(rows, function (rows1) {
  265. rows2.push({ number : rows1.number,
  266. name : rows1.name,
  267. quantity: accounting.formatNumber(rows1.quantity,0, ".", ","),
  268. price_unity : accounting.formatNumber(rows1.price_unity, 2, ".", ","),
  269. standar_price : accounting.formatNumber(rows1.standar_price, 2, ".", ","),
  270. price_tot : accounting.formatNumber(rows1.price_tot, 2, ".", ","),
  271. standar_tot : accounting.formatNumber(rows1.standar_tot, 2, ".", ","),
  272. utility : accounting.formatNumber(rows1.utility, 2, ".", ",")});
  273. });
  274. pdfDoc.autoTable(getColumns, rows2, {
  275. styles: { overflow: 'linebreak', fontSize: 8, columnWidth: 'wrap'},
  276. columnStyles: {number: {fontStyle: 'bold'},
  277. name :{columnWidth: '10px'},
  278. quantity :{halign:'right' },
  279. price_unity : {halign:'right' },
  280. standar_price : {halign:'right' },
  281. price_tot : {halign:'right' },
  282. standar_tot : {halign:'right' },
  283. utility : {halign:'right'},},
  284. margin: { top: 16, horizontal: 7},
  285. addPageContent: function (data) {
  286. pdfDoc.setFontSize(12);
  287. pdfDoc.setFontStyle('bold');
  288. pdfDoc.setTextColor(40);
  289. pdfDoc.text('Análisis de Utilidad '+ sucusal, data.settings.margin.left, 10);
  290. if(desde.length > 0 ){
  291. pdfDoc.setFontSize(10);
  292. pdfDoc.setFontStyle('bold');
  293. pdfDoc.setTextColor(40)
  294. pdfDoc.text('Desde: '+desde+' Hasta: '+hasta, data.settings.margin.left,14);
  295. }
  296. // FOOTER
  297. var str = "Pagina " + data.pageCount;
  298. // Total page number plugin only available in jspdf v1.0+
  299. if (typeof pdfDoc.putTotalPages === 'function') {
  300. str = str + " de " + totalPagesExp;
  301. }
  302. pdfDoc.setFontSize(9);
  303. pdfDoc.setFontStyle('bold');
  304. pdfDoc.setTextColor(40);
  305. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  306. }
  307. });
  308. if (typeof pdfDoc.putTotalPages === 'function') {
  309. pdfDoc.putTotalPages(totalPagesExp);
  310. }
  311. pdfDoc.save('Analisis de utilidad.pdf')
  312. }
  313. });
  314. instance.web.client_actions.add('report_invoice_utility.action_report', 'instance.report_invoice_utility.ReportWidget');
  315. }