1 function openerp_pos_models(instance, module){ //module is instance.point_of_sale
4 var QWeb = instance.web.qweb;
5 var _t = instance.web._t;
6 var barcode_parser_module = instance.barcodes;
8 var round_di = instance.web.round_decimals;
9 var round_pr = instance.web.round_precision
11 // The PosModel contains the Point Of Sale's representation of the backend.
12 // Since the PoS must work in standalone ( Without connection to the server )
13 // it must contains a representation of the server's PoS backend.
14 // (taxes, product list, configuration options, etc.) this representation
15 // is fetched and stored by the PosModel at the initialisation.
16 // this is done asynchronously, a ready deferred alows the GUI to wait interactively
17 // for the loading to be completed
18 // There is a single instance of the PosModel for each Front-End instance, it is usually called
19 // 'pos' and is available to all widgets extending PosWidget.
21 module.PosModel = Backbone.Model.extend({
22 initialize: function(session, attributes) {
23 Backbone.Model.prototype.initialize.call(this, attributes);
25 this.session = session;
26 this.flush_mutex = new $.Mutex(); // used to make sure the orders are sent to the server once at time
27 this.pos_widget = attributes.pos_widget;
29 this.proxy = new module.ProxyDevice(this); // used to communicate to the hardware devices via a local proxy
30 this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy});
32 this.proxy_queue = new module.JobQueue(); // used to prevent parallels communications to the proxy
33 this.db = new module.PosDB(); // a local database used to search trough products and categories & store pending orders
34 this.debug = jQuery.deparam(jQuery.param.querystring()).debug !== undefined; //debug mode
36 // Business data; loaded from the server at launch
37 this.accounting_precision = 2; //TODO
38 this.company_logo = null;
39 this.company_logo_base64 = '';
47 this.cashregisters = [];
48 this.bankstatements = [];
50 this.pos_session = null;
53 this.units_by_id = {};
54 this.pricelist = null;
55 this.order_sequence = 1;
56 window.posmodel = this;
58 // these dynamic attributes can be watched for change by other models or widgets
60 'synch': { state:'connected', pending:0 },
61 'orders': new module.OrderCollection(),
62 'selectedOrder': null,
65 this.bind('change:synch',function(pos,synch){
66 clearTimeout(self.synch_timeout);
67 self.synch_timeout = setTimeout(function(){
68 if(synch.state !== 'disconnected' && synch.pending > 0){
69 self.set('synch',{state:'disconnected', pending:synch.pending});
74 this.get('orders').bind('remove', function(order,_unused_,options){
75 self.on_removed_order(order,options.index,options.reason);
78 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
79 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
80 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
81 this.ready = this.load_server_data()
83 if(self.config.use_proxy){
84 return self.connect_to_proxy();
86 }); // used to read barcodes);
89 // releases ressources holds by the model at the end of life of the posmodel
91 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
94 this.barcode_reader.disconnect();
95 this.barcode_reader.disconnect_from_proxy();
97 connect_to_proxy: function(){
99 var done = new $.Deferred();
100 this.barcode_reader.disconnect_from_proxy();
101 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
102 this.pos_widget.loading_skip(function(){
103 self.proxy.stop_searching();
105 this.proxy.autoconnect({
106 force_ip: self.config.proxy_ip || undefined,
107 progress: function(prog){
108 self.pos_widget.loading_progress(prog);
111 if(self.config.iface_scan_via_proxy){
112 self.barcode_reader.connect_to_proxy();
114 }).always(function(){
120 // helper function to load data from the server. Obsolete use the models loader below.
121 fetch: function(model, fields, domain, ctx){
122 this._load_progress = (this._load_progress || 0) + 0.05;
123 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
124 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
127 // Server side model loaders. This is the list of the models that need to be loaded from
128 // the server. The models are loaded one by one by this list's order. The 'loaded' callback
129 // is used to store the data in the appropriate place once it has been loaded. This callback
130 // can return a deferred that will pause the loading of the next module.
131 // a shared temporary dictionary is available for loaders to communicate private variables
132 // used during loading such as object ids, etc.
136 fields: ['name','company_id'],
137 ids: function(self){ return [self.session.uid]; },
138 loaded: function(self,users){ self.user = users[0]; },
140 model: 'res.company',
141 fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id'],
142 ids: function(self){ return [self.user.company_id[0]] },
143 loaded: function(self,companies){ self.company = companies[0]; },
145 model: 'decimal.precision',
146 fields: ['name','digits'],
147 loaded: function(self,dps){
149 for (var i = 0; i < dps.length; i++) {
150 self.dp[dps[i].name] = dps[i].digits;
154 model: 'product.uom',
157 loaded: function(self,units){
159 var units_by_id = {};
160 for(var i = 0, len = units.length; i < len; i++){
161 units_by_id[units[i].id] = units[i];
162 units[i].groupable = ( units[i].category_id[0] === 1 );
163 units[i].is_unit = ( units[i].id === 1 );
165 self.units_by_id = units_by_id;
168 model: 'res.partner',
169 fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','barcode','write_date'],
171 loaded: function(self,partners){
172 self.partners = partners;
173 self.db.add_partners(partners);
176 model: 'res.country',
178 loaded: function(self,countries){
179 self.countries = countries;
180 self.company.country = null;
181 for (var i = 0; i < countries.length; i++) {
182 if (countries[i].id === self.company.country_id[0]){
183 self.company.country = countries[i];
188 model: 'account.tax',
189 fields: ['name','amount', 'price_include', 'type'],
191 loaded: function(self,taxes){
193 self.taxes_by_id = {};
195 for (var i = 0; i < taxes.length; i++) {
196 self.taxes_by_id[taxes[i].id] = taxes[i];
200 model: 'pos.session',
201 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
202 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
203 loaded: function(self,pos_sessions){
204 self.pos_session = pos_sessions[0];
209 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
210 loaded: function(self,configs){
211 self.config = configs[0];
212 self.config.use_proxy = self.config.iface_payment_terminal ||
213 self.config.iface_electronic_scale ||
214 self.config.iface_print_via_proxy ||
215 self.config.iface_scan_via_proxy ||
216 self.config.iface_cashdrawer;
218 if (self.config.company_id[0] !== self.user.company_id[0]) {
219 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."));
222 self.db.set_uuid(self.config.uuid);
224 var orders = self.db.get_orders();
225 for (var i = 0; i < orders.length; i++) {
226 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
231 fields: ['name','pos_security_pin','groups_id','barcode'],
233 loaded: function(self,users){
234 // we attribute a role to the user, 'cashier' or 'manager', depending
235 // on the group the user belongs.
237 for (var i = 0; i < users.length; i++) {
239 for (var j = 0; j < user.groups_id.length; j++) {
240 var group_id = user.groups_id[j];
241 if (group_id === self.config.group_pos_manager_id[0]) {
242 user.role = 'manager';
244 } else if (group_id === self.config.group_pos_user_id[0]) {
245 user.role = 'cashier';
249 pos_users.push(user);
251 // replace the current user with its updated version
252 if (user.id === self.user.id) {
256 self.users = pos_users;
259 model: 'stock.location',
261 ids: function(self){ return [self.config.stock_location_id[0]]; },
262 loaded: function(self, locations){ self.shop = locations[0]; },
264 model: 'product.pricelist',
265 fields: ['currency_id'],
266 ids: function(self){ return [self.config.pricelist_id[0]]; },
267 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
269 model: 'res.currency',
270 fields: ['symbol','position','rounding','accuracy'],
271 ids: function(self){ return [self.pricelist.currency_id[0]]; },
272 loaded: function(self, currencies){
273 self.currency = currencies[0];
274 if (self.currency.rounding > 0) {
275 self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
277 self.currency.decimals = 0;
282 model: 'product.packaging',
283 fields: ['barcode','product_tmpl_id'],
285 loaded: function(self, packagings){
286 self.db.add_packagings(packagings);
289 model: 'pos.category',
290 fields: ['id','name','parent_id','child_id','image'],
292 loaded: function(self, categories){
293 self.db.add_categories(categories);
296 model: 'product.product',
297 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'barcode', 'default_code',
298 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
300 domain: function(self){ return [['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, bankstatements, tmp){
310 self.bankstatements = bankstatements;
313 _.each(bankstatements,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 bankstatements = self.bankstatements;
326 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
327 for(var j = 0, jlen = journals.length; j < jlen; j++){
328 if(bankstatements[i].journal_id[0] === journals[j].id){
329 bankstatements[i].journal = journals[j];
333 self.cashregisters = bankstatements;
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];
341 loaded: function(self){
342 var fonts_loaded = new $.Deferred();
343 // Waiting for fonts to be loaded to prevent receipt printing
344 // from printing empty receipt while loading Inconsolata
345 // ( The font used for the receipt )
346 waitForWebfonts(['Lato','Inconsolata'], function(){
347 fonts_loaded.resolve();
349 // The JS used to detect font loading is not 100% robust, so
350 // do not wait more than 5sec
351 setTimeout(function(){
352 fonts_loaded.resolve();
359 loaded: function(self){
360 self.company_logo = new Image();
361 var logo_loaded = new $.Deferred();
362 self.company_logo.onload = function(){
363 var img = self.company_logo;
365 var targetwidth = 300;
367 if( img.width !== targetwidth ){
368 ratio = targetwidth / img.width;
370 if( img.height * ratio > maxheight ){
371 ratio = maxheight / img.height;
373 var width = Math.floor(img.width * ratio);
374 var height = Math.floor(img.height * ratio);
375 var c = document.createElement('canvas');
378 var ctx = c.getContext('2d');
379 ctx.drawImage(self.company_logo,0,0, width, height);
381 self.company_logo_base64 = c.toDataURL();
382 logo_loaded.resolve();
384 self.company_logo.onerror = function(){
385 logo_loaded.reject();
387 self.company_logo.crossOrigin = "anonymous";
388 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
394 loaded: function(self) {
395 var barcode_parser = new barcode_parser_module.BarcodeParser({'nomenclature_id': self.config.barcode_nomenclature_id});
396 self.barcode_reader.set_barcode_parser(barcode_parser);
397 return barcode_parser.is_loaded();
402 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
403 load_server_data: function(){
405 var loaded = new $.Deferred();
407 var progress_step = 1.0 / self.models.length;
408 var tmp = {}; // this is used to share a temporary state between models loaders
410 function load_model(index){
411 if(index >= self.models.length){
414 var model = self.models[index];
415 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
417 var cond = typeof model.condition === 'function' ? model.condition(self,tmp) : true;
423 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
424 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
425 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
426 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
427 progress += progress_step;
432 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
434 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
436 records.then(function(result){
437 try{ // catching exceptions in model.loaded(...)
438 $.when(model.loaded(self,result,tmp))
439 .then(function(){ load_model(index + 1); },
440 function(err){ loaded.reject(err); });
442 console.error(err.stack);
448 }else if( model.loaded ){
449 try{ // catching exceptions in model.loaded(...)
450 $.when(model.loaded(self,tmp))
451 .then( function(){ load_model(index +1); },
452 function(err){ loaded.reject(err); });
457 load_model(index + 1);
471 // reload the list of partner, returns as a deferred that resolves if there were
472 // updated partners, and fails if not
473 load_new_partners: function(){
475 var def = new $.Deferred();
476 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
477 new instance.web.Model('res.partner')
479 .filter([['write_date','>',this.db.get_partner_write_date()]])
480 .all({'timeout':3000, 'shadow': true})
481 .then(function(partners){
482 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
487 }, function(){ def.reject(); });
491 // this is called when an order is removed from the order collection. It ensures that there is always an existing
492 // order and a valid selected order
493 on_removed_order: function(removed_order,index,reason){
494 var order_list = this.get_order_list();
495 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
496 // when we intentionally remove an unfinished order, and there is another existing one
497 this.set_order(order_list[index] || order_list[order_list.length -1]);
499 // when the order was automatically removed after completion,
500 // or when we intentionally delete the only concurrent order
501 this.add_new_order();
505 // returns the user who is currently the cashier for this point of sale
506 get_cashier: function(){
507 return this.cashier || this.user;
509 // changes the current cashier
510 set_cashier: function(user){
513 //creates a new empty order and sets it as the current order
514 add_new_order: function(){
515 var order = new module.Order({},{pos:this});
516 this.get('orders').add(order);
517 this.set('selectedOrder', order);
520 // load the locally saved unpaid orders for this session.
521 load_orders: function(){
522 var jsons = this.db.get_unpaid_orders();
524 var not_loaded_count = 0;
526 for (var i = 0; i < jsons.length; i++) {
528 if (json.pos_session_id === this.pos_session.id) {
529 orders.push(new module.Order({},{
534 not_loaded_count += 1;
538 if (not_loaded_count) {
539 console.info('There are '+not_loaded_count+' locally saved unpaid orders belonging to another session');
542 orders = orders.sort(function(a,b){
543 return a.sequence_number - b.sequence_number;
547 this.get('orders').add(orders);
551 set_start_order: function(){
552 var orders = this.get('orders').models;
554 if (orders.length && !this.get('selectedOrder')) {
555 this.set('selectedOrder',orders[0]);
557 this.add_new_order();
561 // return the current order
562 get_order: function(){
563 return this.get('selectedOrder');
566 // change the current order
567 set_order: function(order){
568 this.set({ selectedOrder: order });
571 // return the list of unpaid orders
572 get_order_list: function(){
573 return this.get('orders').models;
576 //removes the current order
577 delete_current_order: function(){
578 var order = this.get_order();
580 order.destroy({'reason':'abandon'});
584 // saves the order locally and try to send it to the backend.
585 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
586 push_order: function(order) {
590 this.proxy.log('push_order',order.export_as_JSON());
591 this.db.add_order(order.export_as_JSON());
594 var pushed = new $.Deferred();
596 this.flush_mutex.exec(function(){
597 var flushed = self._flush_orders(self.db.get_orders());
599 flushed.always(function(ids){
606 // saves the order locally and try to send it to the backend and make an invoice
607 // returns a deferred that succeeds when the order has been posted and successfully generated
608 // an invoice. This method can fail in various ways:
609 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
610 // this error is solved
611 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
612 // the network connection is up
614 push_and_invoice_order: function(order){
616 var invoiced = new $.Deferred();
618 if(!order.get_client()){
619 invoiced.reject('error-no-client');
623 var order_id = this.db.add_order(order.export_as_JSON());
625 this.flush_mutex.exec(function(){
626 var done = new $.Deferred(); // holds the mutex
628 // send the order to the server
629 // we have a 30 seconds timeout on this push.
630 // FIXME: if the server takes more than 30 seconds to accept the order,
631 // the client will believe it wasn't successfully sent, and very bad
632 // things will happen as a duplicate will be sent next time
633 // so we must make sure the server detects and ignores duplicated orders
635 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
637 transfer.fail(function(){
638 invoiced.reject('error-transfer');
642 // on success, get the order id generated by the server
643 transfer.pipe(function(order_server_id){
645 // generate the pdf and download it
646 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
647 active_ids:order_server_id,
661 // wrapper around the _save_to_server that updates the synch status widget
662 _flush_orders: function(orders, options) {
664 this.set('synch',{ state: 'connecting', pending: orders.length});
666 return self._save_to_server(orders, options).done(function (server_ids) {
667 var pending = self.db.get_orders().length;
670 state: pending ? 'connecting' : 'connected',
678 // send an array of orders to the server
679 // available options:
680 // - timeout: timeout for the rpc call in ms
681 // returns a deferred that resolves with the list of
682 // server generated ids for the sent orders
683 _save_to_server: function (orders, options) {
684 if (!orders || !orders.length) {
685 var result = $.Deferred();
690 options = options || {};
693 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
695 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
696 // then we want to notify the user that we are waiting on something )
697 var posOrderModel = new instance.web.Model('pos.order');
698 return posOrderModel.call('create_from_ui',
699 [_.map(orders, function (order) {
700 order.to_invoice = options.to_invoice || false;
705 shadow: !options.to_invoice,
708 ).then(function (server_ids) {
709 _.each(orders, function (order) {
710 self.db.remove_order(order.id);
713 }).fail(function (error, event){
714 if(error.code === 200 ){ // Business Logic Error, not a connection problem
715 //if warning do not need to display traceback!!
716 if (error.data.exception_type == 'warning') {
717 delete error.data.debug;
719 self.pos_widget.screen_selector.show_popup('error-traceback',{
720 message: error.data.message,
721 comment: error.data.debug
724 // prevent an error popup creation by the rpc failure
725 // we want the failure to be silent as we send the orders in the background
726 event.preventDefault();
727 console.error('Failed to send orders:', orders);
731 scan_product: function(parsed_code){
733 var selectedOrder = this.get_order();
734 var product = this.db.get_product_by_barcode(parsed_code.base_code);
740 if(parsed_code.type === 'price'){
741 selectedOrder.add_product(product, {price:parsed_code.value});
742 }else if(parsed_code.type === 'weight'){
743 selectedOrder.add_product(product, {quantity:parsed_code.value, merge:false});
744 }else if(parsed_code.type === 'discount'){
745 selectedOrder.add_product(product, {discount:parsed_code.value, merge:false});
747 selectedOrder.add_product(product);
753 var orderline_id = 1;
755 // An orderline represent one element of the content of a client's shopping cart.
756 // An orderline contains a product, its quantity, its price, discount. etc.
757 // An Order contains zero or more Orderlines.
758 module.Orderline = Backbone.Model.extend({
759 initialize: function(attr,options){
760 this.pos = options.pos;
761 this.order = options.order;
763 this.init_from_JSON(options.json);
766 this.product = options.product;
767 this.price = options.product.price;
769 this.quantityStr = '1';
771 this.discountStr = '0';
773 this.selected = false;
774 this.id = orderline_id++;
776 init_from_JSON: function(json) {
777 this.product = this.pos.db.get_product_by_id(json.product_id);
779 console.error('ERROR: attempting to recover product not available in the point of sale');
781 this.price = json.price_unit;
782 this.set_discount(json.discount);
783 this.set_quantity(json.qty);
786 var orderline = new module.Orderline({},{
789 product: this.product,
792 orderline.quantity = this.quantity;
793 orderline.quantityStr = this.quantityStr;
794 orderline.discount = this.discount;
795 orderline.type = this.type;
796 orderline.selected = false;
799 // sets a discount [0,100]%
800 set_discount: function(discount){
801 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
802 this.discount = disc;
803 this.discountStr = '' + disc;
804 this.trigger('change',this);
806 // returns the discount [0,100]%
807 get_discount: function(){
808 return this.discount;
810 get_discount_str: function(){
811 return this.discountStr;
813 get_product_type: function(){
816 // sets the quantity of the product. The quantity will be rounded according to the
817 // product's unity of measure properties. Quantities greater than zero will not get
819 set_quantity: function(quantity){
820 if(quantity === 'remove'){
821 this.order.remove_orderline(this);
824 var quant = parseFloat(quantity) || 0;
825 var unit = this.get_unit();
828 this.quantity = round_pr(quant, unit.rounding);
829 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
831 this.quantity = round_pr(quant, 1);
832 this.quantityStr = this.quantity.toFixed(0);
835 this.quantity = quant;
836 this.quantityStr = '' + this.quantity;
839 this.trigger('change',this);
841 // return the quantity of product
842 get_quantity: function(){
843 return this.quantity;
845 get_quantity_str: function(){
846 return this.quantityStr;
848 get_quantity_str_with_unit: function(){
849 var unit = this.get_unit();
850 if(unit && !unit.is_unit){
851 return this.quantityStr + ' ' + unit.name;
853 return this.quantityStr;
856 // return the unit of measure of the product
857 get_unit: function(){
858 var unit_id = this.product.uom_id;
862 unit_id = unit_id[0];
866 return this.pos.units_by_id[unit_id];
868 // return the product of this orderline
869 get_product: function(){
872 // selects or deselects this orderline
873 set_selected: function(selected){
874 this.selected = selected;
875 this.trigger('change',this);
877 // returns true if this orderline is selected
878 is_selected: function(){
879 return this.selected;
881 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
882 // in the orderline. This returns true if it makes sense to merge the two
883 can_be_merged_with: function(orderline){
884 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
886 }else if(!this.get_unit() || !this.get_unit().groupable){
888 }else if(this.get_product_type() !== orderline.get_product_type()){
890 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
892 }else if(this.price !== orderline.price){
898 merge: function(orderline){
899 this.set_quantity(this.get_quantity() + orderline.get_quantity());
901 export_as_JSON: function() {
903 qty: this.get_quantity(),
904 price_unit: this.get_unit_price(),
905 discount: this.get_discount(),
906 product_id: this.get_product().id,
909 //used to create a json of the ticket, to be sent to the printer
910 export_for_printing: function(){
912 quantity: this.get_quantity(),
913 unit_name: this.get_unit().name,
914 price: this.get_unit_display_price(),
915 discount: this.get_discount(),
916 product_name: this.get_product().display_name,
917 price_display : this.get_display_price(),
918 price_with_tax : this.get_price_with_tax(),
919 price_without_tax: this.get_price_without_tax(),
921 product_description: this.get_product().description,
922 product_description_sale: this.get_product().description_sale,
925 // changes the base price of the product for this orderline
926 set_unit_price: function(price){
927 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
928 this.trigger('change',this);
930 get_unit_price: function(){
933 get_unit_display_price: function(){
934 if (this.pos.config.iface_tax_included) {
935 var quantity = this.quantity;
937 var price = this.get_all_prices().priceWithTax;
938 this.quantity = quantity;
941 return this.get_unit_price();
944 get_base_price: function(){
945 var rounding = this.pos.currency.rounding;
946 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
948 get_display_price: function(){
949 return this.get_base_price();
950 if (this.pos.config.iface_tax_included) {
951 return this.get_all_prices().priceWithTax;
953 return this.get_base_price();
956 get_price_without_tax: function(){
957 return this.get_all_prices().priceWithoutTax;
959 get_price_with_tax: function(){
960 return this.get_all_prices().priceWithTax;
963 return this.get_all_prices().tax;
965 get_tax_details: function(){
966 return this.get_all_prices().taxDetails;
968 get_taxes: function(){
969 var taxes_ids = this.get_product().taxes_id;
971 for (var i = 0; i < taxes_ids.length; i++) {
972 taxes.push(this.pos.taxes_by_id[taxes_ids[i]]);
976 get_all_prices: function(){
978 var currency_rounding = this.pos.currency.rounding;
979 var base = this.get_base_price();
981 var totalNoTax = base;
983 var product = this.get_product();
984 var taxes_ids = product.taxes_id;
985 var taxes = self.pos.taxes;
988 _.each(taxes_ids, function(el) {
989 var tax = _.detect(taxes, function(t) {return t.id === el;});
990 if (tax.price_include) {
992 if (tax.type === "percent") {
993 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
994 } else if (tax.type === "fixed") {
995 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
997 throw "This type of tax is not supported by the point of sale: " + tax.type;
999 tmp = round_pr(tmp,currency_rounding);
1002 taxdetail[tax.id] = tmp;
1005 if (tax.type === "percent") {
1006 tmp = tax.amount * base;
1007 } else if (tax.type === "fixed") {
1008 tmp = tax.amount * self.get_quantity();
1010 throw "This type of tax is not supported by the point of sale: " + tax.type;
1012 tmp = round_pr(tmp,currency_rounding);
1015 taxdetail[tax.id] = tmp;
1019 "priceWithTax": totalTax,
1020 "priceWithoutTax": totalNoTax,
1022 "taxDetails": taxdetail,
1027 module.OrderlineCollection = Backbone.Collection.extend({
1028 model: module.Orderline,
1031 // Every Paymentline contains a cashregister and an amount of money.
1032 module.Paymentline = Backbone.Model.extend({
1033 initialize: function(attributes, options) {
1034 this.pos = options.pos;
1036 this.selected = false;
1038 this.init_from_JSON(options.json);
1041 this.cashregister = options.cashregister;
1042 this.name = this.cashregister.journal_id[1];
1044 init_from_JSON: function(json){
1045 this.amount = json.amount;
1046 this.cashregister = this.pos.cashregisters_by_id[json.statement_id];
1047 this.name = this.cashregister.journal_id[1];
1049 //sets the amount of money on this payment line
1050 set_amount: function(value){
1051 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
1052 this.trigger('change',this);
1054 // returns the amount of money on this paymentline
1055 get_amount: function(){
1058 get_amount_str: function(){
1059 return this.amount.toFixed(this.pos.currency.decimals);
1061 set_selected: function(selected){
1062 if(this.selected !== selected){
1063 this.selected = selected;
1064 this.trigger('change',this);
1067 // returns the associated cashregister
1068 //exports as JSON for server communication
1069 export_as_JSON: function(){
1071 name: instance.web.datetime_to_str(new Date()),
1072 statement_id: this.cashregister.id,
1073 account_id: this.cashregister.account_id[0],
1074 journal_id: this.cashregister.journal_id[0],
1075 amount: this.get_amount()
1078 //exports as JSON for receipt printing
1079 export_for_printing: function(){
1081 amount: this.get_amount(),
1082 journal: this.cashregister.journal_id[1],
1087 module.PaymentlineCollection = Backbone.Collection.extend({
1088 model: module.Paymentline,
1091 // An order more or less represents the content of a client's shopping cart (the OrderLines)
1092 // plus the associated payment information (the Paymentlines)
1093 // there is always an active ('selected') order in the Pos, a new one is created
1094 // automaticaly once an order is completed and sent to the server.
1095 module.Order = Backbone.Model.extend({
1096 initialize: function(attributes,options){
1097 Backbone.Model.prototype.initialize.apply(this, arguments);
1098 options = options || {};
1100 this.init_locked = true;
1101 this.pos = options.pos;
1102 this.selected_orderline = undefined;
1103 this.selected_paymentline = undefined;
1104 this.screen_data = {}; // see ScreenSelector
1105 this.temporary = options.temporary || false;
1106 this.creation_date = new Date();
1107 this.to_invoice = false;
1108 this.orderlines = new module.OrderlineCollection();
1109 this.paymentlines = new module.PaymentlineCollection();
1110 this.pos_session_id = this.pos.pos_session.id;
1112 this.set({ client: null });
1115 this.init_from_JSON(options.json);
1117 this.sequence_number = this.pos.pos_session.sequence_number++;
1118 this.uid = this.generate_unique_id();
1119 this.name = _t("Order ") + this.uid;
1122 this.on('change', function(){ this.save_to_db("order:change"); }, this);
1123 this.orderlines.on('change', function(){ this.save_to_db("orderline:change"); }, this);
1124 this.orderlines.on('add', function(){ this.save_to_db("orderline:add"); }, this);
1125 this.orderlines.on('remove', function(){ this.save_to_db("orderline:remove"); }, this);
1126 this.paymentlines.on('change', function(){ this.save_to_db("paymentline:change"); }, this);
1127 this.paymentlines.on('add', function(){ this.save_to_db("paymentline:add"); }, this);
1128 this.paymentlines.on('remove', function(){ this.save_to_db("paymentline:rem"); }, this);
1130 this.init_locked = false;
1135 save_to_db: function(){
1136 if (!this.init_locked) {
1137 this.pos.db.save_unpaid_order(this);
1140 init_from_JSON: function(json) {
1141 this.sequence_number = json.sequence_number;
1142 this.pos.pos_session.sequence_number = Math.max(this.sequence_number+1,this.pos.pos_session.sequence_number);
1143 this.session_id = json.pos_session_id;
1144 this.uid = json.uid;
1145 this.name = _t("Order ") + this.uid;
1146 if (json.partner_id) {
1147 var client = this.pos.db.get_partner_by_id(json.partner_id);
1149 console.error('ERROR: trying to load a parner not available in the pos');
1154 this.set_client(client);
1156 this.temporary = false; // FIXME
1157 this.to_invoice = false; // FIXME
1159 var orderlines = json.lines;
1160 for (var i = 0; i < orderlines.length; i++) {
1161 var orderline = orderlines[i][2];
1162 this.add_orderline(new module.Orderline({}, {pos: this.pos, order: this, json: orderline}));
1165 var paymentlines = json.statement_ids;
1166 for (var i = 0; i < paymentlines.length; i++) {
1167 var paymentline = paymentlines[i][2];
1168 var newpaymentline = new module.Paymentline({},{pos: this.pos, json: paymentline});
1169 this.paymentlines.add(newpaymentline);
1171 if (i === paymentlines.length - 1) {
1172 this.select_paymentline(newpaymentline);
1176 export_as_JSON: function() {
1177 var orderLines, paymentLines;
1179 this.orderlines.each(_.bind( function(item) {
1180 return orderLines.push([0, 0, item.export_as_JSON()]);
1183 this.paymentlines.each(_.bind( function(item) {
1184 return paymentLines.push([0, 0, item.export_as_JSON()]);
1187 name: this.get_name(),
1188 amount_paid: this.get_total_paid(),
1189 amount_total: this.get_total_with_tax(),
1190 amount_tax: this.get_total_tax(),
1191 amount_return: this.get_change(),
1193 statement_ids: paymentLines,
1194 pos_session_id: this.pos_session_id,
1195 partner_id: this.get_client() ? this.get_client().id : false,
1196 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1198 sequence_number: this.sequence_number,
1201 export_for_printing: function(){
1202 var orderlines = [];
1205 this.orderlines.each(function(orderline){
1206 orderlines.push(orderline.export_for_printing());
1209 var paymentlines = [];
1210 this.paymentlines.each(function(paymentline){
1211 paymentlines.push(paymentline.export_for_printing());
1213 var client = this.get('client');
1214 var cashier = this.pos.cashier || this.pos.user;
1215 var company = this.pos.company;
1216 var shop = this.pos.shop;
1217 var date = new Date();
1219 function is_xml(subreceipt){
1220 return subreceipt ? (subreceipt.split('\n')[0].indexOf('<!DOCTYPE QWEB') >= 0) : false;
1223 function render_xml(subreceipt){
1224 if (!is_xml(subreceipt)) {
1227 subreceipt = subreceipt.split('\n').slice(1).join('\n');
1228 var qweb = new QWeb2.Engine();
1229 qweb.debug = instance.session.debug;
1230 qweb.default_dict = _.clone(QWeb.default_dict);
1231 qweb.add_template('<templates><t t-name="subreceipt">'+subreceipt+'</t></templates>');
1233 return qweb.render('subreceipt',{'pos':self.pos,'widget':self.pos.pos_widget,'order':self, 'receipt': receipt}) ;
1238 orderlines: orderlines,
1239 paymentlines: paymentlines,
1240 subtotal: this.get_subtotal(),
1241 total_with_tax: this.get_total_with_tax(),
1242 total_without_tax: this.get_total_without_tax(),
1243 total_tax: this.get_total_tax(),
1244 total_paid: this.get_total_paid(),
1245 total_discount: this.get_total_discount(),
1246 tax_details: this.get_tax_details(),
1247 change: this.get_change(),
1248 name : this.get_name(),
1249 client: client ? client.name : null ,
1250 invoice_id: null, //TODO
1251 cashier: cashier ? cashier.name : null,
1252 header: this.pos.config.receipt_header || '',
1253 footer: this.pos.config.receipt_footer || '',
1260 year: date.getFullYear(),
1261 month: date.getMonth(),
1262 date: date.getDate(), // day of the month
1263 day: date.getDay(), // day of the week
1264 hour: date.getHours(),
1265 minute: date.getMinutes() ,
1266 isostring: date.toISOString(),
1267 localestring: date.toLocaleString(),
1270 email: company.email,
1271 website: company.website,
1272 company_registry: company.company_registry,
1273 contact_address: company.partner_id[1],
1276 phone: company.phone,
1277 logo: this.pos.company_logo_base64,
1282 currency: this.pos.currency,
1285 if (is_xml(this.pos.config.receipt_header)){
1286 receipt.header_xml = render_xml(this.pos.config.receipt_header);
1289 if (is_xml(this.pos.config.receipt_footer)){
1290 receipt.footer_xml = render_xml(this.pos.config.receipt_footer);
1295 is_empty: function(){
1296 return this.orderlines.models.length === 0;
1298 generate_unique_id: function() {
1299 // Generates a public identification number for the order.
1300 // The generated number must be unique and sequential. They are made 12 digit long
1301 // to fit into EAN-13 barcodes, should it be needed
1303 function zero_pad(num,size){
1305 while (s.length < size) {
1310 return zero_pad(this.pos.pos_session.id,5) +'-'+
1311 zero_pad(this.pos.pos_session.login_number,3) +'-'+
1312 zero_pad(this.sequence_number,4);
1314 get_name: function() {
1317 /* ---- Order Lines --- */
1318 add_orderline: function(line){
1320 line.order.remove_orderline(line);
1323 this.orderlines.add(line);
1324 this.select_orderline(this.get_last_orderline());
1326 get_orderline: function(id){
1327 var orderlines = this.orderlines.models;
1328 for(var i = 0; i < orderlines.length; i++){
1329 if(orderlines[i].id === id){
1330 return orderlines[i];
1335 get_orderlines: function(){
1336 return this.orderlines.models;
1338 get_last_orderline: function(){
1339 return this.orderlines.at(this.orderlines.length -1);
1341 remove_orderline: function( line ){
1342 this.orderlines.remove(line);
1343 this.select_orderline(this.get_last_orderline());
1345 add_product: function(product, options){
1346 options = options || {};
1347 var attr = JSON.parse(JSON.stringify(product));
1348 attr.pos = this.pos;
1350 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1352 if(options.quantity !== undefined){
1353 line.set_quantity(options.quantity);
1355 if(options.price !== undefined){
1356 line.set_unit_price(options.price);
1358 if(options.discount !== undefined){
1359 line.set_discount(options.discount);
1362 if(options.extras !== undefined){
1363 for (var prop in options.extras) {
1364 line[prop] = options.extras[prop];
1368 var last_orderline = this.get_last_orderline();
1369 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1370 last_orderline.merge(line);
1372 this.orderlines.add(line);
1374 this.select_orderline(this.get_last_orderline());
1376 get_selected_orderline: function(){
1377 return this.selected_orderline;
1379 select_orderline: function(line){
1381 if(line !== this.selected_orderline){
1382 if(this.selected_orderline){
1383 this.selected_orderline.set_selected(false);
1385 this.selected_orderline = line;
1386 this.selected_orderline.set_selected(true);
1389 this.selected_orderline = undefined;
1392 deselect_orderline: function(){
1393 if(this.selected_orderline){
1394 this.selected_orderline.set_selected(false);
1395 this.selected_orderline = undefined;
1398 /* ---- Payment Lines --- */
1399 add_paymentline: function(cashregister) {
1400 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos: this.pos});
1401 if(cashregister.journal.type !== 'cash' || this.pos.config.iface_precompute_cash){
1402 newPaymentline.set_amount( Math.max(this.get_due(),0) );
1404 this.paymentlines.add(newPaymentline);
1405 this.select_paymentline(newPaymentline);
1408 get_paymentlines: function(){
1409 return this.paymentlines.models;
1411 remove_paymentline: function(line){
1412 if(this.selected_paymentline === line){
1413 this.select_paymentline(undefined);
1415 this.paymentlines.remove(line);
1417 clean_empty_paymentlines: function() {
1418 var lines = this.paymentlines.models;
1420 for ( var i = 0; i < lines.length; i++) {
1421 if (!lines[i].get_amount()) {
1422 empty.push(lines[i]);
1425 for ( var i = 0; i < empty.length; i++) {
1426 this.remove_paymentline(empty[i]);
1429 select_paymentline: function(line){
1430 if(line !== this.selected_paymentline){
1431 if(this.selected_paymentline){
1432 this.selected_paymentline.set_selected(false);
1434 this.selected_paymentline = line;
1435 if(this.selected_paymentline){
1436 this.selected_paymentline.set_selected(true);
1438 this.trigger('change:selected_paymentline',this.selected_paymentline);
1441 /* ---- Payment Status --- */
1442 get_subtotal : function(){
1443 return this.orderlines.reduce((function(sum, orderLine){
1444 return sum + orderLine.get_display_price();
1447 get_total_with_tax: function() {
1448 return this.orderlines.reduce((function(sum, orderLine) {
1449 return sum + orderLine.get_price_with_tax();
1452 get_total_without_tax: function() {
1453 return this.orderlines.reduce((function(sum, orderLine) {
1454 return sum + orderLine.get_price_without_tax();
1457 get_total_discount: function() {
1458 return this.orderlines.reduce((function(sum, orderLine) {
1459 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1462 get_total_tax: function() {
1463 return this.orderlines.reduce((function(sum, orderLine) {
1464 return sum + orderLine.get_tax();
1467 get_total_paid: function() {
1468 return this.paymentlines.reduce((function(sum, paymentLine) {
1469 return sum + paymentLine.get_amount();
1472 get_tax_details: function(){
1474 var fulldetails = [];
1475 var taxes_by_id = {};
1477 for(var i = 0; i < this.pos.taxes.length; i++){
1478 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1481 this.orderlines.each(function(line){
1482 var ldetails = line.get_tax_details();
1483 for(var id in ldetails){
1484 if(ldetails.hasOwnProperty(id)){
1485 details[id] = (details[id] || 0) + ldetails[id];
1490 for(var id in details){
1491 if(details.hasOwnProperty(id)){
1492 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1498 // Returns a total only for the orderlines with products belonging to the category
1499 get_total_for_category_with_tax: function(categ_id){
1503 if (categ_id instanceof Array) {
1504 for (var i = 0; i < categ_id.length; i++) {
1505 total += this.get_total_for_category_with_tax(categ_id[i]);
1510 this.orderlines.each(function(line){
1511 if ( self.pos.db.category_contains(categ_id,line.product.id) ) {
1512 total += line.get_price_with_tax();
1518 get_total_for_taxes: function(tax_id){
1522 if (!(tax_id instanceof Array)) {
1528 for (var i = 0; i < tax_id.length; i++) {
1529 tax_set[tax_id[i]] = true;
1532 this.orderlines.each(function(line){
1533 var taxes_ids = line.get_product().taxes_id;
1534 for (var i = 0; i < taxes_ids.length; i++) {
1535 if (tax_set[taxes_ids[i]]) {
1536 total += line.get_price_with_tax();
1544 get_change: function(paymentline) {
1546 var change = this.get_total_paid() - this.get_total_with_tax();
1548 var change = -this.get_total_with_tax();
1549 var lines = this.paymentlines.models;
1550 for (var i = 0; i < lines.length; i++) {
1551 change += lines[i].get_amount();
1552 if (lines[i] === paymentline) {
1557 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1559 get_due: function(paymentline) {
1561 var due = this.get_total_with_tax() - this.get_total_paid();
1563 var due = this.get_total_with_tax();
1564 var lines = this.paymentlines.models;
1565 for (var i = 0; i < lines.length; i++) {
1566 if (lines[i] === paymentline) {
1569 due -= lines[i].get_amount();
1573 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1575 is_paid: function(){
1576 return this.get_due() === 0;
1578 is_paid_with_cash: function(){
1579 return !!this.paymentlines.find( function(pl){
1580 return pl.cashregister.journal.type === 'cash';
1583 finalize: function(){
1586 destroy: function(args){
1587 Backbone.Model.prototype.destroy.apply(this,arguments);
1588 this.pos.db.remove_unpaid_order(this);
1590 /* ---- Invoice --- */
1591 set_to_invoice: function(to_invoice) {
1592 this.to_invoice = to_invoice;
1594 is_to_invoice: function(){
1595 return this.to_invoice;
1597 /* ---- Client / Customer --- */
1598 // the client related to the current order.
1599 set_client: function(client){
1600 this.set('client',client);
1602 get_client: function(){
1603 return this.get('client');
1605 get_client_name: function(){
1606 var client = this.get('client');
1607 return client ? client.name : "";
1609 /* ---- Screen Status --- */
1610 // the order also stores the screen status, as the PoS supports
1611 // different active screens per order. This method is used to
1612 // store the screen status.
1613 set_screen_data: function(key,value){
1614 if(arguments.length === 2){
1615 this.screen_data[key] = value;
1616 }else if(arguments.length === 1){
1617 for(var key in arguments[0]){
1618 this.screen_data[key] = arguments[0][key];
1622 //see set_screen_data
1623 get_screen_data: function(key){
1624 return this.screen_data[key];
1628 module.OrderCollection = Backbone.Collection.extend({
1629 model: module.Order,
1633 The numpad handles both the choice of the property currently being modified
1634 (quantity, price or discount) and the edition of the corresponding numeric value.
1636 module.NumpadState = Backbone.Model.extend({
1641 appendNewChar: function(newChar) {
1643 oldBuffer = this.get('buffer');
1644 if (oldBuffer === '0') {
1648 } else if (oldBuffer === '-0') {
1650 buffer: "-" + newChar
1654 buffer: (this.get('buffer')) + newChar
1657 this.trigger('set_value',this.get('buffer'));
1659 deleteLastChar: function() {
1660 if(this.get('buffer') === ""){
1661 if(this.get('mode') === 'quantity'){
1662 this.trigger('set_value','remove');
1664 this.trigger('set_value',this.get('buffer'));
1667 var newBuffer = this.get('buffer').slice(0,-1) || "";
1668 this.set({ buffer: newBuffer });
1669 this.trigger('set_value',this.get('buffer'));
1672 switchSign: function() {
1674 oldBuffer = this.get('buffer');
1676 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1678 this.trigger('set_value',this.get('buffer'));
1680 changeMode: function(newMode) {
1692 resetValue: function(){
1693 this.set({buffer:'0'});