[FIX] point_of_sale: order invoicing was broken
[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_tmpl_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
328             if(order){
329                 this.proxy.log('push_order',order.export_as_JSON());
330                 this.db.add_order(order.export_as_JSON());
331             }
332             
333             var pushed = new $.Deferred();
334
335             this.flush_mutex.exec(function(){
336                 var flushed = self._flush_orders(self.db.get_orders());
337
338                 flushed.always(function(ids){
339                     console.log('pushed orders:',ids);
340                     pushed.resolve();
341                 });
342             });
343             return pushed;
344         },
345
346         // saves the order locally and try to send it to the backend and make an invoice
347         // returns a deferred that succeeds when the order has been posted and successfully generated
348         // an invoice. This method can fail in various ways:
349         // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
350         //     this error is solved
351         // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
352         //     the network connection is up 
353
354         push_and_invoice_order: function(order){
355             var self = this;
356             var invoiced = new $.Deferred(); 
357
358             if(!order.get_client()){
359                 invoiced.reject('error-no-client');
360                 return invoiced;
361             }
362
363             var order_id = this.db.add_order(order.export_as_JSON());
364
365             this.flush_mutex.exec(function(){
366                 var done = new $.Deferred(); // holds the mutex
367
368                 // send the order to the server
369                 // we have a 30 seconds timeout on this push.
370                 // FIXME: if the server takes more than 30 seconds to accept the order,
371                 // the client will believe it wasn't successfully sent, and very bad
372                 // things will happen as a duplicate will be sent next time
373                 // so we must make sure the server detects and ignores duplicated orders
374
375                 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
376                 
377                 transfer.fail(function(){
378                     invoiced.reject('error-transfer');
379                     done.reject();
380                 });
381
382                 // on success, get the order id generated by the server
383                 transfer.pipe(function(order_server_id){    
384
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
390                     invoiced.resolve();
391                     done.resolve();
392                 });
393
394                 return done;
395
396             });
397
398             return invoiced;
399         },
400
401         // wrapper around the _save_to_server that updates the synch status widget
402         _flush_orders: function(orders, options) {
403             var self = this;
404
405             this.set('synch',{ state: 'connecting', pending: orders.length});
406
407             return self._save_to_server(orders, options).done(function (server_ids) {
408                 var pending = self.db.get_orders().length;
409
410                 self.set('synch', {
411                     state: pending ? 'connecting' : 'connected',
412                     pending: pending
413                 });
414
415                 return server_ids;
416             });
417         },
418
419         // send an array of orders to the server
420         // available options:
421         // - timeout: timeout for the rpc call in ms
422         // returns a deferred that resolves with the list of
423         // server generated ids for the sent orders
424         _save_to_server: function (orders, options) {
425             if (!orders || !orders.length) {
426                 var result = $.Deferred();
427                 result.resolve([]);
428                 return result;
429             }
430                 
431             options = options || {};
432
433             var self = this;
434             var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
435
436             // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
437             // then we want to notify the user that we are waiting on something )
438             var posOrderModel = new instance.web.Model('pos.order');
439             return posOrderModel.call('create_from_ui',
440                 [_.map(orders, function (order) {
441                     order.to_invoice = options.to_invoice || false;
442                     return order;
443                 })],
444                 undefined,
445                 {
446                     shadow: !options.to_invoice,
447                     timeout: timeout
448                 }
449             ).then(function (server_ids) {
450                 _.each(orders, function (order) {
451                     self.db.remove_order(order.id);
452                 });
453                 return server_ids;
454             }).fail(function (unused, event){
455                 // prevent an error popup creation by the rpc failure
456                 // we want the failure to be silent as we send the orders in the background
457                 event.preventDefault();
458                 console.error('Failed to send orders:', orders);
459             });
460         },
461
462         scan_product: function(parsed_code){
463             var self = this;
464             var selectedOrder = this.get('selectedOrder');
465             if(parsed_code.encoding === 'ean13'){
466                 var product = this.db.get_product_by_ean13(parsed_code.base_code);
467             }else if(parsed_code.encoding === 'reference'){
468                 var product = this.db.get_product_by_reference(parsed_code.code);
469             }
470
471             if(!product){
472                 return false;
473             }
474
475             if(parsed_code.type === 'price'){
476                 selectedOrder.addProduct(product, {price:parsed_code.value});
477             }else if(parsed_code.type === 'weight'){
478                 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
479             }else if(parsed_code.type === 'discount'){
480                 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
481             }else{
482                 selectedOrder.addProduct(product);
483             }
484             return true;
485         },
486     });
487
488     var orderline_id = 1;
489
490     // An orderline represent one element of the content of a client's shopping cart.
491     // An orderline contains a product, its quantity, its price, discount. etc. 
492     // An Order contains zero or more Orderlines.
493     module.Orderline = Backbone.Model.extend({
494         initialize: function(attr,options){
495             this.pos = options.pos;
496             this.order = options.order;
497             this.product = options.product;
498             this.price   = options.product.price;
499             this.quantity = 1;
500             this.quantityStr = '1';
501             this.discount = 0;
502             this.discountStr = '0';
503             this.type = 'unit';
504             this.selected = false;
505             this.id       = orderline_id++; 
506         },
507         clone: function(){
508             var orderline = new module.Orderline({},{
509                 pos: this.pos,
510                 order: null,
511                 product: this.product,
512                 price: this.price,
513             });
514             orderline.quantity = this.quantity;
515             orderline.quantityStr = this.quantityStr;
516             orderline.discount = this.discount;
517             orderline.type = this.type;
518             orderline.selected = false;
519             return orderline;
520         },
521         // sets a discount [0,100]%
522         set_discount: function(discount){
523             var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
524             this.discount = disc;
525             this.discountStr = '' + disc;
526             this.trigger('change',this);
527         },
528         // returns the discount [0,100]%
529         get_discount: function(){
530             return this.discount;
531         },
532         get_discount_str: function(){
533             return this.discountStr;
534         },
535         get_product_type: function(){
536             return this.type;
537         },
538         // sets the quantity of the product. The quantity will be rounded according to the 
539         // product's unity of measure properties. Quantities greater than zero will not get 
540         // rounded to zero
541         set_quantity: function(quantity){
542             if(quantity === 'remove'){
543                 this.order.removeOrderline(this);
544                 return;
545             }else{
546                 var quant = parseFloat(quantity) || 0;
547                 var unit = this.get_unit();
548                 if(unit){
549                     this.quantity    = round_pr(quant, unit.rounding);
550                     this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
551                 }else{
552                     this.quantity    = quant;
553                     this.quantityStr = '' + this.quantity;
554                 }
555             }
556             this.trigger('change',this);
557         },
558         // return the quantity of product
559         get_quantity: function(){
560             return this.quantity;
561         },
562         get_quantity_str: function(){
563             return this.quantityStr;
564         },
565         get_quantity_str_with_unit: function(){
566             var unit = this.get_unit();
567             if(unit && !unit.is_unit){
568                 return this.quantityStr + ' ' + unit.name;
569             }else{
570                 return this.quantityStr;
571             }
572         },
573         // return the unit of measure of the product
574         get_unit: function(){
575             var unit_id = (this.product.uos_id || this.product.uom_id);
576             if(!unit_id){
577                 return undefined;
578             }
579             unit_id = unit_id[0];
580             if(!this.pos){
581                 return undefined;
582             }
583             return this.pos.units_by_id[unit_id];
584         },
585         // return the product of this orderline
586         get_product: function(){
587             return this.product;
588         },
589         // selects or deselects this orderline
590         set_selected: function(selected){
591             this.selected = selected;
592             this.trigger('change',this);
593         },
594         // returns true if this orderline is selected
595         is_selected: function(){
596             return this.selected;
597         },
598         // when we add an new orderline we want to merge it with the last line to see reduce the number of items
599         // in the orderline. This returns true if it makes sense to merge the two
600         can_be_merged_with: function(orderline){
601             if( this.get_product().id !== orderline.get_product().id){    //only orderline of the same product can be merged
602                 return false;
603             }else if(!this.get_unit() || !this.get_unit().groupable){
604                 return false;
605             }else if(this.get_product_type() !== orderline.get_product_type()){
606                 return false;
607             }else if(this.get_discount() > 0){             // we don't merge discounted orderlines
608                 return false;
609             }else if(this.price !== orderline.price){
610                 return false;
611             }else{ 
612                 return true;
613             }
614         },
615         merge: function(orderline){
616             this.set_quantity(this.get_quantity() + orderline.get_quantity());
617         },
618         export_as_JSON: function() {
619             return {
620                 qty: this.get_quantity(),
621                 price_unit: this.get_unit_price(),
622                 discount: this.get_discount(),
623                 product_id: this.get_product().id,
624             };
625         },
626         //used to create a json of the ticket, to be sent to the printer
627         export_for_printing: function(){
628             return {
629                 quantity:           this.get_quantity(),
630                 unit_name:          this.get_unit().name,
631                 price:              this.get_unit_price(),
632                 discount:           this.get_discount(),
633                 product_name:       this.get_product().name,
634                 price_display :     this.get_display_price(),
635                 price_with_tax :    this.get_price_with_tax(),
636                 price_without_tax:  this.get_price_without_tax(),
637                 tax:                this.get_tax(),
638                 product_description:      this.get_product().description,
639                 product_description_sale: this.get_product().description_sale,
640             };
641         },
642         // changes the base price of the product for this orderline
643         set_unit_price: function(price){
644             this.price = round_di(parseFloat(price) || 0, 2);
645             this.trigger('change',this);
646         },
647         get_unit_price: function(){
648             var rounding = this.pos.currency.rounding;
649             return round_pr(this.price,rounding);
650         },
651         get_display_price: function(){
652             var rounding = this.pos.currency.rounding;
653             return  round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
654         },
655         get_price_without_tax: function(){
656             return this.get_all_prices().priceWithoutTax;
657         },
658         get_price_with_tax: function(){
659             return this.get_all_prices().priceWithTax;
660         },
661         get_tax: function(){
662             return this.get_all_prices().tax;
663         },
664         get_tax_details: function(){
665             return this.get_all_prices().taxDetails;
666         },
667         get_all_prices: function(){
668             var self = this;
669             var currency_rounding = this.pos.currency.rounding;
670             var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
671             var totalTax = base;
672             var totalNoTax = base;
673             
674             var product =  this.get_product(); 
675             var taxes_ids = product.taxes_id;
676             var taxes =  self.pos.taxes;
677             var taxtotal = 0;
678             var taxdetail = {};
679             _.each(taxes_ids, function(el) {
680                 var tax = _.detect(taxes, function(t) {return t.id === el;});
681                 if (tax.price_include) {
682                     var tmp;
683                     if (tax.type === "percent") {
684                         tmp =  base - round_pr(base / (1 + tax.amount),currency_rounding); 
685                     } else if (tax.type === "fixed") {
686                         tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
687                     } else {
688                         throw "This type of tax is not supported by the point of sale: " + tax.type;
689                     }
690                     tmp = round_pr(tmp,currency_rounding);
691                     taxtotal += tmp;
692                     totalNoTax -= tmp;
693                     taxdetail[tax.id] = tmp;
694                 } else {
695                     var tmp;
696                     if (tax.type === "percent") {
697                         tmp = tax.amount * base;
698                     } else if (tax.type === "fixed") {
699                         tmp = tax.amount * self.get_quantity();
700                     } else {
701                         throw "This type of tax is not supported by the point of sale: " + tax.type;
702                     }
703                     tmp = round_pr(tmp,currency_rounding);
704                     taxtotal += tmp;
705                     totalTax += tmp;
706                     taxdetail[tax.id] = tmp;
707                 }
708             });
709             return {
710                 "priceWithTax": totalTax,
711                 "priceWithoutTax": totalNoTax,
712                 "tax": taxtotal,
713                 "taxDetails": taxdetail,
714             };
715         },
716     });
717
718     module.OrderlineCollection = Backbone.Collection.extend({
719         model: module.Orderline,
720     });
721
722     // Every Paymentline contains a cashregister and an amount of money.
723     module.Paymentline = Backbone.Model.extend({
724         initialize: function(attributes, options) {
725             this.amount = 0;
726             this.cashregister = options.cashregister;
727             this.name = this.cashregister.journal_id[1];
728             this.selected = false;
729         },
730         //sets the amount of money on this payment line
731         set_amount: function(value){
732             this.amount = round_di(parseFloat(value) || 0, 2);
733             this.trigger('change:amount',this);
734         },
735         // returns the amount of money on this paymentline
736         get_amount: function(){
737             return this.amount;
738         },
739         set_selected: function(selected){
740             if(this.selected !== selected){
741                 this.selected = selected;
742                 this.trigger('change:selected',this);
743             }
744         },
745         // returns the associated cashregister
746         //exports as JSON for server communication
747         export_as_JSON: function(){
748             return {
749                 name: instance.web.datetime_to_str(new Date()),
750                 statement_id: this.cashregister.id,
751                 account_id: this.cashregister.account_id[0],
752                 journal_id: this.cashregister.journal_id[0],
753                 amount: this.get_amount()
754             };
755         },
756         //exports as JSON for receipt printing
757         export_for_printing: function(){
758             return {
759                 amount: this.get_amount(),
760                 journal: this.cashregister.journal_id[1],
761             };
762         },
763     });
764
765     module.PaymentlineCollection = Backbone.Collection.extend({
766         model: module.Paymentline,
767     });
768     
769
770     // An order more or less represents the content of a client's shopping cart (the OrderLines) 
771     // plus the associated payment information (the Paymentlines) 
772     // there is always an active ('selected') order in the Pos, a new one is created
773     // automaticaly once an order is completed and sent to the server.
774     module.Order = Backbone.Model.extend({
775         initialize: function(attributes){
776             Backbone.Model.prototype.initialize.apply(this, arguments);
777             this.uid =     this.generateUniqueId();
778             this.set({
779                 creationDate:   new Date(),
780                 orderLines:     new module.OrderlineCollection(),
781                 paymentLines:   new module.PaymentlineCollection(),
782                 name:           "Order " + this.uid,
783                 client:         null,
784             });
785             this.pos = attributes.pos; 
786             this.selected_orderline   = undefined;
787             this.selected_paymentline = undefined;
788             this.screen_data = {};  // see ScreenSelector
789             this.receipt_type = 'receipt';  // 'receipt' || 'invoice'
790             this.temporary = attributes.temporary || false;
791             this.sequence_number = this.pos.pos_session.sequence_number++;
792             return this;
793         },
794         is_empty: function(){
795             return (this.get('orderLines').models.length === 0);
796         },
797         generateUniqueId: function() {
798             return new Date().getTime();
799         },
800         addOrderline: function(line){
801             if(line.order){
802                 order.removeOrderline(line);
803             }
804             line.order = this;
805             this.get('orderLines').add(line);
806             this.selectLine(this.getLastOrderline());
807         },
808         addProduct: function(product, options){
809             options = options || {};
810             var attr = JSON.parse(JSON.stringify(product));
811             attr.pos = this.pos;
812             attr.order = this;
813             var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
814
815             if(options.quantity !== undefined){
816                 line.set_quantity(options.quantity);
817             }
818             if(options.price !== undefined){
819                 line.set_unit_price(options.price);
820             }
821             if(options.discount !== undefined){
822                 line.set_discount(options.discount);
823             }
824
825             var last_orderline = this.getLastOrderline();
826             if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
827                 last_orderline.merge(line);
828             }else{
829                 this.get('orderLines').add(line);
830             }
831             this.selectLine(this.getLastOrderline());
832         },
833         removeOrderline: function( line ){
834             this.get('orderLines').remove(line);
835             this.selectLine(this.getLastOrderline());
836         },
837         getOrderline: function(id){
838             var orderlines = this.get('orderLines').models;
839             for(var i = 0; i < orderlines.length; i++){
840                 if(orderlines[i].id === id){
841                     return orderlines[i];
842                 }
843             }
844             return null;
845         },
846         getLastOrderline: function(){
847             return this.get('orderLines').at(this.get('orderLines').length -1);
848         },
849         addPaymentline: function(cashregister) {
850             var paymentLines = this.get('paymentLines');
851             var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
852             if(cashregister.journal.type !== 'cash'){
853                 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
854             }
855             paymentLines.add(newPaymentline);
856             this.selectPaymentline(newPaymentline);
857
858         },
859         removePaymentline: function(line){
860             if(this.selected_paymentline === line){
861                 this.selectPaymentline(undefined);
862             }
863             this.get('paymentLines').remove(line);
864         },
865         getName: function() {
866             return this.get('name');
867         },
868         getSubtotal : function(){
869             return (this.get('orderLines')).reduce((function(sum, orderLine){
870                 return sum + orderLine.get_display_price();
871             }), 0);
872         },
873         getTotalTaxIncluded: function() {
874             return (this.get('orderLines')).reduce((function(sum, orderLine) {
875                 return sum + orderLine.get_price_with_tax();
876             }), 0);
877         },
878         getDiscountTotal: function() {
879             return (this.get('orderLines')).reduce((function(sum, orderLine) {
880                 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
881             }), 0);
882         },
883         getTotalTaxExcluded: function() {
884             return (this.get('orderLines')).reduce((function(sum, orderLine) {
885                 return sum + orderLine.get_price_without_tax();
886             }), 0);
887         },
888         getTax: function() {
889             return (this.get('orderLines')).reduce((function(sum, orderLine) {
890                 return sum + orderLine.get_tax();
891             }), 0);
892         },
893         getTaxDetails: function(){
894             var details = {};
895             var fulldetails = [];
896             var taxes_by_id = {};
897             
898             for(var i = 0; i < this.pos.taxes.length; i++){
899                 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
900             }
901
902             this.get('orderLines').each(function(line){
903                 var ldetails = line.get_tax_details();
904                 for(var id in ldetails){
905                     if(ldetails.hasOwnProperty(id)){
906                         details[id] = (details[id] || 0) + ldetails[id];
907                     }
908                 }
909             });
910             
911             for(var id in details){
912                 if(details.hasOwnProperty(id)){
913                     fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
914                 }
915             }
916
917             return fulldetails;
918         },
919         getPaidTotal: function() {
920             return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
921                 return sum + paymentLine.get_amount();
922             }), 0);
923         },
924         getChange: function() {
925             return this.getPaidTotal() - this.getTotalTaxIncluded();
926         },
927         getDueLeft: function() {
928             return this.getTotalTaxIncluded() - this.getPaidTotal();
929         },
930         // sets the type of receipt 'receipt'(default) or 'invoice'
931         set_receipt_type: function(type){
932             this.receipt_type = type;
933         },
934         get_receipt_type: function(){
935             return this.receipt_type;
936         },
937         // the client related to the current order.
938         set_client: function(client){
939             this.set('client',client);
940         },
941         get_client: function(){
942             return this.get('client');
943         },
944         get_client_name: function(){
945             var client = this.get('client');
946             return client ? client.name : "";
947         },
948         // the order also stores the screen status, as the PoS supports
949         // different active screens per order. This method is used to
950         // store the screen status.
951         set_screen_data: function(key,value){
952             if(arguments.length === 2){
953                 this.screen_data[key] = value;
954             }else if(arguments.length === 1){
955                 for(key in arguments[0]){
956                     this.screen_data[key] = arguments[0][key];
957                 }
958             }
959         },
960         //see set_screen_data
961         get_screen_data: function(key){
962             return this.screen_data[key];
963         },
964         // exports a JSON for receipt printing
965         export_for_printing: function(){
966             var orderlines = [];
967             this.get('orderLines').each(function(orderline){
968                 orderlines.push(orderline.export_for_printing());
969             });
970
971             var paymentlines = [];
972             this.get('paymentLines').each(function(paymentline){
973                 paymentlines.push(paymentline.export_for_printing());
974             });
975             var client  = this.get('client');
976             var cashier = this.pos.cashier || this.pos.user;
977             var company = this.pos.company;
978             var shop    = this.pos.shop;
979             var date = new Date();
980
981             return {
982                 orderlines: orderlines,
983                 paymentlines: paymentlines,
984                 subtotal: this.getSubtotal(),
985                 total_with_tax: this.getTotalTaxIncluded(),
986                 total_without_tax: this.getTotalTaxExcluded(),
987                 total_tax: this.getTax(),
988                 total_paid: this.getPaidTotal(),
989                 total_discount: this.getDiscountTotal(),
990                 tax_details: this.getTaxDetails(),
991                 change: this.getChange(),
992                 name : this.getName(),
993                 client: client ? client.name : null ,
994                 invoice_id: null,   //TODO
995                 cashier: cashier ? cashier.name : null,
996                 header: this.pos.config.receipt_header || '',
997                 footer: this.pos.config.receipt_footer || '',
998                 precision: {
999                     price: 2,
1000                     money: 2,
1001                     quantity: 3,
1002                 },
1003                 date: { 
1004                     year: date.getFullYear(), 
1005                     month: date.getMonth(), 
1006                     date: date.getDate(),       // day of the month 
1007                     day: date.getDay(),         // day of the week 
1008                     hour: date.getHours(), 
1009                     minute: date.getMinutes() ,
1010                     isostring: date.toISOString(),
1011                     localestring: date.toLocaleString(),
1012                 }, 
1013                 company:{
1014                     email: company.email,
1015                     website: company.website,
1016                     company_registry: company.company_registry,
1017                     contact_address: company.partner_id[1], 
1018                     vat: company.vat,
1019                     name: company.name,
1020                     phone: company.phone,
1021                     logo:  this.pos.company_logo_base64,
1022                 },
1023                 shop:{
1024                     name: shop.name,
1025                 },
1026                 currency: this.pos.currency,
1027             };
1028         },
1029         export_as_JSON: function() {
1030             var orderLines, paymentLines;
1031             orderLines = [];
1032             (this.get('orderLines')).each(_.bind( function(item) {
1033                 return orderLines.push([0, 0, item.export_as_JSON()]);
1034             }, this));
1035             paymentLines = [];
1036             (this.get('paymentLines')).each(_.bind( function(item) {
1037                 return paymentLines.push([0, 0, item.export_as_JSON()]);
1038             }, this));
1039             return {
1040                 name: this.getName(),
1041                 amount_paid: this.getPaidTotal(),
1042                 amount_total: this.getTotalTaxIncluded(),
1043                 amount_tax: this.getTax(),
1044                 amount_return: this.getChange(),
1045                 lines: orderLines,
1046                 statement_ids: paymentLines,
1047                 pos_session_id: this.pos.pos_session.id,
1048                 partner_id: this.get_client() ? this.get_client().id : false,
1049                 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1050                 uid: this.uid,
1051                 sequence_number: this.sequence_number,
1052             };
1053         },
1054         getSelectedLine: function(){
1055             return this.selected_orderline;
1056         },
1057         selectLine: function(line){
1058             if(line){
1059                 if(line !== this.selected_orderline){
1060                     if(this.selected_orderline){
1061                         this.selected_orderline.set_selected(false);
1062                     }
1063                     this.selected_orderline = line;
1064                     this.selected_orderline.set_selected(true);
1065                 }
1066             }else{
1067                 this.selected_orderline = undefined;
1068             }
1069         },
1070         deselectLine: function(){
1071             if(this.selected_orderline){
1072                 this.selected_orderline.set_selected(false);
1073                 this.selected_orderline = undefined;
1074             }
1075         },
1076         selectPaymentline: function(line){
1077             if(line !== this.selected_paymentline){
1078                 if(this.selected_paymentline){
1079                     this.selected_paymentline.set_selected(false);
1080                 }
1081                 this.selected_paymentline = line;
1082                 if(this.selected_paymentline){
1083                     this.selected_paymentline.set_selected(true);
1084                 }
1085                 this.trigger('change:selected_paymentline',this.selected_paymentline);
1086             }
1087         },
1088     });
1089
1090     module.OrderCollection = Backbone.Collection.extend({
1091         model: module.Order,
1092     });
1093
1094     /*
1095      The numpad handles both the choice of the property currently being modified
1096      (quantity, price or discount) and the edition of the corresponding numeric value.
1097      */
1098     module.NumpadState = Backbone.Model.extend({
1099         defaults: {
1100             buffer: "0",
1101             mode: "quantity"
1102         },
1103         appendNewChar: function(newChar) {
1104             var oldBuffer;
1105             oldBuffer = this.get('buffer');
1106             if (oldBuffer === '0') {
1107                 this.set({
1108                     buffer: newChar
1109                 });
1110             } else if (oldBuffer === '-0') {
1111                 this.set({
1112                     buffer: "-" + newChar
1113                 });
1114             } else {
1115                 this.set({
1116                     buffer: (this.get('buffer')) + newChar
1117                 });
1118             }
1119             this.trigger('set_value',this.get('buffer'));
1120         },
1121         deleteLastChar: function() {
1122             if(this.get('buffer') === ""){
1123                 if(this.get('mode') === 'quantity'){
1124                     this.trigger('set_value','remove');
1125                 }else{
1126                     this.trigger('set_value',this.get('buffer'));
1127                 }
1128             }else{
1129                 var newBuffer = this.get('buffer').slice(0,-1) || "";
1130                 this.set({ buffer: newBuffer });
1131                 this.trigger('set_value',this.get('buffer'));
1132             }
1133         },
1134         switchSign: function() {
1135             var oldBuffer;
1136             oldBuffer = this.get('buffer');
1137             this.set({
1138                 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer 
1139             });
1140             this.trigger('set_value',this.get('buffer'));
1141         },
1142         changeMode: function(newMode) {
1143             this.set({
1144                 buffer: "0",
1145                 mode: newMode
1146             });
1147         },
1148         reset: function() {
1149             this.set({
1150                 buffer: "0",
1151                 mode: "quantity"
1152             });
1153         },
1154         resetValue: function(){
1155             this.set({buffer:'0'});
1156         },
1157     });
1158 }