Browse Source

ADD[Descargar Archivos]

Rodney Enciso Arias 7 years ago
parent
commit
1ec626239f

+ 4 - 0
static/src/css/eiru_reporting.css

@@ -76,3 +76,7 @@
 .sucursal{
     font-weight: bold;
 }
+#txt{
+    height: 35px; 
+    font-size: 15px;
+}

+ 162 - 0
static/src/js/download.js

@@ -0,0 +1,162 @@
+//download.js v4.2, by dandavis; 2008-2016. [CCBY2] see http://danml.com/download.html for tests/usage
+// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
+// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
+// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
+// v4 adds AMD/UMD, commonJS, and plain browser support
+// v4.1 adds url download capability via solo URL argument (same domain/CORS only)
+// v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
+// https://github.com/rndme/download
+
+(function (root, factory) {
+	if (typeof define === 'function' && define.amd) {
+		// AMD. Register as an anonymous module.
+		define([], factory);
+	} else if (typeof exports === 'object') {
+		// Node. Does not work with strict CommonJS, but
+		// only CommonJS-like environments that support module.exports,
+		// like Node.
+		module.exports = factory();
+	} else {
+		// Browser globals (root is window)
+		root.download = factory();
+  }
+}(this, function () {
+
+	return function download(data, strFileName, strMimeType) {
+
+		var self = window, // this script is only for browsers anyway...
+			defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
+			mimeType = strMimeType || defaultMime,
+			payload = data,
+			url = !strFileName && !strMimeType && payload,
+			anchor = document.createElement("a"),
+			toString = function(a){return String(a);},
+			myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
+			fileName = strFileName || "download",
+			blob,
+			reader;
+			myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
+	  
+		if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
+			payload=[payload, mimeType];
+			mimeType=payload[0];
+			payload=payload[1];
+		}
+
+
+		if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
+			fileName = url.split("/").pop().split("?")[0];
+			anchor.href = url; // assign href prop to temp anchor
+		  	if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
+        		var ajax=new XMLHttpRequest();
+        		ajax.open( "GET", url, true);
+        		ajax.responseType = 'blob';
+        		ajax.onload= function(e){ 
+				  download(e.target.response, fileName, defaultMime);
+				};
+        		setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
+			    return ajax;
+			} // end if valid url?
+		} // end if url?
+
+
+		//go ahead and download dataURLs right away
+		if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
+		
+			if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
+				payload=dataUrlToBlob(payload);
+				mimeType=payload.type || defaultMime;
+			}else{			
+				return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
+					navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
+					saver(payload) ; // everyone else can save dataURLs un-processed
+			}
+			
+		}//end if dataURL passed?
+
+		blob = payload instanceof myBlob ?
+			payload :
+			new myBlob([payload], {type: mimeType}) ;
+
+
+		function dataUrlToBlob(strUrl) {
+			var parts= strUrl.split(/[:;,]/),
+			type= parts[1],
+			decoder= parts[2] == "base64" ? atob : decodeURIComponent,
+			binData= decoder( parts.pop() ),
+			mx= binData.length,
+			i= 0,
+			uiArr= new Uint8Array(mx);
+
+			for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
+
+			return new myBlob([uiArr], {type: type});
+		 }
+
+		function saver(url, winMode){
+
+			if ('download' in anchor) { //html5 A[download]
+				anchor.href = url;
+				anchor.setAttribute("download", fileName);
+				anchor.className = "download-js-link";
+				anchor.innerHTML = "downloading...";
+				anchor.style.display = "none";
+				document.body.appendChild(anchor);
+				setTimeout(function() {
+					anchor.click();
+					document.body.removeChild(anchor);
+					if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
+				}, 66);
+				return true;
+			}
+
+			// handle non-a[download] safari as best we can:
+			if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
+				url=url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
+				if(!window.open(url)){ // popup blocked, offer direct download:
+					if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
+				}
+				return true;
+			}
+
+			//do iframe dataURL download (old ch+FF):
+			var f = document.createElement("iframe");
+			document.body.appendChild(f);
+
+			if(!winMode){ // force a mime that will download:
+				url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
+			}
+			f.src=url;
+			setTimeout(function(){ document.body.removeChild(f); }, 333);
+
+		}//end saver
+
+
+
+
+		if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
+			return navigator.msSaveBlob(blob, fileName);
+		}
+
+		if(self.URL){ // simple fast and modern way using Blob and URL:
+			saver(self.URL.createObjectURL(blob), true);
+		}else{
+			// handle non-Blob()+non-URL browsers:
+			if(typeof blob === "string" || blob.constructor===toString ){
+				try{
+					return saver( "data:" +  mimeType   + ";base64,"  +  self.btoa(blob)  );
+				}catch(y){
+					return saver( "data:" +  mimeType   + "," + encodeURIComponent(blob)  );
+				}
+			}
+
+			// Blob but not URL support:
+			reader=new FileReader();
+			reader.onload=function(e){
+				saver(this.result);
+			};
+			reader.readAsDataURL(blob);
+		}
+		return true;
+	}; /* end download() */
+}));

+ 79 - 28
static/src/js/reports/report_purchases.js

@@ -16,7 +16,9 @@ function report_purchases (reporting){
         rowsData :[],
         events:{
             'change #current-period' : 'factSearch',
-            'click  #txt' : 'generarTxt',
+            'click #txt' : 'generarTxt',
+            'click .download' : 'downloadAttachment',
+            'click .preview' : 'previewAttachment'
         },
         // Init
         init : function(parent){
@@ -26,7 +28,9 @@ function report_purchases (reporting){
         start: function () {
             var self = this;
             var table = this.$el.find('#table');
-            table.bootstrapTable({data : self.rowsData});
+            table.bootstrapTable(
+                {data : self.rowsData}
+                );
             this.submitForm();
         },
         // Consultar
@@ -133,7 +137,7 @@ function report_purchases (reporting){
                 return id;
             }));
             var attachment = new instance.web.Model('ir.attachment');
-            attachment.query(['id','res_id', 'datas', 'res_model']).filter([['res_model', '=','account.invoice']]).all().then(function (results) {
+            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;
@@ -205,14 +209,20 @@ function report_purchases (reporting){
 
         getAttachment : function(attachment_ids){
             var self = this;
-            return _.map(_.filter(self.attachment,function(item){
+            return _.filter(self.attachment,function(item){
                 return item.id === attachment_ids;
-            }),function(map){
-                return map.datas;
-            });
+            }).shift();
         },
+        // getAttachment : function(attachment_ids){
+        //     var self = this;
+        //     return _.map(_.filter(self.attachment,function(item){
+        //         return item.id === attachment_ids;
+        //     }),function(map){
+        //         return map.datas;
+        //     });
+        // },
 
-        // Cuerpo del registro
+        // Detalle del registro
         fect_generar: function(invoices){
             var self = this;
             var data = [];
@@ -229,6 +239,8 @@ function report_purchases (reporting){
             var adjunto;
             var untaxed;
             var condicion;
+            var contador = 0;
+            var icons = 0;
 
             _.each(invoices, function(invoice){
                 // Obtener el ruc y el DV del proveedor
@@ -282,8 +294,15 @@ function report_purchases (reporting){
 
                 // Obtener binario del archivo adjunto
                 adjunto = self.getAttachment(invoice.attachment_ids[0]);
+                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>&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>';
+                }else{
+                    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" href="javascript:void(0)" title="Vista previa"><i class="fa fa-eye fa-lg" aria-hidden="true"></i></a>';
+                }
+                contador += 1;
                 
                 data.push({
+                    linea: contador,
                     tipo_registro: 2,
                     ruc_proveedor: ruc[0], 
                     dv: ruc[1],
@@ -302,7 +321,8 @@ function report_purchases (reporting){
                     cantidad_cuotas : cuota,
                     period_id : invoice.period_id[0],
                     period_name : invoice.period_id[1],
-                    // attachment_ids : adjunto,
+                    attachment_ids : adjunto,
+                    download_icon : icons,
                 });
             });
             self.newInvoice = data;
@@ -492,30 +512,61 @@ function report_purchases (reporting){
             table.bootstrapTable('load',rowsTable);
         },
 
-        descargarArchivo: function(contenidoEnBlob, nombreArchivo) {
-            var self = this;
-            var reader = new FileReader();
-            reader.onload = function (event) {
-                var save = document.createElement('a');
-                save.href = event.target.result;
-                save.target = '_blank';
-                save.download = nombreArchivo || 'archivo.dat';
-                var clicEvent = new MouseEvent('click', {
-                    'view': window,
-                    'bubbles': true,
-                    'cancelable': true
-                });
-                save.dispatchEvent(clicEvent);
-                (window.URL || window.webkitURL).revokeObjectURL(save.href);
-            };
-            reader.readAsDataURL(contenidoEnBlob);
-        },
+        // descargarArchivo: function(contenidoEnBlob, nombreArchivo) {
+        //     var self = this;
+        //     var reader = new FileReader();
+        //     reader.onload = function (event) {
+        //         var save = document.createElement('a');
+        //         save.href = event.target.result;
+        //         save.target = '_blank';
+        //         save.download = nombreArchivo || 'archivo.dat';
+        //         var clicEvent = new MouseEvent('click', {
+        //             'view': window,
+        //             'bubbles': true,
+        //             'cancelable': true
+        //         });
+        //         save.dispatchEvent(clicEvent);
+        //         (window.URL || window.webkitURL).revokeObjectURL(save.href);
+        //     };
+        //     reader.readAsDataURL(contenidoEnBlob);
+        // },
 
         generarTxt: function () {
             var self = this;
             var periodo = self.newInvoice[0].period_name.split("/");
             var fileName = "Compras " + periodo[1] + periodo[0];
-            self.descargarArchivo(self.newCabecera, fileName);
+            // self.descargarArchivo(self.newCabecera, fileName);
+            download(self.newCabecera, fileName, "text/plain");
+        },
+
+        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;
+            
+            if(dato.file_type == 'image/png'){
+                download("data:image/png;base64,"+ dato.datas +" ",dato.name,"image/png");    
+            }
+            if(dato.file_type == 'application/pdf'){
+                download("data:application/pdf;base64,"+ dato.datas +" ",dato.name,"application/pdf");       
+            }
+            if(dato.file_type == 'application/vnd.ms-excel'){
+                download("data:application/vnd.ms-excel;base64,"+ dato.datas +" ",dato.name,"application/vnd.ms-excel");       
+            }
+            if(dato.file_type == 'application/msword'){
+                download("data:application/msword;base64,"+ dato.datas +" ",dato.name,"application/msword");       
+            }
+            if(dato.file_type == 'image/jpeg'){
+                download("data:image/jpeg;base64,"+ dato.datas +" ",dato.name,"image/jpeg");       
+            }
+        },
+
+        previewAttachment: function () {
+            var self = this;
+            console.log('Previsualizar Adjunto');
         },
     });
 }

+ 78 - 24
static/src/js/reports/report_sales.js

@@ -17,6 +17,8 @@ function report_sales (reporting){
         events:{
             'change #current-period' : 'factSearch',
             'click  #txt' : 'generarTxt',
+            'click .download' : 'downloadAttachment',
+            'click .preview' : 'previewAttachment'
         },
         // Initil
         init : function(parent){
@@ -132,7 +134,7 @@ function report_sales (reporting){
                 return id;
             }));
             var attachment = new instance.web.Model('ir.attachment');
-            attachment.query(['id','res_id', 'datas', 'res_model']).filter([['res_model', '=','account.invoice']]).all().then(function (results) {
+            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;
@@ -203,12 +205,18 @@ function report_sales (reporting){
 
         getAttachment : function(attachment_ids){
             var self = this;
-            return _.map(_.filter(self.attachment,function(item){
+            return _.filter(self.attachment,function(item){
                 return item.id === attachment_ids;
-            }),function(map){
-                return map.datas;
-            });
+            }).shift();
         },
+        // getAttachment : function(attachment_ids){
+        //     var self = this;
+        //     return _.map(_.filter(self.attachment,function(item){
+        //         return item.id === attachment_ids;
+        //     }),function(map){
+        //         return map.datas;
+        //     });
+        // },
 
         // unir los objetos
         fect_generar: function(invoices){
@@ -227,7 +235,11 @@ function report_sales (reporting){
             var condicion;
             var IVA;
             var TAX;
+            var adjunto;
             var untaxed;
+            var contador = 0;
+            var icons = 0;
+
             _.each(invoices, function(invoice){
                 // obtener el ruc y el DV del cliente
                 customer_ruc = self.getCustomer(invoice.partner_id[0]);
@@ -273,7 +285,16 @@ function report_sales (reporting){
                 total = 0;
                 total = parseInt(tasa_10) + parseInt(iva_10) + parseInt(tasa_5) + parseInt(iva_5) + parseInt(untaxed);
                 
+                adjunto = self.getAttachment(invoice.attachment_ids[0]);
+                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>&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>';
+                }else{
+                    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" href="javascript:void(0)" title="Vista previa"><i class="fa fa-eye fa-lg" aria-hidden="true"></i></a>';
+                }
+                contador += 1;
+
                 data.push({
+                    linea: contador,
                     tipo_registro: 2,
                     ruc_cliente: ruc[0],
                     dv: ruc[1],
@@ -293,6 +314,8 @@ function report_sales (reporting){
                     // informacion del periodo
                     period_id : invoice.period_id[0],
                     period_name : invoice.period_id[1],
+                    attachment_ids : adjunto,
+                    download_icon : icons,
                 });
                 
             });
@@ -503,31 +526,62 @@ function report_sales (reporting){
         },
         
         // Descarga el archivo en formato txt
-        descargarArchivo: function(contenidoEnBlob, nombreArchivo) {
-            var self = this;
-            var reader = new FileReader();
-            reader.onload = function (event) {
-                var save = document.createElement('a');
-                save.href = event.target.result;
-                save.target = '_blank';
-                save.download = nombreArchivo || 'archivo.dat';
-                var clicEvent = new MouseEvent('click', {
-                    'view': window,
-                    'bubbles': true,
-                    'cancelable': true
-                });
-                save.dispatchEvent(clicEvent);
-                (window.URL || window.webkitURL).revokeObjectURL(save.href);
-            };
-            reader.readAsDataURL(contenidoEnBlob);
-        },
+        // descargarArchivo: function(contenidoEnBlob, nombreArchivo) {
+        //     var self = this;
+        //     var reader = new FileReader();
+        //     reader.onload = function (event) {
+        //         var save = document.createElement('a');
+        //         save.href = event.target.result;
+        //         save.target = '_blank';
+        //         save.download = nombreArchivo || 'archivo.dat';
+        //         var clicEvent = new MouseEvent('click', {
+        //             'view': window,
+        //             'bubbles': true,
+        //             'cancelable': true
+        //         });
+        //         save.dispatchEvent(clicEvent);
+        //         (window.URL || window.webkitURL).revokeObjectURL(save.href);
+        //     };
+        //     reader.readAsDataURL(contenidoEnBlob);
+        // },
 
         // Genera el archivo txt, con el nombre correspondiente
         generarTxt: function () {
             var self = this;
             var periodo = self.newInvoice[0].period_name.split("/");
             var fileName = "Ventas " + periodo[1] + periodo[0];
-            self.descargarArchivo(self.newCabecera, fileName);
+            // self.descargarArchivo(self.newCabecera, fileName);
+            download(self.newCabecera, fileName, "text/plain");
+        },
+        // 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;
+            
+            if(dato.file_type == 'image/png'){
+                download("data:image/png;base64,"+ dato.datas +" ",dato.name,"image/png");    
+            }
+            if(dato.file_type == 'application/pdf'){
+                download("data:application/pdf;base64,"+ dato.datas +" ",dato.name,"application/pdf");       
+            }
+            if(dato.file_type == 'application/vnd.ms-excel'){
+                download("data:application/vnd.ms-excel;base64,"+ dato.datas +" ",dato.name,"application/vnd.ms-excel");       
+            }
+            if(dato.file_type == 'application/msword'){
+                download("data:application/msword;base64,"+ dato.datas +" ",dato.name,"application/msword");       
+            }
+            if(dato.file_type == 'image/jpeg'){
+                download("data:image/jpeg;base64,"+ dato.datas +" ",dato.name,"image/jpeg");       
+            }
+        },
+        // Vista previa del archivo adjunto 
+        previewAttachment: function () {
+            var self = this;
+            console.log('Previsualizar Adjunto');
         },
     });
 }

+ 4 - 4
static/src/reports/report_purchases.xml

@@ -3,7 +3,7 @@
     <t t-name="ReportPurchases">
         <div class="report_view">
             <div class="reporting_page_header">
-                <h1>Tributación de compras</h1>
+                <h1>Tributación de Compras</h1>
             </div>
             <div class="row">
                 <div class="col-md-6 col-md-offset-3">
@@ -16,7 +16,7 @@
                         </tr>
                         <tr>
                             <th>
-                                <button class="oe_button oe_form_button oe_highlight btn-block txt" value="txt" id="txt">Exportar a txt</button>
+                                <button class="oe_button oe_form_button oe_highlight btn btn-block btn-lg" value="txt" id="txt">Exportar <i class="fa fa-file-text fa-lg"></i></button>   
                             </th>
                         </tr>
                     </table> 
@@ -27,7 +27,6 @@
                 data-toggle="table"
                 data-reorderable-columns="true"
                 data-toolbar="#toolbar"
-                data-show-columns="true"
                 data-buttons-class="oe_button oe_form_button oe_highlight"
                 data-height="auto"
                 data-classes="table table-hover table-condensed table-bordered"
@@ -35,6 +34,7 @@
                 data-search="true">
                 <thead>
                     <tr>
+                        <th data-field="linea">#</th>
                         <th data-field="tipo_registro">Tipo de registro</th>
                         <th data-field="ruc_proveedor">Ruc Proveedor</th>
                         <th data-field="dv">DV Proveedor</th>
@@ -51,7 +51,7 @@
                         <th data-field="tipo_operacion">Tipo de operación</th>
                         <th data-field="condicion_compra">Condición de Compra</th>
                         <th data-field="cantidad_cuotas">Cantidad de Cuotas</th>
-                        <th data-field="attachment_ids">Adjuntos</th>
+                        <th data-field="download_icon" data-align="center">Documentos</th>
                     </tr>
                 </thead>
             </table>

+ 2 - 2
static/src/reports/report_sales.xml

@@ -28,7 +28,6 @@
                 data-toggle="table"
                 data-reorderable-columns="true"
                 data-toolbar="#toolbar"
-                data-show-columns="true"
                 data-buttons-class="oe_button oe_form_button oe_highlight"
                 data-height="auto"
                 data-classes="table table-hover table-condensed table-bordered"
@@ -36,6 +35,7 @@
                 data-search="true">
                 <thead>
                     <tr>
+                        <th data-field="linea">#</th>
                         <th data-field="tipo_registro" >Tipo de Registro</th>
                         <th data-field="ruc_cliente" >RUC Cliente</th>
                         <th data-field="dv">DV Cliente</th>
@@ -52,7 +52,7 @@
                         <th data-field="condicion_venta">Condición de Venta</th>
                         <th data-field="cantidad_cuotas">Cantidad de Cuotas</th>
                         <th data-field="number">Número de Timbrado</th>
-                        <th data-field="attachment_ids">Adjuntos</th>
+                        <th data-field="download_icon" data-align="center">Documentos</th>
                     </tr>
                 </thead>
             </table>

+ 1 - 0
templates.xml

@@ -10,6 +10,7 @@
                 <script type="text/javascript" src="/eiru_set/static/src/js/main.js" />
                 <script type="text/javascript" src="/eiru_set/static/src/js/reporting_base.js" />
                 <script type="text/javascript" src="/eiru_set/static/src/js/configuration_reporting.js" />
+                <script type="text/javascript" src="/eiru_set/static/src/js/download.js" />
 
                 <!-- Reportes -->
                 <script type="text/javascript" src="/eiru_set/static/src/js/reports/report_purchases.js" />