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