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