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