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