1 function openerp_pos_models(instance, module){ //module is instance.point_of_sale
4 var QWeb = instance.web.qweb;
5 var _t = instance.web._t;
7 var round_di = instance.web.round_decimals;
8 var round_pr = instance.web.round_precision
10 // The PosModel contains the Point Of Sale's representation of the backend.
11 // Since the PoS must work in standalone ( Without connection to the server )
12 // it must contains a representation of the server's PoS backend.
13 // (taxes, product list, configuration options, etc.) this representation
14 // is fetched and stored by the PosModel at the initialisation.
15 // this is done asynchronously, a ready deferred alows the GUI to wait interactively
16 // for the loading to be completed
17 // There is a single instance of the PosModel for each Front-End instance, it is usually called
18 // 'pos' and is available to all widgets extending PosWidget.
20 module.PosModel = Backbone.Model.extend({
21 initialize: function(session, attributes) {
22 Backbone.Model.prototype.initialize.call(this, attributes);
24 this.session = session;
25 this.flush_mutex = new $.Mutex(); // used to make sure the orders are sent to the server once at time
26 this.pos_widget = attributes.pos_widget;
28 this.proxy = new module.ProxyDevice(this); // used to communicate to the hardware devices via a local proxy
30 this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy}); // used to read barcodes
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();
90 // releases ressources holds by the model at the end of life of the posmodel
92 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
95 this.barcode_reader.disconnect();
96 this.barcode_reader.disconnect_from_proxy();
98 connect_to_proxy: function(){
100 var done = new $.Deferred();
101 this.barcode_reader.disconnect_from_proxy();
102 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
103 this.pos_widget.loading_skip(function(){
104 self.proxy.stop_searching();
106 this.proxy.autoconnect({
107 force_ip: self.config.proxy_ip || undefined,
108 progress: function(prog){
109 self.pos_widget.loading_progress(prog);
112 if(self.config.iface_scan_via_proxy){
113 self.barcode_reader.connect_to_proxy();
115 }).always(function(){
121 // helper function to load data from the server. Obsolete use the models loader below.
122 fetch: function(model, fields, domain, ctx){
123 this._load_progress = (this._load_progress || 0) + 0.05;
124 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
125 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
128 // Server side model loaders. This is the list of the models that need to be loaded from
129 // the server. The models are loaded one by one by this list's order. The 'loaded' callback
130 // is used to store the data in the appropriate place once it has been loaded. This callback
131 // can return a deferred that will pause the loading of the next module.
132 // a shared temporary dictionary is available for loaders to communicate private variables
133 // used during loading such as object ids, etc.
137 fields: ['name','company_id'],
138 ids: function(self){ return [self.session.uid]; },
139 loaded: function(self,users){ self.user = users[0]; },
141 model: 'res.company',
142 fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id'],
143 ids: function(self){ return [self.user.company_id[0]] },
144 loaded: function(self,companies){ self.company = companies[0]; },
146 model: 'decimal.precision',
147 fields: ['name','digits'],
148 loaded: function(self,dps){
150 for (var i = 0; i < dps.length; i++) {
151 self.dp[dps[i].name] = dps[i].digits;
155 model: 'product.uom',
158 loaded: function(self,units){
160 var units_by_id = {};
161 for(var i = 0, len = units.length; i < len; i++){
162 units_by_id[units[i].id] = units[i];
163 units[i].groupable = ( units[i].category_id[0] === 1 );
164 units[i].is_unit = ( units[i].id === 1 );
166 self.units_by_id = units_by_id;
170 fields: ['name','ean13'],
172 loaded: function(self,users){ self.users = users; },
174 model: 'res.partner',
175 fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','ean13','write_date'],
177 loaded: function(self,partners){
178 self.partners = partners;
179 self.db.add_partners(partners);
182 model: 'res.country',
184 loaded: function(self,countries){
185 self.countries = countries;
186 self.company.country = null;
187 for (var i = 0; i < countries.length; i++) {
188 if (countries[i].id === self.company.country_id[0]){
189 self.company.country = countries[i];
194 model: 'account.tax',
195 fields: ['name','amount', 'price_include', 'type'],
197 loaded: function(self,taxes){ self.taxes = taxes; },
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);
229 model: 'stock.location',
231 ids: function(self){ return [self.config.stock_location_id[0]]; },
232 loaded: function(self, locations){ self.shop = locations[0]; },
234 model: 'product.pricelist',
235 fields: ['currency_id'],
236 ids: function(self){ return [self.config.pricelist_id[0]]; },
237 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
239 model: 'res.currency',
240 fields: ['symbol','position','rounding','accuracy'],
241 ids: function(self){ return [self.pricelist.currency_id[0]]; },
242 loaded: function(self, currencies){
243 self.currency = currencies[0];
244 if (self.currency.rounding > 0) {
245 self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
247 self.currency.decimals = 0;
252 model: 'product.packaging',
253 fields: ['ean','product_tmpl_id'],
255 loaded: function(self, packagings){
256 self.db.add_packagings(packagings);
259 model: 'pos.category',
260 fields: ['id','name','parent_id','child_id','image'],
262 loaded: function(self, categories){
263 self.db.add_categories(categories);
266 model: 'product.product',
267 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
268 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
270 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
271 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
272 loaded: function(self, products){
273 self.db.add_products(products);
276 model: 'account.bank.statement',
277 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
278 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
279 loaded: function(self, bankstatements, tmp){
280 self.bankstatements = bankstatements;
283 _.each(bankstatements,function(statement){
284 tmp.journals.push(statement.journal_id[0]);
288 model: 'account.journal',
290 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
291 loaded: function(self, journals){
292 self.journals = journals;
294 // associate the bank statements with their journals.
295 var bankstatements = self.bankstatements;
296 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
297 for(var j = 0, jlen = journals.length; j < jlen; j++){
298 if(bankstatements[i].journal_id[0] === journals[j].id){
299 bankstatements[i].journal = journals[j];
303 self.cashregisters = bankstatements;
304 self.cashregisters_by_id = {};
305 for (var i = 0; i < self.cashregisters.length; i++) {
306 self.cashregisters_by_id[self.cashregisters[i].id] = self.cashregisters[i];
310 model: 'barcode.nomenclature',
311 fields: ['name','rule_ids'],
312 domain: function(self){ return [] },
313 loaded: function(self,nomenclatures){
314 if (self.config.barcode_nomenclature_id) {
315 for (var i = 0; i < nomenclatures.length; i++) {
316 if (nomenclatures[i].id === self.config.barcode_nomenclature_id[0]) {
317 self.nomenclature = nomenclatures[i];
321 self.nomenclature = self.nomenclature || null;
324 model: 'barcode.rule',
325 fields: ['name','sequence','type','encoding','pattern','alias'],
326 domain: function(self){ return [['barcode_nomenclature_id','=',self.nomenclature ? self.nomenclature.id : 0]]; },
327 loaded: function(self,rules){
328 if (self.nomenclature) {
329 rules = rules.sort(function(a,b){ return a.sequence - b.sequence; });
330 self.nomenclature.rules = rules;
331 /*for (var i = 0; i < rules.length; i++) {
332 var pattern = rules[i].pattern;
333 pattern = pattern.replace(/[x\*]/gi,'x');
335 while (pattern.length < 12) {
338 rules[i].pattern = pattern;
344 loaded: function(self){
345 var fonts_loaded = new $.Deferred();
346 // Waiting for fonts to be loaded to prevent receipt printing
347 // from printing empty receipt while loading Inconsolata
348 // ( The font used for the receipt )
349 waitForWebfonts(['Lato','Inconsolata'], function(){
350 fonts_loaded.resolve();
352 // The JS used to detect font loading is not 100% robust, so
353 // do not wait more than 5sec
354 setTimeout(function(){
355 fonts_loaded.resolve();
362 loaded: function(self){
363 self.company_logo = new Image();
364 var logo_loaded = new $.Deferred();
365 self.company_logo.onload = function(){
366 var img = self.company_logo;
368 var targetwidth = 300;
370 if( img.width !== targetwidth ){
371 ratio = targetwidth / img.width;
373 if( img.height * ratio > maxheight ){
374 ratio = maxheight / img.height;
376 var width = Math.floor(img.width * ratio);
377 var height = Math.floor(img.height * ratio);
378 var c = document.createElement('canvas');
381 var ctx = c.getContext('2d');
382 ctx.drawImage(self.company_logo,0,0, width, height);
384 self.company_logo_base64 = c.toDataURL();
385 logo_loaded.resolve();
387 self.company_logo.onerror = function(){
388 logo_loaded.reject();
390 self.company_logo.crossOrigin = "anonymous";
391 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
398 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
399 load_server_data: function(){
401 var loaded = new $.Deferred();
403 var progress_step = 1.0 / self.models.length;
404 var tmp = {}; // this is used to share a temporary state between models loaders
406 function load_model(index){
407 if(index >= self.models.length){
410 var model = self.models[index];
411 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
413 var cond = typeof model.condition === 'function' ? model.condition(self,tmp) : true;
419 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
420 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
421 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
422 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
423 progress += progress_step;
428 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
430 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
432 records.then(function(result){
433 try{ // catching exceptions in model.loaded(...)
434 $.when(model.loaded(self,result,tmp))
435 .then(function(){ load_model(index + 1); },
436 function(err){ loaded.reject(err); });
438 console.error(err.stack);
444 }else if( model.loaded ){
445 try{ // catching exceptions in model.loaded(...)
446 $.when(model.loaded(self,tmp))
447 .then( function(){ load_model(index +1); },
448 function(err){ loaded.reject(err); });
453 load_model(index + 1);
467 // reload the list of partner, returns as a deferred that resolves if there were
468 // updated partners, and fails if not
469 load_new_partners: function(){
471 var def = new $.Deferred();
472 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
473 new instance.web.Model('res.partner')
475 .filter([['write_date','>',this.db.get_partner_write_date()]])
476 .all({'timeout':3000, 'shadow': true})
477 .then(function(partners){
478 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
483 }, function(){ def.reject(); });
487 // this is called when an order is removed from the order collection. It ensures that there is always an existing
488 // order and a valid selected order
489 on_removed_order: function(removed_order,index,reason){
490 var order_list = this.get_order_list();
491 if( (reason === 'abandon' || removed_order.temporary) && order_list.length > 0){
492 // when we intentionally remove an unfinished order, and there is another existing one
493 this.set_order(order_list[index] || order_list[order_list.length -1]);
495 // when the order was automatically removed after completion,
496 // or when we intentionally delete the only concurrent order
497 this.add_new_order();
501 //creates a new empty order and sets it as the current order
502 add_new_order: function(){
503 var order = new module.Order({},{pos:this});
504 this.get('orders').add(order);
505 this.set('selectedOrder', order);
508 // load the locally saved unpaid orders for this session.
509 load_orders: function(){
510 var jsons = this.db.get_unpaid_orders();
512 var not_loaded_count = 0;
514 for (var i = 0; i < jsons.length; i++) {
516 if (json.pos_session_id === this.pos_session.id) {
517 orders.push(new module.Order({},{
522 not_loaded_count += 1;
526 if (not_loaded_count) {
527 console.info('There are '+not_loaded_count+' locally saved unpaid orders belonging to another session');
530 orders = orders.sort(function(a,b){
531 return a.sequence_number - b.sequence_number;
535 this.get('orders').add(orders);
539 set_start_order: function(){
540 var orders = this.get('orders').models;
542 if (orders.length && !this.get('selectedOrder')) {
543 this.set('selectedOrder',orders[0]);
545 this.add_new_order();
549 // return the current order
550 get_order: function(){
551 return this.get('selectedOrder');
554 // change the current order
555 set_order: function(order){
556 this.set({ selectedOrder: order });
559 // return the list of unpaid orders
560 get_order_list: function(){
561 return this.get('orders').models;
564 //removes the current order
565 delete_current_order: function(){
566 var order = this.get_order();
568 order.destroy({'reason':'abandon'});
572 // saves the order locally and try to send it to the backend.
573 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
574 push_order: function(order) {
578 this.proxy.log('push_order',order.export_as_JSON());
579 this.db.add_order(order.export_as_JSON());
582 var pushed = new $.Deferred();
584 this.flush_mutex.exec(function(){
585 var flushed = self._flush_orders(self.db.get_orders());
587 flushed.always(function(ids){
594 // saves the order locally and try to send it to the backend and make an invoice
595 // returns a deferred that succeeds when the order has been posted and successfully generated
596 // an invoice. This method can fail in various ways:
597 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
598 // this error is solved
599 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
600 // the network connection is up
602 push_and_invoice_order: function(order){
604 var invoiced = new $.Deferred();
606 if(!order.get_client()){
607 invoiced.reject('error-no-client');
611 var order_id = this.db.add_order(order.export_as_JSON());
613 this.flush_mutex.exec(function(){
614 var done = new $.Deferred(); // holds the mutex
616 // send the order to the server
617 // we have a 30 seconds timeout on this push.
618 // FIXME: if the server takes more than 30 seconds to accept the order,
619 // the client will believe it wasn't successfully sent, and very bad
620 // things will happen as a duplicate will be sent next time
621 // so we must make sure the server detects and ignores duplicated orders
623 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
625 transfer.fail(function(){
626 invoiced.reject('error-transfer');
630 // on success, get the order id generated by the server
631 transfer.pipe(function(order_server_id){
633 // generate the pdf and download it
634 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
635 active_ids:order_server_id,
649 // wrapper around the _save_to_server that updates the synch status widget
650 _flush_orders: function(orders, options) {
652 this.set('synch',{ state: 'connecting', pending: orders.length});
654 return self._save_to_server(orders, options).done(function (server_ids) {
655 var pending = self.db.get_orders().length;
658 state: pending ? 'connecting' : 'connected',
666 // send an array of orders to the server
667 // available options:
668 // - timeout: timeout for the rpc call in ms
669 // returns a deferred that resolves with the list of
670 // server generated ids for the sent orders
671 _save_to_server: function (orders, options) {
672 if (!orders || !orders.length) {
673 var result = $.Deferred();
678 options = options || {};
681 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
683 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
684 // then we want to notify the user that we are waiting on something )
685 var posOrderModel = new instance.web.Model('pos.order');
686 return posOrderModel.call('create_from_ui',
687 [_.map(orders, function (order) {
688 order.to_invoice = options.to_invoice || false;
693 shadow: !options.to_invoice,
696 ).then(function (server_ids) {
697 _.each(orders, function (order) {
698 self.db.remove_order(order.id);
701 }).fail(function (error, event){
702 if(error.code === 200 ){ // Business Logic Error, not a connection problem
703 //if warning do not need to display traceback!!
704 if (error.data.exception_type == 'warning') {
705 delete error.data.debug;
707 self.pos_widget.screen_selector.show_popup('error-traceback',{
708 message: error.data.message,
709 comment: error.data.debug
712 // prevent an error popup creation by the rpc failure
713 // we want the failure to be silent as we send the orders in the background
714 event.preventDefault();
715 console.error('Failed to send orders:', orders);
719 scan_product: function(parsed_code){
721 var selectedOrder = this.get_order();
722 //if(parsed_code.encoding === 'barcode'){
723 var product = this.db.get_product_by_ean13(parsed_code.base_code);
724 /*}else if(parsed_code.encoding === 'reference'){
725 var product = this.db.get_product_by_reference(parsed_code.code);
732 if(parsed_code.type === 'price'){
733 selectedOrder.add_product(product, {price:parsed_code.value});
734 }else if(parsed_code.type === 'weight'){
735 selectedOrder.add_product(product, {quantity:parsed_code.value, merge:false});
736 }else if(parsed_code.type === 'discount'){
737 selectedOrder.add_product(product, {discount:parsed_code.value, merge:false});
739 selectedOrder.add_product(product);
745 var orderline_id = 1;
747 // An orderline represent one element of the content of a client's shopping cart.
748 // An orderline contains a product, its quantity, its price, discount. etc.
749 // An Order contains zero or more Orderlines.
750 module.Orderline = Backbone.Model.extend({
751 initialize: function(attr,options){
752 this.pos = options.pos;
753 this.order = options.order;
755 this.init_from_JSON(options.json);
758 this.product = options.product;
759 this.price = options.product.price;
761 this.quantityStr = '1';
763 this.discountStr = '0';
765 this.selected = false;
766 this.id = orderline_id++;
768 init_from_JSON: function(json) {
769 this.product = this.pos.db.get_product_by_id(json.product_id);
771 console.error('ERROR: attempting to recover product not available in the point of sale');
773 this.price = json.price_unit;
774 this.set_discount(json.discount);
775 this.set_quantity(json.qty);
778 var orderline = new module.Orderline({},{
781 product: this.product,
784 orderline.quantity = this.quantity;
785 orderline.quantityStr = this.quantityStr;
786 orderline.discount = this.discount;
787 orderline.type = this.type;
788 orderline.selected = false;
791 // sets a discount [0,100]%
792 set_discount: function(discount){
793 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
794 this.discount = disc;
795 this.discountStr = '' + disc;
796 this.trigger('change',this);
798 // returns the discount [0,100]%
799 get_discount: function(){
800 return this.discount;
802 get_discount_str: function(){
803 return this.discountStr;
805 get_product_type: function(){
808 // sets the quantity of the product. The quantity will be rounded according to the
809 // product's unity of measure properties. Quantities greater than zero will not get
811 set_quantity: function(quantity){
812 if(quantity === 'remove'){
813 this.order.remove_orderline(this);
816 var quant = parseFloat(quantity) || 0;
817 var unit = this.get_unit();
820 this.quantity = round_pr(quant, unit.rounding);
821 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
823 this.quantity = round_pr(quant, 1);
824 this.quantityStr = this.quantity.toFixed(0);
827 this.quantity = quant;
828 this.quantityStr = '' + this.quantity;
831 this.trigger('change',this);
833 // return the quantity of product
834 get_quantity: function(){
835 return this.quantity;
837 get_quantity_str: function(){
838 return this.quantityStr;
840 get_quantity_str_with_unit: function(){
841 var unit = this.get_unit();
842 if(unit && !unit.is_unit){
843 return this.quantityStr + ' ' + unit.name;
845 return this.quantityStr;
848 // return the unit of measure of the product
849 get_unit: function(){
850 var unit_id = this.product.uom_id;
854 unit_id = unit_id[0];
858 return this.pos.units_by_id[unit_id];
860 // return the product of this orderline
861 get_product: function(){
864 // selects or deselects this orderline
865 set_selected: function(selected){
866 this.selected = selected;
867 this.trigger('change',this);
869 // returns true if this orderline is selected
870 is_selected: function(){
871 return this.selected;
873 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
874 // in the orderline. This returns true if it makes sense to merge the two
875 can_be_merged_with: function(orderline){
876 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
878 }else if(!this.get_unit() || !this.get_unit().groupable){
880 }else if(this.get_product_type() !== orderline.get_product_type()){
882 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
884 }else if(this.price !== orderline.price){
890 merge: function(orderline){
891 this.set_quantity(this.get_quantity() + orderline.get_quantity());
893 export_as_JSON: function() {
895 qty: this.get_quantity(),
896 price_unit: this.get_unit_price(),
897 discount: this.get_discount(),
898 product_id: this.get_product().id,
901 //used to create a json of the ticket, to be sent to the printer
902 export_for_printing: function(){
904 quantity: this.get_quantity(),
905 unit_name: this.get_unit().name,
906 price: this.get_unit_display_price(),
907 discount: this.get_discount(),
908 product_name: this.get_product().display_name,
909 price_display : this.get_display_price(),
910 price_with_tax : this.get_price_with_tax(),
911 price_without_tax: this.get_price_without_tax(),
913 product_description: this.get_product().description,
914 product_description_sale: this.get_product().description_sale,
917 // changes the base price of the product for this orderline
918 set_unit_price: function(price){
919 this.price = round_di(parseFloat(price) || 0, this.pos.dp['Product Price']);
920 this.trigger('change',this);
922 get_unit_price: function(){
925 get_unit_display_price: function(){
926 if (this.pos.config.iface_tax_included) {
927 var quantity = this.quantity;
929 var price = this.get_all_prices().priceWithTax;
930 this.quantity = quantity;
933 return this.get_unit_price();
936 get_base_price: function(){
937 var rounding = this.pos.currency.rounding;
938 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
940 get_display_price: function(){
941 return this.get_base_price();
942 if (this.pos.config.iface_tax_included) {
943 return this.get_all_prices().priceWithTax;
945 return this.get_base_price();
948 get_price_without_tax: function(){
949 return this.get_all_prices().priceWithoutTax;
951 get_price_with_tax: function(){
952 return this.get_all_prices().priceWithTax;
955 return this.get_all_prices().tax;
957 get_tax_details: function(){
958 return this.get_all_prices().taxDetails;
960 get_all_prices: function(){
962 var currency_rounding = this.pos.currency.rounding;
963 var base = this.get_base_price();
965 var totalNoTax = base;
967 var product = this.get_product();
968 var taxes_ids = product.taxes_id;
969 var taxes = self.pos.taxes;
972 _.each(taxes_ids, function(el) {
973 var tax = _.detect(taxes, function(t) {return t.id === el;});
974 if (tax.price_include) {
976 if (tax.type === "percent") {
977 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
978 } else if (tax.type === "fixed") {
979 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
981 throw "This type of tax is not supported by the point of sale: " + tax.type;
983 tmp = round_pr(tmp,currency_rounding);
986 taxdetail[tax.id] = tmp;
989 if (tax.type === "percent") {
990 tmp = tax.amount * base;
991 } else if (tax.type === "fixed") {
992 tmp = tax.amount * self.get_quantity();
994 throw "This type of tax is not supported by the point of sale: " + tax.type;
996 tmp = round_pr(tmp,currency_rounding);
999 taxdetail[tax.id] = tmp;
1003 "priceWithTax": totalTax,
1004 "priceWithoutTax": totalNoTax,
1006 "taxDetails": taxdetail,
1011 module.OrderlineCollection = Backbone.Collection.extend({
1012 model: module.Orderline,
1015 // Every Paymentline contains a cashregister and an amount of money.
1016 module.Paymentline = Backbone.Model.extend({
1017 initialize: function(attributes, options) {
1018 this.pos = options.pos;
1020 this.selected = false;
1022 this.init_from_JSON(options.json);
1025 this.cashregister = options.cashregister;
1026 this.name = this.cashregister.journal_id[1];
1028 init_from_JSON: function(json){
1029 this.amount = json.amount;
1030 this.cashregister = this.pos.cashregisters_by_id[json.statement_id];
1031 this.name = this.cashregister.journal_id[1];
1033 //sets the amount of money on this payment line
1034 set_amount: function(value){
1035 this.amount = round_di(parseFloat(value) || 0, this.pos.currency.decimals);
1036 this.trigger('change',this);
1038 // returns the amount of money on this paymentline
1039 get_amount: function(){
1042 get_amount_str: function(){
1043 return this.amount.toFixed(this.pos.currency.decimals);
1045 set_selected: function(selected){
1046 if(this.selected !== selected){
1047 this.selected = selected;
1048 this.trigger('change',this);
1051 // returns the associated cashregister
1052 //exports as JSON for server communication
1053 export_as_JSON: function(){
1055 name: instance.web.datetime_to_str(new Date()),
1056 statement_id: this.cashregister.id,
1057 account_id: this.cashregister.account_id[0],
1058 journal_id: this.cashregister.journal_id[0],
1059 amount: this.get_amount()
1062 //exports as JSON for receipt printing
1063 export_for_printing: function(){
1065 amount: this.get_amount(),
1066 journal: this.cashregister.journal_id[1],
1071 module.PaymentlineCollection = Backbone.Collection.extend({
1072 model: module.Paymentline,
1075 // An order more or less represents the content of a client's shopping cart (the OrderLines)
1076 // plus the associated payment information (the Paymentlines)
1077 // there is always an active ('selected') order in the Pos, a new one is created
1078 // automaticaly once an order is completed and sent to the server.
1079 module.Order = Backbone.Model.extend({
1080 initialize: function(attributes,options){
1081 Backbone.Model.prototype.initialize.apply(this, arguments);
1082 options = options || {};
1084 this.init_locked = true;
1085 this.pos = options.pos;
1086 this.selected_orderline = undefined;
1087 this.selected_paymentline = undefined;
1088 this.screen_data = {}; // see ScreenSelector
1089 this.temporary = options.temporary || false;
1090 this.creation_date = new Date();
1091 this.to_invoice = false;
1092 this.orderlines = new module.OrderlineCollection();
1093 this.paymentlines = new module.PaymentlineCollection();
1094 this.pos_session_id = this.pos.pos_session.id;
1096 this.set({ client: null });
1099 this.init_from_JSON(options.json);
1101 this.sequence_number = this.pos.pos_session.sequence_number++;
1102 this.uid = this.generate_unique_id();
1103 this.name = _t("Order ") + this.uid;
1106 this.on('change', function(){ this.save_to_db("order:change"); }, this);
1107 this.orderlines.on('change', function(){ this.save_to_db("orderline:change"); }, this);
1108 this.orderlines.on('add', function(){ this.save_to_db("orderline:add"); }, this);
1109 this.orderlines.on('remove', function(){ this.save_to_db("orderline:remove"); }, this);
1110 this.paymentlines.on('change', function(){ this.save_to_db("paymentline:change"); }, this);
1111 this.paymentlines.on('add', function(){ this.save_to_db("paymentline:add"); }, this);
1112 this.paymentlines.on('remove', function(){ this.save_to_db("paymentline:rem"); }, this);
1114 this.init_locked = false;
1119 save_to_db: function(){
1120 if (!this.init_locked) {
1121 this.pos.db.save_unpaid_order(this);
1124 init_from_JSON: function(json) {
1125 this.sequence_number = json.sequence_number;
1126 this.pos.pos_session.sequence_number = Math.max(this.sequence_number+1,this.pos.pos_session.sequence_number);
1127 this.session_id = json.pos_session_id;
1128 this.uid = json.uid;
1129 this.name = _t("Order ") + this.uid;
1130 if (json.partner_id) {
1131 var client = this.pos.db.get_partner_by_id(json.partner_id);
1133 console.error('ERROR: trying to load a parner not available in the pos');
1138 this.set_client(client);
1140 this.temporary = false; // FIXME
1141 this.to_invoice = false; // FIXME
1143 var orderlines = json.lines;
1144 for (var i = 0; i < orderlines.length; i++) {
1145 var orderline = orderlines[i][2];
1146 this.add_orderline(new module.Orderline({}, {pos: this.pos, order: this, json: orderline}));
1149 var paymentlines = json.statement_ids;
1150 for (var i = 0; i < paymentlines.length; i++) {
1151 var paymentline = paymentlines[i][2];
1152 var newpaymentline = new module.Paymentline({},{pos: this.pos, json: paymentline});
1153 this.paymentlines.add(newpaymentline);
1155 if (i === paymentlines.length - 1) {
1156 this.select_paymentline(newpaymentline);
1160 export_as_JSON: function() {
1161 var orderLines, paymentLines;
1163 this.orderlines.each(_.bind( function(item) {
1164 return orderLines.push([0, 0, item.export_as_JSON()]);
1167 this.paymentlines.each(_.bind( function(item) {
1168 return paymentLines.push([0, 0, item.export_as_JSON()]);
1171 name: this.get_name(),
1172 amount_paid: this.get_total_paid(),
1173 amount_total: this.get_total_with_tax(),
1174 amount_tax: this.get_total_tax(),
1175 amount_return: this.get_change(),
1177 statement_ids: paymentLines,
1178 pos_session_id: this.pos_session_id,
1179 partner_id: this.get_client() ? this.get_client().id : false,
1180 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1182 sequence_number: this.sequence_number,
1185 export_for_printing: function(){
1186 var orderlines = [];
1189 this.orderlines.each(function(orderline){
1190 orderlines.push(orderline.export_for_printing());
1193 var paymentlines = [];
1194 this.paymentlines.each(function(paymentline){
1195 paymentlines.push(paymentline.export_for_printing());
1197 var client = this.get('client');
1198 var cashier = this.pos.cashier || this.pos.user;
1199 var company = this.pos.company;
1200 var shop = this.pos.shop;
1201 var date = new Date();
1203 function is_xml(subreceipt){
1204 return subreceipt ? (subreceipt.split('\n')[0].indexOf('<!DOCTYPE QWEB') >= 0) : false;
1207 function render_xml(subreceipt){
1208 if (!is_xml(subreceipt)) {
1211 subreceipt = subreceipt.split('\n').slice(1).join('\n');
1212 var qweb = new QWeb2.Engine();
1213 qweb.debug = instance.session.debug;
1214 qweb.default_dict = _.clone(QWeb.default_dict);
1215 qweb.add_template('<templates><t t-name="subreceipt">'+subreceipt+'</t></templates>');
1217 return qweb.render('subreceipt',{'pos':self.pos,'widget':self.pos.pos_widget,'order':self, 'receipt': receipt}) ;
1222 orderlines: orderlines,
1223 paymentlines: paymentlines,
1224 subtotal: this.get_subtotal(),
1225 total_with_tax: this.get_total_with_tax(),
1226 total_without_tax: this.get_total_without_tax(),
1227 total_tax: this.get_total_tax(),
1228 total_paid: this.get_total_paid(),
1229 total_discount: this.get_total_discount(),
1230 tax_details: this.get_tax_details(),
1231 change: this.get_change(),
1232 name : this.get_name(),
1233 client: client ? client.name : null ,
1234 invoice_id: null, //TODO
1235 cashier: cashier ? cashier.name : null,
1236 header: this.pos.config.receipt_header || '',
1237 footer: this.pos.config.receipt_footer || '',
1244 year: date.getFullYear(),
1245 month: date.getMonth(),
1246 date: date.getDate(), // day of the month
1247 day: date.getDay(), // day of the week
1248 hour: date.getHours(),
1249 minute: date.getMinutes() ,
1250 isostring: date.toISOString(),
1251 localestring: date.toLocaleString(),
1254 email: company.email,
1255 website: company.website,
1256 company_registry: company.company_registry,
1257 contact_address: company.partner_id[1],
1260 phone: company.phone,
1261 logo: this.pos.company_logo_base64,
1266 currency: this.pos.currency,
1269 if (is_xml(this.pos.config.receipt_header)){
1270 receipt.header_xml = render_xml(this.pos.config.receipt_header);
1273 if (is_xml(this.pos.config.receipt_footer)){
1274 receipt.footer_xml = render_xml(this.pos.config.receipt_footer);
1279 is_empty: function(){
1280 return this.orderlines.models.length === 0;
1282 generate_unique_id: function() {
1283 // Generates a public identification number for the order.
1284 // The generated number must be unique and sequential. They are made 12 digit long
1285 // to fit into EAN-13 barcodes, should it be needed
1287 function zero_pad(num,size){
1289 while (s.length < size) {
1294 return zero_pad(this.pos.pos_session.id,5) +'-'+
1295 zero_pad(this.pos.pos_session.login_number,3) +'-'+
1296 zero_pad(this.sequence_number,4);
1298 get_name: function() {
1301 /* ---- Order Lines --- */
1302 add_orderline: function(line){
1304 line.order.remove_orderline(line);
1307 this.orderlines.add(line);
1308 this.select_orderline(this.get_last_orderline());
1310 get_orderline: function(id){
1311 var orderlines = this.orderlines.models;
1312 for(var i = 0; i < orderlines.length; i++){
1313 if(orderlines[i].id === id){
1314 return orderlines[i];
1319 get_orderlines: function(){
1320 return this.orderlines.models;
1322 get_last_orderline: function(){
1323 return this.orderlines.at(this.orderlines.length -1);
1325 remove_orderline: function( line ){
1326 this.orderlines.remove(line);
1327 this.select_orderline(this.get_last_orderline());
1329 add_product: function(product, options){
1330 options = options || {};
1331 var attr = JSON.parse(JSON.stringify(product));
1332 attr.pos = this.pos;
1334 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
1336 if(options.quantity !== undefined){
1337 line.set_quantity(options.quantity);
1339 if(options.price !== undefined){
1340 line.set_unit_price(options.price);
1342 if(options.discount !== undefined){
1343 line.set_discount(options.discount);
1346 if(options.extras !== undefined){
1347 for (var prop in options.extras) {
1348 line[prop] = options.extras[prop];
1352 var last_orderline = this.get_last_orderline();
1353 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
1354 last_orderline.merge(line);
1356 this.orderlines.add(line);
1358 this.select_orderline(this.get_last_orderline());
1360 get_selected_orderline: function(){
1361 return this.selected_orderline;
1363 select_orderline: function(line){
1365 if(line !== this.selected_orderline){
1366 if(this.selected_orderline){
1367 this.selected_orderline.set_selected(false);
1369 this.selected_orderline = line;
1370 this.selected_orderline.set_selected(true);
1373 this.selected_orderline = undefined;
1376 deselect_orderline: function(){
1377 if(this.selected_orderline){
1378 this.selected_orderline.set_selected(false);
1379 this.selected_orderline = undefined;
1382 /* ---- Payment Lines --- */
1383 add_paymentline: function(cashregister) {
1384 var newPaymentline = new module.Paymentline({},{cashregister:cashregister, pos: this.pos});
1385 if(cashregister.journal.type !== 'cash' || this.pos.config.iface_precompute_cash){
1386 newPaymentline.set_amount( Math.max(this.get_due(),0) );
1388 this.paymentlines.add(newPaymentline);
1389 this.select_paymentline(newPaymentline);
1392 get_paymentlines: function(){
1393 return this.paymentlines.models;
1395 remove_paymentline: function(line){
1396 if(this.selected_paymentline === line){
1397 this.select_paymentline(undefined);
1399 this.paymentlines.remove(line);
1401 clean_empty_paymentlines: function() {
1402 var lines = this.paymentlines.models;
1404 for ( var i = 0; i < lines.length; i++) {
1405 if (!lines[i].get_amount()) {
1406 empty.push(lines[i]);
1409 for ( var i = 0; i < empty.length; i++) {
1410 this.remove_paymentline(empty[i]);
1413 select_paymentline: function(line){
1414 if(line !== this.selected_paymentline){
1415 if(this.selected_paymentline){
1416 this.selected_paymentline.set_selected(false);
1418 this.selected_paymentline = line;
1419 if(this.selected_paymentline){
1420 this.selected_paymentline.set_selected(true);
1422 this.trigger('change:selected_paymentline',this.selected_paymentline);
1425 /* ---- Payment Status --- */
1426 get_subtotal : function(){
1427 return this.orderlines.reduce((function(sum, orderLine){
1428 return sum + orderLine.get_display_price();
1431 get_total_with_tax: function() {
1432 return this.orderlines.reduce((function(sum, orderLine) {
1433 return sum + orderLine.get_price_with_tax();
1436 get_total_without_tax: function() {
1437 return this.orderlines.reduce((function(sum, orderLine) {
1438 return sum + orderLine.get_price_without_tax();
1441 get_total_discount: function() {
1442 return this.orderlines.reduce((function(sum, orderLine) {
1443 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1446 get_total_tax: function() {
1447 return this.orderlines.reduce((function(sum, orderLine) {
1448 return sum + orderLine.get_tax();
1451 get_total_paid: function() {
1452 return this.paymentlines.reduce((function(sum, paymentLine) {
1453 return sum + paymentLine.get_amount();
1456 get_tax_details: function(){
1458 var fulldetails = [];
1459 var taxes_by_id = {};
1461 for(var i = 0; i < this.pos.taxes.length; i++){
1462 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1465 this.orderlines.each(function(line){
1466 var ldetails = line.get_tax_details();
1467 for(var id in ldetails){
1468 if(ldetails.hasOwnProperty(id)){
1469 details[id] = (details[id] || 0) + ldetails[id];
1474 for(var id in details){
1475 if(details.hasOwnProperty(id)){
1476 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1482 get_change: function(paymentline) {
1484 var change = this.get_total_paid() - this.get_total_with_tax();
1486 var change = -this.get_total_with_tax();
1487 var lines = this.paymentlines.models;
1488 for (var i = 0; i < lines.length; i++) {
1489 change += lines[i].get_amount();
1490 if (lines[i] === paymentline) {
1495 return round_pr(Math.max(0,change), this.pos.currency.rounding);
1497 get_due: function(paymentline) {
1499 var due = this.get_total_with_tax() - this.get_total_paid();
1501 var due = this.get_total_with_tax();
1502 var lines = this.paymentlines.models;
1503 for (var i = 0; i < lines.length; i++) {
1504 if (lines[i] === paymentline) {
1507 due -= lines[i].get_amount();
1511 return round_pr(Math.max(0,due), this.pos.currency.rounding);
1513 is_paid: function(){
1514 return this.get_due() === 0;
1516 is_paid_with_cash: function(){
1517 return !!this.paymentlines.find( function(pl){
1518 return pl.cashregister.journal.type === 'cash';
1521 finalize: function(){
1524 destroy: function(args){
1525 Backbone.Model.prototype.destroy.apply(this,arguments);
1526 this.pos.db.remove_unpaid_order(this);
1528 /* ---- Invoice --- */
1529 set_to_invoice: function(to_invoice) {
1530 this.to_invoice = to_invoice;
1532 is_to_invoice: function(){
1533 return this.to_invoice;
1535 /* ---- Client / Customer --- */
1536 // the client related to the current order.
1537 set_client: function(client){
1538 this.set('client',client);
1540 get_client: function(){
1541 return this.get('client');
1543 get_client_name: function(){
1544 var client = this.get('client');
1545 return client ? client.name : "";
1547 /* ---- Screen Status --- */
1548 // the order also stores the screen status, as the PoS supports
1549 // different active screens per order. This method is used to
1550 // store the screen status.
1551 set_screen_data: function(key,value){
1552 if(arguments.length === 2){
1553 this.screen_data[key] = value;
1554 }else if(arguments.length === 1){
1555 for(var key in arguments[0]){
1556 this.screen_data[key] = arguments[0][key];
1560 //see set_screen_data
1561 get_screen_data: function(key){
1562 return this.screen_data[key];
1566 module.OrderCollection = Backbone.Collection.extend({
1567 model: module.Order,
1571 The numpad handles both the choice of the property currently being modified
1572 (quantity, price or discount) and the edition of the corresponding numeric value.
1574 module.NumpadState = Backbone.Model.extend({
1579 appendNewChar: function(newChar) {
1581 oldBuffer = this.get('buffer');
1582 if (oldBuffer === '0') {
1586 } else if (oldBuffer === '-0') {
1588 buffer: "-" + newChar
1592 buffer: (this.get('buffer')) + newChar
1595 this.trigger('set_value',this.get('buffer'));
1597 deleteLastChar: function() {
1598 if(this.get('buffer') === ""){
1599 if(this.get('mode') === 'quantity'){
1600 this.trigger('set_value','remove');
1602 this.trigger('set_value',this.get('buffer'));
1605 var newBuffer = this.get('buffer').slice(0,-1) || "";
1606 this.set({ buffer: newBuffer });
1607 this.trigger('set_value',this.get('buffer'));
1610 switchSign: function() {
1612 oldBuffer = this.get('buffer');
1614 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1616 this.trigger('set_value',this.get('buffer'));
1618 changeMode: function(newMode) {
1630 resetValue: function(){
1631 this.set({buffer:'0'});