[IMP] hw_escpos: print_xml_receipt() controller allows you to print an xml defined...
[odoo/odoo.git] / addons / hw_escpos / controllers / main.py
1 # -*- coding: utf-8 -*-
2 import commands
3 import logging
4 import simplejson
5 import os
6 import io
7 import base64
8 import openerp
9 import time
10 import random
11 import math
12 import md5
13 import openerp.addons.hw_proxy.controllers.main as hw_proxy
14 import subprocess
15 import traceback
16 from threading import Thread, Lock
17 from Queue import Queue, Empty
18
19 try:
20     import usb.core
21 except ImportError:
22     usb = None
23
24 try:
25     from .. import escpos
26     from ..escpos import printer
27     from ..escpos import supported_devices
28 except ImportError:
29     escpos = printer = None
30
31 from PIL import Image
32
33 from openerp import http
34 from openerp.http import request
35 from openerp.addons.web.controllers.main import manifest_list, module_boot, html_template
36 from openerp.tools.translate import _
37
38 _logger = logging.getLogger(__name__)
39
40 class EscposDriver(Thread):
41     def __init__(self):
42         Thread.__init__(self)
43         self.queue = Queue()
44         self.lock  = Lock()
45         self.status = {'status':'connecting', 'messages':[]}
46
47     def connected_usb_devices(self):
48         connected = []
49         for device in supported_devices.device_list:
50             if usb.core.find(idVendor=device['vendor'], idProduct=device['product']) != None:
51                 connected.append(device)
52         return connected
53
54     def lockedstart(self):
55         self.lock.acquire()
56         if not self.isAlive():
57             self.daemon = True
58             self.start()
59         self.lock.release()
60     
61     def get_escpos_printer(self):
62         try:
63             printers = self.connected_usb_devices()
64             if len(printers) > 0:
65                 self.set_status('connected','Connected to '+printers[0]['name'])
66                 return escpos.printer.Usb(printers[0]['vendor'], printers[0]['product'])
67             else:
68                 self.set_status('disconnected','Printer Not Found')
69                 return None
70         except Exception as e:
71             self.set_status('error',str(e))
72             return None
73
74     def get_status(self):
75         self.push_task('status')
76         return self.status
77
78     def open_cashbox(self,printer):
79         printer.cashdraw(2)
80         printer.cashdraw(5)
81
82     def set_status(self, status, message = None):
83         if status == self.status['status']:
84             if message != None and message != self.status['messages'][-1]:
85                 self.status['messages'].append(message)
86         else:
87             self.status['status'] = status
88             if message:
89                 self.status['messages'] = [message]
90             else:
91                 self.status['messages'] = []
92
93         if status == 'error' and message:
94             _logger.error('ESC/POS Error: '+message)
95         elif status == 'disconnected' and message:
96             _logger.warning('ESC/POS Device Disconnected: '+message)
97
98     def run(self):
99         if not escpos:
100             _logger.error('ESC/POS cannot initialize, please verify system dependencies.')
101             return
102         while True:
103             try:
104                 timestamp, task, data = self.queue.get(True)
105
106                 printer = self.get_escpos_printer()
107
108                 if printer == None:
109                     if task != 'status':
110                         self.queue.put((timestamp,task,data))
111                     time.sleep(5)
112                     continue
113                 elif task == 'receipt': 
114                     if timestamp >= time.time() - 1 * 60 * 60:
115                         self.print_receipt_body(printer,data)
116                         printer.cut()
117                 elif task == 'xml_receipt':
118                     if timestamp >= time.time() - 1 * 60 * 60:
119                         printer.receipt(data)
120                 elif task == 'cashbox':
121                     if timestamp >= time.time() - 12:
122                         self.open_cashbox(printer)
123                 elif task == 'printstatus':
124                     self.print_status(printer)
125                 elif task == 'status':
126                     pass
127
128             except Exception as e:
129                 self.set_status('error', str(e))
130                 errmsg = str(e) + '\n' + '-'*60+'\n' + traceback.format_exc() + '-'*60 + '\n'
131                 _logger.error(errmsg);
132
133     def push_task(self,task, data = None):
134         self.lockedstart()
135         self.queue.put((time.time(),task,data))
136
137     def print_status(self,eprint):
138         localips = ['0.0.0.0','127.0.0.1','127.0.1.1']
139         ips =  [ c.split(':')[1].split(' ')[0] for c in commands.getoutput("/sbin/ifconfig").split('\n') if 'inet addr' in c ]
140         ips =  [ ip for ip in ips if ip not in localips ] 
141         eprint.text('\n\n')
142         eprint.set(align='center',type='b',height=2,width=2)
143         eprint.text('PosBox Status\n')
144         eprint.text('\n')
145         eprint.set(align='center')
146
147         if len(ips) == 0:
148             eprint.text('ERROR: Could not connect to LAN\n\nPlease check that the PosBox is correc-\ntly connected with a network cable,\n that the LAN is setup with DHCP, and\nthat network addresses are available')
149         elif len(ips) == 1:
150             eprint.text('IP Address\n'+ips[0]+'\n')
151         else:
152             eprint.text('IP Addresses\n')
153             for ip in ips:
154                 eprint.text(ip+'\n')
155
156         eprint.text('\n\n')
157         eprint.cut()
158
159     def print_receipt_body(self,eprint,receipt):
160
161         def check(string):
162             return string != True and bool(string) and string.strip()
163         
164         def price(amount):
165             return ("{0:."+str(receipt['precision']['price'])+"f}").format(amount)
166         
167         def money(amount):
168             return ("{0:."+str(receipt['precision']['money'])+"f}").format(amount)
169
170         def quantity(amount):
171             if math.floor(amount) != amount:
172                 return ("{0:."+str(receipt['precision']['quantity'])+"f}").format(amount)
173             else:
174                 return str(amount)
175
176         def printline(left, right='', width=40, ratio=0.5, indent=0):
177             lwidth = int(width * ratio) 
178             rwidth = width - lwidth 
179             lwidth = lwidth - indent
180             
181             left = left[:lwidth]
182             if len(left) != lwidth:
183                 left = left + ' ' * (lwidth - len(left))
184
185             right = right[-rwidth:]
186             if len(right) != rwidth:
187                 right = ' ' * (rwidth - len(right)) + right
188
189             return ' ' * indent + left + right + '\n'
190         
191         def print_taxes():
192             taxes = receipt['tax_details']
193             for tax in taxes:
194                 eprint.text(printline(tax['tax']['name'],price(tax['amount']), width=40,ratio=0.6))
195
196         # Receipt Header
197         if receipt['company']['logo']:
198             eprint.set(align='center')
199             eprint.print_base64_image(receipt['company']['logo'])
200             eprint.text('\n')
201         else:
202             eprint.set(align='center',type='b',height=2,width=2)
203             eprint.text(receipt['company']['name'] + '\n')
204
205         eprint.set(align='center',type='b')
206         if check(receipt['shop']['name']):
207             eprint.text(receipt['shop']['name'] + '\n')
208         if check(receipt['company']['contact_address']):
209             eprint.text(receipt['company']['contact_address'] + '\n')
210         if check(receipt['company']['phone']):
211             eprint.text('Tel:' + receipt['company']['phone'] + '\n')
212         if check(receipt['company']['vat']):
213             eprint.text('VAT:' + receipt['company']['vat'] + '\n')
214         if check(receipt['company']['email']):
215             eprint.text(receipt['company']['email'] + '\n')
216         if check(receipt['company']['website']):
217             eprint.text(receipt['company']['website'] + '\n')
218         if check(receipt['header']):
219             eprint.text(receipt['header']+'\n')
220         if check(receipt['cashier']):
221             eprint.text('-'*32+'\n')
222             eprint.text('Served by '+receipt['cashier']+'\n')
223
224         # Orderlines
225         eprint.text('\n\n')
226         eprint.set(align='center')
227         for line in receipt['orderlines']:
228             pricestr = price(line['price_display'])
229             if line['discount'] == 0 and line['unit_name'] == 'Unit(s)' and line['quantity'] == 1:
230                 eprint.text(printline(line['product_name'],pricestr,ratio=0.6))
231             else:
232                 eprint.text(printline(line['product_name'],ratio=0.6))
233                 if line['discount'] != 0:
234                     eprint.text(printline('Discount: '+str(line['discount'])+'%', ratio=0.6, indent=2))
235                 if line['unit_name'] == 'Unit(s)':
236                     eprint.text( printline( quantity(line['quantity']) + ' x ' + price(line['price']), pricestr, ratio=0.6, indent=2))
237                 else:
238                     eprint.text( printline( quantity(line['quantity']) + line['unit_name'] + ' x ' + price(line['price']), pricestr, ratio=0.6, indent=2))
239
240         # Subtotal if the taxes are not included
241         taxincluded = True
242         if money(receipt['subtotal']) != money(receipt['total_with_tax']):
243             eprint.text(printline('','-------'));
244             eprint.text(printline(_('Subtotal'),money(receipt['subtotal']),width=40, ratio=0.6))
245             print_taxes()
246             #eprint.text(printline(_('Taxes'),money(receipt['total_tax']),width=40, ratio=0.6))
247             taxincluded = False
248
249
250         # Total
251         eprint.text(printline('','-------'));
252         eprint.set(align='center',height=2)
253         eprint.text(printline(_('         TOTAL'),money(receipt['total_with_tax']),width=40, ratio=0.6))
254         eprint.text('\n\n');
255         
256         # Paymentlines
257         eprint.set(align='center')
258         for line in receipt['paymentlines']:
259             eprint.text(printline(line['journal'], money(line['amount']), ratio=0.6))
260
261         eprint.text('\n');
262         eprint.set(align='center',height=2)
263         eprint.text(printline(_('        CHANGE'),money(receipt['change']),width=40, ratio=0.6))
264         eprint.set(align='center')
265         eprint.text('\n');
266
267         # Extra Payment info
268         if receipt['total_discount'] != 0:
269             eprint.text(printline(_('Discounts'),money(receipt['total_discount']),width=40, ratio=0.6))
270         if taxincluded:
271             print_taxes()
272             #eprint.text(printline(_('Taxes'),money(receipt['total_tax']),width=40, ratio=0.6))
273
274         # Footer
275         if check(receipt['footer']):
276             eprint.text('\n'+receipt['footer']+'\n\n')
277         eprint.text(receipt['name']+'\n')
278         eprint.text(      str(receipt['date']['date']).zfill(2)
279                     +'/'+ str(receipt['date']['month']+1).zfill(2)
280                     +'/'+ str(receipt['date']['year']).zfill(4)
281                     +' '+ str(receipt['date']['hour']).zfill(2)
282                     +':'+ str(receipt['date']['minute']).zfill(2) )
283
284 driver = EscposDriver()
285
286 hw_proxy.drivers['escpos'] = driver
287
288 class EscposProxy(hw_proxy.Proxy):
289     
290     @http.route('/hw_proxy/open_cashbox', type='json', auth='none', cors='*')
291     def open_cashbox(self):
292         _logger.info('ESC/POS: OPEN CASHBOX') 
293         driver.push_task('cashbox')
294         
295     @http.route('/hw_proxy/print_receipt', type='json', auth='none', cors='*')
296     def print_receipt(self, receipt):
297         _logger.info('ESC/POS: PRINT RECEIPT') 
298         driver.push_task('receipt',receipt)
299
300     @http.route('/hw_proxy/print_xml_receipt', type='json', auth='none', cors='*')
301     def print_receipt(self, receipt):
302         _logger.info('ESC/POS: PRINT XML RECEIPT') 
303         driver.push_task('xml_receipt',receipt)
304