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