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;
6 var barcode_parser_module = instance.barcodes;
8 var round_di = instance.web.round_decimals;
9 var round_pr = instance.web.round_precision
11 // The PosModel contains the Point Of Sale's representation of the backend.
12 // Since the PoS must work in standalone ( Without connection to the server )
13 // it must contains a representation of the server's PoS backend.
14 // (taxes, product list, configuration options, etc.) this representation
15 // is fetched and stored by the PosModel at the initialisation.
16 // this is done asynchronously, a ready deferred alows the GUI to wait interactively
17 // for the loading to be completed
18 // There is a single instance of the PosModel for each Front-End instance, it is usually called
19 // 'pos' and is available to all widgets extending PosWidget.
21 module.PosModel = Backbone.Model.extend({
22 initialize: function(session, attributes) {
23 Backbone.Model.prototype.initialize.call(this, attributes);
25 this.session = session;
26 this.flush_mutex = new $.Mutex(); // used to make sure the orders are sent to the server once at time
27 this.pos_widget = attributes.pos_widget;
29 this.proxy = new module.ProxyDevice(this); // used to communicate to the hardware devices via a local proxy
30 this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy});
32 this.proxy_queue = new module.JobQueue(); // used to prevent parallels communications to the proxy
33 this.db = new module.PosDB(); // a local database used to search trough products and categories & store pending orders
34 this.debug = jQuery.deparam(jQuery.param.querystring()).debug !== undefined; //debug mode
36 // Business data; loaded from the server at launch
37 this.accounting_precision = 2; //TODO
38 this.company_logo = null;
39 this.company_logo_base64 = '';
47 this.cashregisters = [];
48 this.bankstatements = [];
50 this.pos_session = null;
53 this.units_by_id = {};
54 this.pricelist = null;
55 this.order_sequence = 1;
56 window.posmodel = this;
58 // these dynamic attributes can be watched for change by other models or widgets
60 'synch': { state:'connected', pending:0 },
61 'orders': new module.OrderCollection(),
62 'selectedOrder': null,
65 this.bind('change:synch',function(pos,synch){
66 clearTimeout(self.synch_timeout);
67 self.synch_timeout = setTimeout(function(){
68 if(synch.state !== 'disconnected' && synch.pending > 0){
69 self.set('synch',{state:'disconnected', pending:synch.pending});
74 this.get('orders').bind('remove', function(order,_unused_,options){
75 self.on_removed_order(order,options.index,options.reason);
78 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
79 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
80 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
81 this.ready = this.load_server_data()
83 if(self.config.use_proxy){
84 return self.connect_to_proxy();
86 }); // used to read barcodes);
89 // releases ressources holds by the model at the end of life of the posmodel
91 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
94 this.barcode_reader.disconnect();
95 this.barcode_reader.disconnect_from_proxy();
97 connect_to_proxy: function(){
99 var done = new $.Deferred();
100 this.barcode_reader.disconnect_from_proxy();
101 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
102 this.pos_widget.loading_skip(function(){
103 self.proxy.stop_searching();
105 this.proxy.autoconnect({
106 force_ip: self.config.proxy_ip || undefined,
107 progress: function(prog){
108 self.pos_widget.loading_progress(prog);
111 if(self.config.iface_scan_via_proxy){
112 self.barcode_reader.connect_to_proxy();
114 }).always(function(){
120 // helper function to load data from the server. Obsolete use the models loader below.
121 fetch: function(model, fields, domain, ctx){
122 this._load_progress = (this._load_progress || 0) + 0.05;
123 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
124 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
127 // Server side model loaders. This is the list of the models that need to be loaded from
128 // the server. The models are loaded one by one by this list's order. The 'loaded' callback
129 // is used to store the data in the appropriate place once it has been loaded. This callback
130 // can return a deferred that will pause the loading of the next module.
131 // a shared temporary dictionary is available for loaders to communicate private variables
132 // used during loading such as object ids, etc.
136 fields: ['name','company_id'],
137 ids: function(self){ return [self.session.uid]; },
138 loaded: function(self,users){ self.user = users[0]; },
140 model: 'res.company',
141 fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id'],
142 ids: function(self){ return [self.user.company_id[0]] },
143 loaded: function(self,companies){ self.company = companies[0]; },
145 model: 'decimal.precision',
146 fields: ['name','digits'],
147 loaded: function(self,dps){
149 for (var i = 0; i < dps.length; i++) {
150 self.dp[dps[i].name] = dps[i].digits;
154 model: 'product.uom',
157 loaded: function(self,units){
159 var units_by_id = {};
160 for(var i = 0, len = units.length; i < len; i++){
161 units_by_id[units[i].id] = units[i];
162 units[i].groupable = ( units[i].category_id[0] === 1 );
163 units[i].is_unit = ( units[i].id === 1 );
165 self.units_by_id = units_by_id;
169 fields: ['name','barcode'],
171 loaded: function(self,users){ self.users = users; },
173 model: 'res.partner',
174 fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','barcode','write_date'],
176 loaded: function(self,partners){
177 self.partners = partners;
178 self.db.add_partners(partners);
181 model: 'res.country',
183 loaded: function(self,countries){
184 self.countries = countries;
185 self.company.country = null;
186 for (var i = 0; i < countries.length; i++) {
187 if (countries[i].id === self.company.country_id[0]){
188 self.company.country = countries[i];
193 model: 'account.tax',
194 fields: ['name','amount', 'price_include', 'type'],
196 loaded: function(self,taxes){
198 self.taxes_by_id = {};
200 for (var i = 0; i < taxes.length; i++) {
201 self.taxes_by_id[taxes[i].id] = taxes[i];
205 model: 'pos.session',
206 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
207 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
208 loaded: function(self,pos_sessions){
209 self.pos_session = pos_sessions[0];
214 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
215 loaded: function(self,configs){
216 self.config = configs[0];
217 self.config.use_proxy = self.config.iface_payment_terminal ||
218 self.config.iface_electronic_scale ||
219 self.config.iface_print_via_proxy ||
220 self.config.iface_scan_via_proxy ||
221 self.config.iface_cashdrawer;
223 if (self.config.company_id[0] !== self.user.company_id[0]) {
224 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."));
227 self.db.set_uuid(self.config.uuid);
229 var orders = self.db.get_orders();
230 for (var i = 0; i < orders.length; i++) {
231 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
235 model: 'stock.location',
237 ids: function(self){ return [self.config.stock_location_id[0]]; },
238 loaded: function(self, locations){ self.shop = locations[0]; },
240 model: 'product.pricelist',
241 fields: ['currency_id'],
242 ids: function(self){ return [self.config.pricelist_id[0]]; },
243 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
245 model: 'res.currency',
246 fields: ['symbol','position','rounding','accuracy'],
247 ids: function(self){ return [self.pricelist.currency_id[0]]; },
248 loaded: function(self, currencies){
249 self.currency = currencies[0];
250 if (self.currency.rounding > 0) {
251 self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
253 self.currency.decimals = 0;
258 model: 'product.packaging',
259 fields: ['barcode','product_tmpl_id'],
261 loaded: function(self, packagings){
262 self.db.add_packagings(packagings);
265 model: 'pos.category',
266 fields: ['id','name','parent_id','child_id','image'],
268 loaded: function(self, categories){
269 self.db.add_categories(categories);
272 model: 'product.product',
273 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'barcode', 'default_code',
274 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
276 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
277 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
278 loaded: function(self, products){
279 self.db.add_products(products);
282 model: 'account.bank.statement',
283 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
284 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
285 loaded: function(self, bankstatements, tmp){
286 self.bankstatements = bankstatements;
289 _.each(bankstatements,function(statement){
290 tmp.journals.push(statement.journal_id[0]);
294 model: 'account.journal',
296 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
297 loaded: function(self, journals){
298 self.journals = journals;
300 // associate the bank statements with their journals.
301 var bankstatements = self.bankstatements;
302 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
303 for(var j = 0, jlen = journals.length; j < jlen; j++){
304 if(bankstatements[i].journal_id[0] === journals[j].id){
305 bankstatements[i].journal = journals[j];
309 self.cashregisters = bankstatements;
310 self.cashregisters_by_id = {};
311 for (var i = 0; i < self.cashregisters.length; i++) {
312 self.cashregisters_by_id[self.cashregisters[i].id] = self.cashregisters[i];
317 loaded: function(self){
318 var fonts_loaded = new $.Deferred();
319 // Waiting for fonts to be loaded to prevent receipt printing
320 // from printing empty receipt while loading Inconsolata
321 // ( The font used for the receipt )
322 waitForWebfonts(['Lato','Inconsolata'], function(){
323 fonts_loaded.resolve();
325 // The JS used to detect font loading is not 100% robust, so
326 // do not wait more than 5sec
327 setTimeout(function(){
328 fonts_loaded.resolve();
335 loaded: function(self){
336 self.company_logo = new Image();
337 var logo_loaded = new $.Deferred();
338 self.company_logo.onload = function(){
339 var img = self.company_logo;
341 var targetwidth = 300;
343 if( img.width !== targetwidth ){
344 ratio = targetwidth / img.width;
346 if( img.height * ratio > maxheight ){
347 ratio = maxheight / img.height;
349 var width = Math.floor(img.width * ratio);
350 var height = Math.floor(img.height * ratio);
351 var c = document.createElement('canvas');
354 var ctx = c.getContext('2d');
355 ctx.drawImage(self.company_logo,0,0, width, height);
357 self.company_logo_base64 = c.toDataURL();
358 logo_loaded.resolve();
360 self.company_logo.onerror = function(){
361 logo_loaded.reject();
363 self.company_logo.crossOrigin = "anonymous";
364 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
370 loaded: function(self) {
371 var barcode_parser = new barcode_parser_module.BarcodeParser({'nomenclature_id': self.config.barcode_nomenclature_id});
372 self.barcode_reader.set_barcode_parser(barcode_parser);
373 return barcode_parser.is_loaded();
378 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
379 load_server_data: function(){
381 var loaded = new $.Deferred();
383 var progress_step = 1.0 / self.models.length;
384 var tmp = {}; // this is used to share a temporary state between models loaders
386 function load_model(index){
387 if(index >= self.models.length){
390 var model = self.models[index];
391 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
393 var cond = typeof model.condition === 'function' ? model.condition(self,tmp) : true;
399 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
400 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
401 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
402 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
403 progress += progress_step;
408 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
410 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
412 records.then(function(result){
413 try{ // catching exceptions in model.loaded(...)
414 $.when(model.loaded(self,result,tmp))
415 .then(function(){ load_model(index + 1); },
416 function(err){ loaded.reject(err); });
418 console.error(err.stack);
424 }else if( model.loaded ){
425 try{ // catching exceptions in model.loaded(...)
426 $.when(model.loaded(self,tmp))
427 .then( function(){ load_model(index +1); },
428 function(err){ loaded.reject(err); });
433 load_model(index + 1);
447 // reload the list of partner, returns as a deferred that resolves if there were
448 // updated partners, and fails if not
449 load_new_partners: function(){
451 var def = new $.Deferred();
452 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
453 new instance.web.Model('res.partner')
455 .filter([['write_date','>',this.db.get_partner_write_date()]])
456 .all({'timeout':3000, 'shadow': true})
457 .then(function(partners){
458 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
463 }, function(){ def.reject(); });
467 // this is called when an order is removed from the order collection. It ensures that there is always an existing
468 // order and a valid selected order
469 on_removed_order: function(removed_order,index,reason){
470 var order_list = this.get_order_list();
471 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
472 // when we intentionally remove an unfinished order, and there is another existing one
473 this.set_order(order_list[index] || order_list[order_list.length -1]);
475 // when the order was automatically removed after completion,
476 // or when we intentionally delete the only concurrent order
477 this.add_new_order();
481 //creates a new empty order and sets it as the current order
482 add_new_order: function(){
483 var order = new module.Order({},{pos:this});
484 this.get('orders').add(order);
485 this.set('selectedOrder', order);
488 // load the locally saved unpaid orders for this session.
489 load_orders: function(){
490 var jsons = this.db.get_unpaid_orders();
492 var not_loaded_count = 0;
494 for (var i = 0; i < jsons.length; i++) {
496 if (json.pos_session_id === this.pos_session.id) {
497 orders.push(new module.Order({},{
502 not_loaded_count += 1;
506 if (not_loaded_count) {
507 console.info('There are '+not_loaded_count+' locally saved unpaid orders belonging to another session');
510 orders = orders.sort(function(a,b){
511 return a.sequence_number - b.sequence_number;
515 this.get('orders').add(orders);
519 set_start_order: function(){
520 var orders = this.get('orders').models;
522 if (orders.length && !this.get('selectedOrder')) {
523 this.set('selectedOrder',orders[0]);
525 this.add_new_order();
529 // return the current order
530 get_order: function(){
531 return this.get('selectedOrder');
534 // change the current order
535 set_order: function(order){
536 this.set({ selectedOrder: order });
539 // return the list of unpaid orders
540 get_order_list: function(){
541 return this.get('orders').models;
544 //removes the current order
545 delete_current_order: function(){
546 var order = this.get_order();
548 order.destroy({'reason':'abandon'});
552 // saves the order locally and try to send it to the backend.
553 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
554 push_order: function(order) {
558 this.proxy.log('push_order',order.export_as_JSON());
559 this.db.add_order(order.export_as_JSON());
562 var pushed = new $.Deferred();
564 this.flush_mutex.exec(function(){
565 var flushed = self._flush_orders(self.db.get_orders());
567 flushed.always(function(ids){
574 // saves the order locally and try to send it to the backend and make an invoice
575 // returns a deferred that succeeds when the order has been posted and successfully generated
576 // an invoice. This method can fail in various ways:
577 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
578 // this error is solved
579 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
580 // the network connection is up
582 push_and_invoice_order: function(order){
584 var invoiced = new $.Deferred();
586 if(!order.get_client()){
587 invoiced.reject('error-no-client');
591 var order_id = this.db.add_order(order.export_as_JSON());
593 this.flush_mutex.exec(function(){
594 var done = new $.Deferred(); // holds the mutex
596 // send the order to the server
597 // we have a 30 seconds timeout on this push.
598 // FIXME: if the server takes more than 30 seconds to accept the order,
599 // the client will believe it wasn't successfully sent, and very bad
600 // things will happen as a duplicate will be sent next time
601 // so we must make sure the server detects and ignores duplicated orders
603 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
605 transfer.fail(function(){
606 invoiced.reject('error-transfer');
610 // on success, get the order id generated by the server
611 transfer.pipe(function(order_server_id){
613 // generate the pdf and download it
614 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
615 active_ids:order_server_id,
629 // wrapper around the _save_to_server that updates the synch status widget
630 _flush_orders: function(orders, options) {
632 this.set('synch',{ state: 'connecting', pending: orders.length});
634 return self._save_to_server(orders, options).done(function (server_ids) {
635 var pending = self.db.get_orders().length;
638 state: pending ? 'connecting' : 'connected',
646 // send an array of orders to the server
647 // available options:
648 // - timeout: timeout for the rpc call in ms
649 // returns a deferred that resolves with the list of
650 // server generated ids for the sent orders
651 _save_to_server: function (orders, options) {
652 if (!orders || !orders.length) {
653 var result = $.Deferred();
658 options = options || {};
661 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
663 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
664 // then we want to notify the user that we are waiting on something )
665 var posOrderModel = new instance.web.Model('pos.order');
666 return posOrderModel.call('create_from_ui',
667 [_.map(orders, function (order) {
668 order.to_invoice = options.to_invoice || false;
673 shadow: !options.to_invoice,
676 ).then(function (server_ids) {
677 _.each(orders, function (order) {
678 self.db.remove_order(order.id);
681 }).fail(function (error, event){
682 if(error.code === 200 ){ // Business Logic Error, not a connection problem
683 //if warning do not need to display traceback!!
684 if (error.data.exception_type == 'warning') {
685 delete error.data.debug;
687 self.pos_widget.screen_selector.show_popup('error-traceback',{
688 message: error.data.message,
689 comment: error.data.debug
692 // prevent an error popup creation by the rpc failure
693 // we want the failure to be silent as we send the orders in the background
694 event.preventDefault();
695 console.error('Failed to send orders:', orders);
699 scan_product: function(parsed_code){
701 var selectedOrder = this.get_order();
702 var product = this.db.get_product_by_barcode(parsed_code.base_code);
708 if(parsed_code.type === 'price'){
709 selectedOrder.add_product(product, {price:parsed_code.value});
710 }else if(parsed_code.type === 'weight'){
711 selectedOrder.add_product(product, {quantity:parsed_code.value, merge:false});
712 }else if(parsed_code.type === 'discount'){
713 selectedOrder.add_product(product, {discount:parsed_code.value, merge:false});
715 selectedOrder.add_product(product);
721 var orderline_id = 1;
723 // An orderline represent one element of the content of a client's shopping cart.
724 // An orderline contains a product, its quantity, its price, discount. etc.
725 // An Order contains zero or more Orderlines.
726 module.Orderline = Backbone.Model.extend({
727 initialize: function(attr,options){
728 this.pos = options.pos;
729 this.order = options.order;
731 this.init_from_JSON(options.json);
734 this.product = options.product;
735 this.price = options.product.price;
737 this.quantityStr = '1';
739 this.discountStr = '0';
741 this.selected = false;
742 this.id = orderline_id++;
744 init_from_JSON: function(json) {
745 this.product = this.pos.db.get_product_by_id(json.product_id);
747 console.error('ERROR: attempting to recover product not available in the point of sale');
749 this.price = json.price_unit;
750 this.set_discount(json.discount);
751 this.set_quantity(json.qty);
754 var orderline = new module.Orderline({},{
757 product: this.product,
760 orderline.quantity = this.quantity;
761 orderline.quantityStr = this.quantityStr;
762 orderline.discount = this.discount;
763 orderline.type = this.type;
764 orderline.selected = false;
767 // sets a discount [0,100]%
768 set_discount: function(discount){
769 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
770 this.discount = disc;
771 this.discountStr = '' + disc;
772 this.trigger('change',this);
774 // returns the discount [0,100]%
775 get_discount: function(){
776 return this.discount;
778 get_discount_str: function(){
779 return this.discountStr;
781 get_product_type: function(){
784 // sets the quantity of the product. The quantity will be rounded according to the
785 // product's unity of measure properties. Quantities greater than zero will not get
787 set_quantity: function(quantity){
788 if(quantity === 'remove'){
789 this.order.remove_orderline(this);
792 var quant = parseFloat(quantity) || 0;
793 var unit = this.get_unit();
796 this.quantity = round_pr(quant, unit.rounding);
797 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
799 this.quantity = round_pr(quant, 1);
800 this.quantityStr = this.quantity.toFixed(0);
803 this.quantity = quant;
804 this.quantityStr = '' + this.quantity;
807 this.trigger('change',this);
809 // return the quantity of product
810 get_quantity: function(){
811 return this.quantity;
813 get_quantity_str: function(){
814 return this.quantityStr;
816 get_quantity_str_with_unit: function(){
817 var unit = this.get_unit();
818 if(unit && !unit.is_unit){
819 return this.quantityStr + ' ' + unit.name;
821 return this.quantityStr;
824 // return the unit of measure of the product
825 get_unit: function(){
826 var unit_id = this.product.uom_id;
830 unit_id = unit_id[0];
834 return this.pos.units_by_id[unit_id];
836 // return the product of this orderline
837 get_product: function(){
840 // selects or deselects this orderline
841 set_selected: function(selected){
842 this.selected = selected;
843 this.trigger('change',this);
845 // returns true if this orderline is selected
846 is_selected: function(){
847 return this.selected;
849 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
850 // in the orderline. This returns true if it makes sense to merge the two
851 can_be_merged_with: function(orderline){
852 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
854 }else if(!this.get_unit() || !this.get_unit().groupable){
856 }else if(this.get_product_type() !== orderline.get_product_type()){
858 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
860 }else if(this.price !== orderline.price){
866 merge: function(orderline){
867 this.set_quantity(this.get_quantity() + orderline.get_quantity());
869 export_as_JSON: function() {
871 qty: this.get_quantity(),
872 price_unit: this.get_unit_price(),
873 discount: this.get_discount(),
874 product_id: this.get_product().id,
877 //used to create a json of the ticket, to be sent to the printer
878 export_for_printing: function(){
880 quantity: this.get_quantity(),
881 unit_name: this.get_unit().name,
882 price: this.get_unit_display_price(),
883 discount: this.get_discount(),
884 product_name: this.get_product().display_name,
885 price_display : this.get_display_price(),
886 price_with_tax : this.get_price_with_tax(),
887 price_without_tax: this.get_price_without_tax(),
889 product_description: this.get_product().description,
890 product_description_sale: this.get_product().description_sale,
893 // changes the base price of the product for this orderline
894 set_unit_price: function(price){
895 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
896 this.trigger('change',this);
898 get_unit_price: function(){
901 get_unit_display_price: function(){
902 if (this.pos.config.iface_tax_included) {
903 var quantity = this.quantity;
905 var price = this.get_all_prices().priceWithTax;
906 this.quantity = quantity;
909 return this.get_unit_price();
912 get_base_price: function(){
913 var rounding = this.pos.currency.rounding;
914 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
916 get_display_price: function(){
917 return this.get_base_price();
918 if (this.pos.config.iface_tax_included) {
919 return this.get_all_prices().priceWithTax;
921 return this.get_base_price();
924 get_price_without_tax: function(){
925 return this.get_all_prices().priceWithoutTax;
927 get_price_with_tax: function(){
928 return this.get_all_prices().priceWithTax;
931 return this.get_all_prices().tax;
933 get_tax_details: function(){
934 return this.get_all_prices().taxDetails;
936 get_taxes: function(){
937 var taxes_ids = this.get_product().taxes_id;
939 for (var i = 0; i < taxes_ids.length; i++) {
940 taxes.push(this.pos.taxes_by_id[taxes_ids[i]]);
944 get_all_prices: function(){
946 var currency_rounding = this.pos.currency.rounding;
947 var base = this.get_base_price();
949 var totalNoTax = base;
951 var product = this.get_product();
952 var taxes_ids = product.taxes_id;
953 var taxes = self.pos.taxes;
956 _.each(taxes_ids, function(el) {
957 var tax = _.detect(taxes, function(t) {return t.id === el;});
958 if (tax.price_include) {
960 if (tax.type === "percent") {
961 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
962 } else if (tax.type === "fixed") {
963 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
965 throw "This type of tax is not supported by the point of sale: " + tax.type;
967 tmp = round_pr(tmp,currency_rounding);
970 taxdetail[tax.id] = tmp;
973 if (tax.type === "percent") {
974 tmp = tax.amount * base;
975 } else if (tax.type === "fixed") {
976 tmp = tax.amount * self.get_quantity();
978 throw "This type of tax is not supported by the point of sale: " + tax.type;
980 tmp = round_pr(tmp,currency_rounding);
983 taxdetail[tax.id] = tmp;
987 "priceWithTax": totalTax,
988 "priceWithoutTax": totalNoTax,
990 "taxDetails": taxdetail,
995 module.OrderlineCollection = Backbone.Collection.extend({
996 model: module.Orderline,
999 // Every Paymentline contains a cashregister and an amount of money.
1000 module.Paymentline = Backbone.Model.extend({
1001 initialize: function(attributes, options) {
1002 this.pos = options.pos;
1004 this.selected = false;
1006 this.init_from_JSON(options.json);
1009 this.cashregister = options.cashregister;
1010 this.name = this.cashregister.journal_id[1];
1012 init_from_JSON: function(json){
1013 this.amount = json.amount;
1014 this.cashregister = this.pos.cashregisters_by_id[json.statement_id];
1015 this.name = this.cashregister.journal_id[1];
1017 //sets the amount of money on this payment line
1018 set_amount: function(value){
1019 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
1020 this.trigger('change',this);
1022 // returns the amount of money on this paymentline
1023 get_amount: function(){
1026 get_amount_str: function(){
1027 return this.amount.toFixed(this.pos.currency.decimals);
1029 set_selected: function(selected){
1030 if(this.selected !== selected){
1031 this.selected = selected;
1032 this.trigger('change',this);
1035 // returns the associated cashregister
1036 //exports as JSON for server communication
1037 export_as_JSON: function(){
1039 name: instance.web.datetime_to_str(new Date()),
1040 statement_id: this.cashregister.id,
1041 account_id: this.cashregister.account_id[0],
1042 journal_id: this.cashregister.journal_id[0],
1043 amount: this.get_amount()
1046 //exports as JSON for receipt printing
1047 export_for_printing: function(){
1049 amount: this.get_amount(),
1050 journal: this.cashregister.journal_id[1],
1055 module.PaymentlineCollection = Backbone.Collection.extend({
1056 model: module.Paymentline,
1059 // An order more or less represents the content of a client's shopping cart (the OrderLines)
1060 // plus the associated payment information (the Paymentlines)
1061 // there is always an active ('selected') order in the Pos, a new one is created
1062 // automaticaly once an order is completed and sent to the server.
1063 module.Order = Backbone.Model.extend({
1064 initialize: function(attributes,options){
1065 Backbone.Model.prototype.initialize.apply(this, arguments);
1066 options = options || {};
1068 this.init_locked = true;
1069 this.pos = options.pos;
1070 this.selected_orderline = undefined;
1071 this.selected_paymentline = undefined;
1072 this.screen_data = {}; // see ScreenSelector
1073 this.temporary = options.temporary || false;
1074 this.creation_date = new Date();
1075 this.to_invoice = false;
1076 this.orderlines = new module.OrderlineCollection();
1077 this.paymentlines = new module.PaymentlineCollection();
1078 this.pos_session_id = this.pos.pos_session.id;
1080 this.set({ client: null });
1083 this.init_from_JSON(options.json);
1085 this.sequence_number = this.pos.pos_session.sequence_number++;
1086 this.uid = this.generate_unique_id();
1087 this.name = _t("Order ") + this.uid;
1090 this.on('change', function(){ this.save_to_db("order:change"); }, this);
1091 this.orderlines.on('change', function(){ this.save_to_db("orderline:change"); }, this);
1092 this.orderlines.on('add', function(){ this.save_to_db("orderline:add"); }, this);
1093 this.orderlines.on('remove', function(){ this.save_to_db("orderline:remove"); }, this);
1094 this.paymentlines.on('change', function(){ this.save_to_db("paymentline:change"); }, this);
1095 this.paymentlines.on('add', function(){ this.save_to_db("paymentline:add"); }, this);
1096 this.paymentlines.on('remove', function(){ this.save_to_db("paymentline:rem"); }, this);
1098 this.init_locked = false;
1103 save_to_db: function(){
1104 if (!this.init_locked) {
1105 this.pos.db.save_unpaid_order(this);
1108 init_from_JSON: function(json) {
1109 this.sequence_number = json.sequence_number;
1110 this.pos.pos_session.sequence_number = Math.max(this.sequence_number+1,this.pos.pos_session.sequence_number);
1111 this.session_id = json.pos_session_id;
1112 this.uid = json.uid;
1113 this.name = _t("Order ") + this.uid;
1114 if (json.partner_id) {
1115 var client = this.pos.db.get_partner_by_id(json.partner_id);
1117 console.error('ERROR: trying to load a parner not available in the pos');
1122 this.set_client(client);
1124 this.temporary = false; // FIXME
1125 this.to_invoice = false; // FIXME
1127 var orderlines = json.lines;
1128 for (var i = 0; i < orderlines.length; i++) {
1129 var orderline = orderlines[i][2];
1130 this.add_orderline(new module.Orderline({}, {pos: this.pos, order: this, json: orderline}));
1133 var paymentlines = json.statement_ids;
1134 for (var i = 0; i < paymentlines.length; i++) {
1135 var paymentline = paymentlines[i][2];
1136 var newpaymentline = new module.Paymentline({},{pos: this.pos, json: paymentline});
1137 this.paymentlines.add(newpaymentline);
1139 if (i === paymentlines.length - 1) {
1140 this.select_paymentline(newpaymentline);
1144 export_as_JSON: function() {
1145 var orderLines, paymentLines;
1147 this.orderlines.each(_.bind( function(item) {
1148 return orderLines.push([0, 0, item.export_as_JSON()]);
1151 this.paymentlines.each(_.bind( function(item) {
1152 return paymentLines.push([0, 0, item.export_as_JSON()]);
1155 name: this.get_name(),
1156 amount_paid: this.get_total_paid(),
1157 amount_total: this.get_total_with_tax(),
1158 amount_tax: this.get_total_tax(),
1159 amount_return: this.get_change(),
1161 statement_ids: paymentLines,
1162 pos_session_id: this.pos_session_id,
1163 partner_id: this.get_client() ? this.get_client().id : false,
1164 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1166 sequence_number: this.sequence_number,
1169 export_for_printing: function(){
1170 var orderlines = [];
1173 this.orderlines.each(function(orderline){
1174 orderlines.push(orderline.export_for_printing());
1177 var paymentlines = [];
1178 this.paymentlines.each(function(paymentline){
1179 paymentlines.push(paymentline.export_for_printing());
1181 var client = this.get('client');
1182 var cashier = this.pos.cashier || this.pos.user;
1183 var company = this.pos.company;
1184 var shop = this.pos.shop;
1185 var date = new Date();
1187 function is_xml(subreceipt){
1188 return subreceipt ? (subreceipt.split('\n')[0].indexOf('<!DOCTYPE QWEB') >= 0) : false;
1191 function render_xml(subreceipt){
1192 if (!is_xml(subreceipt)) {
1195 subreceipt = subreceipt.split('\n').slice(1).join('\n');
1196 var qweb = new QWeb2.Engine();
1197 qweb.debug = instance.session.debug;
1198 qweb.default_dict = _.clone(QWeb.default_dict);
1199 qweb.add_template('<templates><t t-name="subreceipt">'+subreceipt+'</t></templates>');
1201 return qweb.render('subreceipt',{'pos':self.pos,'widget':self.pos.pos_widget,'order':self, 'receipt': receipt}) ;
1206 orderlines: orderlines,
1207 paymentlines: paymentlines,
1208 subtotal: this.get_subtotal(),
1209 total_with_tax: this.get_total_with_tax(),
1210 total_without_tax: this.get_total_without_tax(),
1211 total_tax: this.get_total_tax(),
1212 total_paid: this.get_total_paid(),
1213 total_discount: this.get_total_discount(),
1214 tax_details: this.get_tax_details(),
1215 change: this.get_change(),
1216 name : this.get_name(),
1217 client: client ? client.name : null ,
1218 invoice_id: null, //TODO
1219 cashier: cashier ? cashier.name : null,
1220 header: this.pos.config.receipt_header || '',
1221 footer: this.pos.config.receipt_footer || '',
1228 year: date.getFullYear(),
1229 month: date.getMonth(),
1230 date: date.getDate(), // day of the month
1231 day: date.getDay(), // day of the week
1232 hour: date.getHours(),
1233 minute: date.getMinutes() ,
1234 isostring: date.toISOString(),
1235 localestring: date.toLocaleString(),
1238 email: company.email,
1239 website: company.website,
1240 company_registry: company.company_registry,
1241 contact_address: company.partner_id[1],
1244 phone: company.phone,
1245 logo: this.pos.company_logo_base64,
1250 currency: this.pos.currency,
1253 if (is_xml(this.pos.config.receipt_header)){
1254 receipt.header_xml = render_xml(this.pos.config.receipt_header);
1257 if (is_xml(this.pos.config.receipt_footer)){
1258 receipt.footer_xml = render_xml(this.pos.config.receipt_footer);
1263 is_empty: function(){
1264 return this.orderlines.models.length === 0;
1266 generate_unique_id: function() {
1267 // Generates a public identification number for the order.
1268 // The generated number must be unique and sequential. They are made 12 digit long
1269 // to fit into EAN-13 barcodes, should it be needed
1271 function zero_pad(num,size){
1273 while (s.length < size) {
1278 return zero_pad(this.pos.pos_session.id,5) +'-'+
1279 zero_pad(this.pos.pos_session.login_number,3) +'-'+
1280 zero_pad(this.sequence_number,4);
1282 get_name: function() {
1285 /* ---- Order Lines --- */
1286 add_orderline: function(line){
1288 line.order.remove_orderline(line);
1291 this.orderlines.add(line);
1292 this.select_orderline(this.get_last_orderline());
1294 get_orderline: function(id){
1295 var orderlines = this.orderlines.models;
1296 for(var i = 0; i < orderlines.length; i++){
1297 if(orderlines[i].id === id){
1298 return orderlines[i];
1303 get_orderlines: function(){
1304 return this.orderlines.models;
1306 get_last_orderline: function(){
1307 return this.orderlines.at(this.orderlines.length -1);
1309 remove_orderline: function( line ){
1310 this.orderlines.remove(line);
1311 this.select_orderline(this.get_last_orderline());
1313 add_product: function(product, options){
1314 options = options || {};
1315 var attr = JSON.parse(JSON.stringify(product));
1316 attr.pos = this.pos;
1318 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1320 if(options.quantity !== undefined){
1321 line.set_quantity(options.quantity);
1323 if(options.price !== undefined){
1324 line.set_unit_price(options.price);
1326 if(options.discount !== undefined){
1327 line.set_discount(options.discount);
1330 if(options.extras !== undefined){
1331 for (var prop in options.extras) {
1332 line[prop] = options.extras[prop];
1336 var last_orderline = this.get_last_orderline();
1337 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1338 last_orderline.merge(line);
1340 this.orderlines.add(line);
1342 this.select_orderline(this.get_last_orderline());
1344 get_selected_orderline: function(){
1345 return this.selected_orderline;
1347 select_orderline: function(line){
1349 if(line !== this.selected_orderline){
1350 if(this.selected_orderline){
1351 this.selected_orderline.set_selected(false);
1353 this.selected_orderline = line;
1354 this.selected_orderline.set_selected(true);
1357 this.selected_orderline = undefined;
1360 deselect_orderline: function(){
1361 if(this.selected_orderline){
1362 this.selected_orderline.set_selected(false);
1363 this.selected_orderline = undefined;
1366 /* ---- Payment Lines --- */
1367 add_paymentline: function(cashregister) {
1368 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos: this.pos});
1369 if(cashregister.journal.type !== 'cash' || this.pos.config.iface_precompute_cash){
1370 newPaymentline.set_amount( Math.max(this.get_due(),0) );
1372 this.paymentlines.add(newPaymentline);
1373 this.select_paymentline(newPaymentline);
1376 get_paymentlines: function(){
1377 return this.paymentlines.models;
1379 remove_paymentline: function(line){
1380 if(this.selected_paymentline === line){
1381 this.select_paymentline(undefined);
1383 this.paymentlines.remove(line);
1385 clean_empty_paymentlines: function() {
1386 var lines = this.paymentlines.models;
1388 for ( var i = 0; i < lines.length; i++) {
1389 if (!lines[i].get_amount()) {
1390 empty.push(lines[i]);
1393 for ( var i = 0; i < empty.length; i++) {
1394 this.remove_paymentline(empty[i]);
1397 select_paymentline: function(line){
1398 if(line !== this.selected_paymentline){
1399 if(this.selected_paymentline){
1400 this.selected_paymentline.set_selected(false);
1402 this.selected_paymentline = line;
1403 if(this.selected_paymentline){
1404 this.selected_paymentline.set_selected(true);
1406 this.trigger('change:selected_paymentline',this.selected_paymentline);
1409 /* ---- Payment Status --- */
1410 get_subtotal : function(){
1411 return this.orderlines.reduce((function(sum, orderLine){
1412 return sum + orderLine.get_display_price();
1415 get_total_with_tax: function() {
1416 return this.orderlines.reduce((function(sum, orderLine) {
1417 return sum + orderLine.get_price_with_tax();
1420 get_total_without_tax: function() {
1421 return this.orderlines.reduce((function(sum, orderLine) {
1422 return sum + orderLine.get_price_without_tax();
1425 get_total_discount: function() {
1426 return this.orderlines.reduce((function(sum, orderLine) {
1427 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1430 get_total_tax: function() {
1431 return this.orderlines.reduce((function(sum, orderLine) {
1432 return sum + orderLine.get_tax();
1435 get_total_paid: function() {
1436 return this.paymentlines.reduce((function(sum, paymentLine) {
1437 return sum + paymentLine.get_amount();
1440 get_tax_details: function(){
1442 var fulldetails = [];
1443 var taxes_by_id = {};
1445 for(var i = 0; i < this.pos.taxes.length; i++){
1446 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1449 this.orderlines.each(function(line){
1450 var ldetails = line.get_tax_details();
1451 for(var id in ldetails){
1452 if(ldetails.hasOwnProperty(id)){
1453 details[id] = (details[id] || 0) + ldetails[id];
1458 for(var id in details){
1459 if(details.hasOwnProperty(id)){
1460 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1466 // Returns a total only for the orderlines with products belonging to the category
1467 get_total_for_category_with_tax: function(categ_id){
1471 if (categ_id instanceof Array) {
1472 for (var i = 0; i < categ_id.length; i++) {
1473 total += this.get_total_for_category_with_tax(categ_id[i]);
1478 this.orderlines.each(function(line){
1479 if ( self.pos.db.category_contains(categ_id,line.product.id) ) {
1480 total += line.get_price_with_tax();
1486 get_total_for_taxes: function(tax_id){
1490 if (!(tax_id instanceof Array)) {
1496 for (var i = 0; i < tax_id.length; i++) {
1497 tax_set[tax_id[i]] = true;
1500 this.orderlines.each(function(line){
1501 var taxes_ids = line.get_product().taxes_id;
1502 for (var i = 0; i < taxes_ids.length; i++) {
1503 if (tax_set[taxes_ids[i]]) {
1504 total += line.get_price_with_tax();
1512 get_change: function(paymentline) {
1514 var change = this.get_total_paid() - this.get_total_with_tax();
1516 var change = -this.get_total_with_tax();
1517 var lines = this.paymentlines.models;
1518 for (var i = 0; i < lines.length; i++) {
1519 change += lines[i].get_amount();
1520 if (lines[i] === paymentline) {
1525 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1527 get_due: function(paymentline) {
1529 var due = this.get_total_with_tax() - this.get_total_paid();
1531 var due = this.get_total_with_tax();
1532 var lines = this.paymentlines.models;
1533 for (var i = 0; i < lines.length; i++) {
1534 if (lines[i] === paymentline) {
1537 due -= lines[i].get_amount();
1541 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1543 is_paid: function(){
1544 return this.get_due() === 0;
1546 is_paid_with_cash: function(){
1547 return !!this.paymentlines.find( function(pl){
1548 return pl.cashregister.journal.type === 'cash';
1551 finalize: function(){
1554 destroy: function(args){
1555 Backbone.Model.prototype.destroy.apply(this,arguments);
1556 this.pos.db.remove_unpaid_order(this);
1558 /* ---- Invoice --- */
1559 set_to_invoice: function(to_invoice) {
1560 this.to_invoice = to_invoice;
1562 is_to_invoice: function(){
1563 return this.to_invoice;
1565 /* ---- Client / Customer --- */
1566 // the client related to the current order.
1567 set_client: function(client){
1568 this.set('client',client);
1570 get_client: function(){
1571 return this.get('client');
1573 get_client_name: function(){
1574 var client = this.get('client');
1575 return client ? client.name : "";
1577 /* ---- Screen Status --- */
1578 // the order also stores the screen status, as the PoS supports
1579 // different active screens per order. This method is used to
1580 // store the screen status.
1581 set_screen_data: function(key,value){
1582 if(arguments.length === 2){
1583 this.screen_data[key] = value;
1584 }else if(arguments.length === 1){
1585 for(var key in arguments[0]){
1586 this.screen_data[key] = arguments[0][key];
1590 //see set_screen_data
1591 get_screen_data: function(key){
1592 return this.screen_data[key];
1596 module.OrderCollection = Backbone.Collection.extend({
1597 model: module.Order,
1601 The numpad handles both the choice of the property currently being modified
1602 (quantity, price or discount) and the edition of the corresponding numeric value.
1604 module.NumpadState = Backbone.Model.extend({
1609 appendNewChar: function(newChar) {
1611 oldBuffer = this.get('buffer');
1612 if (oldBuffer === '0') {
1616 } else if (oldBuffer === '-0') {
1618 buffer: "-" + newChar
1622 buffer: (this.get('buffer')) + newChar
1625 this.trigger('set_value',this.get('buffer'));
1627 deleteLastChar: function() {
1628 if(this.get('buffer') === ""){
1629 if(this.get('mode') === 'quantity'){
1630 this.trigger('set_value','remove');
1632 this.trigger('set_value',this.get('buffer'));
1635 var newBuffer = this.get('buffer').slice(0,-1) || "";
1636 this.set({ buffer: newBuffer });
1637 this.trigger('set_value',this.get('buffer'));
1640 switchSign: function() {
1642 oldBuffer = this.get('buffer');
1644 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1646 this.trigger('set_value',this.get('buffer'));
1648 changeMode: function(newMode) {
1660 resetValue: function(){
1661 this.set({buffer:'0'});