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];
206 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
207 loaded: function(self,configs){
208 self.config = configs[0];
209 self.config.use_proxy = self.config.iface_payment_terminal ||
210 self.config.iface_electronic_scale ||
211 self.config.iface_print_via_proxy ||
212 self.config.iface_scan_via_proxy ||
213 self.config.iface_cashdrawer;
215 self.barcode_reader.add_barcode_patterns({
216 'product': self.config.barcode_product,
217 'cashier': self.config.barcode_cashier,
218 'client': self.config.barcode_customer,
219 'weight': self.config.barcode_weight,
220 'discount': self.config.barcode_discount,
221 'price': self.config.barcode_price,
225 if (self.config.company_id[0] !== self.user.company_id[0]) {
226 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."));
229 self.db.set_uuid(self.config.uuid);
231 var orders = self.db.get_orders();
232 for (var i = 0; i < orders.length; i++) {
233 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
237 model: 'stock.location',
239 ids: function(self){ return [self.config.stock_location_id[0]]; },
240 loaded: function(self, locations){ self.shop = locations[0]; },
242 model: 'product.pricelist',
243 fields: ['currency_id'],
244 ids: function(self){ return [self.config.pricelist_id[0]]; },
245 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
247 model: 'res.currency',
248 fields: ['symbol','position','rounding','accuracy'],
249 ids: function(self){ return [self.pricelist.currency_id[0]]; },
250 loaded: function(self, currencies){
251 self.currency = currencies[0];
252 if (self.currency.rounding > 0) {
253 self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
255 self.currency.decimals = 0;
260 model: 'product.packaging',
261 fields: ['ean','product_tmpl_id'],
263 loaded: function(self, packagings){
264 self.db.add_packagings(packagings);
267 model: 'pos.category',
268 fields: ['id','name','parent_id','child_id','image'],
270 loaded: function(self, categories){
271 self.db.add_categories(categories);
274 model: 'product.product',
275 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
276 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
278 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
279 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
280 loaded: function(self, products){
281 self.db.add_products(products);
284 model: 'account.bank.statement',
285 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
286 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
287 loaded: function(self, bankstatements, tmp){
288 self.bankstatements = bankstatements;
291 _.each(bankstatements,function(statement){
292 tmp.journals.push(statement.journal_id[0]);
296 model: 'account.journal',
298 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
299 loaded: function(self, journals){
300 self.journals = journals;
302 // associate the bank statements with their journals.
303 var bankstatements = self.bankstatements;
304 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
305 for(var j = 0, jlen = journals.length; j < jlen; j++){
306 if(bankstatements[i].journal_id[0] === journals[j].id){
307 bankstatements[i].journal = journals[j];
311 self.cashregisters = bankstatements;
312 self.cashregisters_by_id = {};
313 for (var i = 0; i < self.cashregisters.length; i++) {
314 self.cashregisters_by_id[self.cashregisters[i].id] = self.cashregisters[i];
319 loaded: function(self){
320 var fonts_loaded = new $.Deferred();
321 // Waiting for fonts to be loaded to prevent receipt printing
322 // from printing empty receipt while loading Inconsolata
323 // ( The font used for the receipt )
324 waitForWebfonts(['Lato','Inconsolata'], function(){
325 fonts_loaded.resolve();
327 // The JS used to detect font loading is not 100% robust, so
328 // do not wait more than 5sec
329 setTimeout(function(){
330 fonts_loaded.resolve();
337 loaded: function(self){
338 self.company_logo = new Image();
339 var logo_loaded = new $.Deferred();
340 self.company_logo.onload = function(){
341 var img = self.company_logo;
343 var targetwidth = 300;
345 if( img.width !== targetwidth ){
346 ratio = targetwidth / img.width;
348 if( img.height * ratio > maxheight ){
349 ratio = maxheight / img.height;
351 var width = Math.floor(img.width * ratio);
352 var height = Math.floor(img.height * ratio);
353 var c = document.createElement('canvas');
356 var ctx = c.getContext('2d');
357 ctx.drawImage(self.company_logo,0,0, width, height);
359 self.company_logo_base64 = c.toDataURL();
360 logo_loaded.resolve();
362 self.company_logo.onerror = function(){
363 logo_loaded.reject();
365 self.company_logo.crossOrigin = "anonymous";
366 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
373 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
374 load_server_data: function(){
376 var loaded = new $.Deferred();
378 var progress_step = 1.0 / self.models.length;
379 var tmp = {}; // this is used to share a temporary state between models loaders
381 function load_model(index){
382 if(index >= self.models.length){
385 var model = self.models[index];
386 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
388 var cond = typeof model.condition === 'function' ? model.condition(self,tmp) : true;
394 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
395 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
396 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
397 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
398 progress += progress_step;
403 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
405 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
407 records.then(function(result){
408 try{ // catching exceptions in model.loaded(...)
409 $.when(model.loaded(self,result,tmp))
410 .then(function(){ load_model(index + 1); },
411 function(err){ loaded.reject(err); });
413 console.error(err.stack);
419 }else if( model.loaded ){
420 try{ // catching exceptions in model.loaded(...)
421 $.when(model.loaded(self,tmp))
422 .then( function(){ load_model(index +1); },
423 function(err){ loaded.reject(err); });
428 load_model(index + 1);
442 // reload the list of partner, returns as a deferred that resolves if there were
443 // updated partners, and fails if not
444 load_new_partners: function(){
446 var def = new $.Deferred();
447 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
448 new instance.web.Model('res.partner')
450 .filter([['write_date','>',this.db.get_partner_write_date()]])
451 .all({'timeout':3000, 'shadow': true})
452 .then(function(partners){
453 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
458 }, function(){ def.reject(); });
462 // this is called when an order is removed from the order collection. It ensures that there is always an existing
463 // order and a valid selected order
464 on_removed_order: function(removed_order,index,reason){
465 var order_list = this.get_order_list();
466 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
467 // when we intentionally remove an unfinished order, and there is another existing one
468 this.set_order(order_list[index] || order_list[order_list.length -1]);
470 // when the order was automatically removed after completion,
471 // or when we intentionally delete the only concurrent order
472 this.add_new_order();
476 //creates a new empty order and sets it as the current order
477 add_new_order: function(){
478 var order = new module.Order({},{pos:this});
479 this.get('orders').add(order);
480 this.set('selectedOrder', order);
483 // load the locally saved unpaid orders for this session.
484 load_orders: function(){
485 var jsons = this.db.get_unpaid_orders();
487 var not_loaded_count = 0;
489 for (var i = 0; i < jsons.length; i++) {
491 if (json.pos_session_id === this.pos_session.id) {
492 orders.push(new module.Order({},{
497 not_loaded_count += 1;
501 if (not_loaded_count) {
502 console.info('There are '+not_loaded_count+' locally saved unpaid orders belonging to another session');
505 orders = orders.sort(function(a,b){
506 return a.sequence_number - b.sequence_number;
510 this.get('orders').add(orders);
514 set_start_order: function(){
515 var orders = this.get('orders').models;
517 if (orders.length && !this.get('selectedOrder')) {
518 this.set('selectedOrder',orders[0]);
520 this.add_new_order();
524 // return the current order
525 get_order: function(){
526 return this.get('selectedOrder');
529 // change the current order
530 set_order: function(order){
531 this.set({ selectedOrder: order });
534 // return the list of unpaid orders
535 get_order_list: function(){
536 return this.get('orders').models;
539 //removes the current order
540 delete_current_order: function(){
541 var order = this.get_order();
543 order.destroy({'reason':'abandon'});
547 // saves the order locally and try to send it to the backend.
548 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
549 push_order: function(order) {
553 this.proxy.log('push_order',order.export_as_JSON());
554 this.db.add_order(order.export_as_JSON());
557 var pushed = new $.Deferred();
559 this.flush_mutex.exec(function(){
560 var flushed = self._flush_orders(self.db.get_orders());
562 flushed.always(function(ids){
569 // saves the order locally and try to send it to the backend and make an invoice
570 // returns a deferred that succeeds when the order has been posted and successfully generated
571 // an invoice. This method can fail in various ways:
572 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
573 // this error is solved
574 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
575 // the network connection is up
577 push_and_invoice_order: function(order){
579 var invoiced = new $.Deferred();
581 if(!order.get_client()){
582 invoiced.reject('error-no-client');
586 var order_id = this.db.add_order(order.export_as_JSON());
588 this.flush_mutex.exec(function(){
589 var done = new $.Deferred(); // holds the mutex
591 // send the order to the server
592 // we have a 30 seconds timeout on this push.
593 // FIXME: if the server takes more than 30 seconds to accept the order,
594 // the client will believe it wasn't successfully sent, and very bad
595 // things will happen as a duplicate will be sent next time
596 // so we must make sure the server detects and ignores duplicated orders
598 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
600 transfer.fail(function(){
601 invoiced.reject('error-transfer');
605 // on success, get the order id generated by the server
606 transfer.pipe(function(order_server_id){
608 // generate the pdf and download it
609 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
610 active_ids:order_server_id,
624 // wrapper around the _save_to_server that updates the synch status widget
625 _flush_orders: function(orders, options) {
627 this.set('synch',{ state: 'connecting', pending: orders.length});
629 return self._save_to_server(orders, options).done(function (server_ids) {
630 var pending = self.db.get_orders().length;
633 state: pending ? 'connecting' : 'connected',
641 // send an array of orders to the server
642 // available options:
643 // - timeout: timeout for the rpc call in ms
644 // returns a deferred that resolves with the list of
645 // server generated ids for the sent orders
646 _save_to_server: function (orders, options) {
647 if (!orders || !orders.length) {
648 var result = $.Deferred();
653 options = options || {};
656 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
658 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
659 // then we want to notify the user that we are waiting on something )
660 var posOrderModel = new instance.web.Model('pos.order');
661 return posOrderModel.call('create_from_ui',
662 [_.map(orders, function (order) {
663 order.to_invoice = options.to_invoice || false;
668 shadow: !options.to_invoice,
671 ).then(function (server_ids) {
672 _.each(orders, function (order) {
673 self.db.remove_order(order.id);
676 }).fail(function (error, event){
677 if(error.code === 200 ){ // Business Logic Error, not a connection problem
678 //if warning do not need to display traceback!!
679 if (error.data.exception_type == 'warning') {
680 delete error.data.debug;
682 self.pos_widget.screen_selector.show_popup('error-traceback',{
683 message: error.data.message,
684 comment: error.data.debug
687 // prevent an error popup creation by the rpc failure
688 // we want the failure to be silent as we send the orders in the background
689 event.preventDefault();
690 console.error('Failed to send orders:', orders);
694 scan_product: function(parsed_code){
696 var selectedOrder = this.get_order();
697 if(parsed_code.encoding === 'ean13'){
698 var product = this.db.get_product_by_ean13(parsed_code.base_code);
699 }else if(parsed_code.encoding === 'reference'){
700 var product = this.db.get_product_by_reference(parsed_code.code);
707 if(parsed_code.type === 'price'){
708 selectedOrder.add_product(product, {price:parsed_code.value});
709 }else if(parsed_code.type === 'weight'){
710 selectedOrder.add_product(product, {quantity:parsed_code.value, merge:false});
711 }else if(parsed_code.type === 'discount'){
712 selectedOrder.add_product(product, {discount:parsed_code.value, merge:false});
714 selectedOrder.add_product(product);
720 var orderline_id = 1;
722 // An orderline represent one element of the content of a client's shopping cart.
723 // An orderline contains a product, its quantity, its price, discount. etc.
724 // An Order contains zero or more Orderlines.
725 module.Orderline = Backbone.Model.extend({
726 initialize: function(attr,options){
727 this.pos = options.pos;
728 this.order = options.order;
730 this.init_from_JSON(options.json);
733 this.product = options.product;
734 this.price = options.product.price;
736 this.quantityStr = '1';
738 this.discountStr = '0';
740 this.selected = false;
741 this.id = orderline_id++;
743 init_from_JSON: function(json) {
744 this.product = this.pos.db.get_product_by_id(json.product_id);
746 console.error('ERROR: attempting to recover product not available in the point of sale');
748 this.price = json.price_unit;
749 this.set_discount(json.discount);
750 this.set_quantity(json.qty);
753 var orderline = new module.Orderline({},{
756 product: this.product,
759 orderline.quantity = this.quantity;
760 orderline.quantityStr = this.quantityStr;
761 orderline.discount = this.discount;
762 orderline.type = this.type;
763 orderline.selected = false;
766 // sets a discount [0,100]%
767 set_discount: function(discount){
768 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
769 this.discount = disc;
770 this.discountStr = '' + disc;
771 this.trigger('change',this);
773 // returns the discount [0,100]%
774 get_discount: function(){
775 return this.discount;
777 get_discount_str: function(){
778 return this.discountStr;
780 get_product_type: function(){
783 // sets the quantity of the product. The quantity will be rounded according to the
784 // product's unity of measure properties. Quantities greater than zero will not get
786 set_quantity: function(quantity){
787 if(quantity === 'remove'){
788 this.order.remove_orderline(this);
791 var quant = parseFloat(quantity) || 0;
792 var unit = this.get_unit();
795 this.quantity = round_pr(quant, unit.rounding);
796 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
798 this.quantity = round_pr(quant, 1);
799 this.quantityStr = this.quantity.toFixed(0);
802 this.quantity = quant;
803 this.quantityStr = '' + this.quantity;
806 this.trigger('change',this);
808 // return the quantity of product
809 get_quantity: function(){
810 return this.quantity;
812 get_quantity_str: function(){
813 return this.quantityStr;
815 get_quantity_str_with_unit: function(){
816 var unit = this.get_unit();
817 if(unit && !unit.is_unit){
818 return this.quantityStr + ' ' + unit.name;
820 return this.quantityStr;
823 // return the unit of measure of the product
824 get_unit: function(){
825 var unit_id = this.product.uom_id;
829 unit_id = unit_id[0];
833 return this.pos.units_by_id[unit_id];
835 // return the product of this orderline
836 get_product: function(){
839 // selects or deselects this orderline
840 set_selected: function(selected){
841 this.selected = selected;
842 this.trigger('change',this);
844 // returns true if this orderline is selected
845 is_selected: function(){
846 return this.selected;
848 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
849 // in the orderline. This returns true if it makes sense to merge the two
850 can_be_merged_with: function(orderline){
851 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
853 }else if(!this.get_unit() || !this.get_unit().groupable){
855 }else if(this.get_product_type() !== orderline.get_product_type()){
857 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
859 }else if(this.price !== orderline.price){
865 merge: function(orderline){
866 this.set_quantity(this.get_quantity() + orderline.get_quantity());
868 export_as_JSON: function() {
870 qty: this.get_quantity(),
871 price_unit: this.get_unit_price(),
872 discount: this.get_discount(),
873 product_id: this.get_product().id,
876 //used to create a json of the ticket, to be sent to the printer
877 export_for_printing: function(){
879 quantity: this.get_quantity(),
880 unit_name: this.get_unit().name,
881 price: this.get_unit_price(),
882 discount: this.get_discount(),
883 product_name: this.get_product().display_name,
884 price_display : this.get_display_price(),
885 price_with_tax : this.get_price_with_tax(),
886 price_without_tax: this.get_price_without_tax(),
888 product_description: this.get_product().description,
889 product_description_sale: this.get_product().description_sale,
892 // changes the base price of the product for this orderline
893 set_unit_price: function(price){
894 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
895 this.trigger('change',this);
897 get_unit_price: function(){
900 get_base_price: function(){
901 var rounding = this.pos.currency.rounding;
902 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
904 get_display_price: function(){
905 return this.get_base_price();
907 get_price_without_tax: function(){
908 return this.get_all_prices().priceWithoutTax;
910 get_price_with_tax: function(){
911 return this.get_all_prices().priceWithTax;
914 return this.get_all_prices().tax;
916 get_tax_details: function(){
917 return this.get_all_prices().taxDetails;
919 get_all_prices: function(){
921 var currency_rounding = this.pos.currency.rounding;
922 var base = this.get_base_price();
924 var totalNoTax = base;
926 var product = this.get_product();
927 var taxes_ids = product.taxes_id;
928 var taxes = self.pos.taxes;
931 _.each(taxes_ids, function(el) {
932 var tax = _.detect(taxes, function(t) {return t.id === el;});
933 if (tax.price_include) {
935 if (tax.type === "percent") {
936 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
937 } else if (tax.type === "fixed") {
938 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
940 throw "This type of tax is not supported by the point of sale: " + tax.type;
942 tmp = round_pr(tmp,currency_rounding);
945 taxdetail[tax.id] = tmp;
948 if (tax.type === "percent") {
949 tmp = tax.amount * base;
950 } else if (tax.type === "fixed") {
951 tmp = tax.amount * self.get_quantity();
953 throw "This type of tax is not supported by the point of sale: " + tax.type;
955 tmp = round_pr(tmp,currency_rounding);
958 taxdetail[tax.id] = tmp;
962 "priceWithTax": totalTax,
963 "priceWithoutTax": totalNoTax,
965 "taxDetails": taxdetail,
970 module.OrderlineCollection = Backbone.Collection.extend({
971 model: module.Orderline,
974 // Every Paymentline contains a cashregister and an amount of money.
975 module.Paymentline = Backbone.Model.extend({
976 initialize: function(attributes, options) {
977 this.pos = options.pos;
979 this.selected = false;
981 this.init_from_JSON(options.json);
984 this.cashregister = options.cashregister;
985 this.name = this.cashregister.journal_id[1];
987 init_from_JSON: function(json){
988 this.amount = json.amount;
989 this.cashregister = this.pos.cashregisters_by_id[json.statement_id];
990 this.name = this.cashregister.journal_id[0];
992 //sets the amount of money on this payment line
993 set_amount: function(value){
994 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
995 this.trigger('change:amount',this);
997 // returns the amount of money on this paymentline
998 get_amount: function(){
1001 get_amount_str: function(){
1002 return this.amount.toFixed(this.pos.currency.decimals);
1004 set_selected: function(selected){
1005 if(this.selected !== selected){
1006 this.selected = selected;
1007 this.trigger('change:selected',this);
1010 // returns the associated cashregister
1011 //exports as JSON for server communication
1012 export_as_JSON: function(){
1014 name: instance.web.datetime_to_str(new Date()),
1015 statement_id: this.cashregister.id,
1016 account_id: this.cashregister.account_id[0],
1017 journal_id: this.cashregister.journal_id[0],
1018 amount: this.get_amount()
1021 //exports as JSON for receipt printing
1022 export_for_printing: function(){
1024 amount: this.get_amount(),
1025 journal: this.cashregister.journal_id[1],
1030 module.PaymentlineCollection = Backbone.Collection.extend({
1031 model: module.Paymentline,
1034 // An order more or less represents the content of a client's shopping cart (the OrderLines)
1035 // plus the associated payment information (the Paymentlines)
1036 // there is always an active ('selected') order in the Pos, a new one is created
1037 // automaticaly once an order is completed and sent to the server.
1038 module.Order = Backbone.Model.extend({
1039 initialize: function(attributes,options){
1040 Backbone.Model.prototype.initialize.apply(this, arguments);
1041 options = options || {};
1043 this.init_locked = true;
1044 this.pos = options.pos;
1045 this.selected_orderline = undefined;
1046 this.selected_paymentline = undefined;
1047 this.screen_data = {}; // see ScreenSelector
1048 this.temporary = options.temporary || false;
1049 this.creation_date = new Date();
1050 this.to_invoice = false;
1051 this.orderlines = new module.OrderlineCollection();
1052 this.paymentlines = new module.PaymentlineCollection();
1053 this.pos_session_id = this.pos.pos_session.id;
1055 this.set({ client: null });
1058 this.init_from_JSON(options.json);
1060 this.sequence_number = this.pos.pos_session.sequence_number++;
1061 this.uid = this.generate_unique_id();
1062 this.name = _t("Order ") + this.uid;
1065 this.on('change', this.save_to_db, this);
1066 this.orderlines.on('change', this.save_to_db, this);
1067 this.paymentlines.on('change', this.save_to_db, this);
1069 this.init_locked = false;
1074 save_to_db: function(){
1075 if (!this.init_locked) {
1076 this.pos.db.save_unpaid_order(this);
1079 init_from_JSON: function(json) {
1080 this.sequence_number = json.sequence_number;
1081 this.pos.pos_session.sequence_number = Math.max(this.sequence_number+1,this.pos.pos_session.sequence_number);
1082 this.session_id = json.pos_session_id;
1083 this.uid = json.uid;
1084 this.name = _t("Order ") + this.uid;
1085 if (json.partner_id) {
1086 var client = this.pos.db.get_partner_by_id(json.partner_id);
1088 console.error('ERROR: trying to load a parner not available in the pos');
1093 this.set_client(client);
1095 this.temporary = false; // FIXME
1096 this.to_invoice = false; // FIXME
1098 var orderlines = json.lines;
1099 for (var i = 0; i < orderlines.length; i++) {
1100 var orderline = orderlines[i][2];
1101 this.add_orderline(new module.Orderline({}, {pos: this.pos, order: this, json: orderline}));
1104 var paymentlines = json.statement_ids;
1105 for (var i = 0; i < paymentlines.length; i++) {
1106 var paymentline = paymentlines[i][2];
1107 this.paymentlines.add(new module.Paymentline({},{pos: this.pos, json: paymentline}));
1110 export_as_JSON: function() {
1111 var orderLines, paymentLines;
1113 this.orderlines.each(_.bind( function(item) {
1114 return orderLines.push([0, 0, item.export_as_JSON()]);
1117 this.paymentlines.each(_.bind( function(item) {
1118 return paymentLines.push([0, 0, item.export_as_JSON()]);
1121 name: this.get_name(),
1122 amount_paid: this.get_total_paid(),
1123 amount_total: this.get_total_with_tax(),
1124 amount_tax: this.get_total_tax(),
1125 amount_return: this.get_change(),
1127 statement_ids: paymentLines,
1128 pos_session_id: this.pos_session_id,
1129 partner_id: this.get_client() ? this.get_client().id : false,
1130 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1132 sequence_number: this.sequence_number,
1135 export_for_printing: function(){
1136 var orderlines = [];
1139 this.orderlines.each(function(orderline){
1140 orderlines.push(orderline.export_for_printing());
1143 var paymentlines = [];
1144 this.paymentlines.each(function(paymentline){
1145 paymentlines.push(paymentline.export_for_printing());
1147 var client = this.get('client');
1148 var cashier = this.pos.cashier || this.pos.user;
1149 var company = this.pos.company;
1150 var shop = this.pos.shop;
1151 var date = new Date();
1153 function is_xml(subreceipt){
1154 return subreceipt ? (subreceipt.split('\n')[0].indexOf('<!DOCTYPE QWEB') >= 0) : false;
1157 function render_xml(subreceipt){
1158 if (!is_xml(subreceipt)) {
1161 subreceipt = subreceipt.split('\n').slice(1).join('\n');
1162 var qweb = new QWeb2.Engine();
1163 qweb.debug = instance.session.debug;
1164 qweb.default_dict = _.clone(QWeb.default_dict);
1165 qweb.add_template('<templates><t t-name="subreceipt">'+subreceipt+'</t></templates>');
1167 return qweb.render('subreceipt',{'pos':self.pos,'widget':self.pos.pos_widget,'order':self, 'receipt': receipt}) ;
1172 orderlines: orderlines,
1173 paymentlines: paymentlines,
1174 subtotal: this.get_subtotal(),
1175 total_with_tax: this.get_total_with_tax(),
1176 total_without_tax: this.get_total_without_tax(),
1177 total_tax: this.get_total_tax(),
1178 total_paid: this.get_total_paid(),
1179 total_discount: this.get_total_discount(),
1180 tax_details: this.get_tax_details(),
1181 change: this.get_change(),
1182 name : this.get_name(),
1183 client: client ? client.name : null ,
1184 invoice_id: null, //TODO
1185 cashier: cashier ? cashier.name : null,
1186 header: this.pos.config.receipt_header || '',
1187 footer: this.pos.config.receipt_footer || '',
1194 year: date.getFullYear(),
1195 month: date.getMonth(),
1196 date: date.getDate(), // day of the month
1197 day: date.getDay(), // day of the week
1198 hour: date.getHours(),
1199 minute: date.getMinutes() ,
1200 isostring: date.toISOString(),
1201 localestring: date.toLocaleString(),
1204 email: company.email,
1205 website: company.website,
1206 company_registry: company.company_registry,
1207 contact_address: company.partner_id[1],
1210 phone: company.phone,
1211 logo: this.pos.company_logo_base64,
1216 currency: this.pos.currency,
1219 if (is_xml(this.pos.config.receipt_header)){
1220 receipt.header_xml = render_xml(this.pos.config.receipt_header);
1223 if (is_xml(this.pos.config.receipt_footer)){
1224 receipt.footer_xml = render_xml(this.pos.config.receipt_footer);
1229 is_empty: function(){
1230 return this.orderlines.models.length === 0;
1232 generate_unique_id: function() {
1233 // Generates a public identification number for the order.
1234 // The generated number must be unique and sequential. They are made 12 digit long
1235 // to fit into EAN-13 barcodes, should it be needed
1237 function zero_pad(num,size){
1239 while (s.length < size) {
1244 return zero_pad(this.pos.pos_session.id,5) +'-'+
1245 zero_pad(this.pos.pos_session.login_number,3) +'-'+
1246 zero_pad(this.sequence_number,4);
1248 get_name: function() {
1251 /* ---- Order Lines --- */
1252 add_orderline: function(line){
1254 line.order.remove_orderline(line);
1257 this.orderlines.add(line);
1258 this.select_orderline(this.get_last_orderline());
1260 get_orderline: function(id){
1261 var orderlines = this.orderlines.models;
1262 for(var i = 0; i < orderlines.length; i++){
1263 if(orderlines[i].id === id){
1264 return orderlines[i];
1269 get_orderlines: function(){
1270 return this.orderlines.models;
1272 get_last_orderline: function(){
1273 return this.orderlines.at(this.orderlines.length -1);
1275 remove_orderline: function( line ){
1276 this.orderlines.remove(line);
1277 this.select_orderline(this.get_last_orderline());
1279 add_product: function(product, options){
1280 options = options || {};
1281 var attr = JSON.parse(JSON.stringify(product));
1282 attr.pos = this.pos;
1284 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1286 if(options.quantity !== undefined){
1287 line.set_quantity(options.quantity);
1289 if(options.price !== undefined){
1290 line.set_unit_price(options.price);
1292 if(options.discount !== undefined){
1293 line.set_discount(options.discount);
1296 if(options.extras !== undefined){
1297 for (var prop in options.extras) {
1298 line[prop] = options.extras[prop];
1302 var last_orderline = this.get_last_orderline();
1303 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1304 last_orderline.merge(line);
1306 this.orderlines.add(line);
1308 this.select_orderline(this.get_last_orderline());
1310 get_selected_orderline: function(){
1311 return this.selected_orderline;
1313 select_orderline: function(line){
1315 if(line !== this.selected_orderline){
1316 if(this.selected_orderline){
1317 this.selected_orderline.set_selected(false);
1319 this.selected_orderline = line;
1320 this.selected_orderline.set_selected(true);
1323 this.selected_orderline = undefined;
1326 deselect_orderline: function(){
1327 if(this.selected_orderline){
1328 this.selected_orderline.set_selected(false);
1329 this.selected_orderline = undefined;
1332 /* ---- Payment Lines --- */
1333 add_paymentline: function(cashregister) {
1334 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos: this.pos});
1335 if(cashregister.journal.type !== 'cash' || this.pos.config.iface_precompute_cash){
1336 newPaymentline.set_amount( Math.max(this.get_due(),0) );
1338 this.paymentlines.add(newPaymentline);
1339 this.select_paymentline(newPaymentline);
1342 get_paymentlines: function(){
1343 return this.paymentlines.models;
1345 remove_paymentline: function(line){
1346 if(this.selected_paymentline === line){
1347 this.select_paymentline(undefined);
1349 this.paymentlines.remove(line);
1351 clean_empty_paymentlines: function() {
1352 var lines = this.paymentlines.models;
1354 for ( var i = 0; i < lines.length; i++) {
1355 if (!lines[i].get_amount()) {
1356 empty.push(lines[i]);
1359 for ( var i = 0; i < empty.length; i++) {
1360 this.remove_paymentline(empty[i]);
1363 select_paymentline: function(line){
1364 if(line !== this.selected_paymentline){
1365 if(this.selected_paymentline){
1366 this.selected_paymentline.set_selected(false);
1368 this.selected_paymentline = line;
1369 if(this.selected_paymentline){
1370 this.selected_paymentline.set_selected(true);
1372 this.trigger('change:selected_paymentline',this.selected_paymentline);
1375 /* ---- Payment Status --- */
1376 get_subtotal : function(){
1377 return this.orderlines.reduce((function(sum, orderLine){
1378 return sum + orderLine.get_display_price();
1381 get_total_with_tax: function() {
1382 return this.orderlines.reduce((function(sum, orderLine) {
1383 return sum + orderLine.get_price_with_tax();
1386 get_total_without_tax: function() {
1387 return this.orderlines.reduce((function(sum, orderLine) {
1388 return sum + orderLine.get_price_without_tax();
1391 get_total_discount: function() {
1392 return this.orderlines.reduce((function(sum, orderLine) {
1393 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1396 get_total_tax: function() {
1397 return this.orderlines.reduce((function(sum, orderLine) {
1398 return sum + orderLine.get_tax();
1401 get_total_paid: function() {
1402 return this.paymentlines.reduce((function(sum, paymentLine) {
1403 return sum + paymentLine.get_amount();
1406 get_tax_details: function(){
1408 var fulldetails = [];
1409 var taxes_by_id = {};
1411 for(var i = 0; i < this.pos.taxes.length; i++){
1412 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1415 this.orderlines.each(function(line){
1416 var ldetails = line.get_tax_details();
1417 for(var id in ldetails){
1418 if(ldetails.hasOwnProperty(id)){
1419 details[id] = (details[id] || 0) + ldetails[id];
1424 for(var id in details){
1425 if(details.hasOwnProperty(id)){
1426 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1432 get_change: function(paymentline) {
1434 var change = this.get_total_paid() - this.get_total_with_tax();
1436 var change = -this.get_total_with_tax();
1437 var lines = this.paymentlines.models;
1438 for (var i = 0; i < lines.length; i++) {
1439 change += lines[i].get_amount();
1440 if (lines[i] === paymentline) {
1445 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1447 get_due: function(paymentline) {
1449 var due = this.get_total_with_tax() - this.get_total_paid();
1451 var due = this.get_total_with_tax();
1452 var lines = this.paymentlines.models;
1453 for (var i = 0; i < lines.length; i++) {
1454 if (lines[i] === paymentline) {
1457 due -= lines[i].get_amount();
1461 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1463 is_paid: function(){
1464 return this.get_due() === 0;
1466 is_paid_with_cash: function(){
1467 return !!this.paymentlines.find( function(pl){
1468 return pl.cashregister.journal.type === 'cash';
1471 finalize: function(){
1474 destroy: function(args){
1475 Backbone.Model.prototype.destroy.apply(this,arguments);
1476 this.pos.db.remove_unpaid_order(this);
1478 /* ---- Invoice --- */
1479 set_to_invoice: function(to_invoice) {
1480 this.to_invoice = to_invoice;
1482 is_to_invoice: function(){
1483 return this.to_invoice;
1485 /* ---- Client / Customer --- */
1486 // the client related to the current order.
1487 set_client: function(client){
1488 this.set('client',client);
1490 get_client: function(){
1491 return this.get('client');
1493 get_client_name: function(){
1494 var client = this.get('client');
1495 return client ? client.name : "";
1497 /* ---- Screen Status --- */
1498 // the order also stores the screen status, as the PoS supports
1499 // different active screens per order. This method is used to
1500 // store the screen status.
1501 set_screen_data: function(key,value){
1502 if(arguments.length === 2){
1503 this.screen_data[key] = value;
1504 }else if(arguments.length === 1){
1505 for(var key in arguments[0]){
1506 this.screen_data[key] = arguments[0][key];
1510 //see set_screen_data
1511 get_screen_data: function(key){
1512 return this.screen_data[key];
1516 module.OrderCollection = Backbone.Collection.extend({
1517 model: module.Order,
1521 The numpad handles both the choice of the property currently being modified
1522 (quantity, price or discount) and the edition of the corresponding numeric value.
1524 module.NumpadState = Backbone.Model.extend({
1529 appendNewChar: function(newChar) {
1531 oldBuffer = this.get('buffer');
1532 if (oldBuffer === '0') {
1536 } else if (oldBuffer === '-0') {
1538 buffer: "-" + newChar
1542 buffer: (this.get('buffer')) + newChar
1545 this.trigger('set_value',this.get('buffer'));
1547 deleteLastChar: function() {
1548 if(this.get('buffer') === ""){
1549 if(this.get('mode') === 'quantity'){
1550 this.trigger('set_value','remove');
1552 this.trigger('set_value',this.get('buffer'));
1555 var newBuffer = this.get('buffer').slice(0,-1) || "";
1556 this.set({ buffer: newBuffer });
1557 this.trigger('set_value',this.get('buffer'));
1560 switchSign: function() {
1562 oldBuffer = this.get('buffer');
1564 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1566 this.trigger('set_value',this.get('buffer'));
1568 changeMode: function(newMode) {
1580 resetValue: function(){
1581 this.set({buffer:'0'});