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