1 function openerp_pos_models(instance, module){ //module is instance.point_of_sale
4 var QWeb = instance.web.qweb;
5 var _t = instance.web._t;
7 var round_di = instance.web.round_decimals;
8 var round_pr = instance.web.round_precision
10 // The PosModel contains the Point Of Sale's representation of the backend.
11 // Since the PoS must work in standalone ( Without connection to the server )
12 // it must contains a representation of the server's PoS backend.
13 // (taxes, product list, configuration options, etc.) this representation
14 // is fetched and stored by the PosModel at the initialisation.
15 // this is done asynchronously, a ready deferred alows the GUI to wait interactively
16 // for the loading to be completed
17 // There is a single instance of the PosModel for each Front-End instance, it is usually called
18 // 'pos' and is available to all widgets extending PosWidget.
20 module.PosModel = Backbone.Model.extend({
21 initialize: function(session, attributes) {
22 Backbone.Model.prototype.initialize.call(this, attributes);
24 this.session = session;
25 this.flush_mutex = new $.Mutex(); // used to make sure the orders are sent to the server once at time
26 this.pos_widget = attributes.pos_widget;
28 this.proxy = new module.ProxyDevice(this); // used to communicate to the hardware devices via a local proxy
29 this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy, patterns: {}}); // used to read barcodes
30 this.proxy_queue = new module.JobQueue(); // used to prevent parallels communications to the proxy
31 this.db = new module.PosDB(); // a local database used to search trough products and categories & store pending orders
32 this.debug = jQuery.deparam(jQuery.param.querystring()).debug !== undefined; //debug mode
34 // Business data; loaded from the server at launch
35 this.accounting_precision = 2; //TODO
36 this.company_logo = null;
37 this.company_logo_base64 = '';
45 this.cashregisters = [];
46 this.bankstatements = [];
48 this.pos_session = null;
51 this.units_by_id = {};
52 this.pricelist = null;
53 this.order_sequence = 1;
54 window.posmodel = this;
56 // these dynamic attributes can be watched for change by other models or widgets
58 'synch': { state:'connected', pending:0 },
59 'orders': new module.OrderCollection(),
60 'selectedOrder': null,
63 this.bind('change:synch',function(pos,synch){
64 clearTimeout(self.synch_timeout);
65 self.synch_timeout = setTimeout(function(){
66 if(synch.state !== 'disconnected' && synch.pending > 0){
67 self.set('synch',{state:'disconnected', pending:synch.pending});
72 this.get('orders').bind('remove', function(order,_unused_,options){
73 self.on_removed_order(order,options.index,options.reason);
76 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
77 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
78 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
79 this.ready = this.load_server_data()
81 if(self.config.use_proxy){
82 return self.connect_to_proxy();
88 // releases ressources holds by the model at the end of life of the posmodel
90 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
93 this.barcode_reader.disconnect();
94 this.barcode_reader.disconnect_from_proxy();
96 connect_to_proxy: function(){
98 var done = new $.Deferred();
99 this.barcode_reader.disconnect_from_proxy();
100 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
101 this.pos_widget.loading_skip(function(){
102 self.proxy.stop_searching();
104 this.proxy.autoconnect({
105 force_ip: self.config.proxy_ip || undefined,
106 progress: function(prog){
107 self.pos_widget.loading_progress(prog);
110 if(self.config.iface_scan_via_proxy){
111 self.barcode_reader.connect_to_proxy();
113 }).always(function(){
119 // helper function to load data from the server. Obsolete use the models loader below.
120 fetch: function(model, fields, domain, ctx){
121 this._load_progress = (this._load_progress || 0) + 0.05;
122 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
123 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
126 // Server side model loaders. This is the list of the models that need to be loaded from
127 // the server. The models are loaded one by one by this list's order. The 'loaded' callback
128 // is used to store the data in the appropriate place once it has been loaded. This callback
129 // can return a deferred that will pause the loading of the next module.
130 // a shared temporary dictionary is available for loaders to communicate private variables
131 // used during loading such as object ids, etc.
135 fields: ['name','company_id'],
136 ids: function(self){ return [self.session.uid]; },
137 loaded: function(self,users){ self.user = users[0]; },
139 model: 'res.company',
140 fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id'],
141 ids: function(self){ return [self.user.company_id[0]] },
142 loaded: function(self,companies){ self.company = companies[0]; },
144 model: 'decimal.precision',
145 fields: ['name','digits'],
146 loaded: function(self,dps){
148 for (var i = 0; i < dps.length; i++) {
149 self.dp[dps[i].name] = dps[i].digits;
153 model: 'product.uom',
156 loaded: function(self,units){
158 var units_by_id = {};
159 for(var i = 0, len = units.length; i < len; i++){
160 units_by_id[units[i].id] = units[i];
161 units[i].groupable = ( units[i].category_id[0] === 1 );
162 units[i].is_unit = ( units[i].id === 1 );
164 self.units_by_id = units_by_id;
168 fields: ['name','ean13'],
170 loaded: function(self,users){ self.users = users; },
172 model: 'res.partner',
173 fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','ean13','write_date'],
175 loaded: function(self,partners){
176 self.partners = partners;
177 self.db.add_partners(partners);
180 model: 'res.country',
182 loaded: function(self,countries){
183 self.countries = countries;
184 self.company.country = null;
185 for (var i = 0; i < countries.length; i++) {
186 if (countries[i].id === self.company.country_id[0]){
187 self.company.country = countries[i];
192 model: 'account.tax',
193 fields: ['name','amount', 'price_include', 'type'],
195 loaded: function(self,taxes){ self.taxes = taxes; },
197 model: 'pos.session',
198 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
199 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
200 loaded: function(self,pos_sessions){
201 self.pos_session = pos_sessions[0];
203 var orders = self.db.get_orders();
204 for (var i = 0; i < orders.length; i++) {
205 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
211 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
212 loaded: function(self,configs){
213 self.config = configs[0];
214 self.config.use_proxy = self.config.iface_payment_terminal ||
215 self.config.iface_electronic_scale ||
216 self.config.iface_print_via_proxy ||
217 self.config.iface_scan_via_proxy ||
218 self.config.iface_cashdrawer;
220 self.barcode_reader.add_barcode_patterns({
221 'product': self.config.barcode_product,
222 'cashier': self.config.barcode_cashier,
223 'client': self.config.barcode_customer,
224 'weight': self.config.barcode_weight,
225 'discount': self.config.barcode_discount,
226 'price': self.config.barcode_price,
229 if (self.config.company_id[0] !== self.user.company_id[0]) {
230 throw new Error(_t("Error: The Point of Sale User must belong to the same company as the Point of Sale. You are probably trying to load the point of sale as an administrator in a multi-company setup, with the administrator account set to the wrong company."));
234 model: 'stock.location',
236 ids: function(self){ return [self.config.stock_location_id[0]]; },
237 loaded: function(self, locations){ self.shop = locations[0]; },
239 model: 'product.pricelist',
240 fields: ['currency_id'],
241 ids: function(self){ return [self.config.pricelist_id[0]]; },
242 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
244 model: 'res.currency',
245 fields: ['symbol','position','rounding','accuracy'],
246 ids: function(self){ return [self.pricelist.currency_id[0]]; },
247 loaded: function(self, currencies){
248 self.currency = currencies[0];
249 if (self.currency.rounding > 0) {
250 self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
252 self.currency.decimals = 0;
257 model: 'product.packaging',
258 fields: ['ean','product_tmpl_id'],
260 loaded: function(self, packagings){
261 self.db.add_packagings(packagings);
264 model: 'pos.category',
265 fields: ['id','name','parent_id','child_id','image'],
267 loaded: function(self, categories){
268 self.db.add_categories(categories);
271 model: 'product.product',
272 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
273 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
275 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
276 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
277 loaded: function(self, products){
278 self.db.add_products(products);
281 model: 'account.bank.statement',
282 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
283 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
284 loaded: function(self, bankstatements, tmp){
285 self.bankstatements = bankstatements;
288 _.each(bankstatements,function(statement){
289 tmp.journals.push(statement.journal_id[0]);
293 model: 'account.journal',
295 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
296 loaded: function(self, journals){
297 self.journals = journals;
299 // associate the bank statements with their journals.
300 var bankstatements = self.bankstatements;
301 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
302 for(var j = 0, jlen = journals.length; j < jlen; j++){
303 if(bankstatements[i].journal_id[0] === journals[j].id){
304 bankstatements[i].journal = journals[j];
308 self.cashregisters = bankstatements;
312 loaded: function(self){
313 var fonts_loaded = new $.Deferred();
314 // Waiting for fonts to be loaded to prevent receipt printing
315 // from printing empty receipt while loading Inconsolata
316 // ( The font used for the receipt )
317 waitForWebfonts(['Lato','Inconsolata'], function(){
318 fonts_loaded.resolve();
320 // The JS used to detect font loading is not 100% robust, so
321 // do not wait more than 5sec
322 setTimeout(function(){
323 fonts_loaded.resolve();
330 loaded: function(self){
331 self.company_logo = new Image();
332 var logo_loaded = new $.Deferred();
333 self.company_logo.onload = function(){
334 var img = self.company_logo;
336 var targetwidth = 300;
338 if( img.width !== targetwidth ){
339 ratio = targetwidth / img.width;
341 if( img.height * ratio > maxheight ){
342 ratio = maxheight / img.height;
344 var width = Math.floor(img.width * ratio);
345 var height = Math.floor(img.height * ratio);
346 var c = document.createElement('canvas');
349 var ctx = c.getContext('2d');
350 ctx.drawImage(self.company_logo,0,0, width, height);
352 self.company_logo_base64 = c.toDataURL();
353 logo_loaded.resolve();
355 self.company_logo.onerror = function(){
356 logo_loaded.reject();
358 self.company_logo.crossOrigin = "anonymous";
359 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
366 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
367 load_server_data: function(){
369 var loaded = new $.Deferred();
371 var progress_step = 1.0 / self.models.length;
372 var tmp = {}; // this is used to share a temporary state between models loaders
374 function load_model(index){
375 if(index >= self.models.length){
378 var model = self.models[index];
379 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
381 var cond = typeof model.condition === 'function' ? model.condition(self,tmp) : true;
387 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
388 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
389 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
390 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
391 progress += progress_step;
396 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
398 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
400 records.then(function(result){
401 try{ // catching exceptions in model.loaded(...)
402 $.when(model.loaded(self,result,tmp))
403 .then(function(){ load_model(index + 1); },
404 function(err){ loaded.reject(err); });
406 console.error(err.stack);
412 }else if( model.loaded ){
413 try{ // catching exceptions in model.loaded(...)
414 $.when(model.loaded(self,tmp))
415 .then( function(){ load_model(index +1); },
416 function(err){ loaded.reject(err); });
421 load_model(index + 1);
435 // reload the list of partner, returns as a deferred that resolves if there were
436 // updated partners, and fails if not
437 load_new_partners: function(){
439 var def = new $.Deferred();
440 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
441 new instance.web.Model('res.partner')
443 .filter([['write_date','>',this.db.get_partner_write_date()]])
444 .all({'timeout':3000, 'shadow': true})
445 .then(function(partners){
446 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
451 }, function(){ def.reject(); });
455 // this is called when an order is removed from the order collection. It ensures that there is always an existing
456 // order and a valid selected order
457 on_removed_order: function(removed_order,index,reason){
458 var order_list = this.get_order_list();
459 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
460 // when we intentionally remove an unfinished order, and there is another existing one
461 this.set_order(order_list[index] || order_list[order_list.length -1]);
463 // when the order was automatically removed after completion,
464 // or when we intentionally delete the only concurrent order
465 this.add_new_order();
469 //creates a new empty order and sets it as the current order
470 add_new_order: function(){
471 var order = new module.Order({pos:this});
472 this.get('orders').add(order);
473 this.set('selectedOrder', order);
477 // return the current order
478 get_order: function(){
479 return this.get('selectedOrder');
482 // change the current order
483 set_order: function(order){
484 this.set({ selectedOrder: order });
487 // return the list of unpaid orders
488 get_order_list: function(){
489 return this.get('orders').models;
492 //removes the current order
493 delete_current_order: function(){
494 var order = this.get_order();
496 order.destroy({'reason':'abandon'});
500 // saves the order locally and try to send it to the backend.
501 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
502 push_order: function(order) {
506 this.proxy.log('push_order',order.export_as_JSON());
507 this.db.add_order(order.export_as_JSON());
510 var pushed = new $.Deferred();
512 this.flush_mutex.exec(function(){
513 var flushed = self._flush_orders(self.db.get_orders());
515 flushed.always(function(ids){
522 // saves the order locally and try to send it to the backend and make an invoice
523 // returns a deferred that succeeds when the order has been posted and successfully generated
524 // an invoice. This method can fail in various ways:
525 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
526 // this error is solved
527 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
528 // the network connection is up
530 push_and_invoice_order: function(order){
532 var invoiced = new $.Deferred();
534 if(!order.get_client()){
535 invoiced.reject('error-no-client');
539 var order_id = this.db.add_order(order.export_as_JSON());
541 this.flush_mutex.exec(function(){
542 var done = new $.Deferred(); // holds the mutex
544 // send the order to the server
545 // we have a 30 seconds timeout on this push.
546 // FIXME: if the server takes more than 30 seconds to accept the order,
547 // the client will believe it wasn't successfully sent, and very bad
548 // things will happen as a duplicate will be sent next time
549 // so we must make sure the server detects and ignores duplicated orders
551 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
553 transfer.fail(function(){
554 invoiced.reject('error-transfer');
558 // on success, get the order id generated by the server
559 transfer.pipe(function(order_server_id){
561 // generate the pdf and download it
562 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
563 active_ids:order_server_id,
577 // wrapper around the _save_to_server that updates the synch status widget
578 _flush_orders: function(orders, options) {
580 this.set('synch',{ state: 'connecting', pending: orders.length});
582 return self._save_to_server(orders, options).done(function (server_ids) {
583 var pending = self.db.get_orders().length;
586 state: pending ? 'connecting' : 'connected',
594 // send an array of orders to the server
595 // available options:
596 // - timeout: timeout for the rpc call in ms
597 // returns a deferred that resolves with the list of
598 // server generated ids for the sent orders
599 _save_to_server: function (orders, options) {
600 if (!orders || !orders.length) {
601 var result = $.Deferred();
606 options = options || {};
609 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
611 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
612 // then we want to notify the user that we are waiting on something )
613 var posOrderModel = new instance.web.Model('pos.order');
614 return posOrderModel.call('create_from_ui',
615 [_.map(orders, function (order) {
616 order.to_invoice = options.to_invoice || false;
621 shadow: !options.to_invoice,
624 ).then(function (server_ids) {
625 _.each(orders, function (order) {
626 self.db.remove_order(order.id);
629 }).fail(function (error, event){
630 if(error.code === 200 ){ // Business Logic Error, not a connection problem
631 //if warning do not need to display traceback!!
632 if (error.data.exception_type == 'warning') {
633 delete error.data.debug;
635 self.pos_widget.screen_selector.show_popup('error-traceback',{
636 message: error.data.message,
637 comment: error.data.debug
640 // prevent an error popup creation by the rpc failure
641 // we want the failure to be silent as we send the orders in the background
642 event.preventDefault();
643 console.error('Failed to send orders:', orders);
647 scan_product: function(parsed_code){
649 var selectedOrder = this.get_order();
650 if(parsed_code.encoding === 'ean13'){
651 var product = this.db.get_product_by_ean13(parsed_code.base_code);
652 }else if(parsed_code.encoding === 'reference'){
653 var product = this.db.get_product_by_reference(parsed_code.code);
660 if(parsed_code.type === 'price'){
661 selectedOrder.addProduct(product, {price:parsed_code.value});
662 }else if(parsed_code.type === 'weight'){
663 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
664 }else if(parsed_code.type === 'discount'){
665 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
667 selectedOrder.addProduct(product);
673 var orderline_id = 1;
675 // An orderline represent one element of the content of a client's shopping cart.
676 // An orderline contains a product, its quantity, its price, discount. etc.
677 // An Order contains zero or more Orderlines.
678 module.Orderline = Backbone.Model.extend({
679 initialize: function(attr,options){
680 this.pos = options.pos;
681 this.order = options.order;
682 this.product = options.product;
683 this.price = options.product.price;
685 this.quantityStr = '1';
687 this.discountStr = '0';
689 this.selected = false;
690 this.id = orderline_id++;
693 var orderline = new module.Orderline({},{
696 product: this.product,
699 orderline.quantity = this.quantity;
700 orderline.quantityStr = this.quantityStr;
701 orderline.discount = this.discount;
702 orderline.type = this.type;
703 orderline.selected = false;
706 // sets a discount [0,100]%
707 set_discount: function(discount){
708 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
709 this.discount = disc;
710 this.discountStr = '' + disc;
711 this.trigger('change',this);
713 // returns the discount [0,100]%
714 get_discount: function(){
715 return this.discount;
717 get_discount_str: function(){
718 return this.discountStr;
720 get_product_type: function(){
723 // sets the quantity of the product. The quantity will be rounded according to the
724 // product's unity of measure properties. Quantities greater than zero will not get
726 set_quantity: function(quantity){
727 if(quantity === 'remove'){
728 this.order.removeOrderline(this);
731 var quant = parseFloat(quantity) || 0;
732 var unit = this.get_unit();
735 this.quantity = round_pr(quant, unit.rounding);
736 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
738 this.quantity = round_pr(quant, 1);
739 this.quantityStr = this.quantity.toFixed(0);
742 this.quantity = quant;
743 this.quantityStr = '' + this.quantity;
746 this.trigger('change',this);
748 // return the quantity of product
749 get_quantity: function(){
750 return this.quantity;
752 get_quantity_str: function(){
753 return this.quantityStr;
755 get_quantity_str_with_unit: function(){
756 var unit = this.get_unit();
757 if(unit && !unit.is_unit){
758 return this.quantityStr + ' ' + unit.name;
760 return this.quantityStr;
763 // return the unit of measure of the product
764 get_unit: function(){
765 var unit_id = this.product.uom_id;
769 unit_id = unit_id[0];
773 return this.pos.units_by_id[unit_id];
775 // return the product of this orderline
776 get_product: function(){
779 // selects or deselects this orderline
780 set_selected: function(selected){
781 this.selected = selected;
782 this.trigger('change',this);
784 // returns true if this orderline is selected
785 is_selected: function(){
786 return this.selected;
788 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
789 // in the orderline. This returns true if it makes sense to merge the two
790 can_be_merged_with: function(orderline){
791 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
793 }else if(!this.get_unit() || !this.get_unit().groupable){
795 }else if(this.get_product_type() !== orderline.get_product_type()){
797 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
799 }else if(this.price !== orderline.price){
805 merge: function(orderline){
806 this.set_quantity(this.get_quantity() + orderline.get_quantity());
808 export_as_JSON: function() {
810 qty: this.get_quantity(),
811 price_unit: this.get_unit_price(),
812 discount: this.get_discount(),
813 product_id: this.get_product().id,
816 //used to create a json of the ticket, to be sent to the printer
817 export_for_printing: function(){
819 quantity: this.get_quantity(),
820 unit_name: this.get_unit().name,
821 price: this.get_unit_price(),
822 discount: this.get_discount(),
823 product_name: this.get_product().display_name,
824 price_display : this.get_display_price(),
825 price_with_tax : this.get_price_with_tax(),
826 price_without_tax: this.get_price_without_tax(),
828 product_description: this.get_product().description,
829 product_description_sale: this.get_product().description_sale,
832 // changes the base price of the product for this orderline
833 set_unit_price: function(price){
834 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
835 this.trigger('change',this);
837 get_unit_price: function(){
840 get_base_price: function(){
841 var rounding = this.pos.currency.rounding;
842 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
844 get_display_price: function(){
845 return this.get_base_price();
847 get_price_without_tax: function(){
848 return this.get_all_prices().priceWithoutTax;
850 get_price_with_tax: function(){
851 return this.get_all_prices().priceWithTax;
854 return this.get_all_prices().tax;
856 get_tax_details: function(){
857 return this.get_all_prices().taxDetails;
859 get_all_prices: function(){
861 var currency_rounding = this.pos.currency.rounding;
862 var base = this.get_base_price();
864 var totalNoTax = base;
866 var product = this.get_product();
867 var taxes_ids = product.taxes_id;
868 var taxes = self.pos.taxes;
871 _.each(taxes_ids, function(el) {
872 var tax = _.detect(taxes, function(t) {return t.id === el;});
873 if (tax.price_include) {
875 if (tax.type === "percent") {
876 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
877 } else if (tax.type === "fixed") {
878 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
880 throw "This type of tax is not supported by the point of sale: " + tax.type;
882 tmp = round_pr(tmp,currency_rounding);
885 taxdetail[tax.id] = tmp;
888 if (tax.type === "percent") {
889 tmp = tax.amount * base;
890 } else if (tax.type === "fixed") {
891 tmp = tax.amount * self.get_quantity();
893 throw "This type of tax is not supported by the point of sale: " + tax.type;
895 tmp = round_pr(tmp,currency_rounding);
898 taxdetail[tax.id] = tmp;
902 "priceWithTax": totalTax,
903 "priceWithoutTax": totalNoTax,
905 "taxDetails": taxdetail,
910 module.OrderlineCollection = Backbone.Collection.extend({
911 model: module.Orderline,
914 // Every Paymentline contains a cashregister and an amount of money.
915 module.Paymentline = Backbone.Model.extend({
916 initialize: function(attributes, options) {
918 this.cashregister = options.cashregister;
919 this.name = this.cashregister.journal_id[1];
920 this.selected = false;
921 this.pos = options.pos;
923 //sets the amount of money on this payment line
924 set_amount: function(value){
925 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
926 this.trigger('change:amount',this);
928 // returns the amount of money on this paymentline
929 get_amount: function(){
932 get_amount_str: function(){
933 return this.amount.toFixed(this.pos.currency.decimals);
935 set_selected: function(selected){
936 if(this.selected !== selected){
937 this.selected = selected;
938 this.trigger('change:selected',this);
941 // returns the associated cashregister
942 //exports as JSON for server communication
943 export_as_JSON: function(){
945 name: instance.web.datetime_to_str(new Date()),
946 statement_id: this.cashregister.id,
947 account_id: this.cashregister.account_id[0],
948 journal_id: this.cashregister.journal_id[0],
949 amount: this.get_amount()
952 //exports as JSON for receipt printing
953 export_for_printing: function(){
955 amount: this.get_amount(),
956 journal: this.cashregister.journal_id[1],
961 module.PaymentlineCollection = Backbone.Collection.extend({
962 model: module.Paymentline,
966 // An order more or less represents the content of a client's shopping cart (the OrderLines)
967 // plus the associated payment information (the Paymentlines)
968 // there is always an active ('selected') order in the Pos, a new one is created
969 // automaticaly once an order is completed and sent to the server.
970 module.Order = Backbone.Model.extend({
971 initialize: function(attributes){
972 Backbone.Model.prototype.initialize.apply(this, arguments);
973 this.pos = attributes.pos;
974 this.sequence_number = this.pos.pos_session.sequence_number++;
975 this.uid = this.generateUniqueId();
977 creationDate: new Date(),
978 orderLines: new module.OrderlineCollection(),
979 paymentLines: new module.PaymentlineCollection(),
980 name: _t("Order ") + this.uid,
983 this.selected_orderline = undefined;
984 this.selected_paymentline = undefined;
985 this.screen_data = {}; // see ScreenSelector
986 this.temporary = attributes.temporary || false;
987 this.to_invoice = false;
990 is_empty: function(){
991 return (this.get('orderLines').models.length === 0);
994 // Generates a public identification number for the order.
995 // The generated number must be unique and sequential. They are made 12 digit long
996 // to fit into EAN-13 barcodes, should it be needed
997 generateUniqueId: function() {
998 function zero_pad(num,size){
1000 while (s.length < size) {
1005 return zero_pad(this.pos.pos_session.id,5) +'-'+
1006 zero_pad(this.pos.pos_session.login_number,3) +'-'+
1007 zero_pad(this.sequence_number,4);
1009 addOrderline: function(line){
1011 order.removeOrderline(line);
1014 this.get('orderLines').add(line);
1015 this.selectLine(this.getLastOrderline());
1017 addProduct: function(product, options){
1018 options = options || {};
1019 var attr = JSON.parse(JSON.stringify(product));
1020 attr.pos = this.pos;
1022 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1024 if(options.quantity !== undefined){
1025 line.set_quantity(options.quantity);
1027 if(options.price !== undefined){
1028 line.set_unit_price(options.price);
1030 if(options.discount !== undefined){
1031 line.set_discount(options.discount);
1034 if(options.extras !== undefined){
1035 for (var prop in options.extras) {
1036 line[prop] = options.extras[prop];
1040 var last_orderline = this.getLastOrderline();
1041 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1042 last_orderline.merge(line);
1044 this.get('orderLines').add(line);
1046 this.selectLine(this.getLastOrderline());
1048 removeOrderline: function( line ){
1049 this.get('orderLines').remove(line);
1050 this.selectLine(this.getLastOrderline());
1052 getOrderline: function(id){
1053 var orderlines = this.get('orderLines').models;
1054 for(var i = 0; i < orderlines.length; i++){
1055 if(orderlines[i].id === id){
1056 return orderlines[i];
1061 getLastOrderline: function(){
1062 return this.get('orderLines').at(this.get('orderLines').length -1);
1064 addPaymentline: function(cashregister) {
1065 var paymentLines = this.get('paymentLines');
1066 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos:this.pos});
1067 if(cashregister.journal.type !== 'cash' || this.pos.config.iface_precompute_cash){
1068 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
1070 paymentLines.add(newPaymentline);
1071 this.selectPaymentline(newPaymentline);
1074 removePaymentline: function(line){
1075 if(this.selected_paymentline === line){
1076 this.selectPaymentline(undefined);
1078 this.get('paymentLines').remove(line);
1080 getName: function() {
1081 return this.get('name');
1083 getSubtotal : function(){
1084 return (this.get('orderLines')).reduce((function(sum, orderLine){
1085 return sum + orderLine.get_display_price();
1088 getTotalTaxIncluded: function() {
1089 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1090 return sum + orderLine.get_price_with_tax();
1093 getDiscountTotal: function() {
1094 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1095 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1098 getTotalTaxExcluded: function() {
1099 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1100 return sum + orderLine.get_price_without_tax();
1103 getTax: function() {
1104 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1105 return sum + orderLine.get_tax();
1108 getTaxDetails: function(){
1110 var fulldetails = [];
1111 var taxes_by_id = {};
1113 for(var i = 0; i < this.pos.taxes.length; i++){
1114 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1117 this.get('orderLines').each(function(line){
1118 var ldetails = line.get_tax_details();
1119 for(var id in ldetails){
1120 if(ldetails.hasOwnProperty(id)){
1121 details[id] = (details[id] || 0) + ldetails[id];
1126 for(var id in details){
1127 if(details.hasOwnProperty(id)){
1128 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1134 getPaidTotal: function() {
1135 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
1136 return sum + paymentLine.get_amount();
1139 getChange: function(paymentline) {
1141 var change = this.getPaidTotal() - this.getTotalTaxIncluded();
1143 var change = -this.getTotalTaxIncluded();
1144 var lines = this.get('paymentLines').models;
1145 for (var i = 0; i < lines.length; i++) {
1146 change += lines[i].get_amount();
1147 if (lines[i] === paymentline) {
1152 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1154 getDueLeft: function(paymentline) {
1156 var due = this.getTotalTaxIncluded() - this.getPaidTotal();
1158 var due = this.getTotalTaxIncluded();
1159 var lines = this.get('paymentLines').models;
1160 for (var i = 0; i < lines.length; i++) {
1161 if (lines[i] === paymentline) {
1164 due -= lines[i].get_amount();
1168 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1171 return this.getDueLeft() === 0;
1173 isPaidWithCash: function(){
1174 return !!this.get('paymentLines').find( function(pl){
1175 return pl.cashregister.journal.type === 'cash';
1178 finalize: function(){
1181 // the client related to the current order.
1182 set_client: function(client){
1183 this.set('client',client);
1185 get_client: function(){
1186 return this.get('client');
1188 get_client_name: function(){
1189 var client = this.get('client');
1190 return client ? client.name : "";
1192 // the order also stores the screen status, as the PoS supports
1193 // different active screens per order. This method is used to
1194 // store the screen status.
1195 set_screen_data: function(key,value){
1196 if(arguments.length === 2){
1197 this.screen_data[key] = value;
1198 }else if(arguments.length === 1){
1199 for(var key in arguments[0]){
1200 this.screen_data[key] = arguments[0][key];
1204 set_to_invoice: function(to_invoice) {
1205 this.to_invoice = to_invoice;
1207 is_to_invoice: function(){
1208 return this.to_invoice;
1210 // remove all the paymentlines with zero money in it
1211 clean_empty_paymentlines: function() {
1212 var lines = this.get('paymentLines').models;
1214 for ( var i = 0; i < lines.length; i++) {
1215 if (!lines[i].get_amount()) {
1216 empty.push(lines[i]);
1219 for ( var i = 0; i < empty.length; i++) {
1220 this.removePaymentline(empty[i]);
1223 //see set_screen_data
1224 get_screen_data: function(key){
1225 return this.screen_data[key];
1227 // exports a JSON for receipt printing
1228 export_for_printing: function(){
1229 var orderlines = [];
1230 this.get('orderLines').each(function(orderline){
1231 orderlines.push(orderline.export_for_printing());
1234 var paymentlines = [];
1235 this.get('paymentLines').each(function(paymentline){
1236 paymentlines.push(paymentline.export_for_printing());
1238 var client = this.get('client');
1239 var cashier = this.pos.cashier || this.pos.user;
1240 var company = this.pos.company;
1241 var shop = this.pos.shop;
1242 var date = new Date();
1245 orderlines: orderlines,
1246 paymentlines: paymentlines,
1247 subtotal: this.getSubtotal(),
1248 total_with_tax: this.getTotalTaxIncluded(),
1249 total_without_tax: this.getTotalTaxExcluded(),
1250 total_tax: this.getTax(),
1251 total_paid: this.getPaidTotal(),
1252 total_discount: this.getDiscountTotal(),
1253 tax_details: this.getTaxDetails(),
1254 change: this.getChange(),
1255 name : this.getName(),
1256 client: client ? client.name : null ,
1257 invoice_id: null, //TODO
1258 cashier: cashier ? cashier.name : null,
1259 header: this.pos.config.receipt_header || '',
1260 footer: this.pos.config.receipt_footer || '',
1267 year: date.getFullYear(),
1268 month: date.getMonth(),
1269 date: date.getDate(), // day of the month
1270 day: date.getDay(), // day of the week
1271 hour: date.getHours(),
1272 minute: date.getMinutes() ,
1273 isostring: date.toISOString(),
1274 localestring: date.toLocaleString(),
1277 email: company.email,
1278 website: company.website,
1279 company_registry: company.company_registry,
1280 contact_address: company.partner_id[1],
1283 phone: company.phone,
1284 logo: this.pos.company_logo_base64,
1289 currency: this.pos.currency,
1292 export_as_JSON: function() {
1293 var orderLines, paymentLines;
1295 (this.get('orderLines')).each(_.bind( function(item) {
1296 return orderLines.push([0, 0, item.export_as_JSON()]);
1299 (this.get('paymentLines')).each(_.bind( function(item) {
1300 return paymentLines.push([0, 0, item.export_as_JSON()]);
1303 name: this.getName(),
1304 amount_paid: this.getPaidTotal(),
1305 amount_total: this.getTotalTaxIncluded(),
1306 amount_tax: this.getTax(),
1307 amount_return: this.getChange(),
1309 statement_ids: paymentLines,
1310 pos_session_id: this.pos.pos_session.id,
1311 partner_id: this.get_client() ? this.get_client().id : false,
1312 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1314 sequence_number: this.sequence_number,
1317 getSelectedLine: function(){
1318 return this.selected_orderline;
1320 selectLine: function(line){
1322 if(line !== this.selected_orderline){
1323 if(this.selected_orderline){
1324 this.selected_orderline.set_selected(false);
1326 this.selected_orderline = line;
1327 this.selected_orderline.set_selected(true);
1330 this.selected_orderline = undefined;
1333 deselectLine: function(){
1334 if(this.selected_orderline){
1335 this.selected_orderline.set_selected(false);
1336 this.selected_orderline = undefined;
1339 selectPaymentline: function(line){
1340 if(line !== this.selected_paymentline){
1341 if(this.selected_paymentline){
1342 this.selected_paymentline.set_selected(false);
1344 this.selected_paymentline = line;
1345 if(this.selected_paymentline){
1346 this.selected_paymentline.set_selected(true);
1348 this.trigger('change:selected_paymentline',this.selected_paymentline);
1353 module.OrderCollection = Backbone.Collection.extend({
1354 model: module.Order,
1358 The numpad handles both the choice of the property currently being modified
1359 (quantity, price or discount) and the edition of the corresponding numeric value.
1361 module.NumpadState = Backbone.Model.extend({
1366 appendNewChar: function(newChar) {
1368 oldBuffer = this.get('buffer');
1369 if (oldBuffer === '0') {
1373 } else if (oldBuffer === '-0') {
1375 buffer: "-" + newChar
1379 buffer: (this.get('buffer')) + newChar
1382 this.trigger('set_value',this.get('buffer'));
1384 deleteLastChar: function() {
1385 if(this.get('buffer') === ""){
1386 if(this.get('mode') === 'quantity'){
1387 this.trigger('set_value','remove');
1389 this.trigger('set_value',this.get('buffer'));
1392 var newBuffer = this.get('buffer').slice(0,-1) || "";
1393 this.set({ buffer: newBuffer });
1394 this.trigger('set_value',this.get('buffer'));
1397 switchSign: function() {
1399 oldBuffer = this.get('buffer');
1401 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1403 this.trigger('set_value',this.get('buffer'));
1405 changeMode: function(newMode) {
1417 resetValue: function(){
1418 this.set({buffer:'0'});