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