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