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