1 openerp.point_of_sale.load_models = function load_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 = [];
49 this.pos_session = null;
52 this.units_by_id = {};
53 this.pricelist = null;
54 this.order_sequence = 1;
55 window.posmodel = this;
57 // these dynamic attributes can be watched for change by other models or widgets
59 'synch': { state:'connected', pending:0 },
60 'orders': new module.OrderCollection(),
61 'selectedOrder': null,
64 this.bind('change:synch',function(pos,synch){
65 clearTimeout(self.synch_timeout);
66 self.synch_timeout = setTimeout(function(){
67 if(synch.state !== 'disconnected' && synch.pending > 0){
68 self.set('synch',{state:'disconnected', pending:synch.pending});
73 this.get('orders').bind('remove', function(order,_unused_,options){
74 self.on_removed_order(order,options.index,options.reason);
77 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
78 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
79 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
80 this.ready = this.load_server_data()
82 if(self.config.use_proxy){
83 return self.connect_to_proxy();
85 }); // used to read barcodes);
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;
167 model: 'res.partner',
168 fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','barcode','write_date'],
169 domain: [['customer','=',true]],
170 loaded: function(self,partners){
171 self.partners = partners;
172 self.db.add_partners(partners);
175 model: 'res.country',
177 loaded: function(self,countries){
178 self.countries = countries;
179 self.company.country = null;
180 for (var i = 0; i < countries.length; i++) {
181 if (countries[i].id === self.company.country_id[0]){
182 self.company.country = countries[i];
187 model: 'account.tax',
188 fields: ['name','amount', 'price_include', 'type'],
190 loaded: function(self,taxes){
192 self.taxes_by_id = {};
194 for (var i = 0; i < taxes.length; i++) {
195 self.taxes_by_id[taxes[i].id] = taxes[i];
199 model: 'pos.session',
200 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
201 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
202 loaded: function(self,pos_sessions){
203 self.pos_session = pos_sessions[0];
208 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
209 loaded: function(self,configs){
210 self.config = configs[0];
211 self.config.use_proxy = self.config.iface_payment_terminal ||
212 self.config.iface_electronic_scale ||
213 self.config.iface_print_via_proxy ||
214 self.config.iface_scan_via_proxy ||
215 self.config.iface_cashdrawer;
217 if (self.config.company_id[0] !== self.user.company_id[0]) {
218 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."));
221 self.db.set_uuid(self.config.uuid);
223 var orders = self.db.get_orders();
224 for (var i = 0; i < orders.length; i++) {
225 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
230 fields: ['name','pos_security_pin','groups_id','barcode'],
231 domain: function(self){ return [['company_id','=',self.user.company_id[0]],'|', ['groups_id','=', self.config.group_pos_manager_id[0]],['groups_id','=', self.config.group_pos_user_id[0]]]; },
232 loaded: function(self,users){
233 // we attribute a role to the user, 'cashier' or 'manager', depending
234 // on the group the user belongs.
236 for (var i = 0; i < users.length; i++) {
238 for (var j = 0; j < user.groups_id.length; j++) {
239 var group_id = user.groups_id[j];
240 if (group_id === self.config.group_pos_manager_id[0]) {
241 user.role = 'manager';
243 } else if (group_id === self.config.group_pos_user_id[0]) {
244 user.role = 'cashier';
248 pos_users.push(user);
250 // replace the current user with its updated version
251 if (user.id === self.user.id) {
255 self.users = pos_users;
258 model: 'stock.location',
260 ids: function(self){ return [self.config.stock_location_id[0]]; },
261 loaded: function(self, locations){ self.shop = locations[0]; },
263 model: 'product.pricelist',
264 fields: ['currency_id'],
265 ids: function(self){ return [self.config.pricelist_id[0]]; },
266 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
268 model: 'res.currency',
269 fields: ['symbol','position','rounding','accuracy'],
270 ids: function(self){ return [self.pricelist.currency_id[0]]; },
271 loaded: function(self, currencies){
272 self.currency = currencies[0];
273 if (self.currency.rounding > 0) {
274 self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
276 self.currency.decimals = 0;
281 model: 'product.packaging',
282 fields: ['barcode','product_tmpl_id'],
284 loaded: function(self, packagings){
285 self.db.add_packagings(packagings);
288 model: 'pos.category',
289 fields: ['id','name','parent_id','child_id','image'],
291 loaded: function(self, categories){
292 self.db.add_categories(categories);
295 model: 'product.product',
296 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'barcode', 'default_code',
297 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
299 order: ['sequence','name'],
300 domain: [['sale_ok','=',true],['available_in_pos','=',true]],
301 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
302 loaded: function(self, products){
303 self.db.add_products(products);
306 model: 'account.bank.statement',
307 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
308 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
309 loaded: function(self, cashregisters, tmp){
310 self.cashregisters = cashregisters;
313 _.each(cashregisters,function(statement){
314 tmp.journals.push(statement.journal_id[0]);
318 model: 'account.journal',
320 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
321 loaded: function(self, journals){
322 self.journals = journals;
324 // associate the bank statements with their journals.
325 var cashregisters = self.cashregisters;
326 for(var i = 0, ilen = cashregisters.length; i < ilen; i++){
327 for(var j = 0, jlen = journals.length; j < jlen; j++){
328 if(cashregisters[i].journal_id[0] === journals[j].id){
329 cashregisters[i].journal = journals[j];
334 self.cashregisters_by_id = {};
335 for (var i = 0; i < self.cashregisters.length; i++) {
336 self.cashregisters_by_id[self.cashregisters[i].id] = self.cashregisters[i];
339 self.cashregisters = self.cashregisters.sort(function(a,b){
340 return a.journal.sequence - b.journal.sequence;
346 loaded: function(self){
347 var fonts_loaded = new $.Deferred();
348 // Waiting for fonts to be loaded to prevent receipt printing
349 // from printing empty receipt while loading Inconsolata
350 // ( The font used for the receipt )
351 waitForWebfonts(['Lato','Inconsolata'], function(){
352 fonts_loaded.resolve();
354 // The JS used to detect font loading is not 100% robust, so
355 // do not wait more than 5sec
356 setTimeout(function(){
357 fonts_loaded.resolve();
364 loaded: function(self){
365 self.company_logo = new Image();
366 var logo_loaded = new $.Deferred();
367 self.company_logo.onload = function(){
368 var img = self.company_logo;
370 var targetwidth = 300;
372 if( img.width !== targetwidth ){
373 ratio = targetwidth / img.width;
375 if( img.height * ratio > maxheight ){
376 ratio = maxheight / img.height;
378 var width = Math.floor(img.width * ratio);
379 var height = Math.floor(img.height * ratio);
380 var c = document.createElement('canvas');
383 var ctx = c.getContext('2d');
384 ctx.drawImage(self.company_logo,0,0, width, height);
386 self.company_logo_base64 = c.toDataURL();
387 logo_loaded.resolve();
389 self.company_logo.onerror = function(){
390 logo_loaded.reject();
392 self.company_logo.crossOrigin = "anonymous";
393 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
399 loaded: function(self) {
400 var barcode_parser = new barcode_parser_module.BarcodeParser({'nomenclature_id': self.config.barcode_nomenclature_id});
401 self.barcode_reader.set_barcode_parser(barcode_parser);
402 return barcode_parser.is_loaded();
407 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
408 load_server_data: function(){
410 var loaded = new $.Deferred();
412 var progress_step = 1.0 / self.models.length;
413 var tmp = {}; // this is used to share a temporary state between models loaders
415 function load_model(index){
416 if(index >= self.models.length){
419 var model = self.models[index];
420 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
422 var cond = typeof model.condition === 'function' ? model.condition(self,tmp) : true;
428 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
429 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
430 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
431 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
432 var order = typeof model.order === 'function' ? model.order(self,tmp): model.order;
433 progress += progress_step;
438 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
440 var records = new instance.web.Model(model.model).query(fields).filter(domain).order_by(order).context(context).all()
442 records.then(function(result){
443 try{ // catching exceptions in model.loaded(...)
444 $.when(model.loaded(self,result,tmp))
445 .then(function(){ load_model(index + 1); },
446 function(err){ loaded.reject(err); });
448 console.error(err.stack);
454 }else if( model.loaded ){
455 try{ // catching exceptions in model.loaded(...)
456 $.when(model.loaded(self,tmp))
457 .then( function(){ load_model(index +1); },
458 function(err){ loaded.reject(err); });
463 load_model(index + 1);
477 // reload the list of partner, returns as a deferred that resolves if there were
478 // updated partners, and fails if not
479 load_new_partners: function(){
481 var def = new $.Deferred();
482 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
483 new instance.web.Model('res.partner')
485 .filter([['write_date','>',this.db.get_partner_write_date()]])
486 .all({'timeout':3000, 'shadow': true})
487 .then(function(partners){
488 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
493 }, function(err,event){ event.preventDefault(); def.reject(); });
497 // this is called when an order is removed from the order collection. It ensures that there is always an existing
498 // order and a valid selected order
499 on_removed_order: function(removed_order,index,reason){
500 var order_list = this.get_order_list();
501 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
502 // when we intentionally remove an unfinished order, and there is another existing one
503 this.set_order(order_list[index] || order_list[order_list.length -1]);
505 // when the order was automatically removed after completion,
506 // or when we intentionally delete the only concurrent order
507 this.add_new_order();
511 // returns the user who is currently the cashier for this point of sale
512 get_cashier: function(){
513 return this.cashier || this.user;
515 // changes the current cashier
516 set_cashier: function(user){
519 //creates a new empty order and sets it as the current order
520 add_new_order: function(){
521 var order = new module.Order({},{pos:this});
522 this.get('orders').add(order);
523 this.set('selectedOrder', order);
526 // load the locally saved unpaid orders for this session.
527 load_orders: function(){
528 var jsons = this.db.get_unpaid_orders();
530 var not_loaded_count = 0;
532 for (var i = 0; i < jsons.length; i++) {
534 if (json.pos_session_id === this.pos_session.id) {
535 orders.push(new module.Order({},{
540 not_loaded_count += 1;
544 if (not_loaded_count) {
545 console.info('There are '+not_loaded_count+' locally saved unpaid orders belonging to another session');
548 orders = orders.sort(function(a,b){
549 return a.sequence_number - b.sequence_number;
553 this.get('orders').add(orders);
557 set_start_order: function(){
558 var orders = this.get('orders').models;
560 if (orders.length && !this.get('selectedOrder')) {
561 this.set('selectedOrder',orders[0]);
563 this.add_new_order();
567 // return the current order
568 get_order: function(){
569 return this.get('selectedOrder');
572 // change the current order
573 set_order: function(order){
574 this.set({ selectedOrder: order });
577 // return the list of unpaid orders
578 get_order_list: function(){
579 return this.get('orders').models;
582 //removes the current order
583 delete_current_order: function(){
584 var order = this.get_order();
586 order.destroy({'reason':'abandon'});
590 // saves the order locally and try to send it to the backend.
591 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
592 push_order: function(order) {
596 this.proxy.log('push_order',order.export_as_JSON());
597 this.db.add_order(order.export_as_JSON());
600 var pushed = new $.Deferred();
602 this.flush_mutex.exec(function(){
603 var flushed = self._flush_orders(self.db.get_orders());
605 flushed.always(function(ids){
612 // saves the order locally and try to send it to the backend and make an invoice
613 // returns a deferred that succeeds when the order has been posted and successfully generated
614 // an invoice. This method can fail in various ways:
615 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
616 // this error is solved
617 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
618 // the network connection is up
620 push_and_invoice_order: function(order){
622 var invoiced = new $.Deferred();
624 if(!order.get_client()){
625 invoiced.reject('error-no-client');
629 var order_id = this.db.add_order(order.export_as_JSON());
631 this.flush_mutex.exec(function(){
632 var done = new $.Deferred(); // holds the mutex
634 // send the order to the server
635 // we have a 30 seconds timeout on this push.
636 // FIXME: if the server takes more than 30 seconds to accept the order,
637 // the client will believe it wasn't successfully sent, and very bad
638 // things will happen as a duplicate will be sent next time
639 // so we must make sure the server detects and ignores duplicated orders
641 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
643 transfer.fail(function(){
644 invoiced.reject('error-transfer');
648 // on success, get the order id generated by the server
649 transfer.pipe(function(order_server_id){
651 // generate the pdf and download it
652 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
653 active_ids:order_server_id,
667 // wrapper around the _save_to_server that updates the synch status widget
668 _flush_orders: function(orders, options) {
670 this.set('synch',{ state: 'connecting', pending: orders.length});
672 return self._save_to_server(orders, options).done(function (server_ids) {
673 var pending = self.db.get_orders().length;
676 state: pending ? 'connecting' : 'connected',
684 // send an array of orders to the server
685 // available options:
686 // - timeout: timeout for the rpc call in ms
687 // returns a deferred that resolves with the list of
688 // server generated ids for the sent orders
689 _save_to_server: function (orders, options) {
690 if (!orders || !orders.length) {
691 var result = $.Deferred();
696 options = options || {};
699 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
701 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
702 // then we want to notify the user that we are waiting on something )
703 var posOrderModel = new instance.web.Model('pos.order');
704 return posOrderModel.call('create_from_ui',
705 [_.map(orders, function (order) {
706 order.to_invoice = options.to_invoice || false;
711 shadow: !options.to_invoice,
714 ).then(function (server_ids) {
715 _.each(orders, function (order) {
716 self.db.remove_order(order.id);
719 }).fail(function (error, event){
720 if(error.code === 200 ){ // Business Logic Error, not a connection problem
721 //if warning do not need to display traceback!!
722 if (error.data.exception_type == 'warning') {
723 delete error.data.debug;
725 self.pos_widget.screen_selector.show_popup('error-traceback',{
726 message: error.data.message,
727 comment: error.data.debug
730 // prevent an error popup creation by the rpc failure
731 // we want the failure to be silent as we send the orders in the background
732 event.preventDefault();
733 console.error('Failed to send orders:', orders);
737 scan_product: function(parsed_code){
739 var selectedOrder = this.get_order();
740 var product = this.db.get_product_by_barcode(parsed_code.base_code);
746 if(parsed_code.type === 'price'){
747 selectedOrder.add_product(product, {price:parsed_code.value});
748 }else if(parsed_code.type === 'weight'){
749 selectedOrder.add_product(product, {quantity:parsed_code.value, merge:false});
750 }else if(parsed_code.type === 'discount'){
751 selectedOrder.add_product(product, {discount:parsed_code.value, merge:false});
753 selectedOrder.add_product(product);
759 var orderline_id = 1;
761 // An orderline represent one element of the content of a client's shopping cart.
762 // An orderline contains a product, its quantity, its price, discount. etc.
763 // An Order contains zero or more Orderlines.
764 module.Orderline = Backbone.Model.extend({
765 initialize: function(attr,options){
766 this.pos = options.pos;
767 this.order = options.order;
769 this.init_from_JSON(options.json);
772 this.product = options.product;
773 this.price = options.product.price;
775 this.quantityStr = '1';
777 this.discountStr = '0';
779 this.selected = false;
780 this.id = orderline_id++;
782 init_from_JSON: function(json) {
783 this.product = this.pos.db.get_product_by_id(json.product_id);
785 console.error('ERROR: attempting to recover product not available in the point of sale');
787 this.price = json.price_unit;
788 this.set_discount(json.discount);
789 this.set_quantity(json.qty);
792 var orderline = new module.Orderline({},{
795 product: this.product,
798 orderline.quantity = this.quantity;
799 orderline.quantityStr = this.quantityStr;
800 orderline.discount = this.discount;
801 orderline.type = this.type;
802 orderline.selected = false;
805 // sets a discount [0,100]%
806 set_discount: function(discount){
807 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
808 this.discount = disc;
809 this.discountStr = '' + disc;
810 this.trigger('change',this);
812 // returns the discount [0,100]%
813 get_discount: function(){
814 return this.discount;
816 get_discount_str: function(){
817 return this.discountStr;
819 get_product_type: function(){
822 // sets the quantity of the product. The quantity will be rounded according to the
823 // product's unity of measure properties. Quantities greater than zero will not get
825 set_quantity: function(quantity){
826 if(quantity === 'remove'){
827 this.order.remove_orderline(this);
830 var quant = parseFloat(quantity) || 0;
831 var unit = this.get_unit();
834 this.quantity = round_pr(quant, unit.rounding);
835 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
837 this.quantity = round_pr(quant, 1);
838 this.quantityStr = this.quantity.toFixed(0);
841 this.quantity = quant;
842 this.quantityStr = '' + this.quantity;
845 this.trigger('change',this);
847 // return the quantity of product
848 get_quantity: function(){
849 return this.quantity;
851 get_quantity_str: function(){
852 return this.quantityStr;
854 get_quantity_str_with_unit: function(){
855 var unit = this.get_unit();
856 if(unit && !unit.is_unit){
857 return this.quantityStr + ' ' + unit.name;
859 return this.quantityStr;
862 // return the unit of measure of the product
863 get_unit: function(){
864 var unit_id = this.product.uom_id;
868 unit_id = unit_id[0];
872 return this.pos.units_by_id[unit_id];
874 // return the product of this orderline
875 get_product: function(){
878 // selects or deselects this orderline
879 set_selected: function(selected){
880 this.selected = selected;
881 this.trigger('change',this);
883 // returns true if this orderline is selected
884 is_selected: function(){
885 return this.selected;
887 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
888 // in the orderline. This returns true if it makes sense to merge the two
889 can_be_merged_with: function(orderline){
890 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
892 }else if(!this.get_unit() || !this.get_unit().groupable){
894 }else if(this.get_product_type() !== orderline.get_product_type()){
896 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
898 }else if(this.price !== orderline.price){
904 merge: function(orderline){
905 this.set_quantity(this.get_quantity() + orderline.get_quantity());
907 export_as_JSON: function() {
909 qty: this.get_quantity(),
910 price_unit: this.get_unit_price(),
911 discount: this.get_discount(),
912 product_id: this.get_product().id,
915 //used to create a json of the ticket, to be sent to the printer
916 export_for_printing: function(){
918 quantity: this.get_quantity(),
919 unit_name: this.get_unit().name,
920 price: this.get_unit_display_price(),
921 discount: this.get_discount(),
922 product_name: this.get_product().display_name,
923 price_display : this.get_display_price(),
924 price_with_tax : this.get_price_with_tax(),
925 price_without_tax: this.get_price_without_tax(),
927 product_description: this.get_product().description,
928 product_description_sale: this.get_product().description_sale,
931 // changes the base price of the product for this orderline
932 set_unit_price: function(price){
933 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
934 this.trigger('change',this);
936 get_unit_price: function(){
939 get_unit_display_price: function(){
940 if (this.pos.config.iface_tax_included) {
941 var quantity = this.quantity;
943 var price = this.get_all_prices().priceWithTax;
944 this.quantity = quantity;
947 return this.get_unit_price();
950 get_base_price: function(){
951 var rounding = this.pos.currency.rounding;
952 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
954 get_display_price: function(){
955 return this.get_base_price();
956 if (this.pos.config.iface_tax_included) {
957 return this.get_all_prices().priceWithTax;
959 return this.get_base_price();
962 get_price_without_tax: function(){
963 return this.get_all_prices().priceWithoutTax;
965 get_price_with_tax: function(){
966 return this.get_all_prices().priceWithTax;
969 return this.get_all_prices().tax;
971 get_tax_details: function(){
972 return this.get_all_prices().taxDetails;
974 get_taxes: function(){
975 var taxes_ids = this.get_product().taxes_id;
977 for (var i = 0; i < taxes_ids.length; i++) {
978 taxes.push(this.pos.taxes_by_id[taxes_ids[i]]);
982 get_all_prices: function(){
984 var currency_rounding = this.pos.currency.rounding;
985 var base = this.get_base_price();
987 var totalNoTax = base;
989 var product = this.get_product();
990 var taxes_ids = product.taxes_id;
991 var taxes = self.pos.taxes;
994 _.each(taxes_ids, function(el) {
995 var tax = _.detect(taxes, function(t) {return t.id === el;});
996 if (tax.price_include) {
998 if (tax.type === "percent") {
999 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
1000 } else if (tax.type === "fixed") {
1001 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
1003 throw "This type of tax is not supported by the point of sale: " + tax.type;
1005 tmp = round_pr(tmp,currency_rounding);
1008 taxdetail[tax.id] = tmp;
1011 if (tax.type === "percent") {
1012 tmp = tax.amount * base;
1013 } else if (tax.type === "fixed") {
1014 tmp = tax.amount * self.get_quantity();
1016 throw "This type of tax is not supported by the point of sale: " + tax.type;
1018 tmp = round_pr(tmp,currency_rounding);
1021 taxdetail[tax.id] = tmp;
1025 "priceWithTax": totalTax,
1026 "priceWithoutTax": totalNoTax,
1028 "taxDetails": taxdetail,
1033 module.OrderlineCollection = Backbone.Collection.extend({
1034 model: module.Orderline,
1037 // Every Paymentline contains a cashregister and an amount of money.
1038 module.Paymentline = Backbone.Model.extend({
1039 initialize: function(attributes, options) {
1040 this.pos = options.pos;
1042 this.selected = false;
1044 this.init_from_JSON(options.json);
1047 this.cashregister = options.cashregister;
1048 this.name = this.cashregister.journal_id[1];
1050 init_from_JSON: function(json){
1051 this.amount = json.amount;
1052 this.cashregister = this.pos.cashregisters_by_id[json.statement_id];
1053 this.name = this.cashregister.journal_id[1];
1055 //sets the amount of money on this payment line
1056 set_amount: function(value){
1057 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
1058 this.trigger('change',this);
1060 // returns the amount of money on this paymentline
1061 get_amount: function(){
1064 get_amount_str: function(){
1065 return this.amount.toFixed(this.pos.currency.decimals);
1067 set_selected: function(selected){
1068 if(this.selected !== selected){
1069 this.selected = selected;
1070 this.trigger('change',this);
1073 // returns the associated cashregister
1074 //exports as JSON for server communication
1075 export_as_JSON: function(){
1077 name: instance.web.datetime_to_str(new Date()),
1078 statement_id: this.cashregister.id,
1079 account_id: this.cashregister.account_id[0],
1080 journal_id: this.cashregister.journal_id[0],
1081 amount: this.get_amount()
1084 //exports as JSON for receipt printing
1085 export_for_printing: function(){
1087 amount: this.get_amount(),
1088 journal: this.cashregister.journal_id[1],
1093 module.PaymentlineCollection = Backbone.Collection.extend({
1094 model: module.Paymentline,
1097 // An order more or less represents the content of a client's shopping cart (the OrderLines)
1098 // plus the associated payment information (the Paymentlines)
1099 // there is always an active ('selected') order in the Pos, a new one is created
1100 // automaticaly once an order is completed and sent to the server.
1101 module.Order = Backbone.Model.extend({
1102 initialize: function(attributes,options){
1103 Backbone.Model.prototype.initialize.apply(this, arguments);
1104 options = options || {};
1106 this.init_locked = true;
1107 this.pos = options.pos;
1108 this.selected_orderline = undefined;
1109 this.selected_paymentline = undefined;
1110 this.screen_data = {}; // see ScreenSelector
1111 this.temporary = options.temporary || false;
1112 this.creation_date = new Date();
1113 this.to_invoice = false;
1114 this.orderlines = new module.OrderlineCollection();
1115 this.paymentlines = new module.PaymentlineCollection();
1116 this.pos_session_id = this.pos.pos_session.id;
1118 this.set({ client: null });
1121 this.init_from_JSON(options.json);
1123 this.sequence_number = this.pos.pos_session.sequence_number++;
1124 this.uid = this.generate_unique_id();
1125 this.name = _t("Order ") + this.uid;
1128 this.on('change', function(){ this.save_to_db("order:change"); }, this);
1129 this.orderlines.on('change', function(){ this.save_to_db("orderline:change"); }, this);
1130 this.orderlines.on('add', function(){ this.save_to_db("orderline:add"); }, this);
1131 this.orderlines.on('remove', function(){ this.save_to_db("orderline:remove"); }, this);
1132 this.paymentlines.on('change', function(){ this.save_to_db("paymentline:change"); }, this);
1133 this.paymentlines.on('add', function(){ this.save_to_db("paymentline:add"); }, this);
1134 this.paymentlines.on('remove', function(){ this.save_to_db("paymentline:rem"); }, this);
1136 this.init_locked = false;
1141 save_to_db: function(){
1142 if (!this.init_locked) {
1143 this.pos.db.save_unpaid_order(this);
1146 init_from_JSON: function(json) {
1147 this.sequence_number = json.sequence_number;
1148 this.pos.pos_session.sequence_number = Math.max(this.sequence_number+1,this.pos.pos_session.sequence_number);
1149 this.session_id = json.pos_session_id;
1150 this.uid = json.uid;
1151 this.name = _t("Order ") + this.uid;
1152 if (json.partner_id) {
1153 var client = this.pos.db.get_partner_by_id(json.partner_id);
1155 console.error('ERROR: trying to load a parner not available in the pos');
1160 this.set_client(client);
1162 this.temporary = false; // FIXME
1163 this.to_invoice = false; // FIXME
1165 var orderlines = json.lines;
1166 for (var i = 0; i < orderlines.length; i++) {
1167 var orderline = orderlines[i][2];
1168 this.add_orderline(new module.Orderline({}, {pos: this.pos, order: this, json: orderline}));
1171 var paymentlines = json.statement_ids;
1172 for (var i = 0; i < paymentlines.length; i++) {
1173 var paymentline = paymentlines[i][2];
1174 var newpaymentline = new module.Paymentline({},{pos: this.pos, json: paymentline});
1175 this.paymentlines.add(newpaymentline);
1177 if (i === paymentlines.length - 1) {
1178 this.select_paymentline(newpaymentline);
1182 export_as_JSON: function() {
1183 var orderLines, paymentLines;
1185 this.orderlines.each(_.bind( function(item) {
1186 return orderLines.push([0, 0, item.export_as_JSON()]);
1189 this.paymentlines.each(_.bind( function(item) {
1190 return paymentLines.push([0, 0, item.export_as_JSON()]);
1193 name: this.get_name(),
1194 amount_paid: this.get_total_paid(),
1195 amount_total: this.get_total_with_tax(),
1196 amount_tax: this.get_total_tax(),
1197 amount_return: this.get_change(),
1199 statement_ids: paymentLines,
1200 pos_session_id: this.pos_session_id,
1201 partner_id: this.get_client() ? this.get_client().id : false,
1202 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1204 sequence_number: this.sequence_number,
1207 export_for_printing: function(){
1208 var orderlines = [];
1211 this.orderlines.each(function(orderline){
1212 orderlines.push(orderline.export_for_printing());
1215 var paymentlines = [];
1216 this.paymentlines.each(function(paymentline){
1217 paymentlines.push(paymentline.export_for_printing());
1219 var client = this.get('client');
1220 var cashier = this.pos.cashier || this.pos.user;
1221 var company = this.pos.company;
1222 var shop = this.pos.shop;
1223 var date = new Date();
1225 function is_xml(subreceipt){
1226 return subreceipt ? (subreceipt.split('\n')[0].indexOf('<!DOCTYPE QWEB') >= 0) : false;
1229 function render_xml(subreceipt){
1230 if (!is_xml(subreceipt)) {
1233 subreceipt = subreceipt.split('\n').slice(1).join('\n');
1234 var qweb = new QWeb2.Engine();
1235 qweb.debug = instance.session.debug;
1236 qweb.default_dict = _.clone(QWeb.default_dict);
1237 qweb.add_template('<templates><t t-name="subreceipt">'+subreceipt+'</t></templates>');
1239 return qweb.render('subreceipt',{'pos':self.pos,'widget':self.pos.pos_widget,'order':self, 'receipt': receipt}) ;
1244 orderlines: orderlines,
1245 paymentlines: paymentlines,
1246 subtotal: this.get_subtotal(),
1247 total_with_tax: this.get_total_with_tax(),
1248 total_without_tax: this.get_total_without_tax(),
1249 total_tax: this.get_total_tax(),
1250 total_paid: this.get_total_paid(),
1251 total_discount: this.get_total_discount(),
1252 tax_details: this.get_tax_details(),
1253 change: this.get_change(),
1254 name : this.get_name(),
1255 client: client ? client.name : null ,
1256 invoice_id: null, //TODO
1257 cashier: cashier ? cashier.name : null,
1258 header: this.pos.config.receipt_header || '',
1259 footer: this.pos.config.receipt_footer || '',
1266 year: date.getFullYear(),
1267 month: date.getMonth(),
1268 date: date.getDate(), // day of the month
1269 day: date.getDay(), // day of the week
1270 hour: date.getHours(),
1271 minute: date.getMinutes() ,
1272 isostring: date.toISOString(),
1273 localestring: date.toLocaleString(),
1276 email: company.email,
1277 website: company.website,
1278 company_registry: company.company_registry,
1279 contact_address: company.partner_id[1],
1282 phone: company.phone,
1283 logo: this.pos.company_logo_base64,
1288 currency: this.pos.currency,
1291 if (is_xml(this.pos.config.receipt_header)){
1292 receipt.header_xml = render_xml(this.pos.config.receipt_header);
1295 if (is_xml(this.pos.config.receipt_footer)){
1296 receipt.footer_xml = render_xml(this.pos.config.receipt_footer);
1301 is_empty: function(){
1302 return this.orderlines.models.length === 0;
1304 generate_unique_id: function() {
1305 // Generates a public identification number for the order.
1306 // The generated number must be unique and sequential. They are made 12 digit long
1307 // to fit into EAN-13 barcodes, should it be needed
1309 function zero_pad(num,size){
1311 while (s.length < size) {
1316 return zero_pad(this.pos.pos_session.id,5) +'-'+
1317 zero_pad(this.pos.pos_session.login_number,3) +'-'+
1318 zero_pad(this.sequence_number,4);
1320 get_name: function() {
1323 /* ---- Order Lines --- */
1324 add_orderline: function(line){
1326 line.order.remove_orderline(line);
1329 this.orderlines.add(line);
1330 this.select_orderline(this.get_last_orderline());
1332 get_orderline: function(id){
1333 var orderlines = this.orderlines.models;
1334 for(var i = 0; i < orderlines.length; i++){
1335 if(orderlines[i].id === id){
1336 return orderlines[i];
1341 get_orderlines: function(){
1342 return this.orderlines.models;
1344 get_last_orderline: function(){
1345 return this.orderlines.at(this.orderlines.length -1);
1347 remove_orderline: function( line ){
1348 this.orderlines.remove(line);
1349 this.select_orderline(this.get_last_orderline());
1351 add_product: function(product, options){
1352 options = options || {};
1353 var attr = JSON.parse(JSON.stringify(product));
1354 attr.pos = this.pos;
1356 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1358 if(options.quantity !== undefined){
1359 line.set_quantity(options.quantity);
1361 if(options.price !== undefined){
1362 line.set_unit_price(options.price);
1364 if(options.discount !== undefined){
1365 line.set_discount(options.discount);
1368 if(options.extras !== undefined){
1369 for (var prop in options.extras) {
1370 line[prop] = options.extras[prop];
1374 var last_orderline = this.get_last_orderline();
1375 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1376 last_orderline.merge(line);
1378 this.orderlines.add(line);
1380 this.select_orderline(this.get_last_orderline());
1382 get_selected_orderline: function(){
1383 return this.selected_orderline;
1385 select_orderline: function(line){
1387 if(line !== this.selected_orderline){
1388 if(this.selected_orderline){
1389 this.selected_orderline.set_selected(false);
1391 this.selected_orderline = line;
1392 this.selected_orderline.set_selected(true);
1395 this.selected_orderline = undefined;
1398 deselect_orderline: function(){
1399 if(this.selected_orderline){
1400 this.selected_orderline.set_selected(false);
1401 this.selected_orderline = undefined;
1404 /* ---- Payment Lines --- */
1405 add_paymentline: function(cashregister) {
1406 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos: this.pos});
1407 if(cashregister.journal.type !== 'cash' || this.pos.config.iface_precompute_cash){
1408 newPaymentline.set_amount( Math.max(this.get_due(),0) );
1410 this.paymentlines.add(newPaymentline);
1411 this.select_paymentline(newPaymentline);
1414 get_paymentlines: function(){
1415 return this.paymentlines.models;
1417 remove_paymentline: function(line){
1418 if(this.selected_paymentline === line){
1419 this.select_paymentline(undefined);
1421 this.paymentlines.remove(line);
1423 clean_empty_paymentlines: function() {
1424 var lines = this.paymentlines.models;
1426 for ( var i = 0; i < lines.length; i++) {
1427 if (!lines[i].get_amount()) {
1428 empty.push(lines[i]);
1431 for ( var i = 0; i < empty.length; i++) {
1432 this.remove_paymentline(empty[i]);
1435 select_paymentline: function(line){
1436 if(line !== this.selected_paymentline){
1437 if(this.selected_paymentline){
1438 this.selected_paymentline.set_selected(false);
1440 this.selected_paymentline = line;
1441 if(this.selected_paymentline){
1442 this.selected_paymentline.set_selected(true);
1444 this.trigger('change:selected_paymentline',this.selected_paymentline);
1447 /* ---- Payment Status --- */
1448 get_subtotal : function(){
1449 return this.orderlines.reduce((function(sum, orderLine){
1450 return sum + orderLine.get_display_price();
1453 get_total_with_tax: function() {
1454 return this.orderlines.reduce((function(sum, orderLine) {
1455 return sum + orderLine.get_price_with_tax();
1458 get_total_without_tax: function() {
1459 return this.orderlines.reduce((function(sum, orderLine) {
1460 return sum + orderLine.get_price_without_tax();
1463 get_total_discount: function() {
1464 return this.orderlines.reduce((function(sum, orderLine) {
1465 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1468 get_total_tax: function() {
1469 return this.orderlines.reduce((function(sum, orderLine) {
1470 return sum + orderLine.get_tax();
1473 get_total_paid: function() {
1474 return this.paymentlines.reduce((function(sum, paymentLine) {
1475 return sum + paymentLine.get_amount();
1478 get_tax_details: function(){
1480 var fulldetails = [];
1481 var taxes_by_id = {};
1483 for(var i = 0; i < this.pos.taxes.length; i++){
1484 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1487 this.orderlines.each(function(line){
1488 var ldetails = line.get_tax_details();
1489 for(var id in ldetails){
1490 if(ldetails.hasOwnProperty(id)){
1491 details[id] = (details[id] || 0) + ldetails[id];
1496 for(var id in details){
1497 if(details.hasOwnProperty(id)){
1498 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1504 // Returns a total only for the orderlines with products belonging to the category
1505 get_total_for_category_with_tax: function(categ_id){
1509 if (categ_id instanceof Array) {
1510 for (var i = 0; i < categ_id.length; i++) {
1511 total += this.get_total_for_category_with_tax(categ_id[i]);
1516 this.orderlines.each(function(line){
1517 if ( self.pos.db.category_contains(categ_id,line.product.id) ) {
1518 total += line.get_price_with_tax();
1524 get_total_for_taxes: function(tax_id){
1528 if (!(tax_id instanceof Array)) {
1534 for (var i = 0; i < tax_id.length; i++) {
1535 tax_set[tax_id[i]] = true;
1538 this.orderlines.each(function(line){
1539 var taxes_ids = line.get_product().taxes_id;
1540 for (var i = 0; i < taxes_ids.length; i++) {
1541 if (tax_set[taxes_ids[i]]) {
1542 total += line.get_price_with_tax();
1550 get_change: function(paymentline) {
1552 var change = this.get_total_paid() - this.get_total_with_tax();
1554 var change = -this.get_total_with_tax();
1555 var lines = this.paymentlines.models;
1556 for (var i = 0; i < lines.length; i++) {
1557 change += lines[i].get_amount();
1558 if (lines[i] === paymentline) {
1563 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1565 get_due: function(paymentline) {
1567 var due = this.get_total_with_tax() - this.get_total_paid();
1569 var due = this.get_total_with_tax();
1570 var lines = this.paymentlines.models;
1571 for (var i = 0; i < lines.length; i++) {
1572 if (lines[i] === paymentline) {
1575 due -= lines[i].get_amount();
1579 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1581 is_paid: function(){
1582 return this.get_due() === 0;
1584 is_paid_with_cash: function(){
1585 return !!this.paymentlines.find( function(pl){
1586 return pl.cashregister.journal.type === 'cash';
1589 finalize: function(){
1592 destroy: function(args){
1593 Backbone.Model.prototype.destroy.apply(this,arguments);
1594 this.pos.db.remove_unpaid_order(this);
1596 /* ---- Invoice --- */
1597 set_to_invoice: function(to_invoice) {
1598 this.to_invoice = to_invoice;
1600 is_to_invoice: function(){
1601 return this.to_invoice;
1603 /* ---- Client / Customer --- */
1604 // the client related to the current order.
1605 set_client: function(client){
1606 this.set('client',client);
1608 get_client: function(){
1609 return this.get('client');
1611 get_client_name: function(){
1612 var client = this.get('client');
1613 return client ? client.name : "";
1615 /* ---- Screen Status --- */
1616 // the order also stores the screen status, as the PoS supports
1617 // different active screens per order. This method is used to
1618 // store the screen status.
1619 set_screen_data: function(key,value){
1620 if(arguments.length === 2){
1621 this.screen_data[key] = value;
1622 }else if(arguments.length === 1){
1623 for(var key in arguments[0]){
1624 this.screen_data[key] = arguments[0][key];
1628 //see set_screen_data
1629 get_screen_data: function(key){
1630 return this.screen_data[key];
1634 module.OrderCollection = Backbone.Collection.extend({
1635 model: module.Order,
1639 The numpad handles both the choice of the property currently being modified
1640 (quantity, price or discount) and the edition of the corresponding numeric value.
1642 module.NumpadState = Backbone.Model.extend({
1647 appendNewChar: function(newChar) {
1649 oldBuffer = this.get('buffer');
1650 if (oldBuffer === '0') {
1654 } else if (oldBuffer === '-0') {
1656 buffer: "-" + newChar
1660 buffer: (this.get('buffer')) + newChar
1663 this.trigger('set_value',this.get('buffer'));
1665 deleteLastChar: function() {
1666 if(this.get('buffer') === ""){
1667 if(this.get('mode') === 'quantity'){
1668 this.trigger('set_value','remove');
1670 this.trigger('set_value',this.get('buffer'));
1673 var newBuffer = this.get('buffer').slice(0,-1) || "";
1674 this.set({ buffer: newBuffer });
1675 this.trigger('set_value',this.get('buffer'));
1678 switchSign: function() {
1680 oldBuffer = this.get('buffer');
1682 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1684 this.trigger('set_value',this.get('buffer'));
1686 changeMode: function(newMode) {
1698 resetValue: function(){
1699 this.set({buffer:'0'});