Browse Source

[FIX] socket engine

Gogs 6 năm trước cách đây
mục cha
commit
0ebe500e60

+ 5 - 3
__openerp__.py

@@ -7,9 +7,11 @@
     'depends': ['base', 'web'],
     'data': [
         'templates.xml',
-        'views/print_engine_sockets.xml',
-        'views/print_engine_printers.xml',
+        'views/print_engine_printer_view.xml',
+        'views/res_config_view.xml',
         'security/printers_group.xml'
     ],
-    'qweb': ['static/src/xml/*.xml'],
+    'qweb': [
+        'static/src/xml/*.xml'
+    ]
 }

+ 19 - 30
controllers/main.py

@@ -39,42 +39,31 @@ class PrintEngineController(http.Controller):
  
     '''
     '''
-    @http.route('/print_engine/update', auth='user', type='json', methods=['POST'], cors='*')
+    @http.route('/print_engine/update_printers', auth='user', type='json', methods=['POST'], cors='*')
     def printers_update(self, **kw):
-        printer_obj = request.env['print.engine.printer']
-
-        for printer in request.env.user.socket_ids.printer_ids:
-            printer.unlink()
-
-        for printer_name in json.loads(kw.get('data'))['printers']:
-            printer_obj.create({
-                'name': printer_name,
-                'socket_id': request.env.user.socket_ids.id
-            })
 
+        import pdb; pdb.set_trace()
         return True
 
     '''
     '''
-    def get_sockets(self):
-        socket_obj = request.env['print.engine.socket']
-
-        return [{
-            'protocol': socket.protocol,
-            'host': socket.host,
-            'port': socket.port,
-            'path': socket.path,
-            'printers': [{
-                'name': printer.name,
-                'isDefault': printer.is_default
-            } for printer in socket.printer_ids]
-        } for socket in socket_obj.search([('active', '=', True)])]
+    @http.route('/print_engine/socket_config', auth='user', type='json')
+    def socket_config(self, **kw):
+        settings_obj = request.env['print.engine.settings']
+        settings = settings_obj.search([])
+        
+        return {
+            'host': settings.host or None,
+            'port': settings.port or None,
+            'path': settings.path or None
+        }
 
     '''
     '''
-    @http.route('/print_engine/sockets', auth='user', methods=['GET'], cors='*')
-    def printers_get_sockets(self, **kw):
-        return self.make_gzip_response({
-            'sockets': self.get_sockets()
-        })
-        
+    @http.route('/print_engine/get_pdf', auth='user', type='json')
+    def get_pdf(self, **kw):
+        import pdb; pdb.set_trace()
+
+        return {
+            'pdf_data': None
+        }

+ 2 - 3
models/__init__.py

@@ -1,4 +1,3 @@
 # -*- coding: utf-8 -*-
-import printer
-import socket
-import res_users
+import print_engine_printer
+import res_config

+ 1 - 12
models/printer.py → models/print_engine_printer.py

@@ -1,4 +1,4 @@
-# -*- coding: utf-8 -*-
+#-*- coding: utf-8 -*-
 from openerp import api, models, fields
 
 class PrintEnginePrinter(models.Model):
@@ -8,14 +8,3 @@ class PrintEnginePrinter(models.Model):
     is_default = fields.Boolean(string='Por defecto', default=False)
     prints_success_count = fields.Integer(string='Impresiones con éxito', default=0)
     prints_failed_count = fields.Integer(string='Impresiones fallidas', default=0)
-    socket_id = fields.Many2one(comodel_name='print.engine.socket')
-
-    @api.onchange('is_default')
-    def update_defaults(self):
-        printer_ids = self.search([('id', '!=', self._origin.id), ('socket_id.user_id', '=', self.env.user.id)])
-
-        for printer in printer_ids:
-            printer.write({
-                'is_default': False
-            })
-   

+ 11 - 0
models/res_config.py

@@ -0,0 +1,11 @@
+# -*- coding: utf-8 -*-
+from openerp import api, models, fields
+
+class PrintEngineSettings(models.TransientModel):
+    _name = 'print.engine.settings'
+    _inherit = 'res.config.settings'
+
+    host = fields.Char(string='Dirección', default='localhost', required=True)
+    port = fields.Integer(string='Puerto', default=8070, required=True)
+    path = fields.Char(string='Recurso', default='/printers-tray', required=True)
+    show_printers = fields.Boolean(string='Preguntar al imprimir', default=True)

+ 0 - 7
models/res_users.py

@@ -1,7 +0,0 @@
-# -*- coding: utf-8 -*-
-from openerp import models, fields
-
-class ResUsers(models.Model):
-    _inherit = 'res.users'
-
-    socket_ids = fields.One2many(comodel_name='print.engine.socket', inverse_name='user_id')

+ 0 - 24
models/socket.py

@@ -1,24 +0,0 @@
-# -*- coding: utf-8 -*-
-from openerp import api, models, fields
-
-AVAILABLE_PROTOCOLS = [
-    ('ws', 'ws'),
-    ('wss', 'wss'),
-]
-
-class PrintEngineSocket(models.Model):
-    _name = 'print.engine.socket'
-
-    @api.multi
-    def _default_user(self):
-        return self.env.user.id
-
-    name = fields.Char(string='Nombre', size=35, required=True)
-    protocol = fields.Selection(string='Protocolo', selection=AVAILABLE_PROTOCOLS, default='ws')
-    host = fields.Char(string='Host', default='localhost', required=True)
-    port = fields.Integer(string='Puerto', default=8070, required=True)
-    path = fields.Char(string='Recurso', default='/')
-    last_connection = fields.Datetime(string='Última conexión', readonly=True)
-    active = fields.Boolean(string='Activo', default=True)
-    user_id = fields.Many2one(comodel_name='res.users', default=_default_user)
-    printer_ids = fields.One2many(comodel_name='print.engine.printer', inverse_name='socket_id')        

+ 65 - 369
static/src/js/main.js

@@ -1,399 +1,95 @@
-
-(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({
+openerp.print_engine = function (instance, local) {
+    local.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();
-            });
+            this.open_socket();
         },
-        getSockets: function () {
-            var defer = $.Deferred();
+        open_socket: function () {
             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;
+            var set_socket = function (socket) {
+                var protocol = window.location.protocol;
+                self.socket = io(protocol + '//' + socket.host + ':' + socket.port, {
+                    path: socket.path
+                });
+                self.socket.on('connect', self.handle_connect);
+                self.socket.on('connect_error', self.handle_connect_error);
+                self.socket.on('show-printers', self.handle_printers);
             }
 
-            setTimeout(function () {
-                self.connect();
-
-                self.attemps = self.attemps + 1;
-            }, 3000);
+            this.get_socket_config().then(set_socket);
         },
-        handleOpen: function (e) {
-            this.state = 'online';
-
+        handle_connect: function () {
             $('#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');
+        handle_connect_error: function () {
+            $('#printer-status').removeClass();
+            $('#printer-status').addClass('printer-status-offline');
+        },
+        handle_printers: function (printers) {
+            console.log(printers);
+        },
+        get_socket_config: function () {
+            var url = '/print_engine/socket_config';
+            return this.get_from_server(url);
+        },
+        get_from_server: function (url) {
+            instance.web.blockUI();
+            return $.Deferred(function (d) {
+                instance.web.jsonRpc(url, 'call').done(function () {
+                    instance.web.unblockUI();
+                    d.resolve.apply(d, arguments);
+                }).fail(function (e) {
+                    instance.web.unblockUI();
+                    d.reject.apply(d, arguments);
                 });
-            }
-        },
-        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({
+    local.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;
+            // this.$el.click(this, this.selectDefaultPrinter);
         }
+    });
 
-        instance.print_engine.socket_manager.discoveryPrinters();
-    }
-    
-    /**
-     * 
-     */
-    instance.print_engine.test_printer = function (element, action) {
-        if (!instance.print_engine.socket_manager) {
-            return;
+    if (instance.web) {
+        if (instance.web.UserMenu) {
+            instance.web.UserMenu.include({
+                do_update: function(){
+                    var printer = new local.PrinterTopWidget(this);
+                    printer.appendTo($('.oe_systray'));
+                    local.socket = new local.SocketManager()
+                    return this._super.apply(this, arguments);
+                }
+            });
         }
 
-        instance.print_engine.socket_manager.test();
-    }
-
-    /**
-     * 
-     */
-    instance.print_engine.print = function (element, action) {
-        if (!instance.print_engine.socket_manager) {
-            return;
+        if (instance.web.ActionManager) {
+            instance.web.ActionManager.include({
+                ir_actions_report_xml: function (action, options) {
+                    var url = '/print_engine/get_pdf';
+
+                    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);
+                    }).fail(function (e) {
+                        console.log(e);
+                    });
+                }
+            });
         }
-
-        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);
-            }
-        });
     }
-})()
+}

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

@@ -0,0 +1,399 @@
+
+(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);
+            }
+        });
+    }
+})()

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 5 - 0
static/src/lib/socket.io.js


+ 1 - 0
templates.xml

@@ -3,6 +3,7 @@
     <data>
         <template id="printers_manager_assets" inherit_id="web.assets_backend">
             <xpath expr="." position="inside">
+                <script type="text/javascript" src="/print_engine/static/src/lib/socket.io.js" />
                 <script type="text/javascript" src="/print_engine/static/src/js/main.js" />
                 <link rel="stylesheet" href="/print_engine/static/src/css/main.css" />
             </xpath>

+ 1 - 1
views/print_engine_printers.xml → views/print_engine_printer_view.xml

@@ -2,7 +2,7 @@
 <openerp>
     <data>
         <!-- Printers Tree  -->
-        <record id="print_engine.printers_tree" model="ir.ui.view">
+        <record id="print_engine.printer_tree" model="ir.ui.view">
             <field name="name">print.engine.printer.tree</field>
             <field name="model">print.engine.printer</field>
             <field name="priority">2</field>

+ 0 - 80
views/print_engine_sockets.xml

@@ -1,80 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<openerp>
-    <data>
-        <!-- Sockets Tree  -->
-        <record id="print_engine.sockets_tree" model="ir.ui.view">
-            <field name="name">print.engine.socket.tree</field>
-            <field name="model">print.engine.socket</field>
-            <field name="priority">2</field>
-            <field name="arch" type="xml">
-                <tree string="Sockets">
-                    <field name="name" string="Nombre Local"/>
-                    <field name="protocol"/>
-                    <field name="host"/>
-                    <field name="port"/>
-                    <field name="path"/>
-                </tree>
-            </field>
-        </record>
-
-        <!-- Socket Form -->
-        <record id="print_engine.sockets_form" model="ir.ui.view">
-            <field name="name">print.engine.socket.form</field>
-            <field name="model">print.engine.socket</field>
-            <field name="arch" type="xml">
-                <form string="Socket">
-                    <header>
-                        <button type="action" name="print_engine.ping_action" string="Ping" />
-                        <button type="action" name="print_engine.discovery_printers_action" string="Actualizar impresoras" />
-                    </header>
-                    <sheet>
-                        <h1>
-                            <field name="name"/>
-                        </h1>
-                        <group>
-                            <field name="protocol"/>
-                            <field name="host"/>
-                            <field name="port"/>
-                            <field name="path"/>
-                            <field name="user_id" string="Usuario" groups="print_engine.printers_group"/>
-                        </group>
-                    </sheet>
-                    <notebook>
-                        <page string="Impresoras">
-                            <field name="printer_ids"/>
-                        </page>
-                    </notebook>
-                </form>
-            </field>
-        </record>
-
-        <!-- Socket Actions -->
-        <record id="print_engine.action_sockets" model="ir.actions.act_window">
-            <field name="name">Sockets</field>
-            <field name="type">ir.actions.act_window</field>
-            <field name="res_model">print.engine.socket</field>
-            <field name="view_type">form</field>
-            <field name="view_mode">tree,form</field>
-            <field name="help" type="html">
-                <p class="oe_view_nocontent_create">
-                    Click para registrar un nuevo socket de impresoras
-                </p><p>
-                    Es necesario recordar que cada socket corresponde a un máquina al que se halla conectados las impresoras.
-                    Por ende es posible registrar varios sockets y tener mayor flexibilidad en la impresión.
-                </p>
-            </field>
-        </record>
-
-        <record id="print_engine.ping_action" model="ir.actions.client">
-            <field name="name">Ping socket action</field>
-            <field name="tag">print_engine.ping</field>
-        </record>
-
-        <record id="print_engine.discovery_printers_action" model="ir.actions.client">
-            <field name="name">Discovery printers action</field>
-            <field name="tag">print_engine.discovery_printers</field>
-        </record>
-
-        <menuitem id="print_engine.sockets" name="Impresión" parent="base.menu_config" action="print_engine.action_sockets" sequence="150" />
-    </data>
-</openerp>

+ 36 - 0
views/res_config_view.xml

@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<openerp>
+    <data>
+        <record id="print_engine_settings_view" model="ir.ui.view">
+            <field name="name">print engine settings</field>
+            <field name="model">print.engine.settings</field>
+            <field name="arch" type="xml">
+                <form string="Impresiones">
+                    <header>
+                        <button string="Aplicar" type="object" name="execute" class="oe_highlight" />
+                        o
+                        <button string="Cancelar" type="object" name="cancel" class="oe_link" />
+                    </header>
+                    <group string="Preferencias">
+                        <field name="host" class="oe_inline" />
+                        <field name="port" class="oe_inline" />
+                        <field name="path" class="oe_inline" />
+                    </group>
+                    <group string="Impresoras">
+                        <field name="show_printers" class="oe_inline" />
+                    </group>
+                </form>
+            </field>
+        </record>
+
+        <record id="print_engine_settings_action" model="ir.actions.act_window">
+            <field name="name">Gestor de Impresión</field>
+            <field name="type">ir.actions.act_window</field>
+            <field name="res_model">print.engine.settings</field>
+            <field name="view_mode">form</field>
+            <field name="target">inline</field>
+        </record>
+
+        <menuitem id="menu_print_engine_settings" name="Gestor de Impresión" parent="base.menu_config" action="print_engine_settings_action" />
+    </data>
+</openerp>

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác