1 function openerp_pos_models(instance, module){ //module is instance.point_of_sale
2 var QWeb = instance.web.qweb;
3 var _t = instance.web._t;
5 var round_di = instance.web.round_decimals;
6 var round_pr = instance.web.round_precision
8 // The PosModel contains the Point Of Sale's representation of the backend.
9 // Since the PoS must work in standalone ( Without connection to the server )
10 // it must contains a representation of the server's PoS backend.
11 // (taxes, product list, configuration options, etc.) this representation
12 // is fetched and stored by the PosModel at the initialisation.
13 // this is done asynchronously, a ready deferred alows the GUI to wait interactively
14 // for the loading to be completed
15 // There is a single instance of the PosModel for each Front-End instance, it is usually called
16 // 'pos' and is available to all widgets extending PosWidget.
18 module.PosModel = Backbone.Model.extend({
19 initialize: function(session, attributes) {
20 Backbone.Model.prototype.initialize.call(this, attributes);
22 this.session = session;
23 this.flush_mutex = new $.Mutex(); // used to make sure the orders are sent to the server once at time
24 this.pos_widget = attributes.pos_widget;
26 this.proxy = new module.ProxyDevice(this); // used to communicate to the hardware devices via a local proxy
27 this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy, patterns: {}}); // used to read barcodes
28 this.proxy_queue = new module.JobQueue(); // used to prevent parallels communications to the proxy
29 this.db = new module.PosDB(); // a local database used to search trough products and categories & store pending orders
30 this.debug = jQuery.deparam(jQuery.param.querystring()).debug !== undefined; //debug mode
32 // Business data; loaded from the server at launch
33 this.accounting_precision = 2; //TODO
34 this.company_logo = null;
35 this.company_logo_base64 = '';
43 this.cashregisters = [];
44 this.bankstatements = [];
46 this.pos_session = null;
49 this.units_by_id = {};
50 this.pricelist = null;
51 this.order_sequence = 1;
52 window.posmodel = this;
54 // these dynamic attributes can be watched for change by other models or widgets
56 'synch': { state:'connected', pending:0 },
57 'orders': new module.OrderCollection(),
58 'selectedOrder': null,
61 this.bind('change:synch',function(pos,synch){
62 clearTimeout(self.synch_timeout);
63 self.synch_timeout = setTimeout(function(){
64 if(synch.state !== 'disconnected' && synch.pending > 0){
65 self.set('synch',{state:'disconnected', pending:synch.pending});
70 this.get('orders').bind('remove', function(order,_unused_,options){
71 self.on_removed_order(order,options.index,options.reason);
74 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
75 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
76 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
77 this.ready = this.load_server_data()
79 if(self.config.use_proxy){
80 return self.connect_to_proxy();
86 // releases ressources holds by the model at the end of life of the posmodel
88 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
91 this.barcode_reader.disconnect();
92 this.barcode_reader.disconnect_from_proxy();
94 connect_to_proxy: function(){
96 var done = new $.Deferred();
97 this.barcode_reader.disconnect_from_proxy();
98 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
99 this.pos_widget.loading_skip(function(){
100 self.proxy.stop_searching();
102 this.proxy.autoconnect({
103 force_ip: self.config.proxy_ip || undefined,
104 progress: function(prog){
105 self.pos_widget.loading_progress(prog);
108 if(self.config.iface_scan_via_proxy){
109 self.barcode_reader.connect_to_proxy();
111 }).always(function(){
117 // helper function to load data from the server. Obsolete use the models loader below.
118 fetch: function(model, fields, domain, ctx){
119 this._load_progress = (this._load_progress || 0) + 0.05;
120 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
121 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
124 // Server side model loaders. This is the list of the models that need to be loaded from
125 // the server. The models are loaded one by one by this list's order. The 'loaded' callback
126 // is used to store the data in the appropriate place once it has been loaded. This callback
127 // can return a deferred that will pause the loading of the next module.
128 // a shared temporary dictionary is available for loaders to communicate private variables
129 // used during loading such as object ids, etc.
133 fields: ['name','company_id'],
134 domain: function(self){ return [['id','=',self.session.uid]]; },
135 loaded: function(self,users){ self.user = users[0]; },
137 model: 'res.company',
138 fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' ],
139 domain: function(self){ return [['id','=',self.user.company_id[0]]]; },
140 loaded: function(self,companies){ self.company = companies[0]; },
142 model: 'product.uom',
145 loaded: function(self,units){
147 var units_by_id = {};
148 for(var i = 0, len = units.length; i < len; i++){
149 units_by_id[units[i].id] = units[i];
150 units[i].groupable = ( units[i].category_id[0] === 1 );
151 units[i].is_unit = ( units[i].id === 1 );
153 self.units_by_id = units_by_id;
157 fields: ['name','ean13'],
159 loaded: function(self,users){ self.users = users; },
161 model: 'res.partner',
162 fields: ['name','street','city','country_id','phone','zip','mobile','email','ean13','write_date'],
164 loaded: function(self,partners){
165 self.partners = partners;
166 self.db.add_partners(partners);
169 model: 'account.tax',
170 fields: ['name','amount', 'price_include', 'type'],
172 loaded: function(self,taxes){ self.taxes = taxes; },
174 model: 'pos.session',
175 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
176 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
177 loaded: function(self,pos_sessions){
178 self.pos_session = pos_sessions[0];
180 var orders = self.db.get_orders();
181 for (var i = 0; i < orders.length; i++) {
182 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
188 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
189 loaded: function(self,configs){
190 self.config = configs[0];
191 self.config.use_proxy = self.config.iface_payment_terminal ||
192 self.config.iface_electronic_scale ||
193 self.config.iface_print_via_proxy ||
194 self.config.iface_scan_via_proxy ||
195 self.config.iface_cashdrawer;
197 self.barcode_reader.add_barcode_patterns({
198 'product': self.config.barcode_product,
199 'cashier': self.config.barcode_cashier,
200 'client': self.config.barcode_customer,
201 'weight': self.config.barcode_weight,
202 'discount': self.config.barcode_discount,
203 'price': self.config.barcode_price,
207 model: 'stock.location',
209 domain: function(self){ return [['id','=', self.config.stock_location_id[0]]]; },
210 loaded: function(self, locations){ self.shop = locations[0]; },
212 model: 'product.pricelist',
213 fields: ['currency_id'],
214 domain: function(self){ return [['id','=',self.config.pricelist_id[0]]]; },
215 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
217 model: 'res.currency',
218 fields: ['symbol','position','rounding','accuracy'],
219 domain: function(self){ return [['id','=',self.pricelist.currency_id[0]]]; },
220 loaded: function(self, currencies){
221 self.currency = currencies[0];
224 model: 'product.packaging',
225 fields: ['ean','product_tmpl_id'],
227 loaded: function(self, packagings){
228 self.db.add_packagings(packagings);
231 model: 'pos.category',
232 fields: ['id','name','parent_id','child_id','image'],
234 loaded: function(self, categories){
235 self.db.add_categories(categories);
238 model: 'product.product',
239 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
240 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
242 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
243 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
244 loaded: function(self, products){
245 self.db.add_products(products);
248 model: 'account.bank.statement',
249 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
250 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
251 loaded: function(self, bankstatements, tmp){
252 self.bankstatements = bankstatements;
255 _.each(bankstatements,function(statement){
256 tmp.journals.push(statement.journal_id[0]);
260 model: 'account.journal',
262 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
263 loaded: function(self, journals){
264 self.journals = journals;
266 // associate the bank statements with their journals.
267 var bankstatements = self.bankstatements;
268 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
269 for(var j = 0, jlen = journals.length; j < jlen; j++){
270 if(bankstatements[i].journal_id[0] === journals[j].id){
271 bankstatements[i].journal = journals[j];
272 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
276 self.cashregisters = bankstatements;
280 loaded: function(self){
281 var fonts_loaded = new $.Deferred();
283 // Waiting for fonts to be loaded to prevent receipt printing
284 // from printing empty receipt while loading Inconsolata
285 // ( The font used for the receipt )
286 waitForWebfonts(['Lato','Inconsolata'], function(){
287 fonts_loaded.resolve();
290 // The JS used to detect font loading is not 100% robust, so
291 // do not wait more than 5sec
292 setTimeout(function(){
293 fonts_loaded.resolve();
300 loaded: function(self){
301 self.company_logo = new Image();
302 self.company_logo.crossOrigin = 'anonymous';
303 var logo_loaded = new $.Deferred();
304 self.company_logo.onload = function(){
305 var img = self.company_logo;
307 var targetwidth = 300;
309 if( img.width !== targetwidth ){
310 ratio = targetwidth / img.width;
312 if( img.height * ratio > maxheight ){
313 ratio = maxheight / img.height;
315 var width = Math.floor(img.width * ratio);
316 var height = Math.floor(img.height * ratio);
317 var c = document.createElement('canvas');
320 var ctx = c.getContext('2d');
321 ctx.drawImage(self.company_logo,0,0, width, height);
323 self.company_logo_base64 = c.toDataURL();
324 window.logo64 = self.company_logo_base64;
325 logo_loaded.resolve();
327 self.company_logo.onerror = function(){
328 logo_loaded.reject();
330 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
337 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
338 load_server_data: function(){
340 var loaded = new $.Deferred();
342 var progress_step = 1.0 / self.models.length;
343 var tmp = {}; // this is used to share a temporary state between models loaders
345 function load_model(index){
346 if(index >= self.models.length){
349 var model = self.models[index];
350 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
351 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
352 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
353 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
354 progress += progress_step;
357 new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
358 .then(function(result){
359 try{ // catching exceptions in model.loaded(...)
360 $.when(model.loaded(self,result,tmp))
361 .then(function(){ load_model(index + 1); },
362 function(err){ loaded.reject(err); });
369 }else if( model.loaded ){
370 try{ // catching exceptions in model.loaded(...)
371 $.when(model.loaded(self,tmp))
372 .then( function(){ load_model(index +1); },
373 function(err){ loaded.reject(err); });
378 load_model(index + 1);
392 // reload the list of partner, returns as a deferred that resolves if there were
393 // updated partners, and fails if not
394 load_new_partners: function(){
396 var def = new $.Deferred();
397 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
398 new instance.web.Model('res.partner')
400 .filter([['write_date','>',this.db.get_partner_write_date()]])
401 .all({'timeout':3000, 'shadow': true})
402 .then(function(partners){
403 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
408 }, function(){ def.reject(); });
412 // this is called when an order is removed from the order collection. It ensures that there is always an existing
413 // order and a valid selected order
414 on_removed_order: function(removed_order,index,reason){
415 if( (reason === 'abandon' || removed_order.temporary) && this.get('orders').size() > 0){
416 // when we intentionally remove an unfinished order, and there is another existing one
417 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
419 // when the order was automatically removed after completion,
420 // or when we intentionally delete the only concurrent order
421 this.add_new_order();
425 //creates a new empty order and sets it as the current order
426 add_new_order: function(){
427 var order = new module.Order({pos:this});
428 this.get('orders').add(order);
429 this.set('selectedOrder', order);
432 get_order: function(){
433 return this.get('selectedOrder');
436 //removes the current order
437 delete_current_order: function(){
438 this.get('selectedOrder').destroy({'reason':'abandon'});
441 // saves the order locally and try to send it to the backend.
442 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
443 push_order: function(order) {
447 this.proxy.log('push_order',order.export_as_JSON());
448 this.db.add_order(order.export_as_JSON());
451 var pushed = new $.Deferred();
453 this.flush_mutex.exec(function(){
454 var flushed = self._flush_orders(self.db.get_orders());
456 flushed.always(function(ids){
463 // saves the order locally and try to send it to the backend and make an invoice
464 // returns a deferred that succeeds when the order has been posted and successfully generated
465 // an invoice. This method can fail in various ways:
466 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
467 // this error is solved
468 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
469 // the network connection is up
471 push_and_invoice_order: function(order){
473 var invoiced = new $.Deferred();
475 if(!order.get_client()){
476 invoiced.reject('error-no-client');
480 var order_id = this.db.add_order(order.export_as_JSON());
482 this.flush_mutex.exec(function(){
483 var done = new $.Deferred(); // holds the mutex
485 // send the order to the server
486 // we have a 30 seconds timeout on this push.
487 // FIXME: if the server takes more than 30 seconds to accept the order,
488 // the client will believe it wasn't successfully sent, and very bad
489 // things will happen as a duplicate will be sent next time
490 // so we must make sure the server detects and ignores duplicated orders
492 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
494 transfer.fail(function(){
495 invoiced.reject('error-transfer');
499 // on success, get the order id generated by the server
500 transfer.pipe(function(order_server_id){
502 // generate the pdf and download it
503 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
504 active_ids:order_server_id,
518 // wrapper around the _save_to_server that updates the synch status widget
519 _flush_orders: function(orders, options) {
522 this.set('synch',{ state: 'connecting', pending: orders.length});
524 return self._save_to_server(orders, options).done(function (server_ids) {
525 var pending = self.db.get_orders().length;
528 state: pending ? 'connecting' : 'connected',
536 // send an array of orders to the server
537 // available options:
538 // - timeout: timeout for the rpc call in ms
539 // returns a deferred that resolves with the list of
540 // server generated ids for the sent orders
541 _save_to_server: function (orders, options) {
542 if (!orders || !orders.length) {
543 var result = $.Deferred();
548 options = options || {};
551 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
553 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
554 // then we want to notify the user that we are waiting on something )
555 var posOrderModel = new instance.web.Model('pos.order');
556 return posOrderModel.call('create_from_ui',
557 [_.map(orders, function (order) {
558 order.to_invoice = options.to_invoice || false;
563 shadow: !options.to_invoice,
566 ).then(function (server_ids) {
567 _.each(orders, function (order) {
568 self.db.remove_order(order.id);
571 }).fail(function (error, event){
572 if(error.code === 200 ){ // Business Logic Error, not a connection problem
573 self.pos_widget.screen_selector.show_popup('error-traceback',{
574 message: error.data.message,
575 comment: error.data.debug
578 // prevent an error popup creation by the rpc failure
579 // we want the failure to be silent as we send the orders in the background
580 event.preventDefault();
581 console.error('Failed to send orders:', orders);
585 scan_product: function(parsed_code){
587 var selectedOrder = this.get('selectedOrder');
588 if(parsed_code.encoding === 'ean13'){
589 var product = this.db.get_product_by_ean13(parsed_code.base_code);
590 }else if(parsed_code.encoding === 'reference'){
591 var product = this.db.get_product_by_reference(parsed_code.code);
598 if(parsed_code.type === 'price'){
599 selectedOrder.addProduct(product, {price:parsed_code.value});
600 }else if(parsed_code.type === 'weight'){
601 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
602 }else if(parsed_code.type === 'discount'){
603 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
605 selectedOrder.addProduct(product);
611 var orderline_id = 1;
613 // An orderline represent one element of the content of a client's shopping cart.
614 // An orderline contains a product, its quantity, its price, discount. etc.
615 // An Order contains zero or more Orderlines.
616 module.Orderline = Backbone.Model.extend({
617 initialize: function(attr,options){
618 this.pos = options.pos;
619 this.order = options.order;
620 this.product = options.product;
621 this.price = options.product.price;
623 this.quantityStr = '1';
625 this.discountStr = '0';
627 this.selected = false;
628 this.id = orderline_id++;
631 var orderline = new module.Orderline({},{
634 product: this.product,
637 orderline.quantity = this.quantity;
638 orderline.quantityStr = this.quantityStr;
639 orderline.discount = this.discount;
640 orderline.type = this.type;
641 orderline.selected = false;
644 // sets a discount [0,100]%
645 set_discount: function(discount){
646 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
647 this.discount = disc;
648 this.discountStr = '' + disc;
649 this.trigger('change',this);
651 // returns the discount [0,100]%
652 get_discount: function(){
653 return this.discount;
655 get_discount_str: function(){
656 return this.discountStr;
658 get_product_type: function(){
661 // sets the quantity of the product. The quantity will be rounded according to the
662 // product's unity of measure properties. Quantities greater than zero will not get
664 set_quantity: function(quantity){
665 if(quantity === 'remove'){
666 this.order.removeOrderline(this);
669 var quant = parseFloat(quantity) || 0;
670 var unit = this.get_unit();
672 this.quantity = round_pr(quant, unit.rounding);
673 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
675 this.quantity = quant;
676 this.quantityStr = '' + this.quantity;
679 this.trigger('change',this);
681 // return the quantity of product
682 get_quantity: function(){
683 return this.quantity;
685 get_quantity_str: function(){
686 return this.quantityStr;
688 get_quantity_str_with_unit: function(){
689 var unit = this.get_unit();
690 if(unit && !unit.is_unit){
691 return this.quantityStr + ' ' + unit.name;
693 return this.quantityStr;
696 // return the unit of measure of the product
697 get_unit: function(){
698 var unit_id = (this.product.uos_id || this.product.uom_id);
702 unit_id = unit_id[0];
706 return this.pos.units_by_id[unit_id];
708 // return the product of this orderline
709 get_product: function(){
712 // selects or deselects this orderline
713 set_selected: function(selected){
714 this.selected = selected;
715 this.trigger('change',this);
717 // returns true if this orderline is selected
718 is_selected: function(){
719 return this.selected;
721 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
722 // in the orderline. This returns true if it makes sense to merge the two
723 can_be_merged_with: function(orderline){
724 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
726 }else if(!this.get_unit() || !this.get_unit().groupable){
728 }else if(this.get_product_type() !== orderline.get_product_type()){
730 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
732 }else if(this.price !== orderline.price){
738 merge: function(orderline){
739 this.set_quantity(this.get_quantity() + orderline.get_quantity());
741 export_as_JSON: function() {
743 qty: this.get_quantity(),
744 price_unit: this.get_unit_price(),
745 discount: this.get_discount(),
746 product_id: this.get_product().id,
749 //used to create a json of the ticket, to be sent to the printer
750 export_for_printing: function(){
752 quantity: this.get_quantity(),
753 unit_name: this.get_unit().name,
754 price: this.get_unit_price(),
755 discount: this.get_discount(),
756 product_name: this.get_product().display_name,
757 price_display : this.get_display_price(),
758 price_with_tax : this.get_price_with_tax(),
759 price_without_tax: this.get_price_without_tax(),
761 product_description: this.get_product().description,
762 product_description_sale: this.get_product().description_sale,
765 // changes the base price of the product for this orderline
766 set_unit_price: function(price){
767 this.price = round_di(parseFloat(price) || 0, 2);
768 this.trigger('change',this);
770 get_unit_price: function(){
771 var rounding = this.pos.currency.rounding;
772 return round_pr(this.price,rounding);
774 get_display_price: function(){
775 var rounding = this.pos.currency.rounding;
776 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
778 get_price_without_tax: function(){
779 return this.get_all_prices().priceWithoutTax;
781 get_price_with_tax: function(){
782 return this.get_all_prices().priceWithTax;
785 return this.get_all_prices().tax;
787 get_tax_details: function(){
788 return this.get_all_prices().taxDetails;
790 get_all_prices: function(){
792 var currency_rounding = this.pos.currency.rounding;
793 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
795 var totalNoTax = base;
797 var product = this.get_product();
798 var taxes_ids = product.taxes_id;
799 var taxes = self.pos.taxes;
802 _.each(taxes_ids, function(el) {
803 var tax = _.detect(taxes, function(t) {return t.id === el;});
804 if (tax.price_include) {
806 if (tax.type === "percent") {
807 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
808 } else if (tax.type === "fixed") {
809 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
811 throw "This type of tax is not supported by the point of sale: " + tax.type;
813 tmp = round_pr(tmp,currency_rounding);
816 taxdetail[tax.id] = tmp;
819 if (tax.type === "percent") {
820 tmp = tax.amount * base;
821 } else if (tax.type === "fixed") {
822 tmp = tax.amount * self.get_quantity();
824 throw "This type of tax is not supported by the point of sale: " + tax.type;
826 tmp = round_pr(tmp,currency_rounding);
829 taxdetail[tax.id] = tmp;
833 "priceWithTax": totalTax,
834 "priceWithoutTax": totalNoTax,
836 "taxDetails": taxdetail,
841 module.OrderlineCollection = Backbone.Collection.extend({
842 model: module.Orderline,
845 // Every Paymentline contains a cashregister and an amount of money.
846 module.Paymentline = Backbone.Model.extend({
847 initialize: function(attributes, options) {
849 this.cashregister = options.cashregister;
850 this.name = this.cashregister.journal_id[1];
851 this.selected = false;
853 //sets the amount of money on this payment line
854 set_amount: function(value){
855 this.amount = round_di(parseFloat(value) || 0, 2);
856 this.trigger('change:amount',this);
858 // returns the amount of money on this paymentline
859 get_amount: function(){
862 set_selected: function(selected){
863 if(this.selected !== selected){
864 this.selected = selected;
865 this.trigger('change:selected',this);
868 // returns the associated cashregister
869 //exports as JSON for server communication
870 export_as_JSON: function(){
872 name: instance.web.datetime_to_str(new Date()),
873 statement_id: this.cashregister.id,
874 account_id: this.cashregister.account_id[0],
875 journal_id: this.cashregister.journal_id[0],
876 amount: this.get_amount()
879 //exports as JSON for receipt printing
880 export_for_printing: function(){
882 amount: this.get_amount(),
883 journal: this.cashregister.journal_id[1],
888 module.PaymentlineCollection = Backbone.Collection.extend({
889 model: module.Paymentline,
893 // An order more or less represents the content of a client's shopping cart (the OrderLines)
894 // plus the associated payment information (the Paymentlines)
895 // there is always an active ('selected') order in the Pos, a new one is created
896 // automaticaly once an order is completed and sent to the server.
897 module.Order = Backbone.Model.extend({
898 initialize: function(attributes){
899 Backbone.Model.prototype.initialize.apply(this, arguments);
900 this.pos = attributes.pos;
901 this.sequence_number = this.pos.pos_session.sequence_number++;
902 this.uid = this.generateUniqueId();
904 creationDate: new Date(),
905 orderLines: new module.OrderlineCollection(),
906 paymentLines: new module.PaymentlineCollection(),
907 name: _t("Order ") + this.uid,
910 this.selected_orderline = undefined;
911 this.selected_paymentline = undefined;
912 this.screen_data = {}; // see ScreenSelector
913 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
914 this.temporary = attributes.temporary || false;
917 is_empty: function(){
918 return (this.get('orderLines').models.length === 0);
920 // Generates a public identification number for the order.
921 // The generated number must be unique and sequential. They are made 12 digit long
922 // to fit into EAN-13 barcodes, should it be needed
923 generateUniqueId: function() {
924 function zero_pad(num,size){
926 while (s.length < size) {
931 return zero_pad(this.pos.pos_session.id,5) +'-'+
932 zero_pad(this.pos.pos_session.login_number,3) +'-'+
933 zero_pad(this.sequence_number,4);
935 addOrderline: function(line){
937 order.removeOrderline(line);
940 this.get('orderLines').add(line);
941 this.selectLine(this.getLastOrderline());
943 addProduct: function(product, options){
944 options = options || {};
945 var attr = JSON.parse(JSON.stringify(product));
948 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
950 if(options.quantity !== undefined){
951 line.set_quantity(options.quantity);
953 if(options.price !== undefined){
954 line.set_unit_price(options.price);
956 if(options.discount !== undefined){
957 line.set_discount(options.discount);
960 var last_orderline = this.getLastOrderline();
961 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
962 last_orderline.merge(line);
964 this.get('orderLines').add(line);
966 this.selectLine(this.getLastOrderline());
968 removeOrderline: function( line ){
969 this.get('orderLines').remove(line);
970 this.selectLine(this.getLastOrderline());
972 getOrderline: function(id){
973 var orderlines = this.get('orderLines').models;
974 for(var i = 0; i < orderlines.length; i++){
975 if(orderlines[i].id === id){
976 return orderlines[i];
981 getLastOrderline: function(){
982 return this.get('orderLines').at(this.get('orderLines').length -1);
984 addPaymentline: function(cashregister) {
985 var paymentLines = this.get('paymentLines');
986 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
987 if(cashregister.journal.type !== 'cash'){
988 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
990 paymentLines.add(newPaymentline);
991 this.selectPaymentline(newPaymentline);
994 removePaymentline: function(line){
995 if(this.selected_paymentline === line){
996 this.selectPaymentline(undefined);
998 this.get('paymentLines').remove(line);
1000 getName: function() {
1001 return this.get('name');
1003 getSubtotal : function(){
1004 return (this.get('orderLines')).reduce((function(sum, orderLine){
1005 return sum + orderLine.get_display_price();
1008 getTotalTaxIncluded: function() {
1009 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1010 return sum + orderLine.get_price_with_tax();
1013 getDiscountTotal: function() {
1014 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1015 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1018 getTotalTaxExcluded: function() {
1019 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1020 return sum + orderLine.get_price_without_tax();
1023 getTax: function() {
1024 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1025 return sum + orderLine.get_tax();
1028 getTaxDetails: function(){
1030 var fulldetails = [];
1031 var taxes_by_id = {};
1033 for(var i = 0; i < this.pos.taxes.length; i++){
1034 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1037 this.get('orderLines').each(function(line){
1038 var ldetails = line.get_tax_details();
1039 for(var id in ldetails){
1040 if(ldetails.hasOwnProperty(id)){
1041 details[id] = (details[id] || 0) + ldetails[id];
1046 for(var id in details){
1047 if(details.hasOwnProperty(id)){
1048 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
1054 getPaidTotal: function() {
1055 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
1056 return sum + paymentLine.get_amount();
1059 getChange: function() {
1060 return this.getPaidTotal() - this.getTotalTaxIncluded();
1062 getDueLeft: function() {
1063 return this.getTotalTaxIncluded() - this.getPaidTotal();
1065 // sets the type of receipt 'receipt'(default) or 'invoice'
1066 set_receipt_type: function(type){
1067 this.receipt_type = type;
1069 get_receipt_type: function(){
1070 return this.receipt_type;
1072 // the client related to the current order.
1073 set_client: function(client){
1074 this.set('client',client);
1076 get_client: function(){
1077 return this.get('client');
1079 get_client_name: function(){
1080 var client = this.get('client');
1081 return client ? client.name : "";
1083 // the order also stores the screen status, as the PoS supports
1084 // different active screens per order. This method is used to
1085 // store the screen status.
1086 set_screen_data: function(key,value){
1087 if(arguments.length === 2){
1088 this.screen_data[key] = value;
1089 }else if(arguments.length === 1){
1090 for(key in arguments[0]){
1091 this.screen_data[key] = arguments[0][key];
1095 //see set_screen_data
1096 get_screen_data: function(key){
1097 return this.screen_data[key];
1099 // exports a JSON for receipt printing
1100 export_for_printing: function(){
1101 var orderlines = [];
1102 this.get('orderLines').each(function(orderline){
1103 orderlines.push(orderline.export_for_printing());
1106 var paymentlines = [];
1107 this.get('paymentLines').each(function(paymentline){
1108 paymentlines.push(paymentline.export_for_printing());
1110 var client = this.get('client');
1111 var cashier = this.pos.cashier || this.pos.user;
1112 var company = this.pos.company;
1113 var shop = this.pos.shop;
1114 var date = new Date();
1117 orderlines: orderlines,
1118 paymentlines: paymentlines,
1119 subtotal: this.getSubtotal(),
1120 total_with_tax: this.getTotalTaxIncluded(),
1121 total_without_tax: this.getTotalTaxExcluded(),
1122 total_tax: this.getTax(),
1123 total_paid: this.getPaidTotal(),
1124 total_discount: this.getDiscountTotal(),
1125 tax_details: this.getTaxDetails(),
1126 change: this.getChange(),
1127 name : this.getName(),
1128 client: client ? client.name : null ,
1129 invoice_id: null, //TODO
1130 cashier: cashier ? cashier.name : null,
1131 header: this.pos.config.receipt_header || '',
1132 footer: this.pos.config.receipt_footer || '',
1139 year: date.getFullYear(),
1140 month: date.getMonth(),
1141 date: date.getDate(), // day of the month
1142 day: date.getDay(), // day of the week
1143 hour: date.getHours(),
1144 minute: date.getMinutes() ,
1145 isostring: date.toISOString(),
1146 localestring: date.toLocaleString(),
1149 email: company.email,
1150 website: company.website,
1151 company_registry: company.company_registry,
1152 contact_address: company.partner_id[1],
1155 phone: company.phone,
1156 logo: this.pos.company_logo_base64,
1161 currency: this.pos.currency,
1164 export_as_JSON: function() {
1165 var orderLines, paymentLines;
1167 (this.get('orderLines')).each(_.bind( function(item) {
1168 return orderLines.push([0, 0, item.export_as_JSON()]);
1171 (this.get('paymentLines')).each(_.bind( function(item) {
1172 return paymentLines.push([0, 0, item.export_as_JSON()]);
1175 name: this.getName(),
1176 amount_paid: this.getPaidTotal(),
1177 amount_total: this.getTotalTaxIncluded(),
1178 amount_tax: this.getTax(),
1179 amount_return: this.getChange(),
1181 statement_ids: paymentLines,
1182 pos_session_id: this.pos.pos_session.id,
1183 partner_id: this.get_client() ? this.get_client().id : false,
1184 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1186 sequence_number: this.sequence_number,
1189 getSelectedLine: function(){
1190 return this.selected_orderline;
1192 selectLine: function(line){
1194 if(line !== this.selected_orderline){
1195 if(this.selected_orderline){
1196 this.selected_orderline.set_selected(false);
1198 this.selected_orderline = line;
1199 this.selected_orderline.set_selected(true);
1202 this.selected_orderline = undefined;
1205 deselectLine: function(){
1206 if(this.selected_orderline){
1207 this.selected_orderline.set_selected(false);
1208 this.selected_orderline = undefined;
1211 selectPaymentline: function(line){
1212 if(line !== this.selected_paymentline){
1213 if(this.selected_paymentline){
1214 this.selected_paymentline.set_selected(false);
1216 this.selected_paymentline = line;
1217 if(this.selected_paymentline){
1218 this.selected_paymentline.set_selected(true);
1220 this.trigger('change:selected_paymentline',this.selected_paymentline);
1225 module.OrderCollection = Backbone.Collection.extend({
1226 model: module.Order,
1230 The numpad handles both the choice of the property currently being modified
1231 (quantity, price or discount) and the edition of the corresponding numeric value.
1233 module.NumpadState = Backbone.Model.extend({
1238 appendNewChar: function(newChar) {
1240 oldBuffer = this.get('buffer');
1241 if (oldBuffer === '0') {
1245 } else if (oldBuffer === '-0') {
1247 buffer: "-" + newChar
1251 buffer: (this.get('buffer')) + newChar
1254 this.trigger('set_value',this.get('buffer'));
1256 deleteLastChar: function() {
1257 if(this.get('buffer') === ""){
1258 if(this.get('mode') === 'quantity'){
1259 this.trigger('set_value','remove');
1261 this.trigger('set_value',this.get('buffer'));
1264 var newBuffer = this.get('buffer').slice(0,-1) || "";
1265 this.set({ buffer: newBuffer });
1266 this.trigger('set_value',this.get('buffer'));
1269 switchSign: function() {
1271 oldBuffer = this.get('buffer');
1273 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1275 this.trigger('set_value',this.get('buffer'));
1277 changeMode: function(newMode) {
1289 resetValue: function(){
1290 this.set({buffer:'0'});