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