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