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