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