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