[MERGE] forward port of branch 8.0 up to 262eb66
[odoo/odoo.git] / addons / point_of_sale / static / src / js / models.js
1 function openerp_pos_models(instance, module){ //module is instance.point_of_sale
2     var QWeb = instance.web.qweb;
3         var _t = instance.web._t;
4
5     var round_di = instance.web.round_decimals;
6     var round_pr = instance.web.round_precision
7     
8     // The PosModel contains the Point Of Sale's representation of the backend.
9     // Since the PoS must work in standalone ( Without connection to the server ) 
10     // it must contains a representation of the server's PoS backend. 
11     // (taxes, product list, configuration options, etc.)  this representation
12     // is fetched and stored by the PosModel at the initialisation. 
13     // this is done asynchronously, a ready deferred alows the GUI to wait interactively 
14     // for the loading to be completed 
15     // There is a single instance of the PosModel for each Front-End instance, it is usually called
16     // 'pos' and is available to all widgets extending PosWidget.
17
18     module.PosModel = Backbone.Model.extend({
19         initialize: function(session, attributes) {
20             Backbone.Model.prototype.initialize.call(this, attributes);
21             var  self = this;
22             this.session = session;                 
23             this.flush_mutex = new $.Mutex();                   // used to make sure the orders are sent to the server once at time
24             this.pos_widget = attributes.pos_widget;
25
26             this.proxy = new module.ProxyDevice(this);              // used to communicate to the hardware devices via a local proxy
27             this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy, patterns: {}});  // used to read barcodes
28             this.proxy_queue = new module.JobQueue();           // used to prevent parallels communications to the proxy
29             this.db = new module.PosDB();                       // a local database used to search trough products and categories & store pending orders
30             this.debug = jQuery.deparam(jQuery.param.querystring()).debug !== undefined;    //debug mode 
31             
32             // Business data; loaded from the server at launch
33             this.accounting_precision = 2; //TODO
34             this.company_logo = null;
35             this.company_logo_base64 = '';
36             this.currency = null;
37             this.shop = null;
38             this.company = null;
39             this.user = null;
40             this.users = [];
41             this.partners = [];
42             this.cashier = null;
43             this.cashregisters = [];
44             this.bankstatements = [];
45             this.taxes = [];
46             this.pos_session = null;
47             this.config = null;
48             this.units = [];
49             this.units_by_id = {};
50             this.pricelist = null;
51             this.order_sequence = 1;
52             window.posmodel = this;
53
54             // these dynamic attributes can be watched for change by other models or widgets
55             this.set({
56                 'synch':            { state:'connected', pending:0 }, 
57                 'orders':           new module.OrderCollection(),
58                 'selectedOrder':    null,
59             });
60
61             this.bind('change:synch',function(pos,synch){
62                 clearTimeout(self.synch_timeout);
63                 self.synch_timeout = setTimeout(function(){
64                     if(synch.state !== 'disconnected' && synch.pending > 0){
65                         self.set('synch',{state:'disconnected', pending:synch.pending});
66                     }
67                 },3000);
68             });
69
70             this.get('orders').bind('remove', function(order,_unused_,options){ 
71                 self.on_removed_order(order,options.index,options.reason); 
72             });
73             
74             // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
75             // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched. 
76             // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used. 
77             this.ready = this.load_server_data()
78                 .then(function(){
79                     if(self.config.use_proxy){
80                         return self.connect_to_proxy();
81                     }
82                 });
83             
84         },
85
86         // releases ressources holds by the model at the end of life of the posmodel
87         destroy: function(){
88             // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
89             // this.flush();
90             this.proxy.close();
91             this.barcode_reader.disconnect();
92             this.barcode_reader.disconnect_from_proxy();
93         },
94         connect_to_proxy: function(){
95             var self = this;
96             var  done = new $.Deferred();
97             this.barcode_reader.disconnect_from_proxy();
98             this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
99             this.pos_widget.loading_skip(function(){
100                     self.proxy.stop_searching();
101                 });
102             this.proxy.autoconnect({
103                     force_ip: self.config.proxy_ip || undefined,
104                     progress: function(prog){ 
105                         self.pos_widget.loading_progress(prog);
106                     },
107                 }).then(function(){
108                     if(self.config.iface_scan_via_proxy){
109                         self.barcode_reader.connect_to_proxy();
110                     }
111                 }).always(function(){
112                     done.resolve();
113                 });
114             return done;
115         },
116
117         // helper function to load data from the server. Obsolete use the models loader below.
118         fetch: function(model, fields, domain, ctx){
119             this._load_progress = (this._load_progress || 0) + 0.05; 
120             this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
121             return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
122         },
123
124         // Server side model loaders. This is the list of the models that need to be loaded from
125         // the server. The models are loaded one by one by this list's order. The 'loaded' callback
126         // is used to store the data in the appropriate place once it has been loaded. This callback
127         // can return a deferred that will pause the loading of the next module. 
128         // a shared temporary dictionary is available for loaders to communicate private variables
129         // used during loading such as object ids, etc. 
130         models: [
131         {
132             model:  'res.users',
133             fields: ['name','company_id'],
134             domain: function(self){ return [['id','=',self.session.uid]]; },
135             loaded: function(self,users){ self.user = users[0]; },
136         },{ 
137             model:  'res.company',
138             fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id'],
139             domain: function(self){ return [['id','=',self.user.company_id[0]]]; },
140             loaded: function(self,companies){ self.company = companies[0]; },
141         },{
142             model:  'product.uom',
143             fields: [],
144             domain: null,
145             loaded: function(self,units){
146                 self.units = units;
147                 var units_by_id = {};
148                 for(var i = 0, len = units.length; i < len; i++){
149                     units_by_id[units[i].id] = units[i];
150                     units[i].groupable = ( units[i].category_id[0] === 1 );
151                     units[i].is_unit   = ( units[i].id === 1 );
152                 }
153                 self.units_by_id = units_by_id;
154             }
155         },{
156             model:  'res.users',
157             fields: ['name','ean13'],
158             domain: null,
159             loaded: function(self,users){ self.users = users; },
160         },{
161             model:  'res.partner',
162             fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','ean13','write_date'],
163             domain: null,
164             loaded: function(self,partners){
165                 self.partners = partners;
166                 self.db.add_partners(partners);
167             },
168         },{
169             model:  'res.country',
170             fields: ['name'],
171             loaded: function(self,countries){
172                 self.countries = countries;
173                 self.company.country = null;
174                 for (var i = 0; i < countries.length; i++) {
175                     if (countries[i].id === self.company.country_id[0]){
176                         self.company.country = countries[i];
177                     }
178                 }
179             },
180         },{
181             model:  'account.tax',
182             fields: ['name','amount', 'price_include', 'type'],
183             domain: null,
184             loaded: function(self,taxes){ self.taxes = taxes; },
185         },{
186             model:  'pos.session',
187             fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
188             domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
189             loaded: function(self,pos_sessions){
190                 self.pos_session = pos_sessions[0]; 
191
192                 var orders = self.db.get_orders();
193                 for (var i = 0; i < orders.length; i++) {
194                     self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
195                 }
196             },
197         },{
198             model: 'pos.config',
199             fields: [],
200             domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
201             loaded: function(self,configs){
202                 self.config = configs[0];
203                 self.config.use_proxy = self.config.iface_payment_terminal || 
204                                         self.config.iface_electronic_scale ||
205                                         self.config.iface_print_via_proxy  ||
206                                         self.config.iface_scan_via_proxy   ||
207                                         self.config.iface_cashdrawer;
208                 
209                 self.barcode_reader.add_barcode_patterns({
210                     'product':  self.config.barcode_product,
211                     'cashier':  self.config.barcode_cashier,
212                     'client':   self.config.barcode_customer,
213                     'weight':   self.config.barcode_weight,
214                     'discount': self.config.barcode_discount,
215                     'price':    self.config.barcode_price,
216                 });
217
218                 if (self.config.company_id[0] !== self.user.company_id[0]) {
219                     throw new Error(_t("Error: The Point of Sale User must belong to the same company as the Point of Sale. You are probably trying to load the point of sale as an administrator in a multi-company setup, with the administrator account set to the wrong company."));
220                 }
221             },
222         },{
223             model: 'stock.location',
224             fields: [],
225             domain: function(self){ return [['id','=', self.config.stock_location_id[0]]]; },
226             loaded: function(self, locations){ self.shop = locations[0]; },
227         },{
228             model:  'product.pricelist',
229             fields: ['currency_id'],
230             domain: function(self){ return [['id','=',self.config.pricelist_id[0]]]; },
231             loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
232         },{
233             model: 'res.currency',
234             fields: ['symbol','position','rounding','accuracy'],
235             domain: function(self){ return [['id','=',self.pricelist.currency_id[0]]]; },
236             loaded: function(self, currencies){
237                 self.currency = currencies[0];
238             },
239         },{
240             model: 'product.packaging',
241             fields: ['ean','product_tmpl_id'],
242             domain: null,
243             loaded: function(self, packagings){ 
244                 self.db.add_packagings(packagings);
245             },
246         },{
247             model:  'pos.category',
248             fields: ['id','name','parent_id','child_id','image'],
249             domain: null,
250             loaded: function(self, categories){
251                 self.db.add_categories(categories);
252             },
253         },{
254             model:  'product.product',
255             fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code', 
256                      'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
257                      'product_tmpl_id'],
258             domain:  function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
259             context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
260             loaded: function(self, products){
261                 self.db.add_products(products);
262             },
263         },{
264             model:  'account.bank.statement',
265             fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
266             domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
267             loaded: function(self, bankstatements, tmp){
268                 self.bankstatements = bankstatements;
269
270                 tmp.journals = [];
271                 _.each(bankstatements,function(statement){
272                     tmp.journals.push(statement.journal_id[0]);
273                 });
274             },
275         },{
276             model:  'account.journal',
277             fields: [],
278             domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
279             loaded: function(self, journals){
280                 self.journals = journals;
281
282                 // associate the bank statements with their journals. 
283                 var bankstatements = self.bankstatements;
284                 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
285                     for(var j = 0, jlen = journals.length; j < jlen; j++){
286                         if(bankstatements[i].journal_id[0] === journals[j].id){
287                             bankstatements[i].journal = journals[j];
288                         }
289                     }
290                 }
291                 self.cashregisters = bankstatements;
292             },
293         },{
294             label: 'fonts',
295             loaded: function(self){
296                 var fonts_loaded = new $.Deferred();
297                 // Waiting for fonts to be loaded to prevent receipt printing
298                 // from printing empty receipt while loading Inconsolata
299                 // ( The font used for the receipt ) 
300                 waitForWebfonts(['Lato','Inconsolata'], function(){
301                     fonts_loaded.resolve();
302                 });
303                 // The JS used to detect font loading is not 100% robust, so
304                 // do not wait more than 5sec
305                 setTimeout(function(){
306                     fonts_loaded.resolve();
307                 },5000);
308
309                 return fonts_loaded;
310             },
311         },{
312             label: 'pictures',
313             loaded: function(self){
314                 self.company_logo = new Image();
315                 var  logo_loaded = new $.Deferred();
316                 self.company_logo.onload = function(){
317                     var img = self.company_logo;
318                     var ratio = 1;
319                     var targetwidth = 300;
320                     var maxheight = 150;
321                     if( img.width !== targetwidth ){
322                         ratio = targetwidth / img.width;
323                     }
324                     if( img.height * ratio > maxheight ){
325                         ratio = maxheight / img.height;
326                     }
327                     var width  = Math.floor(img.width * ratio);
328                     var height = Math.floor(img.height * ratio);
329                     var c = document.createElement('canvas');
330                         c.width  = width;
331                         c.height = height
332                     var ctx = c.getContext('2d');
333                         ctx.drawImage(self.company_logo,0,0, width, height);
334
335                     self.company_logo_base64 = c.toDataURL();
336                     logo_loaded.resolve();
337                 };
338                 self.company_logo.onerror = function(){
339                     logo_loaded.reject();
340                 };
341                     self.company_logo.crossOrigin = "anonymous";
342                 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
343
344                 return logo_loaded;
345             },
346         },
347         ],
348
349         // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded. 
350         load_server_data: function(){
351             var self = this;
352             var loaded = new $.Deferred();
353             var progress = 0;
354             var progress_step = 1.0 / self.models.length;
355             var tmp = {}; // this is used to share a temporary state between models loaders
356
357             function load_model(index){
358                 if(index >= self.models.length){
359                     loaded.resolve();
360                 }else{
361                     var model = self.models[index];
362                     self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
363                     var fields =  typeof model.fields === 'function'  ? model.fields(self,tmp)  : model.fields;
364                     var domain =  typeof model.domain === 'function'  ? model.domain(self,tmp)  : model.domain;
365                     var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context; 
366                     progress += progress_step;
367                     
368                     if( model.model ){
369                         new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
370                             .then(function(result){
371                                 try{    // catching exceptions in model.loaded(...)
372                                     $.when(model.loaded(self,result,tmp))
373                                         .then(function(){ load_model(index + 1); },
374                                               function(err){ loaded.reject(err); });
375                                 }catch(err){
376                                     loaded.reject(err);
377                                 }
378                             },function(err){
379                                 loaded.reject(err);
380                             });
381                     }else if( model.loaded ){
382                         try{    // catching exceptions in model.loaded(...)
383                             $.when(model.loaded(self,tmp))
384                                 .then(  function(){ load_model(index +1); },
385                                         function(err){ loaded.reject(err); });
386                         }catch(err){
387                             loaded.reject(err);
388                         }
389                     }else{
390                         load_model(index + 1);
391                     }
392                 }
393             }
394
395             try{
396                 load_model(0);
397             }catch(err){
398                 loaded.reject(err);
399             }
400
401             return loaded;
402         },
403
404         // reload the list of partner, returns as a deferred that resolves if there were
405         // updated partners, and fails if not
406         load_new_partners: function(){
407             var self = this;
408             var def  = new $.Deferred();
409             var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
410             new instance.web.Model('res.partner')
411                 .query(fields)
412                 .filter([['write_date','>',this.db.get_partner_write_date()]])
413                 .all({'timeout':3000, 'shadow': true})
414                 .then(function(partners){
415                     if (self.db.add_partners(partners)) {   // check if the partners we got were real updates
416                         def.resolve();
417                     } else {
418                         def.reject();
419                     }
420                 }, function(){ def.reject(); });    
421             return def;
422         },
423
424         // this is called when an order is removed from the order collection. It ensures that there is always an existing
425         // order and a valid selected order
426         on_removed_order: function(removed_order,index,reason){
427             if( (reason === 'abandon' || removed_order.temporary) && this.get('orders').size() > 0){
428                 // when we intentionally remove an unfinished order, and there is another existing one
429                 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
430             }else{
431                 // when the order was automatically removed after completion, 
432                 // or when we intentionally delete the only concurrent order
433                 this.add_new_order();
434             }
435         },
436
437         //creates a new empty order and sets it as the current order
438         add_new_order: function(){
439             var order = new module.Order({pos:this});
440             this.get('orders').add(order);
441             this.set('selectedOrder', order);
442         },
443
444         get_order: function(){
445             return this.get('selectedOrder');
446         },
447
448         //removes the current order
449         delete_current_order: function(){
450             this.get('selectedOrder').destroy({'reason':'abandon'});
451         },
452
453         // saves the order locally and try to send it to the backend. 
454         // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
455         push_order: function(order) {
456             var self = this;
457
458             if(order){
459                 this.proxy.log('push_order',order.export_as_JSON());
460                 this.db.add_order(order.export_as_JSON());
461             }
462             
463             var pushed = new $.Deferred();
464
465             this.flush_mutex.exec(function(){
466                 var flushed = self._flush_orders(self.db.get_orders());
467
468                 flushed.always(function(ids){
469                     pushed.resolve();
470                 });
471             });
472             return pushed;
473         },
474
475         // saves the order locally and try to send it to the backend and make an invoice
476         // returns a deferred that succeeds when the order has been posted and successfully generated
477         // an invoice. This method can fail in various ways:
478         // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
479         //     this error is solved
480         // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
481         //     the network connection is up 
482
483         push_and_invoice_order: function(order){
484             var self = this;
485             var invoiced = new $.Deferred(); 
486
487             if(!order.get_client()){
488                 invoiced.reject('error-no-client');
489                 return invoiced;
490             }
491
492             var order_id = this.db.add_order(order.export_as_JSON());
493
494             this.flush_mutex.exec(function(){
495                 var done = new $.Deferred(); // holds the mutex
496
497                 // send the order to the server
498                 // we have a 30 seconds timeout on this push.
499                 // FIXME: if the server takes more than 30 seconds to accept the order,
500                 // the client will believe it wasn't successfully sent, and very bad
501                 // things will happen as a duplicate will be sent next time
502                 // so we must make sure the server detects and ignores duplicated orders
503
504                 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
505                 
506                 transfer.fail(function(){
507                     invoiced.reject('error-transfer');
508                     done.reject();
509                 });
510
511                 // on success, get the order id generated by the server
512                 transfer.pipe(function(order_server_id){    
513
514                     // generate the pdf and download it
515                     self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{ 
516                         active_ids:order_server_id,
517                     }});
518
519                     invoiced.resolve();
520                     done.resolve();
521                 });
522
523                 return done;
524
525             });
526
527             return invoiced;
528         },
529
530         // wrapper around the _save_to_server that updates the synch status widget
531         _flush_orders: function(orders, options) {
532             var self = this;
533             this.set('synch',{ state: 'connecting', pending: orders.length});
534
535             return self._save_to_server(orders, options).done(function (server_ids) {
536                 var pending = self.db.get_orders().length;
537
538                 self.set('synch', {
539                     state: pending ? 'connecting' : 'connected',
540                     pending: pending
541                 });
542
543                 return server_ids;
544             });
545         },
546
547         // send an array of orders to the server
548         // available options:
549         // - timeout: timeout for the rpc call in ms
550         // returns a deferred that resolves with the list of
551         // server generated ids for the sent orders
552         _save_to_server: function (orders, options) {
553             if (!orders || !orders.length) {
554                 var result = $.Deferred();
555                 result.resolve([]);
556                 return result;
557             }
558                 
559             options = options || {};
560
561             var self = this;
562             var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
563
564             // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
565             // then we want to notify the user that we are waiting on something )
566             var posOrderModel = new instance.web.Model('pos.order');
567             return posOrderModel.call('create_from_ui',
568                 [_.map(orders, function (order) {
569                     order.to_invoice = options.to_invoice || false;
570                     return order;
571                 })],
572                 undefined,
573                 {
574                     shadow: !options.to_invoice,
575                     timeout: timeout
576                 }
577             ).then(function (server_ids) {
578                 _.each(orders, function (order) {
579                     self.db.remove_order(order.id);
580                 });
581                 return server_ids;
582             }).fail(function (error, event){
583                 if(error.code === 200 ){    // Business Logic Error, not a connection problem
584                     //if warning do not need to dispaly traceback!!
585                     if(error.data.exception_type == 'warning'){
586                         delete error.data.debug;
587                     }
588                     self.pos_widget.screen_selector.show_popup('error-traceback',{
589                         message: error.data.message,
590                         comment: error.data.debug
591                     });
592                 }
593                 // prevent an error popup creation by the rpc failure
594                 // we want the failure to be silent as we send the orders in the background
595                 event.preventDefault();
596                 console.error('Failed to send orders:', orders);
597             });
598         },
599
600         scan_product: function(parsed_code){
601             var self = this;
602             var selectedOrder = this.get('selectedOrder');
603             if(parsed_code.encoding === 'ean13'){
604                 var product = this.db.get_product_by_ean13(parsed_code.base_code);
605             }else if(parsed_code.encoding === 'reference'){
606                 var product = this.db.get_product_by_reference(parsed_code.code);
607             }
608
609             if(!product){
610                 return false;
611             }
612
613             if(parsed_code.type === 'price'){
614                 selectedOrder.addProduct(product, {price:parsed_code.value});
615             }else if(parsed_code.type === 'weight'){
616                 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
617             }else if(parsed_code.type === 'discount'){
618                 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
619             }else{
620                 selectedOrder.addProduct(product);
621             }
622             return true;
623         },
624     });
625
626     var orderline_id = 1;
627
628     // An orderline represent one element of the content of a client's shopping cart.
629     // An orderline contains a product, its quantity, its price, discount. etc. 
630     // An Order contains zero or more Orderlines.
631     module.Orderline = Backbone.Model.extend({
632         initialize: function(attr,options){
633             this.pos = options.pos;
634             this.order = options.order;
635             this.product = options.product;
636             this.price   = options.product.price;
637             this.quantity = 1;
638             this.quantityStr = '1';
639             this.discount = 0;
640             this.discountStr = '0';
641             this.type = 'unit';
642             this.selected = false;
643             this.id       = orderline_id++; 
644         },
645         clone: function(){
646             var orderline = new module.Orderline({},{
647                 pos: this.pos,
648                 order: null,
649                 product: this.product,
650                 price: this.price,
651             });
652             orderline.quantity = this.quantity;
653             orderline.quantityStr = this.quantityStr;
654             orderline.discount = this.discount;
655             orderline.type = this.type;
656             orderline.selected = false;
657             return orderline;
658         },
659         // sets a discount [0,100]%
660         set_discount: function(discount){
661             var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
662             this.discount = disc;
663             this.discountStr = '' + disc;
664             this.trigger('change',this);
665         },
666         // returns the discount [0,100]%
667         get_discount: function(){
668             return this.discount;
669         },
670         get_discount_str: function(){
671             return this.discountStr;
672         },
673         get_product_type: function(){
674             return this.type;
675         },
676         // sets the quantity of the product. The quantity will be rounded according to the 
677         // product's unity of measure properties. Quantities greater than zero will not get 
678         // rounded to zero
679         set_quantity: function(quantity){
680             if(quantity === 'remove'){
681                 this.order.removeOrderline(this);
682                 return;
683             }else{
684                 var quant = parseFloat(quantity) || 0;
685                 var unit = this.get_unit();
686                 if(unit){
687                     this.quantity    = round_pr(quant, unit.rounding);
688                     this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
689                 }else{
690                     this.quantity    = quant;
691                     this.quantityStr = '' + this.quantity;
692                 }
693             }
694             this.trigger('change',this);
695         },
696         // return the quantity of product
697         get_quantity: function(){
698             return this.quantity;
699         },
700         get_quantity_str: function(){
701             return this.quantityStr;
702         },
703         get_quantity_str_with_unit: function(){
704             var unit = this.get_unit();
705             if(unit && !unit.is_unit){
706                 return this.quantityStr + ' ' + unit.name;
707             }else{
708                 return this.quantityStr;
709             }
710         },
711         // return the unit of measure of the product
712         get_unit: function(){
713             var unit_id = (this.product.uos_id || this.product.uom_id);
714             if(!unit_id){
715                 return undefined;
716             }
717             unit_id = unit_id[0];
718             if(!this.pos){
719                 return undefined;
720             }
721             return this.pos.units_by_id[unit_id];
722         },
723         // return the product of this orderline
724         get_product: function(){
725             return this.product;
726         },
727         // selects or deselects this orderline
728         set_selected: function(selected){
729             this.selected = selected;
730             this.trigger('change',this);
731         },
732         // returns true if this orderline is selected
733         is_selected: function(){
734             return this.selected;
735         },
736         // when we add an new orderline we want to merge it with the last line to see reduce the number of items
737         // in the orderline. This returns true if it makes sense to merge the two
738         can_be_merged_with: function(orderline){
739             if( this.get_product().id !== orderline.get_product().id){    //only orderline of the same product can be merged
740                 return false;
741             }else if(!this.get_unit() || !this.get_unit().groupable){
742                 return false;
743             }else if(this.get_product_type() !== orderline.get_product_type()){
744                 return false;
745             }else if(this.get_discount() > 0){             // we don't merge discounted orderlines
746                 return false;
747             }else if(this.price !== orderline.price){
748                 return false;
749             }else{ 
750                 return true;
751             }
752         },
753         merge: function(orderline){
754             this.set_quantity(this.get_quantity() + orderline.get_quantity());
755         },
756         export_as_JSON: function() {
757             return {
758                 qty: this.get_quantity(),
759                 price_unit: this.get_unit_price(),
760                 discount: this.get_discount(),
761                 product_id: this.get_product().id,
762             };
763         },
764         //used to create a json of the ticket, to be sent to the printer
765         export_for_printing: function(){
766             return {
767                 quantity:           this.get_quantity(),
768                 unit_name:          this.get_unit().name,
769                 price:              this.get_unit_price(),
770                 discount:           this.get_discount(),
771                 product_name:       this.get_product().display_name,
772                 price_display :     this.get_display_price(),
773                 price_with_tax :    this.get_price_with_tax(),
774                 price_without_tax:  this.get_price_without_tax(),
775                 tax:                this.get_tax(),
776                 product_description:      this.get_product().description,
777                 product_description_sale: this.get_product().description_sale,
778             };
779         },
780         // changes the base price of the product for this orderline
781         set_unit_price: function(price){
782             this.price = round_di(parseFloat(price) || 0, 2);
783             this.trigger('change',this);
784         },
785         get_unit_price: function(){
786             var rounding = this.pos.currency.rounding;
787             return round_pr(this.price,rounding);
788         },
789         get_display_price: function(){
790             var rounding = this.pos.currency.rounding;
791             return  round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
792         },
793         get_price_without_tax: function(){
794             return this.get_all_prices().priceWithoutTax;
795         },
796         get_price_with_tax: function(){
797             return this.get_all_prices().priceWithTax;
798         },
799         get_tax: function(){
800             return this.get_all_prices().tax;
801         },
802         get_tax_details: function(){
803             return this.get_all_prices().taxDetails;
804         },
805         get_all_prices: function(){
806             var self = this;
807             var currency_rounding = this.pos.currency.rounding;
808             var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
809             var totalTax = base;
810             var totalNoTax = base;
811             
812             var product =  this.get_product(); 
813             var taxes_ids = product.taxes_id;
814             var taxes =  self.pos.taxes;
815             var taxtotal = 0;
816             var taxdetail = {};
817             _.each(taxes_ids, function(el) {
818                 var tax = _.detect(taxes, function(t) {return t.id === el;});
819                 if (tax.price_include) {
820                     var tmp;
821                     if (tax.type === "percent") {
822                         tmp =  base - round_pr(base / (1 + tax.amount),currency_rounding); 
823                     } else if (tax.type === "fixed") {
824                         tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
825                     } else {
826                         throw "This type of tax is not supported by the point of sale: " + tax.type;
827                     }
828                     tmp = round_pr(tmp,currency_rounding);
829                     taxtotal += tmp;
830                     totalNoTax -= tmp;
831                     taxdetail[tax.id] = tmp;
832                 } else {
833                     var tmp;
834                     if (tax.type === "percent") {
835                         tmp = tax.amount * base;
836                     } else if (tax.type === "fixed") {
837                         tmp = tax.amount * self.get_quantity();
838                     } else {
839                         throw "This type of tax is not supported by the point of sale: " + tax.type;
840                     }
841                     tmp = round_pr(tmp,currency_rounding);
842                     taxtotal += tmp;
843                     totalTax += tmp;
844                     taxdetail[tax.id] = tmp;
845                 }
846             });
847             return {
848                 "priceWithTax": totalTax,
849                 "priceWithoutTax": totalNoTax,
850                 "tax": taxtotal,
851                 "taxDetails": taxdetail,
852             };
853         },
854     });
855
856     module.OrderlineCollection = Backbone.Collection.extend({
857         model: module.Orderline,
858     });
859
860     // Every Paymentline contains a cashregister and an amount of money.
861     module.Paymentline = Backbone.Model.extend({
862         initialize: function(attributes, options) {
863             this.amount = 0;
864             this.cashregister = options.cashregister;
865             this.name = this.cashregister.journal_id[1];
866             this.selected = false;
867         },
868         //sets the amount of money on this payment line
869         set_amount: function(value){
870             this.amount = round_di(parseFloat(value) || 0, 2);
871             this.trigger('change:amount',this);
872         },
873         // returns the amount of money on this paymentline
874         get_amount: function(){
875             return this.amount;
876         },
877         set_selected: function(selected){
878             if(this.selected !== selected){
879                 this.selected = selected;
880                 this.trigger('change:selected',this);
881             }
882         },
883         // returns the associated cashregister
884         //exports as JSON for server communication
885         export_as_JSON: function(){
886             return {
887                 name: instance.web.datetime_to_str(new Date()),
888                 statement_id: this.cashregister.id,
889                 account_id: this.cashregister.account_id[0],
890                 journal_id: this.cashregister.journal_id[0],
891                 amount: this.get_amount()
892             };
893         },
894         //exports as JSON for receipt printing
895         export_for_printing: function(){
896             return {
897                 amount: this.get_amount(),
898                 journal: this.cashregister.journal_id[1],
899             };
900         },
901     });
902
903     module.PaymentlineCollection = Backbone.Collection.extend({
904         model: module.Paymentline,
905     });
906     
907
908     // An order more or less represents the content of a client's shopping cart (the OrderLines) 
909     // plus the associated payment information (the Paymentlines) 
910     // there is always an active ('selected') order in the Pos, a new one is created
911     // automaticaly once an order is completed and sent to the server.
912     module.Order = Backbone.Model.extend({
913         initialize: function(attributes){
914             Backbone.Model.prototype.initialize.apply(this, arguments);
915             this.pos = attributes.pos; 
916             this.sequence_number = this.pos.pos_session.sequence_number++;
917             this.uid =     this.generateUniqueId();
918             this.set({
919                 creationDate:   new Date(),
920                 orderLines:     new module.OrderlineCollection(),
921                 paymentLines:   new module.PaymentlineCollection(),
922                 name:           _t("Order ") + this.uid,
923                 client:         null,
924             });
925             this.selected_orderline   = undefined;
926             this.selected_paymentline = undefined;
927             this.screen_data = {};  // see ScreenSelector
928             this.receipt_type = 'receipt';  // 'receipt' || 'invoice'
929             this.temporary = attributes.temporary || false;
930             this.to_invoice = false;
931             return this;
932         },
933         is_empty: function(){
934             return (this.get('orderLines').models.length === 0);
935         },
936         // Generates a public identification number for the order.
937         // The generated number must be unique and sequential. They are made 12 digit long
938         // to fit into EAN-13 barcodes, should it be needed 
939         generateUniqueId: function() {
940             function zero_pad(num,size){
941                 var s = ""+num;
942                 while (s.length < size) {
943                     s = "0" + s;
944                 }
945                 return s;
946             }
947             return zero_pad(this.pos.pos_session.id,5) +'-'+
948                    zero_pad(this.pos.pos_session.login_number,3) +'-'+
949                    zero_pad(this.sequence_number,4);
950         },
951         addOrderline: function(line){
952             if(line.order){
953                 order.removeOrderline(line);
954             }
955             line.order = this;
956             this.get('orderLines').add(line);
957             this.selectLine(this.getLastOrderline());
958         },
959         addProduct: function(product, options){
960             options = options || {};
961             var attr = JSON.parse(JSON.stringify(product));
962             attr.pos = this.pos;
963             attr.order = this;
964             var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
965
966             if(options.quantity !== undefined){
967                 line.set_quantity(options.quantity);
968             }
969             if(options.price !== undefined){
970                 line.set_unit_price(options.price);
971             }
972             if(options.discount !== undefined){
973                 line.set_discount(options.discount);
974             }
975
976             var last_orderline = this.getLastOrderline();
977             if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
978                 last_orderline.merge(line);
979             }else{
980                 this.get('orderLines').add(line);
981             }
982             this.selectLine(this.getLastOrderline());
983         },
984         removeOrderline: function( line ){
985             this.get('orderLines').remove(line);
986             this.selectLine(this.getLastOrderline());
987         },
988         getOrderline: function(id){
989             var orderlines = this.get('orderLines').models;
990             for(var i = 0; i < orderlines.length; i++){
991                 if(orderlines[i].id === id){
992                     return orderlines[i];
993                 }
994             }
995             return null;
996         },
997         getLastOrderline: function(){
998             return this.get('orderLines').at(this.get('orderLines').length -1);
999         },
1000         addPaymentline: function(cashregister) {
1001             var paymentLines = this.get('paymentLines');
1002             var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
1003             if(cashregister.journal.type !== 'cash'){
1004                 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
1005             }
1006             paymentLines.add(newPaymentline);
1007             this.selectPaymentline(newPaymentline);
1008
1009         },
1010         removePaymentline: function(line){
1011             if(this.selected_paymentline === line){
1012                 this.selectPaymentline(undefined);
1013             }
1014             this.get('paymentLines').remove(line);
1015         },
1016         getName: function() {
1017             return this.get('name');
1018         },
1019         getSubtotal : function(){
1020             return (this.get('orderLines')).reduce((function(sum, orderLine){
1021                 return sum + orderLine.get_display_price();
1022             }), 0);
1023         },
1024         getTotalTaxIncluded: function() {
1025             return (this.get('orderLines')).reduce((function(sum, orderLine) {
1026                 return sum + orderLine.get_price_with_tax();
1027             }), 0);
1028         },
1029         getDiscountTotal: function() {
1030             return (this.get('orderLines')).reduce((function(sum, orderLine) {
1031                 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1032             }), 0);
1033         },
1034         getTotalTaxExcluded: function() {
1035             return (this.get('orderLines')).reduce((function(sum, orderLine) {
1036                 return sum + orderLine.get_price_without_tax();
1037             }), 0);
1038         },
1039         getTax: function() {
1040             return (this.get('orderLines')).reduce((function(sum, orderLine) {
1041                 return sum + orderLine.get_tax();
1042             }), 0);
1043         },
1044         getTaxDetails: function(){
1045             var details = {};
1046             var fulldetails = [];
1047             var taxes_by_id = {};
1048             
1049             for(var i = 0; i < this.pos.taxes.length; i++){
1050                 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1051             }
1052
1053             this.get('orderLines').each(function(line){
1054                 var ldetails = line.get_tax_details();
1055                 for(var id in ldetails){
1056                     if(ldetails.hasOwnProperty(id)){
1057                         details[id] = (details[id] || 0) + ldetails[id];
1058                     }
1059                 }
1060             });
1061             
1062             for(var id in details){
1063                 if(details.hasOwnProperty(id)){
1064                     fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1065                 }
1066             }
1067
1068             return fulldetails;
1069         },
1070         getPaidTotal: function() {
1071             return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
1072                 return sum + paymentLine.get_amount();
1073             }), 0);
1074         },
1075         getChange: function(paymentline) {
1076             if (!paymentline) {
1077                 var change = this.getPaidTotal() - this.getTotalTaxIncluded();
1078             } else {
1079                 var change = -this.getTotalTaxIncluded(); 
1080                 var lines  = this.get('paymentLines').models;
1081                 for (var i = 0; i < lines.length; i++) {
1082                     change += lines[i].get_amount();
1083                     if (lines[i] === paymentline) {
1084                         break;
1085                     }
1086                 }
1087             }
1088             return round_pr(Math.max(0,change), this.pos.currency.rounding);
1089         },
1090         getDueLeft: function(paymentline) {
1091             if (!paymentline) {
1092                 var due = this.getTotalTaxIncluded() - this.getPaidTotal();
1093             } else {
1094                 var due = this.getTotalTaxIncluded();
1095                 var lines = this.get('paymentLines').models;
1096                 for (var i = 0; i < lines.length; i++) {
1097                     if (lines[i] === paymentline) {
1098                         break;
1099                     } else {
1100                         due -= lines[i].get_amount();
1101                     }
1102                 }
1103             }
1104             return round_pr(Math.max(0,due), this.pos.currency.rounding);
1105         },
1106         isPaid: function(){
1107             return this.getDueLeft() === 0;
1108         },
1109         isPaidWithCash: function(){
1110             return !!this.get('paymentLines').find( function(pl){
1111                 return pl.cashregister.journal.type === 'cash';
1112             });
1113         },
1114         finalize: function(){
1115             this.destroy();
1116         },
1117         // sets the type of receipt 'receipt'(default) or 'invoice'
1118         set_receipt_type: function(type){
1119             this.receipt_type = type;
1120         },
1121         get_receipt_type: function(){
1122             return this.receipt_type;
1123         },
1124         // the client related to the current order.
1125         set_client: function(client){
1126             this.set('client',client);
1127         },
1128         get_client: function(){
1129             return this.get('client');
1130         },
1131         get_client_name: function(){
1132             var client = this.get('client');
1133             return client ? client.name : "";
1134         },
1135         // the order also stores the screen status, as the PoS supports
1136         // different active screens per order. This method is used to
1137         // store the screen status.
1138         set_screen_data: function(key,value){
1139             if(arguments.length === 2){
1140                 this.screen_data[key] = value;
1141             }else if(arguments.length === 1){
1142                 for(key in arguments[0]){
1143                     this.screen_data[key] = arguments[0][key];
1144                 }
1145             }
1146         },
1147         set_to_invoice: function(to_invoice) {
1148             this.to_invoice = to_invoice;
1149         },
1150         is_to_invoice: function(){
1151             return this.to_invoice;
1152         },
1153         // remove all the paymentlines with zero money in it
1154         clean_empty_paymentlines: function() {
1155             var lines = this.get('paymentLines').models;
1156             var empty = [];
1157             for ( var i = 0; i < lines.length; i++) {
1158                 if (!lines[i].get_amount()) {
1159                     empty.push(lines[i]);
1160                 }
1161             }
1162             for ( var i = 0; i < empty.length; i++) {
1163                 this.removePaymentline(empty[i]);
1164             }
1165         },
1166         //see set_screen_data
1167         get_screen_data: function(key){
1168             return this.screen_data[key];
1169         },
1170         // exports a JSON for receipt printing
1171         export_for_printing: function(){
1172             var orderlines = [];
1173             this.get('orderLines').each(function(orderline){
1174                 orderlines.push(orderline.export_for_printing());
1175             });
1176
1177             var paymentlines = [];
1178             this.get('paymentLines').each(function(paymentline){
1179                 paymentlines.push(paymentline.export_for_printing());
1180             });
1181             var client  = this.get('client');
1182             var cashier = this.pos.cashier || this.pos.user;
1183             var company = this.pos.company;
1184             var shop    = this.pos.shop;
1185             var date = new Date();
1186
1187             return {
1188                 orderlines: orderlines,
1189                 paymentlines: paymentlines,
1190                 subtotal: this.getSubtotal(),
1191                 total_with_tax: this.getTotalTaxIncluded(),
1192                 total_without_tax: this.getTotalTaxExcluded(),
1193                 total_tax: this.getTax(),
1194                 total_paid: this.getPaidTotal(),
1195                 total_discount: this.getDiscountTotal(),
1196                 tax_details: this.getTaxDetails(),
1197                 change: this.getChange(),
1198                 name : this.getName(),
1199                 client: client ? client.name : null ,
1200                 invoice_id: null,   //TODO
1201                 cashier: cashier ? cashier.name : null,
1202                 header: this.pos.config.receipt_header || '',
1203                 footer: this.pos.config.receipt_footer || '',
1204                 precision: {
1205                     price: 2,
1206                     money: 2,
1207                     quantity: 3,
1208                 },
1209                 date: { 
1210                     year: date.getFullYear(), 
1211                     month: date.getMonth(), 
1212                     date: date.getDate(),       // day of the month 
1213                     day: date.getDay(),         // day of the week 
1214                     hour: date.getHours(), 
1215                     minute: date.getMinutes() ,
1216                     isostring: date.toISOString(),
1217                     localestring: date.toLocaleString(),
1218                 }, 
1219                 company:{
1220                     email: company.email,
1221                     website: company.website,
1222                     company_registry: company.company_registry,
1223                     contact_address: company.partner_id[1], 
1224                     vat: company.vat,
1225                     name: company.name,
1226                     phone: company.phone,
1227                     logo:  this.pos.company_logo_base64,
1228                 },
1229                 shop:{
1230                     name: shop.name,
1231                 },
1232                 currency: this.pos.currency,
1233             };
1234         },
1235         export_as_JSON: function() {
1236             var orderLines, paymentLines;
1237             orderLines = [];
1238             (this.get('orderLines')).each(_.bind( function(item) {
1239                 return orderLines.push([0, 0, item.export_as_JSON()]);
1240             }, this));
1241             paymentLines = [];
1242             (this.get('paymentLines')).each(_.bind( function(item) {
1243                 return paymentLines.push([0, 0, item.export_as_JSON()]);
1244             }, this));
1245             return {
1246                 name: this.getName(),
1247                 amount_paid: this.getPaidTotal(),
1248                 amount_total: this.getTotalTaxIncluded(),
1249                 amount_tax: this.getTax(),
1250                 amount_return: this.getChange(),
1251                 lines: orderLines,
1252                 statement_ids: paymentLines,
1253                 pos_session_id: this.pos.pos_session.id,
1254                 partner_id: this.get_client() ? this.get_client().id : false,
1255                 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1256                 uid: this.uid,
1257                 sequence_number: this.sequence_number,
1258             };
1259         },
1260         getSelectedLine: function(){
1261             return this.selected_orderline;
1262         },
1263         selectLine: function(line){
1264             if(line){
1265                 if(line !== this.selected_orderline){
1266                     if(this.selected_orderline){
1267                         this.selected_orderline.set_selected(false);
1268                     }
1269                     this.selected_orderline = line;
1270                     this.selected_orderline.set_selected(true);
1271                 }
1272             }else{
1273                 this.selected_orderline = undefined;
1274             }
1275         },
1276         deselectLine: function(){
1277             if(this.selected_orderline){
1278                 this.selected_orderline.set_selected(false);
1279                 this.selected_orderline = undefined;
1280             }
1281         },
1282         selectPaymentline: function(line){
1283             if(line !== this.selected_paymentline){
1284                 if(this.selected_paymentline){
1285                     this.selected_paymentline.set_selected(false);
1286                 }
1287                 this.selected_paymentline = line;
1288                 if(this.selected_paymentline){
1289                     this.selected_paymentline.set_selected(true);
1290                 }
1291                 this.trigger('change:selected_paymentline',this.selected_paymentline);
1292             }
1293         },
1294     });
1295
1296     module.OrderCollection = Backbone.Collection.extend({
1297         model: module.Order,
1298     });
1299
1300     /*
1301      The numpad handles both the choice of the property currently being modified
1302      (quantity, price or discount) and the edition of the corresponding numeric value.
1303      */
1304     module.NumpadState = Backbone.Model.extend({
1305         defaults: {
1306             buffer: "0",
1307             mode: "quantity"
1308         },
1309         appendNewChar: function(newChar) {
1310             var oldBuffer;
1311             oldBuffer = this.get('buffer');
1312             if (oldBuffer === '0') {
1313                 this.set({
1314                     buffer: newChar
1315                 });
1316             } else if (oldBuffer === '-0') {
1317                 this.set({
1318                     buffer: "-" + newChar
1319                 });
1320             } else {
1321                 this.set({
1322                     buffer: (this.get('buffer')) + newChar
1323                 });
1324             }
1325             this.trigger('set_value',this.get('buffer'));
1326         },
1327         deleteLastChar: function() {
1328             if(this.get('buffer') === ""){
1329                 if(this.get('mode') === 'quantity'){
1330                     this.trigger('set_value','remove');
1331                 }else{
1332                     this.trigger('set_value',this.get('buffer'));
1333                 }
1334             }else{
1335                 var newBuffer = this.get('buffer').slice(0,-1) || "";
1336                 this.set({ buffer: newBuffer });
1337                 this.trigger('set_value',this.get('buffer'));
1338             }
1339         },
1340         switchSign: function() {
1341             var oldBuffer;
1342             oldBuffer = this.get('buffer');
1343             this.set({
1344                 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer 
1345             });
1346             this.trigger('set_value',this.get('buffer'));
1347         },
1348         changeMode: function(newMode) {
1349             this.set({
1350                 buffer: "0",
1351                 mode: newMode
1352             });
1353         },
1354         reset: function() {
1355             this.set({
1356                 buffer: "0",
1357                 mode: "quantity"
1358             });
1359         },
1360         resetValue: function(){
1361             this.set({buffer:'0'});
1362         },
1363     });
1364 }