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;
5 var round_di = instance.web.round_decimals;
6 var round_pr = instance.web.round_precision
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.
18 module.PosModel = Backbone.Model.extend({
19 initialize: function(session, attributes) {
20 Backbone.Model.prototype.initialize.call(this, attributes);
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;
26 this.proxy = new module.ProxyDevice(this); // used to communicate to the hardware devices via a local proxy
27 this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy, patterns: {}}); // used to read barcodes
28 this.proxy_queue = new module.JobQueue(); // used to prevent parallels communications to the proxy
29 this.db = new module.PosDB(); // a local database used to search trough products and categories & store pending orders
30 this.debug = jQuery.deparam(jQuery.param.querystring()).debug !== undefined; //debug mode
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 = '';
43 this.cashregisters = [];
44 this.bankstatements = [];
46 this.pos_session = null;
49 this.units_by_id = {};
50 this.pricelist = null;
51 this.order_sequence = 1;
52 window.posmodel = this;
54 // these dynamic attributes can be watched for change by other models or widgets
56 'synch': { state:'connected', pending:0 },
57 'orders': new module.OrderCollection(),
58 'selectedOrder': null,
61 this.bind('change:synch',function(pos,synch){
62 clearTimeout(self.synch_timeout);
63 self.synch_timeout = setTimeout(function(){
64 if(synch.state !== 'disconnected' && synch.pending > 0){
65 self.set('synch',{state:'disconnected', pending:synch.pending});
70 this.get('orders').bind('remove', function(order,_unused_,options){
71 self.on_removed_order(order,options.index,options.reason);
74 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
75 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
76 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
77 this.ready = this.load_server_data()
79 if(self.config.use_proxy){
80 return self.connect_to_proxy();
86 // releases ressources holds by the model at the end of life of the posmodel
88 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
91 this.barcode_reader.disconnect();
92 this.barcode_reader.disconnect_from_proxy();
94 connect_to_proxy: function(){
96 var done = new $.Deferred();
97 this.barcode_reader.disconnect_from_proxy();
98 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
99 this.pos_widget.loading_skip(function(){
100 self.proxy.stop_searching();
102 this.proxy.autoconnect({
103 force_ip: self.config.proxy_ip || undefined,
104 progress: function(prog){
105 self.pos_widget.loading_progress(prog);
108 if(self.config.iface_scan_via_proxy){
109 self.barcode_reader.connect_to_proxy();
111 }).always(function(){
117 // helper function to load data from the server. Obsolete use the models loader below.
118 fetch: function(model, fields, domain, ctx){
119 this._load_progress = (this._load_progress || 0) + 0.05;
120 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
121 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
124 // Server side model loaders. This is the list of the models that need to be loaded from
125 // the server. The models are loaded one by one by this list's order. The 'loaded' callback
126 // is used to store the data in the appropriate place once it has been loaded. This callback
127 // can return a deferred that will pause the loading of the next module.
128 // a shared temporary dictionary is available for loaders to communicate private variables
129 // used during loading such as object ids, etc.
133 fields: ['name','company_id'],
134 ids: function(self){ return [self.session.uid]; },
135 loaded: function(self,users){ self.user = users[0]; },
137 model: 'res.company',
138 fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id'],
139 ids: function(self){ return [self.user.company_id[0]] },
140 loaded: function(self,companies){ self.company = companies[0]; },
142 model: 'decimal.precision',
143 fields: ['name','digits'],
144 loaded: function(self,dps){
146 for (var i = 0; i < dps.length; i++) {
147 self.dp[dps[i].name] = dps[i].digits;
151 model: 'product.uom',
154 loaded: function(self,units){
156 var units_by_id = {};
157 for(var i = 0, len = units.length; i < len; i++){
158 units_by_id[units[i].id] = units[i];
159 units[i].groupable = ( units[i].category_id[0] === 1 );
160 units[i].is_unit = ( units[i].id === 1 );
162 self.units_by_id = units_by_id;
166 fields: ['name','ean13'],
168 loaded: function(self,users){ self.users = users; },
170 model: 'res.partner',
171 fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','ean13','write_date'],
173 loaded: function(self,partners){
174 self.partners = partners;
175 self.db.add_partners(partners);
178 model: 'res.country',
180 loaded: function(self,countries){
181 self.countries = countries;
182 self.company.country = null;
183 for (var i = 0; i < countries.length; i++) {
184 if (countries[i].id === self.company.country_id[0]){
185 self.company.country = countries[i];
190 model: 'account.tax',
191 fields: ['name','amount', 'price_include', 'type'],
193 loaded: function(self,taxes){ self.taxes = taxes; },
195 model: 'pos.session',
196 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
197 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
198 loaded: function(self,pos_sessions){
199 self.pos_session = pos_sessions[0];
201 var orders = self.db.get_orders();
202 for (var i = 0; i < orders.length; i++) {
203 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
209 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
210 loaded: function(self,configs){
211 self.config = configs[0];
212 self.config.use_proxy = self.config.iface_payment_terminal ||
213 self.config.iface_electronic_scale ||
214 self.config.iface_print_via_proxy ||
215 self.config.iface_scan_via_proxy ||
216 self.config.iface_cashdrawer;
218 self.barcode_reader.add_barcode_patterns({
219 'product': self.config.barcode_product,
220 'cashier': self.config.barcode_cashier,
221 'client': self.config.barcode_customer,
222 'weight': self.config.barcode_weight,
223 'discount': self.config.barcode_discount,
224 'price': self.config.barcode_price,
227 if (self.config.company_id[0] !== self.user.company_id[0]) {
228 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."));
232 model: 'stock.location',
234 ids: function(self){ return [self.config.stock_location_id[0]]; },
235 loaded: function(self, locations){ self.shop = locations[0]; },
237 model: 'product.pricelist',
238 fields: ['currency_id'],
239 ids: function(self){ return [self.config.pricelist_id[0]]; },
240 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
242 model: 'res.currency',
243 fields: ['symbol','position','rounding','accuracy'],
244 ids: function(self){ return [self.pricelist.currency_id[0]]; },
245 loaded: function(self, currencies){
246 self.currency = currencies[0];
247 if (self.currency.rounding > 0) {
248 self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
250 self.currency.decimals = 0;
255 model: 'product.packaging',
256 fields: ['ean','product_tmpl_id'],
258 loaded: function(self, packagings){
259 self.db.add_packagings(packagings);
262 model: 'pos.category',
263 fields: ['id','name','parent_id','child_id','image'],
265 loaded: function(self, categories){
266 self.db.add_categories(categories);
269 model: 'product.product',
270 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
271 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
273 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
274 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
275 loaded: function(self, products){
276 self.db.add_products(products);
279 model: 'account.bank.statement',
280 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
281 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
282 loaded: function(self, bankstatements, tmp){
283 self.bankstatements = bankstatements;
286 _.each(bankstatements,function(statement){
287 tmp.journals.push(statement.journal_id[0]);
291 model: 'account.journal',
293 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
294 loaded: function(self, journals){
295 self.journals = journals;
297 // associate the bank statements with their journals.
298 var bankstatements = self.bankstatements;
299 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
300 for(var j = 0, jlen = journals.length; j < jlen; j++){
301 if(bankstatements[i].journal_id[0] === journals[j].id){
302 bankstatements[i].journal = journals[j];
306 self.cashregisters = bankstatements;
310 loaded: function(self){
311 var fonts_loaded = new $.Deferred();
312 // Waiting for fonts to be loaded to prevent receipt printing
313 // from printing empty receipt while loading Inconsolata
314 // ( The font used for the receipt )
315 waitForWebfonts(['Lato','Inconsolata'], function(){
316 fonts_loaded.resolve();
318 // The JS used to detect font loading is not 100% robust, so
319 // do not wait more than 5sec
320 setTimeout(function(){
321 fonts_loaded.resolve();
328 loaded: function(self){
329 self.company_logo = new Image();
330 var logo_loaded = new $.Deferred();
331 self.company_logo.onload = function(){
332 var img = self.company_logo;
334 var targetwidth = 300;
336 if( img.width !== targetwidth ){
337 ratio = targetwidth / img.width;
339 if( img.height * ratio > maxheight ){
340 ratio = maxheight / img.height;
342 var width = Math.floor(img.width * ratio);
343 var height = Math.floor(img.height * ratio);
344 var c = document.createElement('canvas');
347 var ctx = c.getContext('2d');
348 ctx.drawImage(self.company_logo,0,0, width, height);
350 self.company_logo_base64 = c.toDataURL();
351 logo_loaded.resolve();
353 self.company_logo.onerror = function(){
354 logo_loaded.reject();
356 self.company_logo.crossOrigin = "anonymous";
357 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
364 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
365 load_server_data: function(){
367 var loaded = new $.Deferred();
369 var progress_step = 1.0 / self.models.length;
370 var tmp = {}; // this is used to share a temporary state between models loaders
372 function load_model(index){
373 if(index >= self.models.length){
376 var model = self.models[index];
377 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
378 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
379 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
380 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
381 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
382 progress += progress_step;
387 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
389 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
391 records.then(function(result){
392 try{ // catching exceptions in model.loaded(...)
393 $.when(model.loaded(self,result,tmp))
394 .then(function(){ load_model(index + 1); },
395 function(err){ loaded.reject(err); });
397 console.error(err.stack);
403 }else if( model.loaded ){
404 try{ // catching exceptions in model.loaded(...)
405 $.when(model.loaded(self,tmp))
406 .then( function(){ load_model(index +1); },
407 function(err){ loaded.reject(err); });
412 load_model(index + 1);
426 // reload the list of partner, returns as a deferred that resolves if there were
427 // updated partners, and fails if not
428 load_new_partners: function(){
430 var def = new $.Deferred();
431 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
432 new instance.web.Model('res.partner')
434 .filter([['write_date','>',this.db.get_partner_write_date()]])
435 .all({'timeout':3000, 'shadow': true})
436 .then(function(partners){
437 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
442 }, function(){ def.reject(); });
446 // this is called when an order is removed from the order collection. It ensures that there is always an existing
447 // order and a valid selected order
448 on_removed_order: function(removed_order,index,reason){
449 var order_list = this.get_order_list();
450 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
451 // when we intentionally remove an unfinished order, and there is another existing one
452 this.set_order(order_list[index] || order_list[order_list.length -1]);
454 // when the order was automatically removed after completion,
455 // or when we intentionally delete the only concurrent order
456 this.add_new_order();
460 //creates a new empty order and sets it as the current order
461 add_new_order: function(){
462 var order = new module.Order({pos:this});
463 this.get('orders').add(order);
464 this.set('selectedOrder', order);
468 // return the current order
469 get_order: function(){
470 return this.get('selectedOrder');
473 // change the current order
474 set_order: function(order){
475 this.set({ selectedOrder: order });
478 // return the list of unpaid orders
479 get_order_list: function(){
480 return this.get('orders').models;
483 //removes the current order
484 delete_current_order: function(){
485 var order = this.get_order();
487 order.destroy({'reason':'abandon'});
491 // saves the order locally and try to send it to the backend.
492 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
493 push_order: function(order) {
497 this.proxy.log('push_order',order.export_as_JSON());
498 this.db.add_order(order.export_as_JSON());
501 var pushed = new $.Deferred();
503 this.flush_mutex.exec(function(){
504 var flushed = self._flush_orders(self.db.get_orders());
506 flushed.always(function(ids){
513 // saves the order locally and try to send it to the backend and make an invoice
514 // returns a deferred that succeeds when the order has been posted and successfully generated
515 // an invoice. This method can fail in various ways:
516 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
517 // this error is solved
518 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
519 // the network connection is up
521 push_and_invoice_order: function(order){
523 var invoiced = new $.Deferred();
525 if(!order.get_client()){
526 invoiced.reject('error-no-client');
530 var order_id = this.db.add_order(order.export_as_JSON());
532 this.flush_mutex.exec(function(){
533 var done = new $.Deferred(); // holds the mutex
535 // send the order to the server
536 // we have a 30 seconds timeout on this push.
537 // FIXME: if the server takes more than 30 seconds to accept the order,
538 // the client will believe it wasn't successfully sent, and very bad
539 // things will happen as a duplicate will be sent next time
540 // so we must make sure the server detects and ignores duplicated orders
542 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
544 transfer.fail(function(){
545 invoiced.reject('error-transfer');
549 // on success, get the order id generated by the server
550 transfer.pipe(function(order_server_id){
552 // generate the pdf and download it
553 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
554 active_ids:order_server_id,
568 // wrapper around the _save_to_server that updates the synch status widget
569 _flush_orders: function(orders, options) {
571 this.set('synch',{ state: 'connecting', pending: orders.length});
573 return self._save_to_server(orders, options).done(function (server_ids) {
574 var pending = self.db.get_orders().length;
577 state: pending ? 'connecting' : 'connected',
585 // send an array of orders to the server
586 // available options:
587 // - timeout: timeout for the rpc call in ms
588 // returns a deferred that resolves with the list of
589 // server generated ids for the sent orders
590 _save_to_server: function (orders, options) {
591 if (!orders || !orders.length) {
592 var result = $.Deferred();
597 options = options || {};
600 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
602 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
603 // then we want to notify the user that we are waiting on something )
604 var posOrderModel = new instance.web.Model('pos.order');
605 return posOrderModel.call('create_from_ui',
606 [_.map(orders, function (order) {
607 order.to_invoice = options.to_invoice || false;
612 shadow: !options.to_invoice,
615 ).then(function (server_ids) {
616 _.each(orders, function (order) {
617 self.db.remove_order(order.id);
620 }).fail(function (error, event){
621 if(error.code === 200 ){ // Business Logic Error, not a connection problem
622 //if warning do not need to display traceback!!
623 if (error.data.exception_type == 'warning') {
624 delete error.data.debug;
626 self.pos_widget.screen_selector.show_popup('error-traceback',{
627 message: error.data.message,
628 comment: error.data.debug
631 // prevent an error popup creation by the rpc failure
632 // we want the failure to be silent as we send the orders in the background
633 event.preventDefault();
634 console.error('Failed to send orders:', orders);
638 scan_product: function(parsed_code){
640 var selectedOrder = this.get_order();
641 if(parsed_code.encoding === 'ean13'){
642 var product = this.db.get_product_by_ean13(parsed_code.base_code);
643 }else if(parsed_code.encoding === 'reference'){
644 var product = this.db.get_product_by_reference(parsed_code.code);
651 if(parsed_code.type === 'price'){
652 selectedOrder.addProduct(product, {price:parsed_code.value});
653 }else if(parsed_code.type === 'weight'){
654 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
655 }else if(parsed_code.type === 'discount'){
656 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
658 selectedOrder.addProduct(product);
664 var orderline_id = 1;
666 // An orderline represent one element of the content of a client's shopping cart.
667 // An orderline contains a product, its quantity, its price, discount. etc.
668 // An Order contains zero or more Orderlines.
669 module.Orderline = Backbone.Model.extend({
670 initialize: function(attr,options){
671 this.pos = options.pos;
672 this.order = options.order;
673 this.product = options.product;
674 this.price = options.product.price;
676 this.quantityStr = '1';
678 this.discountStr = '0';
680 this.selected = false;
681 this.id = orderline_id++;
684 var orderline = new module.Orderline({},{
687 product: this.product,
690 orderline.quantity = this.quantity;
691 orderline.quantityStr = this.quantityStr;
692 orderline.discount = this.discount;
693 orderline.type = this.type;
694 orderline.selected = false;
697 // sets a discount [0,100]%
698 set_discount: function(discount){
699 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
700 this.discount = disc;
701 this.discountStr = '' + disc;
702 this.trigger('change',this);
704 // returns the discount [0,100]%
705 get_discount: function(){
706 return this.discount;
708 get_discount_str: function(){
709 return this.discountStr;
711 get_product_type: function(){
714 // sets the quantity of the product. The quantity will be rounded according to the
715 // product's unity of measure properties. Quantities greater than zero will not get
717 set_quantity: function(quantity){
718 if(quantity === 'remove'){
719 this.order.removeOrderline(this);
722 var quant = parseFloat(quantity) || 0;
723 var unit = this.get_unit();
726 this.quantity = round_pr(quant, unit.rounding);
727 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
729 this.quantity = round_pr(quant, 1);
730 this.quantityStr = this.quantity.toFixed(0);
733 this.quantity = quant;
734 this.quantityStr = '' + this.quantity;
737 this.trigger('change',this);
739 // return the quantity of product
740 get_quantity: function(){
741 return this.quantity;
743 get_quantity_str: function(){
744 return this.quantityStr;
746 get_quantity_str_with_unit: function(){
747 var unit = this.get_unit();
748 if(unit && !unit.is_unit){
749 return this.quantityStr + ' ' + unit.name;
751 return this.quantityStr;
754 // return the unit of measure of the product
755 get_unit: function(){
756 var unit_id = this.product.uom_id;
760 unit_id = unit_id[0];
764 return this.pos.units_by_id[unit_id];
766 // return the product of this orderline
767 get_product: function(){
770 // selects or deselects this orderline
771 set_selected: function(selected){
772 this.selected = selected;
773 this.trigger('change',this);
775 // returns true if this orderline is selected
776 is_selected: function(){
777 return this.selected;
779 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
780 // in the orderline. This returns true if it makes sense to merge the two
781 can_be_merged_with: function(orderline){
782 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
784 }else if(!this.get_unit() || !this.get_unit().groupable){
786 }else if(this.get_product_type() !== orderline.get_product_type()){
788 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
790 }else if(this.price !== orderline.price){
796 merge: function(orderline){
797 this.set_quantity(this.get_quantity() + orderline.get_quantity());
799 export_as_JSON: function() {
801 qty: this.get_quantity(),
802 price_unit: this.get_unit_price(),
803 discount: this.get_discount(),
804 product_id: this.get_product().id,
807 //used to create a json of the ticket, to be sent to the printer
808 export_for_printing: function(){
810 quantity: this.get_quantity(),
811 unit_name: this.get_unit().name,
812 price: this.get_unit_price(),
813 discount: this.get_discount(),
814 product_name: this.get_product().display_name,
815 price_display : this.get_display_price(),
816 price_with_tax : this.get_price_with_tax(),
817 price_without_tax: this.get_price_without_tax(),
819 product_description: this.get_product().description,
820 product_description_sale: this.get_product().description_sale,
823 // changes the base price of the product for this orderline
824 set_unit_price: function(price){
825 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
826 this.trigger('change',this);
828 get_unit_price: function(){
831 get_base_price: function(){
832 var rounding = this.pos.currency.rounding;
833 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
835 get_display_price: function(){
836 return this.get_base_price();
838 get_price_without_tax: function(){
839 return this.get_all_prices().priceWithoutTax;
841 get_price_with_tax: function(){
842 return this.get_all_prices().priceWithTax;
845 return this.get_all_prices().tax;
847 get_tax_details: function(){
848 return this.get_all_prices().taxDetails;
850 get_all_prices: function(){
852 var currency_rounding = this.pos.currency.rounding;
853 var base = this.get_base_price();
855 var totalNoTax = base;
857 var product = this.get_product();
858 var taxes_ids = product.taxes_id;
859 var taxes = self.pos.taxes;
862 _.each(taxes_ids, function(el) {
863 var tax = _.detect(taxes, function(t) {return t.id === el;});
864 if (tax.price_include) {
866 if (tax.type === "percent") {
867 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
868 } else if (tax.type === "fixed") {
869 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
871 throw "This type of tax is not supported by the point of sale: " + tax.type;
873 tmp = round_pr(tmp,currency_rounding);
876 taxdetail[tax.id] = tmp;
879 if (tax.type === "percent") {
880 tmp = tax.amount * base;
881 } else if (tax.type === "fixed") {
882 tmp = tax.amount * self.get_quantity();
884 throw "This type of tax is not supported by the point of sale: " + tax.type;
886 tmp = round_pr(tmp,currency_rounding);
889 taxdetail[tax.id] = tmp;
893 "priceWithTax": totalTax,
894 "priceWithoutTax": totalNoTax,
896 "taxDetails": taxdetail,
901 module.OrderlineCollection = Backbone.Collection.extend({
902 model: module.Orderline,
905 // Every Paymentline contains a cashregister and an amount of money.
906 module.Paymentline = Backbone.Model.extend({
907 initialize: function(attributes, options) {
909 this.cashregister = options.cashregister;
910 this.name = this.cashregister.journal_id[1];
911 this.selected = false;
912 this.pos = options.pos;
914 //sets the amount of money on this payment line
915 set_amount: function(value){
916 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
917 this.trigger('change:amount',this);
919 // returns the amount of money on this paymentline
920 get_amount: function(){
923 get_amount_str: function(){
924 return this.amount.toFixed(this.pos.currency.decimals);
926 set_selected: function(selected){
927 if(this.selected !== selected){
928 this.selected = selected;
929 this.trigger('change:selected',this);
932 // returns the associated cashregister
933 //exports as JSON for server communication
934 export_as_JSON: function(){
936 name: instance.web.datetime_to_str(new Date()),
937 statement_id: this.cashregister.id,
938 account_id: this.cashregister.account_id[0],
939 journal_id: this.cashregister.journal_id[0],
940 amount: this.get_amount()
943 //exports as JSON for receipt printing
944 export_for_printing: function(){
946 amount: this.get_amount(),
947 journal: this.cashregister.journal_id[1],
952 module.PaymentlineCollection = Backbone.Collection.extend({
953 model: module.Paymentline,
957 // An order more or less represents the content of a client's shopping cart (the OrderLines)
958 // plus the associated payment information (the Paymentlines)
959 // there is always an active ('selected') order in the Pos, a new one is created
960 // automaticaly once an order is completed and sent to the server.
961 module.Order = Backbone.Model.extend({
962 initialize: function(attributes){
963 Backbone.Model.prototype.initialize.apply(this, arguments);
964 this.pos = attributes.pos;
965 this.sequence_number = this.pos.pos_session.sequence_number++;
966 this.uid = this.generateUniqueId();
968 creationDate: new Date(),
969 orderLines: new module.OrderlineCollection(),
970 paymentLines: new module.PaymentlineCollection(),
971 name: _t("Order ") + this.uid,
974 this.selected_orderline = undefined;
975 this.selected_paymentline = undefined;
976 this.screen_data = {}; // see ScreenSelector
977 this.temporary = attributes.temporary || false;
978 this.to_invoice = false;
981 is_empty: function(){
982 return (this.get('orderLines').models.length === 0);
985 // Generates a public identification number for the order.
986 // The generated number must be unique and sequential. They are made 12 digit long
987 // to fit into EAN-13 barcodes, should it be needed
988 generateUniqueId: function() {
989 function zero_pad(num,size){
991 while (s.length < size) {
996 return zero_pad(this.pos.pos_session.id,5) +'-'+
997 zero_pad(this.pos.pos_session.login_number,3) +'-'+
998 zero_pad(this.sequence_number,4);
1000 addOrderline: function(line){
1002 order.removeOrderline(line);
1005 this.get('orderLines').add(line);
1006 this.selectLine(this.getLastOrderline());
1008 addProduct: function(product, options){
1009 options = options || {};
1010 var attr = JSON.parse(JSON.stringify(product));
1011 attr.pos = this.pos;
1013 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1015 if(options.quantity !== undefined){
1016 line.set_quantity(options.quantity);
1018 if(options.price !== undefined){
1019 line.set_unit_price(options.price);
1021 if(options.discount !== undefined){
1022 line.set_discount(options.discount);
1025 var last_orderline = this.getLastOrderline();
1026 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1027 last_orderline.merge(line);
1029 this.get('orderLines').add(line);
1031 this.selectLine(this.getLastOrderline());
1033 removeOrderline: function( line ){
1034 this.get('orderLines').remove(line);
1035 this.selectLine(this.getLastOrderline());
1037 getOrderline: function(id){
1038 var orderlines = this.get('orderLines').models;
1039 for(var i = 0; i < orderlines.length; i++){
1040 if(orderlines[i].id === id){
1041 return orderlines[i];
1046 getLastOrderline: function(){
1047 return this.get('orderLines').at(this.get('orderLines').length -1);
1049 addPaymentline: function(cashregister) {
1050 var paymentLines = this.get('paymentLines');
1051 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos:this.pos});
1052 if(cashregister.journal.type !== 'cash'){
1053 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
1055 paymentLines.add(newPaymentline);
1056 this.selectPaymentline(newPaymentline);
1059 removePaymentline: function(line){
1060 if(this.selected_paymentline === line){
1061 this.selectPaymentline(undefined);
1063 this.get('paymentLines').remove(line);
1065 getName: function() {
1066 return this.get('name');
1068 getSubtotal : function(){
1069 return (this.get('orderLines')).reduce((function(sum, orderLine){
1070 return sum + orderLine.get_display_price();
1073 getTotalTaxIncluded: function() {
1074 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1075 return sum + orderLine.get_price_with_tax();
1078 getDiscountTotal: function() {
1079 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1080 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1083 getTotalTaxExcluded: function() {
1084 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1085 return sum + orderLine.get_price_without_tax();
1088 getTax: function() {
1089 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1090 return sum + orderLine.get_tax();
1093 getTaxDetails: function(){
1095 var fulldetails = [];
1096 var taxes_by_id = {};
1098 for(var i = 0; i < this.pos.taxes.length; i++){
1099 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1102 this.get('orderLines').each(function(line){
1103 var ldetails = line.get_tax_details();
1104 for(var id in ldetails){
1105 if(ldetails.hasOwnProperty(id)){
1106 details[id] = (details[id] || 0) + ldetails[id];
1111 for(var id in details){
1112 if(details.hasOwnProperty(id)){
1113 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1119 getPaidTotal: function() {
1120 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
1121 return sum + paymentLine.get_amount();
1124 getChange: function(paymentline) {
1126 var change = this.getPaidTotal() - this.getTotalTaxIncluded();
1128 var change = -this.getTotalTaxIncluded();
1129 var lines = this.get('paymentLines').models;
1130 for (var i = 0; i < lines.length; i++) {
1131 change += lines[i].get_amount();
1132 if (lines[i] === paymentline) {
1137 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1139 getDueLeft: function(paymentline) {
1141 var due = this.getTotalTaxIncluded() - this.getPaidTotal();
1143 var due = this.getTotalTaxIncluded();
1144 var lines = this.get('paymentLines').models;
1145 for (var i = 0; i < lines.length; i++) {
1146 if (lines[i] === paymentline) {
1149 due -= lines[i].get_amount();
1153 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1156 return this.getDueLeft() === 0;
1158 isPaidWithCash: function(){
1159 return !!this.get('paymentLines').find( function(pl){
1160 return pl.cashregister.journal.type === 'cash';
1163 finalize: function(){
1166 set_to_invoice: function(to_invoice) {
1167 this.to_invoice = to_invoice;
1169 is_to_invoice: function(){
1170 return this.to_invoice;
1172 // remove all the paymentlines with zero money in it
1173 clean_empty_paymentlines: function() {
1174 var lines = this.get('paymentLines').models;
1176 for ( var i = 0; i < lines.length; i++) {
1177 if (!lines[i].get_amount()) {
1178 empty.push(lines[i]);
1181 for ( var i = 0; i < empty.length; i++) {
1182 this.removePaymentline(empty[i]);
1185 // the client related to the current order.
1186 set_client: function(client){
1187 this.set('client',client);
1189 get_client: function(){
1190 return this.get('client');
1192 get_client_name: function(){
1193 var client = this.get('client');
1194 return client ? client.name : "";
1196 // the order also stores the screen status, as the PoS supports
1197 // different active screens per order. This method is used to
1198 // store the screen status.
1199 set_screen_data: function(key,value){
1200 if(arguments.length === 2){
1201 this.screen_data[key] = value;
1202 }else if(arguments.length === 1){
1203 for(key in arguments[0]){
1204 this.screen_data[key] = arguments[0][key];
1208 set_to_invoice: function(to_invoice) {
1209 this.to_invoice = to_invoice;
1211 is_to_invoice: function(){
1212 return this.to_invoice;
1214 // remove all the paymentlines with zero money in it
1215 clean_empty_paymentlines: function() {
1216 var lines = this.get('paymentLines').models;
1218 for ( var i = 0; i < lines.length; i++) {
1219 if (!lines[i].get_amount()) {
1220 empty.push(lines[i]);
1223 for ( var i = 0; i < empty.length; i++) {
1224 this.removePaymentline(empty[i]);
1227 //see set_screen_data
1228 get_screen_data: function(key){
1229 return this.screen_data[key];
1231 // exports a JSON for receipt printing
1232 export_for_printing: function(){
1233 var orderlines = [];
1234 this.get('orderLines').each(function(orderline){
1235 orderlines.push(orderline.export_for_printing());
1238 var paymentlines = [];
1239 this.get('paymentLines').each(function(paymentline){
1240 paymentlines.push(paymentline.export_for_printing());
1242 var client = this.get('client');
1243 var cashier = this.pos.cashier || this.pos.user;
1244 var company = this.pos.company;
1245 var shop = this.pos.shop;
1246 var date = new Date();
1249 orderlines: orderlines,
1250 paymentlines: paymentlines,
1251 subtotal: this.getSubtotal(),
1252 total_with_tax: this.getTotalTaxIncluded(),
1253 total_without_tax: this.getTotalTaxExcluded(),
1254 total_tax: this.getTax(),
1255 total_paid: this.getPaidTotal(),
1256 total_discount: this.getDiscountTotal(),
1257 tax_details: this.getTaxDetails(),
1258 change: this.getChange(),
1259 name : this.getName(),
1260 client: client ? client.name : null ,
1261 invoice_id: null, //TODO
1262 cashier: cashier ? cashier.name : null,
1263 header: this.pos.config.receipt_header || '',
1264 footer: this.pos.config.receipt_footer || '',
1271 year: date.getFullYear(),
1272 month: date.getMonth(),
1273 date: date.getDate(), // day of the month
1274 day: date.getDay(), // day of the week
1275 hour: date.getHours(),
1276 minute: date.getMinutes() ,
1277 isostring: date.toISOString(),
1278 localestring: date.toLocaleString(),
1281 email: company.email,
1282 website: company.website,
1283 company_registry: company.company_registry,
1284 contact_address: company.partner_id[1],
1287 phone: company.phone,
1288 logo: this.pos.company_logo_base64,
1293 currency: this.pos.currency,
1296 export_as_JSON: function() {
1297 var orderLines, paymentLines;
1299 (this.get('orderLines')).each(_.bind( function(item) {
1300 return orderLines.push([0, 0, item.export_as_JSON()]);
1303 (this.get('paymentLines')).each(_.bind( function(item) {
1304 return paymentLines.push([0, 0, item.export_as_JSON()]);
1307 name: this.getName(),
1308 amount_paid: this.getPaidTotal(),
1309 amount_total: this.getTotalTaxIncluded(),
1310 amount_tax: this.getTax(),
1311 amount_return: this.getChange(),
1313 statement_ids: paymentLines,
1314 pos_session_id: this.pos.pos_session.id,
1315 partner_id: this.get_client() ? this.get_client().id : false,
1316 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1318 sequence_number: this.sequence_number,
1321 getSelectedLine: function(){
1322 return this.selected_orderline;
1324 selectLine: function(line){
1326 if(line !== this.selected_orderline){
1327 if(this.selected_orderline){
1328 this.selected_orderline.set_selected(false);
1330 this.selected_orderline = line;
1331 this.selected_orderline.set_selected(true);
1334 this.selected_orderline = undefined;
1337 deselectLine: function(){
1338 if(this.selected_orderline){
1339 this.selected_orderline.set_selected(false);
1340 this.selected_orderline = undefined;
1343 selectPaymentline: function(line){
1344 if(line !== this.selected_paymentline){
1345 if(this.selected_paymentline){
1346 this.selected_paymentline.set_selected(false);
1348 this.selected_paymentline = line;
1349 if(this.selected_paymentline){
1350 this.selected_paymentline.set_selected(true);
1352 this.trigger('change:selected_paymentline',this.selected_paymentline);
1357 module.OrderCollection = Backbone.Collection.extend({
1358 model: module.Order,
1362 The numpad handles both the choice of the property currently being modified
1363 (quantity, price or discount) and the edition of the corresponding numeric value.
1365 module.NumpadState = Backbone.Model.extend({
1370 appendNewChar: function(newChar) {
1372 oldBuffer = this.get('buffer');
1373 if (oldBuffer === '0') {
1377 } else if (oldBuffer === '-0') {
1379 buffer: "-" + newChar
1383 buffer: (this.get('buffer')) + newChar
1386 this.trigger('set_value',this.get('buffer'));
1388 deleteLastChar: function() {
1389 if(this.get('buffer') === ""){
1390 if(this.get('mode') === 'quantity'){
1391 this.trigger('set_value','remove');
1393 this.trigger('set_value',this.get('buffer'));
1396 var newBuffer = this.get('buffer').slice(0,-1) || "";
1397 this.set({ buffer: newBuffer });
1398 this.trigger('set_value',this.get('buffer'));
1401 switchSign: function() {
1403 oldBuffer = this.get('buffer');
1405 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1407 this.trigger('set_value',this.get('buffer'));
1409 changeMode: function(newMode) {
1421 resetValue: function(){
1422 this.set({buffer:'0'});