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