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