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