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