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