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