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