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