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