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