Bläddra i källkod

[ADD] base64 encode reports

Gogs 6 år sedan
förälder
incheckning
4c7dfb5e2f
4 ändrade filer med 45 tillägg och 410 borttagningar
  1. 16 4
      controllers/main.py
  2. BIN
      files/sample.pdf
  3. 29 7
      static/src/js/main.js
  4. 0 399
      static/src/js/main.js.bkp

+ 16 - 4
controllers/main.py

@@ -1,13 +1,14 @@
 # -*- coding: utf-8 -*-
 from openerp import http
 from openerp.http import request
+from openerp.report import render_report
 from werkzeug.wrappers import Response
 from werkzeug.datastructures import Headers
-from werkzeug.utils import redirect
 from gzip import GzipFile
 from StringIO import StringIO as IO
 import json
 import logging
+import base64
 
 LOGGER = logging.getLogger(__name__)
 GZIP_COMPRESSION_LEVEL = 9
@@ -62,8 +63,19 @@ class PrintEngineController(http.Controller):
     '''
     @http.route('/print_engine/get_pdf', auth='user', type='json')
     def get_pdf(self, **kw):
-        import pdb; pdb.set_trace()
+        ctx = request.context
+
+        ir_action = request.env['ir.actions.report.xml'].browse(ctx.get('params').get('action'))
+        res_ids = request.env[ctx.get('active_model')].browse(ctx.get('active_ids'))
+
+        if ir_action.report_type in ['qweb-html', 'qweb-pdf']:
+            result, format = request.env['report'].get_pdf(res_ids, ir_action.report_name), 'pdf'
+        else:
+            # TODO: mejorar el renderización de reportes rml de la api v7 a v8
+            result, format = render_report(request._cr, request.uid, [res_ids.id], ir_action.report_name, {'model': ctx.get('active_model')}, ctx)
+
+        encoded_result = base64.b64encode(result)
 
         return {
-            'pdf_data': None
-        }
+            'data': 'data:application/%s;base64,%s' % (format, encoded_result)
+        }

BIN
files/sample.pdf


+ 29 - 7
static/src/js/main.js

@@ -18,6 +18,8 @@ openerp.print_engine = function (instance, local) {
                 self.socket.on('connect', self.handle_connect);
                 self.socket.on('connect_error', self.handle_connect_error);
                 self.socket.on('show-printers', self.handle_printers);
+                self.socket.on('print-error', self.handle_print_error);
+                self.socket.on('print-finished', self.handle_print_finished);
             }
 
             this.get_socket_config().then(set_socket);
@@ -33,6 +35,12 @@ openerp.print_engine = function (instance, local) {
         handle_printers: function (printers) {
             console.log(printers);
         },
+        handle_print_error: function () {
+            console.log('error');
+        },
+        handle_print_finished: function () {
+            console.log('finished');
+        },
         get_socket_config: function () {
             var url = '/print_engine/socket_config';
             return this.get_from_server(url);
@@ -48,6 +56,20 @@ openerp.print_engine = function (instance, local) {
                     d.reject.apply(d, arguments);
                 });
             });
+        },
+        request_print: function (b64_data) {
+            if (!this.socket || !this.socket.connected) {
+                instance.web.notification.do_warn('Impresión', 'La impresora no está preparada');
+                return;
+            }
+
+            try {
+                this.socket.emit('request-print', {
+                    data: b64_data
+                });
+            } catch (e) {
+                instance.webclient.crashmanager.show_message(e);
+            }
         }
     });
 
@@ -77,16 +99,16 @@ openerp.print_engine = function (instance, local) {
             instance.web.ActionManager.include({
                 ir_actions_report_xml: function (action, options) {
                     var url = '/print_engine/get_pdf';
+                    var ctx = _.clone(action.context);
+
+                    ctx.report_name = action.report_name;
 
                     instance.web.jsonRpc(url, 'call', {
-                        model: action.model,
-                        report_name: action.report_name,
-                        ids: action.id,
-                        context: action.context
-                    }).done(function (data) {
-                        console.log(data);
+                        context: ctx
+                    }).done(function (result) {
+                        instance.print_engine.socket.request_print(result.data);
                     }).fail(function (e) {
-                        console.log(e);
+                        instance.webclient.crashmanager.show_message(e);
                     });
                 }
             });

+ 0 - 399
static/src/js/main.js.bkp

@@ -1,399 +0,0 @@
-
-(function () {
-    var instance = openerp
-    openerp.print_engine = {}
-
-    String.prototype.add = function (string) {
-        return this.concat(string);
-    }
-
-    String.prototype.center = function (width, padding) {
-        padding = padding || '';
-        padding = padding.substr(0, 1);
-
-        if (this.length < width) {
-            var length = width - this.length;
-            var remain = (length % 2 == 0) ? '' : padding;
-            var pads = padding.repeat(parseInt(length / 2));
-
-            return pads + this + pads + remain;
-        } else {
-            return this;
-        }
-    }
-
-    String.prototype.lineFeed = function () {
-        return this + '\n';
-    }
-    
-    /**
-     * 
-     */
-    instance.print_engine.SocketManager = instance.web.Class.extend({
-        init: function () {
-            this.socket = null;
-            this.state = 'offline';
-            this.attemps = 0;
-
-            this.start();
-        },
-        start: function () {
-            var self = this;
-            this.getSockets().then(function () {
-                self.connect();
-            });
-        },
-        getSockets: function () {
-            var defer = $.Deferred();
-            var self = this;
-
-            $.get('/print_engine/sockets').done(function (data) {
-                self.sockets = data.sockets;
-                defer.resolve(data.sockets);
-            }).fail(function (error){
-                defer.reject(error);
-            });
-
-            return defer;
-        },
-        urlize: function (info) {
-            return info.protocol + '://' + info.host + ':' + info.port + info.path;
-        },
-        connect: function () {
-            if (this.sockets.length === 0) {
-                return
-            }
-
-            var self = this;
-            var url = this.urlize(this.sockets[0]);
-
-            if (this.socket) {
-                this.socket = null;
-            }
-            
-            try {
-                this.socket = new WebSocket(url);
-
-                this.socket.onopen = function (e) {
-                    self.handleOpen(e);
-                };
-                this.socket.onclose = function (e) {
-                    self.handleClose(e);
-                };
-                this.socket.onerror = function (e) {
-                    self.handleError(e);
-                };
-                this.socket.onmessage = function (e) {
-                    self.handleMessage(e);
-                };
-            } catch(e) {
-                // Ignore this error
-            }
-        },
-        reconnect: function () {
-            this.state = 'reconnecting';
-
-            $('#printer-status').removeClass();
-            $('#printer-status').addClass('printer-status-reconnect');
-
-            var self = this;
-
-            if (this.attemps === 3) {
-                this.state = 'offline';
-
-                $('#printer-status').removeClass();
-                $('#printer-status').addClass('printer-status-offline');
-
-                return;
-            }
-
-            setTimeout(function () {
-                self.connect();
-
-                self.attemps = self.attemps + 1;
-            }, 3000);
-        },
-        handleOpen: function (e) {
-            this.state = 'online';
-
-            $('#printer-status').removeClass();
-            $('#printer-status').addClass('printer-status-online');
-        },
-        handleClose: function (e) {
-            this.reconnect();
-        },
-        handleMessage: function (e) {
-            var obj = JSON.parse(e.data);
-
-            if (obj.printers) {
-                this.sendToServer('/print_engine/update', e.data).then(function () {
-                    instance.client.action_manager.inner_widget.views['form'].controller.reload();
-                    instance.web.notification.do_notify('Información', 'Impresoras actualizadas con éxito');
-                });
-            }
-        },
-        handleError: function (e) {
-            // Ignore this error
-        },
-        sendToSocket: function (data) {
-            if (this.state !== 'online') {
-                return;
-            }
-
-            if (!data) {
-                return;
-            }
-
-            this.socket.send(JSON.stringify(data));
-        },
-        sendToServer: function (url, data) {
-            var defer = $.Deferred();
-
-            var json = {
-                jsonrpc: '2.0',
-                method: 'call',
-                params: {
-                    data: data
-                }
-            }
-
-            $.ajax({
-                type: 'POST',
-                url: url,
-                dataType: 'json',
-                data: JSON.stringify(json),
-                beforeSend: function(xhr) {
-                    xhr.setRequestHeader('Content-Type', 'application/json');
-                },
-                success: function (ok) {
-                    defer.resolve(ok);
-                },
-            });
-
-            return defer;
-        },
-        discoveryPrinters: function () {
-            var commands = {
-                action: 'list'
-            }
-
-            this.sendToSocket(commands);
-        },
-        print(printer, data) {
-            if (this.state !== 'online') {
-                instance.web.notification.do_warn('Atención', 'La impresora está fuera de servicio');
-                return;
-            }
-
-            if (!printer) {
-                instance.web.notification.do_warn('Atención', 'La impresora no se encuentra');
-                return;
-            }
-
-            if (!data) {
-                instance.web.notification.do_warn('Atención', 'No se encuentran datos para imprimir');
-                return;
-            }
-
-            var commands = {
-                action: 'print',
-                printer: printer,
-                data: data
-            }
-
-            this.sendToSocket(commands)
-        },
-        printTicket(company, city, street, state, phone, website, datetime, symbol, items, total, received, customer, ruc, cashier, ref) {
-            if (this.sockets.length == 0) {
-                instance.web.notification.do_warn('Atención', 'No se encuentran sockets definidos');
-                return;
-            }
-
-            if (this.sockets[0].printers.length == 0) {
-                instance.web.notification.do_warn('Atención', 'No se encuentran impresoras definidas');
-                return;
-            }
-
-            var printer = null;
-            for (var j = 0; j < this.sockets[0].printers.length; j++) {
-                if (this.sockets[0].printers[j].isDefault) {
-                    printer = this.sockets[0].printers[j];
-                    break;
-                }
-            }
-
-            if (!printer) {
-                instance.web.notification.do_warn('Atención', 'No hay ninguna impresora por defecto');
-                return;
-            }
-
-            company = company || 'SIN NOMBRE';
-            var buffer = '';
-            buffer = buffer.add(company.center(40, ' ').toUpperCase()).lineFeed();
-            
-            if (city) {
-                buffer = buffer.add(city.center(40, ' ')).lineFeed();
-            }
-
-            if (street) {
-                buffer = buffer.add(street.center(40, ' ')).lineFeed();
-            }
-
-            if (state) {
-                buffer = buffer.add(state.center(40, ' ')).lineFeed();
-            }
-
-            if (phone) {
-                buffer = buffer.add(phone.center(40, ' ')).lineFeed();
-            }
-
-            if (website) {
-                buffer = buffer.add(website.center(40, ' ')).lineFeed()
-            }
-
-            buffer = buffer.lineFeed().lineFeed();
-            buffer = buffer.add('TICKET DE VENTA'.center(40, ' '));
-            buffer = buffer.lineFeed();
-
-            if (datetime) {
-                buffer = buffer.add(('Fecha: ' + datetime).center(40, ' ')).lineFeed().lineFeed();
-            }
-
-            symbol = symbol || '$';
-            ruc = ruc || '';
-            cashier = cashier || '';
-            ref = ref || '';
-
-            buffer = buffer.add('-'.center(40, '-')).lineFeed();
-            buffer = buffer.add('DESCRIPCION').lineFeed();
-            buffer = buffer.add('PRECIO        CANTIDAD        SUBTOTAL').lineFeed();
-            buffer = buffer.add('-'.center(40, '-')).lineFeed();
-
-            if (!!items && items.length > 0) {
-                for (var i = 0; i < items.length; i++) {
-                    buffer = buffer.add(items[i][0].toUpperCase()).lineFeed();
-                    buffer = buffer.add(items[i][1] + '\t' + items[i][2] + '\t' + items[i][3]).lineFeed();
-                }
-            }
-
-            buffer = buffer.add('-'.center(40, '-')).lineFeed();
-
-            buffer = buffer.add('TOTAL    (' + symbol + '):   ' + total).lineFeed();
-            buffer = buffer.add('RECIBIDO (' + symbol + '):   ' + received).lineFeed();
-            buffer = buffer.add('VUELTO   (' + symbol + '):   ' + (received - total)).lineFeed();
-
-            buffer = buffer.add('-'.center(40, '-')).lineFeed();
-
-            buffer = buffer.add('CLIENTE:   ' + customer).lineFeed();
-            buffer = buffer.add('RUC    :   ' + ruc).lineFeed().lineFeed();
-
-            buffer = buffer.add('-'.center(40, '-')).lineFeed();
-            buffer = buffer.add('ATENDIDO POR:   ' + cashier).lineFeed();
-            buffer = buffer.add('REFERENCIA  :   ' + ref).lineFeed().lineFeed();
-
-            buffer = buffer.add('GRACIAS POR SU PREFERENCIA!!!'.center(40, ' ')).lineFeed().lineFeed()
-
-            buffer = buffer.add('Diseñado por Eiru Software'.center(40, ' ')).lineFeed();
-            buffer = buffer.add('www.eiru.com.py'.center(40, ' ')).lineFeed().lineFeed().lineFeed().lineFeed().lineFeed().lineFeed()
-
-            this.print(printer.name, buffer);
-        }
-    });
-
-    /**
-     * 
-     */
-    instance.print_engine.PrinterTopWidget = instance.web.Widget.extend({
-        template: 'printEngine.PrinterTopWidget',
-        init: function (parent) {
-            this._super(parent)
-        },
-        start: function () {
-            this.$el.click(this, this.selectDefaultPrinter);
-        },
-        selectDefaultPrinter: function (e) {
-            e.preventDefault();
-            var self = e.data;
-
-            instance.client.action_manager.do_action({
-                context: self.session.user_context,
-                name: 'Impresora por defecto',
-                type: 'ir.actions.act_window',
-                res_model: 'print.engine.printer',
-                views: [[false, 'list'], [false, 'form']],
-                domain : [['socket_id.user_id', '=', self.session.user_context.uid]],
-                target: 'new',
-                flags: {
-                    action_buttons: true
-                }
-            })
-        }
-    })
-
-    /**
-     * 
-     * 
-     */
-    instance.print_engine.ping = function () {
-        if (!instance.print_engine.socket_manager) {
-            return;
-        }
-
-        instance.web.notification.do_notify('Información', 'Pong')
-    }
-    
-    /**
-     * 
-     */
-    instance.print_engine.discovery_printers = function (element, action) {
-        if (!instance.print_engine.socket_manager) {
-            return;
-        }
-
-        if(!confirm('Ésta acción quitará la impresora por defecto')) {
-            return;
-        }
-
-        instance.print_engine.socket_manager.discoveryPrinters();
-    }
-    
-    /**
-     * 
-     */
-    instance.print_engine.test_printer = function (element, action) {
-        if (!instance.print_engine.socket_manager) {
-            return;
-        }
-
-        instance.print_engine.socket_manager.test();
-    }
-
-    /**
-     * 
-     */
-    instance.print_engine.print = function (element, action) {
-        if (!instance.print_engine.socket_manager) {
-            return;
-        }
-
-        instance.print_engine.socket_manager.print();
-    }
-
-    instance.web.client_actions.add('print_engine.ping', 'instance.print_engine.ping')
-    instance.web.client_actions.add('print_engine.discovery_printers', 'instance.print_engine.discovery_printers')
-    instance.web.client_actions.add('print_engine.test_printer', 'instance.print_engine.test_printer')
-
-
-    if (instance.web && instance.web.UserMenu) {
-        instance.web.UserMenu.include({
-            do_update: function(){
-                var printer = new openerp.print_engine.PrinterTopWidget(this);
-                printer.appendTo($('.oe_systray'));
-
-                instance.print_engine.socket_manager = new instance.print_engine.SocketManager()
-
-                return this._super.apply(this, arguments);
-            }
-        });
-    }
-})()