report_purchases.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. function report_purchases (reporting){
  2. "use strict";
  3. var instance = openerp;
  4. reporting.ReportPurchasesWidget = reporting.Base.extend({
  5. template: 'ReportPurchases',
  6. invoice: [],
  7. Currency:[],
  8. resCurrency :[],
  9. resCompany:[],
  10. accountJournal:[],
  11. supplier:[],
  12. newInvoice:[],
  13. newCabecera:[],
  14. rowsData :[],
  15. events:{
  16. 'change #current-period' : 'factSearch',
  17. 'click #txt' : 'generarTxt',
  18. 'click .download' : 'downloadAttachment',
  19. 'click .preview' : 'previewAttachment'
  20. },
  21. // Init
  22. init : function(parent){
  23. this._super(parent);
  24. },
  25. // start
  26. start: function () {
  27. var self = this;
  28. var table = this.$el.find('#table');
  29. table.bootstrapTable(
  30. {data : self.rowsData}
  31. );
  32. this.submitForm();
  33. },
  34. // Consultar
  35. submitForm: function () {
  36. var self = this;
  37. self.fetchPeriod().then(function(period) {
  38. return period;
  39. }).then(function (period) {
  40. self.period = period;
  41. self.$el.find('#current-period').append('<option value="9999999">Todos los períodos</option>');
  42. _.each(period, function (item) {
  43. self.$el.find('#current-period').append('<option value="' + item.id + '">' + item.name + '</option>');
  44. });
  45. return self.fetchJournal();
  46. }).then(function (journal) {
  47. self.accountJournal =journal;
  48. return self.fetchInvoiceP2();
  49. }).then(function (invoice){
  50. self.invoice = invoice;
  51. return self.fetchSupplier(invoice);
  52. }).then(function (supplier){
  53. self.supplier=supplier;
  54. return self.fetchPaymentTerm();
  55. }).then(function (paymentTerm){
  56. self.paymentTerm=paymentTerm;
  57. return self.fetchAttachment();
  58. }).then(function(attachment){
  59. self.attachment=attachment;
  60. return self.fecthComanyCurrency();
  61. }).then(function(resCompany){
  62. self.resCompany = resCompany;
  63. self.inicializarBuscadorsup();
  64. return self.fect_generar(self.invoice);
  65. }).then(function(currency){
  66. self.currency = currency;
  67. // return self.fect_cabecera(self.resCompany, self.newInvoice);
  68. });
  69. },
  70. // Buscar Diario
  71. fetchJournal: function () {
  72. var self = this;
  73. var defer = $.Deferred();
  74. var Journal = new instance.web.Model('account.journal');
  75. Journal.query(['id', 'name']).filter([['type', '=', ['purchase','purchase_refund']]]).all().then(function(results){
  76. defer.resolve(results);
  77. });
  78. return defer;
  79. },
  80. // Periodo
  81. fetchPeriod: function () {
  82. var defer = $.Deferred();
  83. var period = new instance.web.Model('account.period');
  84. var fields = ['id', 'name'];
  85. var domain = [['special', '!=', true]];
  86. period.query(fields).filter(domain).all().then(function (results) {
  87. defer.resolve(results);
  88. });
  89. return defer;
  90. },
  91. // Invoice (FACTURAS)
  92. fetchInvoiceP2: function () {
  93. var journal_ids = _.flatten(_.map(this.accountJournal, function (item) {
  94. return item.id;
  95. }));
  96. var filter =[['state', 'in',['open','paid']],['type', '=', ['in_invoice','in_refund']],['journal_id', 'in',journal_ids]];
  97. 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'];
  98. var defer = $.Deferred();
  99. var Invoice = new instance.web.Model('account.invoice');
  100. Invoice.query(field).filter(filter).all().then(function (results) {
  101. defer.resolve(results);
  102. });
  103. return defer;
  104. },
  105. // company_curency
  106. fecthComanyCurrency: function(){
  107. var self = this;
  108. var defer = $.Deferred();
  109. var currency = new instance.web.Model('res.company');
  110. var field=['id', 'currency_id','exportador','agent_ruc','legal_agent','company_ruc','name','juridico'];
  111. var domain=[['id','=',1]];
  112. currency.query(field).filter(domain).all().then(function(results){
  113. defer.resolve(results);
  114. });
  115. return defer;
  116. },
  117. // Partner (Proveeedor)
  118. fetchSupplier: function() {
  119. var self = this;
  120. var defer = $.Deferred();
  121. var supplier = new instance.web.Model('res.partner');
  122. supplier.query(['id', 'name', 'ruc', 'active', 'supplier']).filter([['active', '=', true], ['supplier', '=', true]]).all().then(function (results) {
  123. defer.resolve(results);
  124. });
  125. return defer;
  126. },
  127. // Archivos Adjuntos
  128. fetchAttachment: function() {
  129. var self = this;
  130. var defer = $.Deferred();
  131. var id = _.flatten(_.map(self.invoice,function(map){
  132. return id;
  133. }));
  134. var attachment = new instance.web.Model('ir.attachment');
  135. attachment.query(['id','res_id', 'datas', 'res_model','file_type','name']).filter([['res_model', '=','account.invoice']]).all().then(function (results) {
  136. defer.resolve(results);
  137. });
  138. return defer;
  139. },
  140. // Plazos de pagos
  141. fetchPaymentTerm: function () {
  142. var self = this;
  143. var defer = $.Deferred();
  144. var payment_term = _.flatten(_.map(self.invoice,function(map){
  145. return map.payment_term[0];
  146. }));
  147. var paymentTerm = new instance.web.Model('account.payment.term');
  148. paymentTerm.query(['id','name','line_ids']).filter([['id', '=', payment_term]]).all().then(function(results){
  149. defer.resolve(results);
  150. });
  151. return defer;
  152. },
  153. // Verificar si los Valores no son nulos
  154. valorNull:function(dato){
  155. var valor ="";
  156. if (dato){
  157. valor=dato;
  158. }
  159. return valor;
  160. },
  161. // Buscador
  162. inicializarBuscadorsup: function () {
  163. var self = this;
  164. var results = self.supplier;
  165. results = _.map(results, function (item) {
  166. return {
  167. label: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc),
  168. value: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc)
  169. }
  170. });
  171. self.$('#customer').autocomplete({
  172. source: results,
  173. minLength:0,
  174. search: function(event, ui) {
  175. if (!(self.$('#customer').val())){
  176. self.factSearch();
  177. }
  178. },
  179. close: function( event, ui ) {
  180. self.factSearch();
  181. },
  182. select: function(event, ui) {
  183. self.factSearch();
  184. }
  185. });
  186. },
  187. getSupplier : function(partner_id){
  188. var self = this;
  189. return _.filter(self.supplier,function(item){
  190. return item.id === partner_id;
  191. }).shift();
  192. },
  193. getPaymentTerm : function(id){
  194. var self = this;
  195. return _.filter(self.paymentTerm,function(item){
  196. return item.id === id;
  197. }).shift();
  198. },
  199. getAttachment : function(attachment_ids){
  200. var self = this;
  201. return _.filter(self.attachment,function(item){
  202. return item.id === attachment_ids;
  203. }).shift();
  204. },
  205. // Detalle del registro
  206. fect_generar: function(invoices){
  207. var self = this;
  208. var data = [];
  209. var supplier_ruc;
  210. var ruc;
  211. var cuota;
  212. var tipo;
  213. var tasa_10 = 0;
  214. var tasa_5 = 0;
  215. var iva_5 = 0;
  216. var iva_10 = 0;
  217. var IVA = 0;
  218. var TAX = 0;
  219. var adjunto;
  220. var untaxed;
  221. var condicion;
  222. var contador = 0;
  223. var icons = 0;
  224. var imagen;
  225. var img;
  226. _.each(invoices, function(invoice){
  227. // Obtener el ruc y el DV del proveedor
  228. supplier_ruc = self.getSupplier(invoice.partner_id[0]);
  229. ruc = supplier_ruc.ruc.split("-");
  230. // Determinar si la factura es a credito o al contado.
  231. condicion = 1;
  232. if (invoice.credito == true){
  233. condicion = 2;
  234. }
  235. // Determinar la cantidad de cuotas.
  236. cuota = _.flatten(self.getPaymentTerm(invoice.payment_term[0])).length - 2;
  237. // Validar. Si la factura es al contado, la cuota debe ser cero.
  238. if (condicion == 1 || cuota < 1){
  239. cuota = 0;
  240. }
  241. // Determinar el tipo de factura.
  242. if(invoice.type == 'in_invoice'){
  243. tipo = 1;
  244. }else{
  245. tipo = 2;
  246. }
  247. // Manejo de impuestos
  248. IVA = accounting.formatNumber(((invoice.amount_untaxed * 10)/100),"","");
  249. TAX = accounting.formatNumber(invoice.amount_tax,"","");
  250. untaxed = 0;
  251. iva_5 = 0;
  252. iva_10 = 0;
  253. tasa_10 = 0;
  254. tasa_5 = 0;
  255. // Determinar si fue aplicado algun impuesto a la factura.
  256. if(invoice.amount_total == invoice.amount_untaxed){
  257. untaxed = accounting.formatNumber(invoice.amount_untaxed,"","");
  258. }else{
  259. // Si fue aplicado impuesto, determina si fue de 10% o 5%.
  260. if(IVA == TAX){
  261. iva_10 = accounting.formatNumber(invoice.amount_tax,"","");;
  262. tasa_10 = accounting.formatNumber(invoice.amount_untaxed,"","");
  263. }else{
  264. iva_5 = accounting.formatNumber(invoice.amount_tax,"","");;
  265. tasa_5 = accounting.formatNumber(invoice.amount_untaxed,"","");
  266. }
  267. }
  268. // Obtener binario del archivo adjunto
  269. adjunto = self.getAttachment(invoice.attachment_ids[0]);
  270. imagen = _.flatten(adjunto);
  271. // Obtener el tipo de adjunto
  272. if(adjunto == undefined){
  273. icons = '<a class="" href="javascript:void(0)" title="Descarga no disponible"><i class="fa fa-file fa-lg" aria-hidden="true"></i></a>&nbsp;&nbsp;&nbsp;<a class="" href="javascript:void(0)" title="Vista previa no disponible"><i class="fa fa-eye-slash fa-lg" aria-hidden="true"></i></a>';
  274. }else{
  275. if(imagen[1]=='image/png' || imagen[1]=='image/jpeg'){
  276. icons = '<a class="download" href="javascript:void(0)" title="Descargar"><i class="fa fa-download fa-lg" aria-hidden="true"></i></a>&nbsp;&nbsp;&nbsp;<a class="preview" title="Vista previa"><i class="fa fa-eye fa-lg" aria-hidden="true"></i></a>';
  277. }else{
  278. icons = '<a class="download" href="javascript:void(0)" title="Descargar"><i class="fa fa-download fa-lg" aria-hidden="true"></i></a>&nbsp;&nbsp;&nbsp;<a class="" href="javascript:void(0)" title="Vista previa no disponible"><i class="fa fa-eye-slash fa-lg" aria-hidden="true"></i></a>';
  279. }
  280. }
  281. // Indice de la tabla
  282. contador += 1;
  283. // Crear el objeto que se muestra en la tabla
  284. data.push({
  285. linea: contador,
  286. tipo_registro: 2,
  287. ruc_proveedor: ruc[0],
  288. dv: ruc[1],
  289. partner : invoice.partner_id[1],
  290. supplier_invoice_number: self.valorNull(invoice.timbrado),
  291. tipo_documento : tipo,
  292. number: self.valorNull(invoice.supplier_invoice_number),
  293. date: moment(invoice.date_invoice).format("DD/MM/YYYY"),
  294. tasa_10 : tasa_10,
  295. iva_10 : iva_10,
  296. tasa_5 : tasa_5,
  297. iva_5 : iva_5,
  298. amount_untaxed: untaxed,
  299. tipo_operacion : 8,
  300. condicion_compra : condicion,
  301. cantidad_cuotas : cuota,
  302. period_id : invoice.period_id[0],
  303. period_name : invoice.period_id[1],
  304. attachment_ids : adjunto,
  305. download_icon : icons,
  306. });
  307. });
  308. self.newInvoice = data;
  309. this.loadTable(data);
  310. },
  311. // Informacion para el txt.
  312. fect_cabecera: function(resCompanys, invoices){
  313. var self = this;
  314. // Cabecera
  315. var datos = [];
  316. var company_ruc;
  317. var agent_ruc;
  318. var version = 2;
  319. var total = 0;
  320. var cantidad = 0;
  321. var valor = 0;
  322. var periodo;
  323. var ruc_agente = 0;
  324. var dv_agente = 0;
  325. var nombre_agente = 0;
  326. var period =this.$el.find('#current-period').val();
  327. _.each(resCompanys, function(resCompany){
  328. // Obtener el RUC y el DV de la compania
  329. company_ruc = resCompany.company_ruc.split("-");
  330. // Determinar si la persona es fisica o juridica
  331. if(resCompany.juridico == true){
  332. agent = resCompany.agent_ruc.split("-");
  333. ruc_agente = agent[0];
  334. dv_agente = agent[1];
  335. nombre_agente = resCompany.legal_agent;
  336. }
  337. // Tipo de registro
  338. datos.push(1);
  339. datos.push('\t');
  340. // Periodo
  341. datos.push(201708);
  342. // moment(periodo).format("YYYYMM")
  343. datos.push('\t');
  344. // Tipo de reporte
  345. datos.push(1);
  346. datos.push('\t');
  347. // Codigo Obligacion
  348. datos.push(911);
  349. datos.push('\t');
  350. // Codigo Formulario
  351. datos.push(211);
  352. datos.push('\t');
  353. // Ruc agente de informacion
  354. datos.push(company_ruc[0]);
  355. datos.push('\t');
  356. // DV agente de informacion
  357. datos.push(company_ruc[1]);
  358. datos.push('\t');
  359. // Nombre o denominacion del agente de informacion
  360. datos.push(resCompany.name);
  361. datos.push('\t');
  362. // Ruc representante legal
  363. datos.push(ruc_agente);
  364. datos.push('\t');
  365. // DV representante legal
  366. datos.push(dv_agente);
  367. datos.push('\t');
  368. // Nombre y apellido de representante legal
  369. datos.push(nombre_agente);
  370. datos.push('\t');
  371. // Cantidad de registros
  372. datos.push(50);
  373. datos.push('\t');
  374. // Monto total
  375. datos.push(2654122);
  376. datos.push('\t');
  377. // Exportador
  378. datos.push(resCompany.exportador);
  379. datos.push('\t');
  380. // Version
  381. datos.push(version);
  382. datos.push('\r\n');
  383. });
  384. // detalles
  385. _.each(invoices, function(newInvoice){
  386. if(newInvoice.period_id == period){
  387. // tipo de registro
  388. datos.push(newInvoice.tipo_registro);
  389. datos.push('\t');
  390. // ruc del proveedor
  391. datos.push(newInvoice.ruc_proveedor);
  392. datos.push('\t');
  393. // dv del proveedor
  394. datos.push(newInvoice.dv);
  395. datos.push('\t');
  396. // Nombre o denominacion del proveedor
  397. datos.push(newInvoice.partner);
  398. datos.push('\t');
  399. // Numero de timbrado
  400. datos.push(newInvoice.supplier_invoice_number);
  401. datos.push('\t');
  402. // Tipo de documento
  403. datos.push(newInvoice.tipo_documento);
  404. datos.push('\t');
  405. // Numero de documento
  406. datos.push(newInvoice.number);
  407. datos.push('\t');
  408. // Fecha de documento
  409. datos.push(newInvoice.date);
  410. datos.push('\t');
  411. // Monto de la compra a la tasa 10%
  412. datos.push(newInvoice.tasa_10);
  413. datos.push('\t');
  414. // IVA credito 10%
  415. datos.push(newInvoice.iva_10);
  416. datos.push('\t');
  417. // Monto de la compra a la tasa 5%
  418. datos.push(newInvoice.tasa_5);
  419. datos.push('\t');
  420. // IVA credito 5%
  421. datos.push(newInvoice.iva_5);
  422. datos.push('\t');
  423. // Monto de la compra no gravada o exenta
  424. datos.push(newInvoice.amount_untaxed);
  425. datos.push('\t');
  426. // Tipo de operacion
  427. datos.push(newInvoice.tipo_operacion);
  428. datos.push('\t');
  429. // Condicion de compra
  430. datos.push(newInvoice.condicion_compra);
  431. datos.push('\t');
  432. // Cantidad de cuotas
  433. datos.push(newInvoice.cantidad_cuotas);
  434. datos.push('\r\n');
  435. // Catidad de registros
  436. cantidad += 1;
  437. valor = parseInt(newInvoice.amount_untaxed) + parseInt(newInvoice.tasa_5) + parseInt(newInvoice.tasa_10);
  438. total += valor;
  439. periodo = newInvoice.period_name.split("/");
  440. }
  441. });
  442. datos.splice(2,0);
  443. datos[2] = periodo[1] + periodo[0];
  444. datos.splice(22,0);
  445. datos[22] = cantidad;
  446. datos.splice(24,0);
  447. datos[24] = accounting.formatNumber(total,"","");
  448. self.newCabecera = new Blob(datos, {type: 'text/plain'});
  449. },
  450. // Buscar
  451. factSearch: function(){
  452. var self = this;
  453. var period =this.$el.find('#current-period').val();
  454. var newInvoice = self.newInvoice;
  455. // Buscar por Periodo
  456. if (period != 9999999){
  457. newInvoice=_.filter(newInvoice, function (inv){
  458. return inv.period_id == period;
  459. });
  460. }
  461. self.loadTable(newInvoice)
  462. },
  463. // cargara la tabla
  464. loadTable:function(rowsTable){
  465. var self = this;
  466. self.rowsData = rowsTable;
  467. var table = this.$el.find('#table');
  468. table.bootstrapTable('load',rowsTable);
  469. },
  470. // Generar el txt con el nombre correspondiente
  471. generarTxt: function () {
  472. var self = this;
  473. var newInvoice = self.newInvoice;
  474. var period =this.$el.find('#current-period').val();
  475. if (period != 9999999){
  476. newInvoice=_.filter(newInvoice, function (inv){
  477. return inv.period_id == period;
  478. });
  479. if(newInvoice.length != 0){
  480. var periodo = newInvoice[0].period_name.split("/");
  481. var fileName = "Compras " + periodo[1] + periodo[0];
  482. self.fect_cabecera(self.resCompany, self.newInvoice);
  483. download(self.newCabecera, fileName, "text/plain");
  484. }else{
  485. self.showMensajeRegistro();
  486. }
  487. }else{
  488. self.showMensaje();
  489. }
  490. },
  491. // Descargar el archivo adjunto
  492. downloadAttachment: function (e) {
  493. var self = this;
  494. var newInvoice = self.newInvoice;
  495. var fila = $(e.target).closest('tr');
  496. var columnas = fila.children();
  497. var orden = parseInt(columnas[0].textContent);
  498. var dato = newInvoice[orden - 1].attachment_ids;
  499. download("data:"+dato.file_type+";base64,"+dato.datas+"",dato.name,dato.file_type);
  500. },
  501. // Vista previa del archivo
  502. previewAttachment: function (e) {
  503. var self = this;
  504. var newInvoice = self.newInvoice;
  505. var fila = $(e.target).closest('tr');
  506. var columnas = fila.children();
  507. var orden = parseInt(columnas[0].textContent);
  508. var dato = newInvoice[orden -1].attachment_ids;
  509. var img = 'data:'+dato.file_type+';base64,'+dato.datas;
  510. lightbox.option({
  511. 'showImageNumberLabel': false
  512. });
  513. $(".preview").attr("data-lightbox",dato.name);
  514. $(".preview").attr("href",img);
  515. },
  516. // Lanzar el mensaje de pediodo
  517. showMensaje : function(modelos){
  518. var self = this;
  519. $("#dialog" ).dialog({
  520. autoOpen: true,
  521. resizable: false,
  522. modal: true,
  523. title: 'Atención',
  524. width: 500,
  525. open: function() {
  526. $(this).html('Debe elegir un periodo');
  527. },
  528. show: {
  529. effect: "fade",
  530. duration: 200
  531. },
  532. hide: {
  533. effect: "fade",
  534. duration: 200
  535. },
  536. buttons: {
  537. Aceptar: function() {
  538. $(this).dialog('close');
  539. }
  540. }
  541. });
  542. return
  543. },
  544. // Lanzar mensaje de registros
  545. showMensajeRegistro : function(modelos){
  546. var self = this;
  547. $("#dialog" ).dialog({
  548. autoOpen: true,
  549. resizable: false,
  550. modal: true,
  551. title: 'Atención',
  552. width: 500,
  553. open: function() {
  554. $(this).html('No hay registros que exportar');
  555. },
  556. show: {
  557. effect: "fade",
  558. duration: 200
  559. },
  560. hide: {
  561. effect: "fade",
  562. duration: 200
  563. },
  564. buttons: {
  565. Aceptar: function() {
  566. $(this).dialog('close');
  567. }
  568. }
  569. });
  570. return
  571. },
  572. });
  573. }