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