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