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