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 = [];
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'],
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 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
300 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
301 loaded: function(self, products){
302 self.db.add_products(products);
305 model: 'account.bank.statement',
306 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
307 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
308 loaded: function(self, cashregisters, tmp){
309 self.cashregisters = cashregisters;
312 _.each(cashregisters,function(statement){
313 tmp.journals.push(statement.journal_id[0]);
317 model: 'account.journal',
319 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
320 loaded: function(self, journals){
321 self.journals = journals;
323 // associate the bank statements with their journals.
324 var cashregisters = self.cashregisters;
325 for(var i = 0, ilen = cashregisters.length; i < ilen; i++){
326 for(var j = 0, jlen = journals.length; j < jlen; j++){
327 if(cashregisters[i].journal_id[0] === journals[j].id){
328 cashregisters[i].journal = journals[j];
333 self.cashregisters_by_id = {};
334 for (var i = 0; i < self.cashregisters.length; i++) {
335 self.cashregisters_by_id[self.cashregisters[i].id] = self.cashregisters[i];
338 self.cashregisters = self.cashregisters.sort(function(a,b){
339 return a.journal.sequence - b.journal.sequence;
345 loaded: function(self){
346 var fonts_loaded = new $.Deferred();
347 // Waiting for fonts to be loaded to prevent receipt printing
348 // from printing empty receipt while loading Inconsolata
349 // ( The font used for the receipt )
350 waitForWebfonts(['Lato','Inconsolata'], function(){
351 fonts_loaded.resolve();
353 // The JS used to detect font loading is not 100% robust, so
354 // do not wait more than 5sec
355 setTimeout(function(){
356 fonts_loaded.resolve();
363 loaded: function(self){
364 self.company_logo = new Image();
365 var logo_loaded = new $.Deferred();
366 self.company_logo.onload = function(){
367 var img = self.company_logo;
369 var targetwidth = 300;
371 if( img.width !== targetwidth ){
372 ratio = targetwidth / img.width;
374 if( img.height * ratio > maxheight ){
375 ratio = maxheight / img.height;
377 var width = Math.floor(img.width * ratio);
378 var height = Math.floor(img.height * ratio);
379 var c = document.createElement('canvas');
382 var ctx = c.getContext('2d');
383 ctx.drawImage(self.company_logo,0,0, width, height);
385 self.company_logo_base64 = c.toDataURL();
386 logo_loaded.resolve();
388 self.company_logo.onerror = function(){
389 logo_loaded.reject();
391 self.company_logo.crossOrigin = "anonymous";
392 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
398 loaded: function(self) {
399 var barcode_parser = new barcode_parser_module.BarcodeParser({'nomenclature_id': self.config.barcode_nomenclature_id});
400 self.barcode_reader.set_barcode_parser(barcode_parser);
401 return barcode_parser.is_loaded();
406 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
407 load_server_data: function(){
409 var loaded = new $.Deferred();
411 var progress_step = 1.0 / self.models.length;
412 var tmp = {}; // this is used to share a temporary state between models loaders
414 function load_model(index){
415 if(index >= self.models.length){
418 var model = self.models[index];
419 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
421 var cond = typeof model.condition === 'function' ? model.condition(self,tmp) : true;
427 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
428 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
429 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
430 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
431 progress += progress_step;
436 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
438 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
440 records.then(function(result){
441 try{ // catching exceptions in model.loaded(...)
442 $.when(model.loaded(self,result,tmp))
443 .then(function(){ load_model(index + 1); },
444 function(err){ loaded.reject(err); });
446 console.error(err.stack);
452 }else if( model.loaded ){
453 try{ // catching exceptions in model.loaded(...)
454 $.when(model.loaded(self,tmp))
455 .then( function(){ load_model(index +1); },
456 function(err){ loaded.reject(err); });
461 load_model(index + 1);
475 // reload the list of partner, returns as a deferred that resolves if there were
476 // updated partners, and fails if not
477 load_new_partners: function(){
479 var def = new $.Deferred();
480 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
481 new instance.web.Model('res.partner')
483 .filter([['write_date','>',this.db.get_partner_write_date()]])
484 .all({'timeout':3000, 'shadow': true})
485 .then(function(partners){
486 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
491 }, function(){ def.reject(); });
495 // this is called when an order is removed from the order collection. It ensures that there is always an existing
496 // order and a valid selected order
497 on_removed_order: function(removed_order,index,reason){
498 var order_list = this.get_order_list();
499 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
500 // when we intentionally remove an unfinished order, and there is another existing one
501 this.set_order(order_list[index] || order_list[order_list.length -1]);
503 // when the order was automatically removed after completion,
504 // or when we intentionally delete the only concurrent order
505 this.add_new_order();
509 // returns the user who is currently the cashier for this point of sale
510 get_cashier: function(){
511 return this.cashier || this.user;
513 // changes the current cashier
514 set_cashier: function(user){
517 //creates a new empty order and sets it as the current order
518 add_new_order: function(){
519 var order = new module.Order({},{pos:this});
520 this.get('orders').add(order);
521 this.set('selectedOrder', order);
524 // load the locally saved unpaid orders for this session.
525 load_orders: function(){
526 var jsons = this.db.get_unpaid_orders();
528 var not_loaded_count = 0;
530 for (var i = 0; i < jsons.length; i++) {
532 if (json.pos_session_id === this.pos_session.id) {
533 orders.push(new module.Order({},{
538 not_loaded_count += 1;
542 if (not_loaded_count) {
543 console.info('There are '+not_loaded_count+' locally saved unpaid orders belonging to another session');
546 orders = orders.sort(function(a,b){
547 return a.sequence_number - b.sequence_number;
551 this.get('orders').add(orders);
555 set_start_order: function(){
556 var orders = this.get('orders').models;
558 if (orders.length && !this.get('selectedOrder')) {
559 this.set('selectedOrder',orders[0]);
561 this.add_new_order();
565 // return the current order
566 get_order: function(){
567 return this.get('selectedOrder');
570 // change the current order
571 set_order: function(order){
572 this.set({ selectedOrder: order });
575 // return the list of unpaid orders
576 get_order_list: function(){
577 return this.get('orders').models;
580 //removes the current order
581 delete_current_order: function(){
582 var order = this.get_order();
584 order.destroy({'reason':'abandon'});
588 // saves the order locally and try to send it to the backend.
589 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
590 push_order: function(order) {
594 this.proxy.log('push_order',order.export_as_JSON());
595 this.db.add_order(order.export_as_JSON());
598 var pushed = new $.Deferred();
600 this.flush_mutex.exec(function(){
601 var flushed = self._flush_orders(self.db.get_orders());
603 flushed.always(function(ids){
610 // saves the order locally and try to send it to the backend and make an invoice
611 // returns a deferred that succeeds when the order has been posted and successfully generated
612 // an invoice. This method can fail in various ways:
613 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
614 // this error is solved
615 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
616 // the network connection is up
618 push_and_invoice_order: function(order){
620 var invoiced = new $.Deferred();
622 if(!order.get_client()){
623 invoiced.reject('error-no-client');
627 var order_id = this.db.add_order(order.export_as_JSON());
629 this.flush_mutex.exec(function(){
630 var done = new $.Deferred(); // holds the mutex
632 // send the order to the server
633 // we have a 30 seconds timeout on this push.
634 // FIXME: if the server takes more than 30 seconds to accept the order,
635 // the client will believe it wasn't successfully sent, and very bad
636 // things will happen as a duplicate will be sent next time
637 // so we must make sure the server detects and ignores duplicated orders
639 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
641 transfer.fail(function(){
642 invoiced.reject('error-transfer');
646 // on success, get the order id generated by the server
647 transfer.pipe(function(order_server_id){
649 // generate the pdf and download it
650 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
651 active_ids:order_server_id,
665 // wrapper around the _save_to_server that updates the synch status widget
666 _flush_orders: function(orders, options) {
668 this.set('synch',{ state: 'connecting', pending: orders.length});
670 return self._save_to_server(orders, options).done(function (server_ids) {
671 var pending = self.db.get_orders().length;
674 state: pending ? 'connecting' : 'connected',
682 // send an array of orders to the server
683 // available options:
684 // - timeout: timeout for the rpc call in ms
685 // returns a deferred that resolves with the list of
686 // server generated ids for the sent orders
687 _save_to_server: function (orders, options) {
688 if (!orders || !orders.length) {
689 var result = $.Deferred();
694 options = options || {};
697 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
699 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
700 // then we want to notify the user that we are waiting on something )
701 var posOrderModel = new instance.web.Model('pos.order');
702 return posOrderModel.call('create_from_ui',
703 [_.map(orders, function (order) {
704 order.to_invoice = options.to_invoice || false;
709 shadow: !options.to_invoice,
712 ).then(function (server_ids) {
713 _.each(orders, function (order) {
714 self.db.remove_order(order.id);
717 }).fail(function (error, event){
718 if(error.code === 200 ){ // Business Logic Error, not a connection problem
719 //if warning do not need to display traceback!!
720 if (error.data.exception_type == 'warning') {
721 delete error.data.debug;
723 self.pos_widget.screen_selector.show_popup('error-traceback',{
724 message: error.data.message,
725 comment: error.data.debug
728 // prevent an error popup creation by the rpc failure
729 // we want the failure to be silent as we send the orders in the background
730 event.preventDefault();
731 console.error('Failed to send orders:', orders);
735 scan_product: function(parsed_code){
737 var selectedOrder = this.get_order();
738 var product = this.db.get_product_by_barcode(parsed_code.base_code);
744 if(parsed_code.type === 'price'){
745 selectedOrder.add_product(product, {price:parsed_code.value});
746 }else if(parsed_code.type === 'weight'){
747 selectedOrder.add_product(product, {quantity:parsed_code.value, merge:false});
748 }else if(parsed_code.type === 'discount'){
749 selectedOrder.add_product(product, {discount:parsed_code.value, merge:false});
751 selectedOrder.add_product(product);
757 var orderline_id = 1;
759 // An orderline represent one element of the content of a client's shopping cart.
760 // An orderline contains a product, its quantity, its price, discount. etc.
761 // An Order contains zero or more Orderlines.
762 module.Orderline = Backbone.Model.extend({
763 initialize: function(attr,options){
764 this.pos = options.pos;
765 this.order = options.order;
767 this.init_from_JSON(options.json);
770 this.product = options.product;
771 this.price = options.product.price;
773 this.quantityStr = '1';
775 this.discountStr = '0';
777 this.selected = false;
778 this.id = orderline_id++;
780 init_from_JSON: function(json) {
781 this.product = this.pos.db.get_product_by_id(json.product_id);
783 console.error('ERROR: attempting to recover product not available in the point of sale');
785 this.price = json.price_unit;
786 this.set_discount(json.discount);
787 this.set_quantity(json.qty);
790 var orderline = new module.Orderline({},{
793 product: this.product,
796 orderline.quantity = this.quantity;
797 orderline.quantityStr = this.quantityStr;
798 orderline.discount = this.discount;
799 orderline.type = this.type;
800 orderline.selected = false;
803 // sets a discount [0,100]%
804 set_discount: function(discount){
805 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
806 this.discount = disc;
807 this.discountStr = '' + disc;
808 this.trigger('change',this);
810 // returns the discount [0,100]%
811 get_discount: function(){
812 return this.discount;
814 get_discount_str: function(){
815 return this.discountStr;
817 get_product_type: function(){
820 // sets the quantity of the product. The quantity will be rounded according to the
821 // product's unity of measure properties. Quantities greater than zero will not get
823 set_quantity: function(quantity){
824 if(quantity === 'remove'){
825 this.order.remove_orderline(this);
828 var quant = parseFloat(quantity) || 0;
829 var unit = this.get_unit();
832 this.quantity = round_pr(quant, unit.rounding);
833 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
835 this.quantity = round_pr(quant, 1);
836 this.quantityStr = this.quantity.toFixed(0);
839 this.quantity = quant;
840 this.quantityStr = '' + this.quantity;
843 this.trigger('change',this);
845 // return the quantity of product
846 get_quantity: function(){
847 return this.quantity;
849 get_quantity_str: function(){
850 return this.quantityStr;
852 get_quantity_str_with_unit: function(){
853 var unit = this.get_unit();
854 if(unit && !unit.is_unit){
855 return this.quantityStr + ' ' + unit.name;
857 return this.quantityStr;
860 // return the unit of measure of the product
861 get_unit: function(){
862 var unit_id = this.product.uom_id;
866 unit_id = unit_id[0];
870 return this.pos.units_by_id[unit_id];
872 // return the product of this orderline
873 get_product: function(){
876 // selects or deselects this orderline
877 set_selected: function(selected){
878 this.selected = selected;
879 this.trigger('change',this);
881 // returns true if this orderline is selected
882 is_selected: function(){
883 return this.selected;
885 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
886 // in the orderline. This returns true if it makes sense to merge the two
887 can_be_merged_with: function(orderline){
888 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
890 }else if(!this.get_unit() || !this.get_unit().groupable){
892 }else if(this.get_product_type() !== orderline.get_product_type()){
894 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
896 }else if(this.price !== orderline.price){
902 merge: function(orderline){
903 this.set_quantity(this.get_quantity() + orderline.get_quantity());
905 export_as_JSON: function() {
907 qty: this.get_quantity(),
908 price_unit: this.get_unit_price(),
909 discount: this.get_discount(),
910 product_id: this.get_product().id,
913 //used to create a json of the ticket, to be sent to the printer
914 export_for_printing: function(){
916 quantity: this.get_quantity(),
917 unit_name: this.get_unit().name,
918 price: this.get_unit_display_price(),
919 discount: this.get_discount(),
920 product_name: this.get_product().display_name,
921 price_display : this.get_display_price(),
922 price_with_tax : this.get_price_with_tax(),
923 price_without_tax: this.get_price_without_tax(),
925 product_description: this.get_product().description,
926 product_description_sale: this.get_product().description_sale,
929 // changes the base price of the product for this orderline
930 set_unit_price: function(price){
931 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
932 this.trigger('change',this);
934 get_unit_price: function(){
937 get_unit_display_price: function(){
938 if (this.pos.config.iface_tax_included) {
939 var quantity = this.quantity;
941 var price = this.get_all_prices().priceWithTax;
942 this.quantity = quantity;
945 return this.get_unit_price();
948 get_base_price: function(){
949 var rounding = this.pos.currency.rounding;
950 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
952 get_display_price: function(){
953 return this.get_base_price();
954 if (this.pos.config.iface_tax_included) {
955 return this.get_all_prices().priceWithTax;
957 return this.get_base_price();
960 get_price_without_tax: function(){
961 return this.get_all_prices().priceWithoutTax;
963 get_price_with_tax: function(){
964 return this.get_all_prices().priceWithTax;
967 return this.get_all_prices().tax;
969 get_tax_details: function(){
970 return this.get_all_prices().taxDetails;
972 get_taxes: function(){
973 var taxes_ids = this.get_product().taxes_id;
975 for (var i = 0; i < taxes_ids.length; i++) {
976 taxes.push(this.pos.taxes_by_id[taxes_ids[i]]);
980 get_all_prices: function(){
982 var currency_rounding = this.pos.currency.rounding;
983 var base = this.get_base_price();
985 var totalNoTax = base;
987 var product = this.get_product();
988 var taxes_ids = product.taxes_id;
989 var taxes = self.pos.taxes;
992 _.each(taxes_ids, function(el) {
993 var tax = _.detect(taxes, function(t) {return t.id === el;});
994 if (tax.price_include) {
996 if (tax.type === "percent") {
997 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
998 } else if (tax.type === "fixed") {
999 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
1001 throw "This type of tax is not supported by the point of sale: " + tax.type;
1003 tmp = round_pr(tmp,currency_rounding);
1006 taxdetail[tax.id] = tmp;
1009 if (tax.type === "percent") {
1010 tmp = tax.amount * base;
1011 } else if (tax.type === "fixed") {
1012 tmp = tax.amount * self.get_quantity();
1014 throw "This type of tax is not supported by the point of sale: " + tax.type;
1016 tmp = round_pr(tmp,currency_rounding);
1019 taxdetail[tax.id] = tmp;
1023 "priceWithTax": totalTax,
1024 "priceWithoutTax": totalNoTax,
1026 "taxDetails": taxdetail,
1031 module.OrderlineCollection = Backbone.Collection.extend({
1032 model: module.Orderline,
1035 // Every Paymentline contains a cashregister and an amount of money.
1036 module.Paymentline = Backbone.Model.extend({
1037 initialize: function(attributes, options) {
1038 this.pos = options.pos;
1040 this.selected = false;
1042 this.init_from_JSON(options.json);
1045 this.cashregister = options.cashregister;
1046 this.name = this.cashregister.journal_id[1];
1048 init_from_JSON: function(json){
1049 this.amount = json.amount;
1050 this.cashregister = this.pos.cashregisters_by_id[json.statement_id];
1051 this.name = this.cashregister.journal_id[1];
1053 //sets the amount of money on this payment line
1054 set_amount: function(value){
1055 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
1056 this.trigger('change',this);
1058 // returns the amount of money on this paymentline
1059 get_amount: function(){
1062 get_amount_str: function(){
1063 return this.amount.toFixed(this.pos.currency.decimals);
1065 set_selected: function(selected){
1066 if(this.selected !== selected){
1067 this.selected = selected;
1068 this.trigger('change',this);
1071 // returns the associated cashregister
1072 //exports as JSON for server communication
1073 export_as_JSON: function(){
1075 name: instance.web.datetime_to_str(new Date()),
1076 statement_id: this.cashregister.id,
1077 account_id: this.cashregister.account_id[0],
1078 journal_id: this.cashregister.journal_id[0],
1079 amount: this.get_amount()
1082 //exports as JSON for receipt printing
1083 export_for_printing: function(){
1085 amount: this.get_amount(),
1086 journal: this.cashregister.journal_id[1],
1091 module.PaymentlineCollection = Backbone.Collection.extend({
1092 model: module.Paymentline,
1095 // An order more or less represents the content of a client's shopping cart (the OrderLines)
1096 // plus the associated payment information (the Paymentlines)
1097 // there is always an active ('selected') order in the Pos, a new one is created
1098 // automaticaly once an order is completed and sent to the server.
1099 module.Order = Backbone.Model.extend({
1100 initialize: function(attributes,options){
1101 Backbone.Model.prototype.initialize.apply(this, arguments);
1102 options = options || {};
1104 this.init_locked = true;
1105 this.pos = options.pos;
1106 this.selected_orderline = undefined;
1107 this.selected_paymentline = undefined;
1108 this.screen_data = {}; // see ScreenSelector
1109 this.temporary = options.temporary || false;
1110 this.creation_date = new Date();
1111 this.to_invoice = false;
1112 this.orderlines = new module.OrderlineCollection();
1113 this.paymentlines = new module.PaymentlineCollection();
1114 this.pos_session_id = this.pos.pos_session.id;
1116 this.set({ client: null });
1119 this.init_from_JSON(options.json);
1121 this.sequence_number = this.pos.pos_session.sequence_number++;
1122 this.uid = this.generate_unique_id();
1123 this.name = _t("Order ") + this.uid;
1126 this.on('change', function(){ this.save_to_db("order:change"); }, this);
1127 this.orderlines.on('change', function(){ this.save_to_db("orderline:change"); }, this);
1128 this.orderlines.on('add', function(){ this.save_to_db("orderline:add"); }, this);
1129 this.orderlines.on('remove', function(){ this.save_to_db("orderline:remove"); }, this);
1130 this.paymentlines.on('change', function(){ this.save_to_db("paymentline:change"); }, this);
1131 this.paymentlines.on('add', function(){ this.save_to_db("paymentline:add"); }, this);
1132 this.paymentlines.on('remove', function(){ this.save_to_db("paymentline:rem"); }, this);
1134 this.init_locked = false;
1139 save_to_db: function(){
1140 if (!this.init_locked) {
1141 this.pos.db.save_unpaid_order(this);
1144 init_from_JSON: function(json) {
1145 this.sequence_number = json.sequence_number;
1146 this.pos.pos_session.sequence_number = Math.max(this.sequence_number+1,this.pos.pos_session.sequence_number);
1147 this.session_id = json.pos_session_id;
1148 this.uid = json.uid;
1149 this.name = _t("Order ") + this.uid;
1150 if (json.partner_id) {
1151 var client = this.pos.db.get_partner_by_id(json.partner_id);
1153 console.error('ERROR: trying to load a parner not available in the pos');
1158 this.set_client(client);
1160 this.temporary = false; // FIXME
1161 this.to_invoice = false; // FIXME
1163 var orderlines = json.lines;
1164 for (var i = 0; i < orderlines.length; i++) {
1165 var orderline = orderlines[i][2];
1166 this.add_orderline(new module.Orderline({}, {pos: this.pos, order: this, json: orderline}));
1169 var paymentlines = json.statement_ids;
1170 for (var i = 0; i < paymentlines.length; i++) {
1171 var paymentline = paymentlines[i][2];
1172 var newpaymentline = new module.Paymentline({},{pos: this.pos, json: paymentline});
1173 this.paymentlines.add(newpaymentline);
1175 if (i === paymentlines.length - 1) {
1176 this.select_paymentline(newpaymentline);
1180 export_as_JSON: function() {
1181 var orderLines, paymentLines;
1183 this.orderlines.each(_.bind( function(item) {
1184 return orderLines.push([0, 0, item.export_as_JSON()]);
1187 this.paymentlines.each(_.bind( function(item) {
1188 return paymentLines.push([0, 0, item.export_as_JSON()]);
1191 name: this.get_name(),
1192 amount_paid: this.get_total_paid(),
1193 amount_total: this.get_total_with_tax(),
1194 amount_tax: this.get_total_tax(),
1195 amount_return: this.get_change(),
1197 statement_ids: paymentLines,
1198 pos_session_id: this.pos_session_id,
1199 partner_id: this.get_client() ? this.get_client().id : false,
1200 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1202 sequence_number: this.sequence_number,
1205 export_for_printing: function(){
1206 var orderlines = [];
1209 this.orderlines.each(function(orderline){
1210 orderlines.push(orderline.export_for_printing());
1213 var paymentlines = [];
1214 this.paymentlines.each(function(paymentline){
1215 paymentlines.push(paymentline.export_for_printing());
1217 var client = this.get('client');
1218 var cashier = this.pos.cashier || this.pos.user;
1219 var company = this.pos.company;
1220 var shop = this.pos.shop;
1221 var date = new Date();
1223 function is_xml(subreceipt){
1224 return subreceipt ? (subreceipt.split('\n')[0].indexOf('<!DOCTYPE QWEB') >= 0) : false;
1227 function render_xml(subreceipt){
1228 if (!is_xml(subreceipt)) {
1231 subreceipt = subreceipt.split('\n').slice(1).join('\n');
1232 var qweb = new QWeb2.Engine();
1233 qweb.debug = instance.session.debug;
1234 qweb.default_dict = _.clone(QWeb.default_dict);
1235 qweb.add_template('<templates><t t-name="subreceipt">'+subreceipt+'</t></templates>');
1237 return qweb.render('subreceipt',{'pos':self.pos,'widget':self.pos.pos_widget,'order':self, 'receipt': receipt}) ;
1242 orderlines: orderlines,
1243 paymentlines: paymentlines,
1244 subtotal: this.get_subtotal(),
1245 total_with_tax: this.get_total_with_tax(),
1246 total_without_tax: this.get_total_without_tax(),
1247 total_tax: this.get_total_tax(),
1248 total_paid: this.get_total_paid(),
1249 total_discount: this.get_total_discount(),
1250 tax_details: this.get_tax_details(),
1251 change: this.get_change(),
1252 name : this.get_name(),
1253 client: client ? client.name : null ,
1254 invoice_id: null, //TODO
1255 cashier: cashier ? cashier.name : null,
1256 header: this.pos.config.receipt_header || '',
1257 footer: this.pos.config.receipt_footer || '',
1264 year: date.getFullYear(),
1265 month: date.getMonth(),
1266 date: date.getDate(), // day of the month
1267 day: date.getDay(), // day of the week
1268 hour: date.getHours(),
1269 minute: date.getMinutes() ,
1270 isostring: date.toISOString(),
1271 localestring: date.toLocaleString(),
1274 email: company.email,
1275 website: company.website,
1276 company_registry: company.company_registry,
1277 contact_address: company.partner_id[1],
1280 phone: company.phone,
1281 logo: this.pos.company_logo_base64,
1286 currency: this.pos.currency,
1289 if (is_xml(this.pos.config.receipt_header)){
1290 receipt.header_xml = render_xml(this.pos.config.receipt_header);
1293 if (is_xml(this.pos.config.receipt_footer)){
1294 receipt.footer_xml = render_xml(this.pos.config.receipt_footer);
1299 is_empty: function(){
1300 return this.orderlines.models.length === 0;
1302 generate_unique_id: function() {
1303 // Generates a public identification number for the order.
1304 // The generated number must be unique and sequential. They are made 12 digit long
1305 // to fit into EAN-13 barcodes, should it be needed
1307 function zero_pad(num,size){
1309 while (s.length < size) {
1314 return zero_pad(this.pos.pos_session.id,5) +'-'+
1315 zero_pad(this.pos.pos_session.login_number,3) +'-'+
1316 zero_pad(this.sequence_number,4);
1318 get_name: function() {
1321 /* ---- Order Lines --- */
1322 add_orderline: function(line){
1324 line.order.remove_orderline(line);
1327 this.orderlines.add(line);
1328 this.select_orderline(this.get_last_orderline());
1330 get_orderline: function(id){
1331 var orderlines = this.orderlines.models;
1332 for(var i = 0; i < orderlines.length; i++){
1333 if(orderlines[i].id === id){
1334 return orderlines[i];
1339 get_orderlines: function(){
1340 return this.orderlines.models;
1342 get_last_orderline: function(){
1343 return this.orderlines.at(this.orderlines.length -1);
1345 remove_orderline: function( line ){
1346 this.orderlines.remove(line);
1347 this.select_orderline(this.get_last_orderline());
1349 add_product: function(product, options){
1350 options = options || {};
1351 var attr = JSON.parse(JSON.stringify(product));
1352 attr.pos = this.pos;
1354 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1356 if(options.quantity !== undefined){
1357 line.set_quantity(options.quantity);
1359 if(options.price !== undefined){
1360 line.set_unit_price(options.price);
1362 if(options.discount !== undefined){
1363 line.set_discount(options.discount);
1366 if(options.extras !== undefined){
1367 for (var prop in options.extras) {
1368 line[prop] = options.extras[prop];
1372 var last_orderline = this.get_last_orderline();
1373 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1374 last_orderline.merge(line);
1376 this.orderlines.add(line);
1378 this.select_orderline(this.get_last_orderline());
1380 get_selected_orderline: function(){
1381 return this.selected_orderline;
1383 select_orderline: function(line){
1385 if(line !== this.selected_orderline){
1386 if(this.selected_orderline){
1387 this.selected_orderline.set_selected(false);
1389 this.selected_orderline = line;
1390 this.selected_orderline.set_selected(true);
1393 this.selected_orderline = undefined;
1396 deselect_orderline: function(){
1397 if(this.selected_orderline){
1398 this.selected_orderline.set_selected(false);
1399 this.selected_orderline = undefined;
1402 /* ---- Payment Lines --- */
1403 add_paymentline: function(cashregister) {
1404 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos: this.pos});
1405 if(cashregister.journal.type !== 'cash' || this.pos.config.iface_precompute_cash){
1406 newPaymentline.set_amount( Math.max(this.get_due(),0) );
1408 this.paymentlines.add(newPaymentline);
1409 this.select_paymentline(newPaymentline);
1412 get_paymentlines: function(){
1413 return this.paymentlines.models;
1415 remove_paymentline: function(line){
1416 if(this.selected_paymentline === line){
1417 this.select_paymentline(undefined);
1419 this.paymentlines.remove(line);
1421 clean_empty_paymentlines: function() {
1422 var lines = this.paymentlines.models;
1424 for ( var i = 0; i < lines.length; i++) {
1425 if (!lines[i].get_amount()) {
1426 empty.push(lines[i]);
1429 for ( var i = 0; i < empty.length; i++) {
1430 this.remove_paymentline(empty[i]);
1433 select_paymentline: function(line){
1434 if(line !== this.selected_paymentline){
1435 if(this.selected_paymentline){
1436 this.selected_paymentline.set_selected(false);
1438 this.selected_paymentline = line;
1439 if(this.selected_paymentline){
1440 this.selected_paymentline.set_selected(true);
1442 this.trigger('change:selected_paymentline',this.selected_paymentline);
1445 /* ---- Payment Status --- */
1446 get_subtotal : function(){
1447 return this.orderlines.reduce((function(sum, orderLine){
1448 return sum + orderLine.get_display_price();
1451 get_total_with_tax: function() {
1452 return this.orderlines.reduce((function(sum, orderLine) {
1453 return sum + orderLine.get_price_with_tax();
1456 get_total_without_tax: function() {
1457 return this.orderlines.reduce((function(sum, orderLine) {
1458 return sum + orderLine.get_price_without_tax();
1461 get_total_discount: function() {
1462 return this.orderlines.reduce((function(sum, orderLine) {
1463 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1466 get_total_tax: function() {
1467 return this.orderlines.reduce((function(sum, orderLine) {
1468 return sum + orderLine.get_tax();
1471 get_total_paid: function() {
1472 return this.paymentlines.reduce((function(sum, paymentLine) {
1473 return sum + paymentLine.get_amount();
1476 get_tax_details: function(){
1478 var fulldetails = [];
1479 var taxes_by_id = {};
1481 for(var i = 0; i < this.pos.taxes.length; i++){
1482 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1485 this.orderlines.each(function(line){
1486 var ldetails = line.get_tax_details();
1487 for(var id in ldetails){
1488 if(ldetails.hasOwnProperty(id)){
1489 details[id] = (details[id] || 0) + ldetails[id];
1494 for(var id in details){
1495 if(details.hasOwnProperty(id)){
1496 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1502 // Returns a total only for the orderlines with products belonging to the category
1503 get_total_for_category_with_tax: function(categ_id){
1507 if (categ_id instanceof Array) {
1508 for (var i = 0; i < categ_id.length; i++) {
1509 total += this.get_total_for_category_with_tax(categ_id[i]);
1514 this.orderlines.each(function(line){
1515 if ( self.pos.db.category_contains(categ_id,line.product.id) ) {
1516 total += line.get_price_with_tax();
1522 get_total_for_taxes: function(tax_id){
1526 if (!(tax_id instanceof Array)) {
1532 for (var i = 0; i < tax_id.length; i++) {
1533 tax_set[tax_id[i]] = true;
1536 this.orderlines.each(function(line){
1537 var taxes_ids = line.get_product().taxes_id;
1538 for (var i = 0; i < taxes_ids.length; i++) {
1539 if (tax_set[taxes_ids[i]]) {
1540 total += line.get_price_with_tax();
1548 get_change: function(paymentline) {
1550 var change = this.get_total_paid() - this.get_total_with_tax();
1552 var change = -this.get_total_with_tax();
1553 var lines = this.paymentlines.models;
1554 for (var i = 0; i < lines.length; i++) {
1555 change += lines[i].get_amount();
1556 if (lines[i] === paymentline) {
1561 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1563 get_due: function(paymentline) {
1565 var due = this.get_total_with_tax() - this.get_total_paid();
1567 var due = this.get_total_with_tax();
1568 var lines = this.paymentlines.models;
1569 for (var i = 0; i < lines.length; i++) {
1570 if (lines[i] === paymentline) {
1573 due -= lines[i].get_amount();
1577 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1579 is_paid: function(){
1580 return this.get_due() === 0;
1582 is_paid_with_cash: function(){
1583 return !!this.paymentlines.find( function(pl){
1584 return pl.cashregister.journal.type === 'cash';
1587 finalize: function(){
1590 destroy: function(args){
1591 Backbone.Model.prototype.destroy.apply(this,arguments);
1592 this.pos.db.remove_unpaid_order(this);
1594 /* ---- Invoice --- */
1595 set_to_invoice: function(to_invoice) {
1596 this.to_invoice = to_invoice;
1598 is_to_invoice: function(){
1599 return this.to_invoice;
1601 /* ---- Client / Customer --- */
1602 // the client related to the current order.
1603 set_client: function(client){
1604 this.set('client',client);
1606 get_client: function(){
1607 return this.get('client');
1609 get_client_name: function(){
1610 var client = this.get('client');
1611 return client ? client.name : "";
1613 /* ---- Screen Status --- */
1614 // the order also stores the screen status, as the PoS supports
1615 // different active screens per order. This method is used to
1616 // store the screen status.
1617 set_screen_data: function(key,value){
1618 if(arguments.length === 2){
1619 this.screen_data[key] = value;
1620 }else if(arguments.length === 1){
1621 for(var key in arguments[0]){
1622 this.screen_data[key] = arguments[0][key];
1626 //see set_screen_data
1627 get_screen_data: function(key){
1628 return this.screen_data[key];
1632 module.OrderCollection = Backbone.Collection.extend({
1633 model: module.Order,
1637 The numpad handles both the choice of the property currently being modified
1638 (quantity, price or discount) and the edition of the corresponding numeric value.
1640 module.NumpadState = Backbone.Model.extend({
1645 appendNewChar: function(newChar) {
1647 oldBuffer = this.get('buffer');
1648 if (oldBuffer === '0') {
1652 } else if (oldBuffer === '-0') {
1654 buffer: "-" + newChar
1658 buffer: (this.get('buffer')) + newChar
1661 this.trigger('set_value',this.get('buffer'));
1663 deleteLastChar: function() {
1664 if(this.get('buffer') === ""){
1665 if(this.get('mode') === 'quantity'){
1666 this.trigger('set_value','remove');
1668 this.trigger('set_value',this.get('buffer'));
1671 var newBuffer = this.get('buffer').slice(0,-1) || "";
1672 this.set({ buffer: newBuffer });
1673 this.trigger('set_value',this.get('buffer'));
1676 switchSign: function() {
1678 oldBuffer = this.get('buffer');
1680 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1682 this.trigger('set_value',this.get('buffer'));
1684 changeMode: function(newMode) {
1696 resetValue: function(){
1697 this.set({buffer:'0'});