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