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