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