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 ids: function(self){ return [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' , 'country_id'],
139 ids: function(self){ return [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','state_id','country_id','vat','phone','zip','mobile','email','ean13','write_date'],
164 loaded: function(self,partners){
165 self.partners = partners;
166 self.db.add_partners(partners);
169 model: 'res.country',
171 loaded: function(self,countries){
172 self.countries = countries;
173 self.company.country = null;
174 for (var i = 0; i < countries.length; i++) {
175 if (countries[i].id === self.company.country_id[0]){
176 self.company.country = countries[i];
181 model: 'account.tax',
182 fields: ['name','amount', 'price_include', 'type'],
184 loaded: function(self,taxes){ self.taxes = taxes; },
186 model: 'pos.session',
187 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
188 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
189 loaded: function(self,pos_sessions){
190 self.pos_session = pos_sessions[0];
192 var orders = self.db.get_orders();
193 for (var i = 0; i < orders.length; i++) {
194 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
200 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
201 loaded: function(self,configs){
202 self.config = configs[0];
203 self.config.use_proxy = self.config.iface_payment_terminal ||
204 self.config.iface_electronic_scale ||
205 self.config.iface_print_via_proxy ||
206 self.config.iface_scan_via_proxy ||
207 self.config.iface_cashdrawer;
209 self.barcode_reader.add_barcode_patterns({
210 'product': self.config.barcode_product,
211 'cashier': self.config.barcode_cashier,
212 'client': self.config.barcode_customer,
213 'weight': self.config.barcode_weight,
214 'discount': self.config.barcode_discount,
215 'price': self.config.barcode_price,
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."));
223 model: 'stock.location',
225 ids: function(self){ return [self.config.stock_location_id[0]]; },
226 loaded: function(self, locations){ self.shop = locations[0]; },
228 model: 'product.pricelist',
229 fields: ['currency_id'],
230 ids: function(self){ return [self.config.pricelist_id[0]]; },
231 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
233 model: 'res.currency',
234 fields: ['symbol','position','rounding','accuracy'],
235 ids: function(self){ return [self.pricelist.currency_id[0]]; },
236 loaded: function(self, currencies){
237 self.currency = currencies[0];
240 model: 'product.packaging',
241 fields: ['ean','product_tmpl_id'],
243 loaded: function(self, packagings){
244 self.db.add_packagings(packagings);
247 model: 'pos.category',
248 fields: ['id','name','parent_id','child_id','image'],
250 loaded: function(self, categories){
251 self.db.add_categories(categories);
254 model: 'product.product',
255 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
256 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
258 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
259 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
260 loaded: function(self, products){
261 self.db.add_products(products);
264 model: 'account.bank.statement',
265 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
266 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
267 loaded: function(self, bankstatements, tmp){
268 self.bankstatements = bankstatements;
271 _.each(bankstatements,function(statement){
272 tmp.journals.push(statement.journal_id[0]);
276 model: 'account.journal',
278 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
279 loaded: function(self, journals){
280 self.journals = journals;
282 // associate the bank statements with their journals.
283 var bankstatements = self.bankstatements;
284 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
285 for(var j = 0, jlen = journals.length; j < jlen; j++){
286 if(bankstatements[i].journal_id[0] === journals[j].id){
287 bankstatements[i].journal = journals[j];
291 self.cashregisters = bankstatements;
295 loaded: function(self){
296 var fonts_loaded = new $.Deferred();
298 // Waiting for fonts to be loaded to prevent receipt printing
299 // from printing empty receipt while loading Inconsolata
300 // ( The font used for the receipt )
301 waitForWebfonts(['Lato','Inconsolata'], function(){
302 fonts_loaded.resolve();
305 // The JS used to detect font loading is not 100% robust, so
306 // do not wait more than 5sec
307 setTimeout(function(){
308 fonts_loaded.resolve();
315 loaded: function(self){
316 self.company_logo = new Image();
317 var logo_loaded = new $.Deferred();
318 self.company_logo.onload = function(){
319 var img = self.company_logo;
321 var targetwidth = 300;
323 if( img.width !== targetwidth ){
324 ratio = targetwidth / img.width;
326 if( img.height * ratio > maxheight ){
327 ratio = maxheight / img.height;
329 var width = Math.floor(img.width * ratio);
330 var height = Math.floor(img.height * ratio);
331 var c = document.createElement('canvas');
334 var ctx = c.getContext('2d');
335 ctx.drawImage(self.company_logo,0,0, width, height);
337 self.company_logo_base64 = c.toDataURL();
338 logo_loaded.resolve();
340 self.company_logo.onerror = function(){
341 logo_loaded.reject();
343 self.company_logo.crossOrigin = "anonymous";
344 self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
351 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
352 load_server_data: function(){
354 var loaded = new $.Deferred();
356 var progress_step = 1.0 / self.models.length;
357 var tmp = {}; // this is used to share a temporary state between models loaders
359 function load_model(index){
360 if(index >= self.models.length){
363 var model = self.models[index];
364 self.pos_widget.loading_message(_t('Loading')+' '+(model.label || model.model || ''), progress);
365 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
366 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
367 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
368 var ids = typeof model.ids === 'function' ? model.ids(self,tmp) : model.ids;
369 progress += progress_step;
374 var records = new instance.web.Model(model.model).call('read',[ids,fields],context);
376 var records = new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
378 records.then(function(result){
379 try{ // catching exceptions in model.loaded(...)
380 $.when(model.loaded(self,result,tmp))
381 .then(function(){ load_model(index + 1); },
382 function(err){ loaded.reject(err); });
389 }else if( model.loaded ){
390 try{ // catching exceptions in model.loaded(...)
391 $.when(model.loaded(self,tmp))
392 .then( function(){ load_model(index +1); },
393 function(err){ loaded.reject(err); });
398 load_model(index + 1);
412 // reload the list of partner, returns as a deferred that resolves if there were
413 // updated partners, and fails if not
414 load_new_partners: function(){
416 var def = new $.Deferred();
417 var fields = _.find(this.models,function(model){ return model.model === 'res.partner'; }).fields;
418 new instance.web.Model('res.partner')
420 .filter([['write_date','>',this.db.get_partner_write_date()]])
421 .all({'timeout':3000, 'shadow': true})
422 .then(function(partners){
423 if (self.db.add_partners(partners)) { // check if the partners we got were real updates
428 }, function(){ def.reject(); });
432 // this is called when an order is removed from the order collection. It ensures that there is always an existing
433 // order and a valid selected order
434 on_removed_order: function(removed_order,index,reason){
435 if( (reason === 'abandon' || removed_order.temporary) && this.get('orders').size() > 0){
436 // when we intentionally remove an unfinished order, and there is another existing one
437 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
439 // when the order was automatically removed after completion,
440 // or when we intentionally delete the only concurrent order
441 this.add_new_order();
445 //creates a new empty order and sets it as the current order
446 add_new_order: function(){
447 var order = new module.Order({pos:this});
448 this.get('orders').add(order);
449 this.set('selectedOrder', order);
452 get_order: function(){
453 return this.get('selectedOrder');
456 //removes the current order
457 delete_current_order: function(){
458 this.get('selectedOrder').destroy({'reason':'abandon'});
461 // saves the order locally and try to send it to the backend.
462 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
463 push_order: function(order) {
467 this.proxy.log('push_order',order.export_as_JSON());
468 this.db.add_order(order.export_as_JSON());
471 var pushed = new $.Deferred();
473 this.flush_mutex.exec(function(){
474 var flushed = self._flush_orders(self.db.get_orders());
476 flushed.always(function(ids){
483 // saves the order locally and try to send it to the backend and make an invoice
484 // returns a deferred that succeeds when the order has been posted and successfully generated
485 // an invoice. This method can fail in various ways:
486 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
487 // this error is solved
488 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
489 // the network connection is up
491 push_and_invoice_order: function(order){
493 var invoiced = new $.Deferred();
495 if(!order.get_client()){
496 invoiced.reject('error-no-client');
500 var order_id = this.db.add_order(order.export_as_JSON());
502 this.flush_mutex.exec(function(){
503 var done = new $.Deferred(); // holds the mutex
505 // send the order to the server
506 // we have a 30 seconds timeout on this push.
507 // FIXME: if the server takes more than 30 seconds to accept the order,
508 // the client will believe it wasn't successfully sent, and very bad
509 // things will happen as a duplicate will be sent next time
510 // so we must make sure the server detects and ignores duplicated orders
512 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
514 transfer.fail(function(){
515 invoiced.reject('error-transfer');
519 // on success, get the order id generated by the server
520 transfer.pipe(function(order_server_id){
522 // generate the pdf and download it
523 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
524 active_ids:order_server_id,
538 // wrapper around the _save_to_server that updates the synch status widget
539 _flush_orders: function(orders, options) {
542 this.set('synch',{ state: 'connecting', pending: orders.length});
544 return self._save_to_server(orders, options).done(function (server_ids) {
545 var pending = self.db.get_orders().length;
548 state: pending ? 'connecting' : 'connected',
556 // send an array of orders to the server
557 // available options:
558 // - timeout: timeout for the rpc call in ms
559 // returns a deferred that resolves with the list of
560 // server generated ids for the sent orders
561 _save_to_server: function (orders, options) {
562 if (!orders || !orders.length) {
563 var result = $.Deferred();
568 options = options || {};
571 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
573 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
574 // then we want to notify the user that we are waiting on something )
575 var posOrderModel = new instance.web.Model('pos.order');
576 return posOrderModel.call('create_from_ui',
577 [_.map(orders, function (order) {
578 order.to_invoice = options.to_invoice || false;
583 shadow: !options.to_invoice,
586 ).then(function (server_ids) {
587 _.each(orders, function (order) {
588 self.db.remove_order(order.id);
591 }).fail(function (error, event){
592 if(error.code === 200 ){ // Business Logic Error, not a connection problem
593 self.pos_widget.screen_selector.show_popup('error-traceback',{
594 message: error.data.message,
595 comment: error.data.debug
598 // prevent an error popup creation by the rpc failure
599 // we want the failure to be silent as we send the orders in the background
600 event.preventDefault();
601 console.error('Failed to send orders:', orders);
605 scan_product: function(parsed_code){
607 var selectedOrder = this.get('selectedOrder');
608 if(parsed_code.encoding === 'ean13'){
609 var product = this.db.get_product_by_ean13(parsed_code.base_code);
610 }else if(parsed_code.encoding === 'reference'){
611 var product = this.db.get_product_by_reference(parsed_code.code);
618 if(parsed_code.type === 'price'){
619 selectedOrder.addProduct(product, {price:parsed_code.value});
620 }else if(parsed_code.type === 'weight'){
621 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
622 }else if(parsed_code.type === 'discount'){
623 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
625 selectedOrder.addProduct(product);
631 var orderline_id = 1;
633 // An orderline represent one element of the content of a client's shopping cart.
634 // An orderline contains a product, its quantity, its price, discount. etc.
635 // An Order contains zero or more Orderlines.
636 module.Orderline = Backbone.Model.extend({
637 initialize: function(attr,options){
638 this.pos = options.pos;
639 this.order = options.order;
640 this.product = options.product;
641 this.price = options.product.price;
643 this.quantityStr = '1';
645 this.discountStr = '0';
647 this.selected = false;
648 this.id = orderline_id++;
651 var orderline = new module.Orderline({},{
654 product: this.product,
657 orderline.quantity = this.quantity;
658 orderline.quantityStr = this.quantityStr;
659 orderline.discount = this.discount;
660 orderline.type = this.type;
661 orderline.selected = false;
664 // sets a discount [0,100]%
665 set_discount: function(discount){
666 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
667 this.discount = disc;
668 this.discountStr = '' + disc;
669 this.trigger('change',this);
671 // returns the discount [0,100]%
672 get_discount: function(){
673 return this.discount;
675 get_discount_str: function(){
676 return this.discountStr;
678 get_product_type: function(){
681 // sets the quantity of the product. The quantity will be rounded according to the
682 // product's unity of measure properties. Quantities greater than zero will not get
684 set_quantity: function(quantity){
685 if(quantity === 'remove'){
686 this.order.removeOrderline(this);
689 var quant = parseFloat(quantity) || 0;
690 var unit = this.get_unit();
693 this.quantity = round_pr(quant, unit.rounding);
694 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
696 this.quantity = round_pr(quant, 1);
697 this.quantityStr = this.quantity.toFixed(0);
700 this.quantity = quant;
701 this.quantityStr = '' + this.quantity;
704 this.trigger('change',this);
706 // return the quantity of product
707 get_quantity: function(){
708 return this.quantity;
710 get_quantity_str: function(){
711 return this.quantityStr;
713 get_quantity_str_with_unit: function(){
714 var unit = this.get_unit();
715 if(unit && !unit.is_unit){
716 return this.quantityStr + ' ' + unit.name;
718 return this.quantityStr;
721 // return the unit of measure of the product
722 get_unit: function(){
723 var unit_id = (this.product.uos_id || this.product.uom_id);
727 unit_id = unit_id[0];
731 return this.pos.units_by_id[unit_id];
733 // return the product of this orderline
734 get_product: function(){
737 // selects or deselects this orderline
738 set_selected: function(selected){
739 this.selected = selected;
740 this.trigger('change',this);
742 // returns true if this orderline is selected
743 is_selected: function(){
744 return this.selected;
746 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
747 // in the orderline. This returns true if it makes sense to merge the two
748 can_be_merged_with: function(orderline){
749 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
751 }else if(!this.get_unit() || !this.get_unit().groupable){
753 }else if(this.get_product_type() !== orderline.get_product_type()){
755 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
757 }else if(this.price !== orderline.price){
763 merge: function(orderline){
764 this.set_quantity(this.get_quantity() + orderline.get_quantity());
766 export_as_JSON: function() {
768 qty: this.get_quantity(),
769 price_unit: this.get_unit_price(),
770 discount: this.get_discount(),
771 product_id: this.get_product().id,
774 //used to create a json of the ticket, to be sent to the printer
775 export_for_printing: function(){
777 quantity: this.get_quantity(),
778 unit_name: this.get_unit().name,
779 price: this.get_unit_price(),
780 discount: this.get_discount(),
781 product_name: this.get_product().display_name,
782 price_display : this.get_display_price(),
783 price_with_tax : this.get_price_with_tax(),
784 price_without_tax: this.get_price_without_tax(),
786 product_description: this.get_product().description,
787 product_description_sale: this.get_product().description_sale,
790 // changes the base price of the product for this orderline
791 set_unit_price: function(price){
792 this.price = round_di(parseFloat(price) || 0, 2);
793 this.trigger('change',this);
795 get_unit_price: function(){
796 var rounding = this.pos.currency.rounding;
797 return round_pr(this.price,rounding);
799 get_display_price: function(){
800 var rounding = this.pos.currency.rounding;
801 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
803 get_price_without_tax: function(){
804 return this.get_all_prices().priceWithoutTax;
806 get_price_with_tax: function(){
807 return this.get_all_prices().priceWithTax;
810 return this.get_all_prices().tax;
812 get_tax_details: function(){
813 return this.get_all_prices().taxDetails;
815 get_all_prices: function(){
817 var currency_rounding = this.pos.currency.rounding;
818 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
820 var totalNoTax = base;
822 var product = this.get_product();
823 var taxes_ids = product.taxes_id;
824 var taxes = self.pos.taxes;
827 _.each(taxes_ids, function(el) {
828 var tax = _.detect(taxes, function(t) {return t.id === el;});
829 if (tax.price_include) {
831 if (tax.type === "percent") {
832 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
833 } else if (tax.type === "fixed") {
834 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
836 throw "This type of tax is not supported by the point of sale: " + tax.type;
838 tmp = round_pr(tmp,currency_rounding);
841 taxdetail[tax.id] = tmp;
844 if (tax.type === "percent") {
845 tmp = tax.amount * base;
846 } else if (tax.type === "fixed") {
847 tmp = tax.amount * self.get_quantity();
849 throw "This type of tax is not supported by the point of sale: " + tax.type;
851 tmp = round_pr(tmp,currency_rounding);
854 taxdetail[tax.id] = tmp;
858 "priceWithTax": totalTax,
859 "priceWithoutTax": totalNoTax,
861 "taxDetails": taxdetail,
866 module.OrderlineCollection = Backbone.Collection.extend({
867 model: module.Orderline,
870 // Every Paymentline contains a cashregister and an amount of money.
871 module.Paymentline = Backbone.Model.extend({
872 initialize: function(attributes, options) {
874 this.cashregister = options.cashregister;
875 this.name = this.cashregister.journal_id[1];
876 this.selected = false;
878 //sets the amount of money on this payment line
879 set_amount: function(value){
880 this.amount = round_di(parseFloat(value) || 0, 2);
881 this.trigger('change:amount',this);
883 // returns the amount of money on this paymentline
884 get_amount: function(){
887 set_selected: function(selected){
888 if(this.selected !== selected){
889 this.selected = selected;
890 this.trigger('change:selected',this);
893 // returns the associated cashregister
894 //exports as JSON for server communication
895 export_as_JSON: function(){
897 name: instance.web.datetime_to_str(new Date()),
898 statement_id: this.cashregister.id,
899 account_id: this.cashregister.account_id[0],
900 journal_id: this.cashregister.journal_id[0],
901 amount: this.get_amount()
904 //exports as JSON for receipt printing
905 export_for_printing: function(){
907 amount: this.get_amount(),
908 journal: this.cashregister.journal_id[1],
913 module.PaymentlineCollection = Backbone.Collection.extend({
914 model: module.Paymentline,
918 // An order more or less represents the content of a client's shopping cart (the OrderLines)
919 // plus the associated payment information (the Paymentlines)
920 // there is always an active ('selected') order in the Pos, a new one is created
921 // automaticaly once an order is completed and sent to the server.
922 module.Order = Backbone.Model.extend({
923 initialize: function(attributes){
924 Backbone.Model.prototype.initialize.apply(this, arguments);
925 this.pos = attributes.pos;
926 this.sequence_number = this.pos.pos_session.sequence_number++;
927 this.uid = this.generateUniqueId();
929 creationDate: new Date(),
930 orderLines: new module.OrderlineCollection(),
931 paymentLines: new module.PaymentlineCollection(),
932 name: _t("Order ") + this.uid,
935 this.selected_orderline = undefined;
936 this.selected_paymentline = undefined;
937 this.screen_data = {}; // see ScreenSelector
938 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
939 this.temporary = attributes.temporary || false;
942 is_empty: function(){
943 return (this.get('orderLines').models.length === 0);
945 // Generates a public identification number for the order.
946 // The generated number must be unique and sequential. They are made 12 digit long
947 // to fit into EAN-13 barcodes, should it be needed
948 generateUniqueId: function() {
949 function zero_pad(num,size){
951 while (s.length < size) {
956 return zero_pad(this.pos.pos_session.id,5) +'-'+
957 zero_pad(this.pos.pos_session.login_number,3) +'-'+
958 zero_pad(this.sequence_number,4);
960 addOrderline: function(line){
962 order.removeOrderline(line);
965 this.get('orderLines').add(line);
966 this.selectLine(this.getLastOrderline());
968 addProduct: function(product, options){
969 options = options || {};
970 var attr = JSON.parse(JSON.stringify(product));
973 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
975 if(options.quantity !== undefined){
976 line.set_quantity(options.quantity);
978 if(options.price !== undefined){
979 line.set_unit_price(options.price);
981 if(options.discount !== undefined){
982 line.set_discount(options.discount);
985 var last_orderline = this.getLastOrderline();
986 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
987 last_orderline.merge(line);
989 this.get('orderLines').add(line);
991 this.selectLine(this.getLastOrderline());
993 removeOrderline: function( line ){
994 this.get('orderLines').remove(line);
995 this.selectLine(this.getLastOrderline());
997 getOrderline: function(id){
998 var orderlines = this.get('orderLines').models;
999 for(var i = 0; i < orderlines.length; i++){
1000 if(orderlines[i].id === id){
1001 return orderlines[i];
1006 getLastOrderline: function(){
1007 return this.get('orderLines').at(this.get('orderLines').length -1);
1009 addPaymentline: function(cashregister) {
1010 var paymentLines = this.get('paymentLines');
1011 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
1012 if(cashregister.journal.type !== 'cash'){
1013 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
1015 paymentLines.add(newPaymentline);
1016 this.selectPaymentline(newPaymentline);
1019 removePaymentline: function(line){
1020 if(this.selected_paymentline === line){
1021 this.selectPaymentline(undefined);
1023 this.get('paymentLines').remove(line);
1025 getName: function() {
1026 return this.get('name');
1028 getSubtotal : function(){
1029 return (this.get('orderLines')).reduce((function(sum, orderLine){
1030 return sum + orderLine.get_display_price();
1033 getTotalTaxIncluded: function() {
1034 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1035 return sum + orderLine.get_price_with_tax();
1038 getDiscountTotal: function() {
1039 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1040 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
1043 getTotalTaxExcluded: function() {
1044 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1045 return sum + orderLine.get_price_without_tax();
1048 getTax: function() {
1049 return (this.get('orderLines')).reduce((function(sum, orderLine) {
1050 return sum + orderLine.get_tax();
1053 getTaxDetails: function(){
1055 var fulldetails = [];
1056 var taxes_by_id = {};
1058 for(var i = 0; i < this.pos.taxes.length; i++){
1059 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
1062 this.get('orderLines').each(function(line){
1063 var ldetails = line.get_tax_details();
1064 for(var id in ldetails){
1065 if(ldetails.hasOwnProperty(id)){
1066 details[id] = (details[id] || 0) + ldetails[id];
1071 for(var id in details){
1072 if(details.hasOwnProperty(id)){
1073 fulldetails.push({amount: details[id], tax: taxes_by_id[id], name: taxes_by_id[id].name});
1079 getPaidTotal: function() {
1080 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
1081 return sum + paymentLine.get_amount();
1084 getChange: function() {
1085 return this.getPaidTotal() - this.getTotalTaxIncluded();
1087 getDueLeft: function() {
1088 return this.getTotalTaxIncluded() - this.getPaidTotal();
1090 // sets the type of receipt 'receipt'(default) or 'invoice'
1091 set_receipt_type: function(type){
1092 this.receipt_type = type;
1094 get_receipt_type: function(){
1095 return this.receipt_type;
1097 // the client related to the current order.
1098 set_client: function(client){
1099 this.set('client',client);
1101 get_client: function(){
1102 return this.get('client');
1104 get_client_name: function(){
1105 var client = this.get('client');
1106 return client ? client.name : "";
1108 // the order also stores the screen status, as the PoS supports
1109 // different active screens per order. This method is used to
1110 // store the screen status.
1111 set_screen_data: function(key,value){
1112 if(arguments.length === 2){
1113 this.screen_data[key] = value;
1114 }else if(arguments.length === 1){
1115 for(key in arguments[0]){
1116 this.screen_data[key] = arguments[0][key];
1120 //see set_screen_data
1121 get_screen_data: function(key){
1122 return this.screen_data[key];
1124 // exports a JSON for receipt printing
1125 export_for_printing: function(){
1126 var orderlines = [];
1127 this.get('orderLines').each(function(orderline){
1128 orderlines.push(orderline.export_for_printing());
1131 var paymentlines = [];
1132 this.get('paymentLines').each(function(paymentline){
1133 paymentlines.push(paymentline.export_for_printing());
1135 var client = this.get('client');
1136 var cashier = this.pos.cashier || this.pos.user;
1137 var company = this.pos.company;
1138 var shop = this.pos.shop;
1139 var date = new Date();
1142 orderlines: orderlines,
1143 paymentlines: paymentlines,
1144 subtotal: this.getSubtotal(),
1145 total_with_tax: this.getTotalTaxIncluded(),
1146 total_without_tax: this.getTotalTaxExcluded(),
1147 total_tax: this.getTax(),
1148 total_paid: this.getPaidTotal(),
1149 total_discount: this.getDiscountTotal(),
1150 tax_details: this.getTaxDetails(),
1151 change: this.getChange(),
1152 name : this.getName(),
1153 client: client ? client.name : null ,
1154 invoice_id: null, //TODO
1155 cashier: cashier ? cashier.name : null,
1156 header: this.pos.config.receipt_header || '',
1157 footer: this.pos.config.receipt_footer || '',
1164 year: date.getFullYear(),
1165 month: date.getMonth(),
1166 date: date.getDate(), // day of the month
1167 day: date.getDay(), // day of the week
1168 hour: date.getHours(),
1169 minute: date.getMinutes() ,
1170 isostring: date.toISOString(),
1171 localestring: date.toLocaleString(),
1174 email: company.email,
1175 website: company.website,
1176 company_registry: company.company_registry,
1177 contact_address: company.partner_id[1],
1180 phone: company.phone,
1181 logo: this.pos.company_logo_base64,
1186 currency: this.pos.currency,
1189 export_as_JSON: function() {
1190 var orderLines, paymentLines;
1192 (this.get('orderLines')).each(_.bind( function(item) {
1193 return orderLines.push([0, 0, item.export_as_JSON()]);
1196 (this.get('paymentLines')).each(_.bind( function(item) {
1197 return paymentLines.push([0, 0, item.export_as_JSON()]);
1200 name: this.getName(),
1201 amount_paid: this.getPaidTotal(),
1202 amount_total: this.getTotalTaxIncluded(),
1203 amount_tax: this.getTax(),
1204 amount_return: this.getChange(),
1206 statement_ids: paymentLines,
1207 pos_session_id: this.pos.pos_session.id,
1208 partner_id: this.get_client() ? this.get_client().id : false,
1209 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1211 sequence_number: this.sequence_number,
1214 getSelectedLine: function(){
1215 return this.selected_orderline;
1217 selectLine: function(line){
1219 if(line !== this.selected_orderline){
1220 if(this.selected_orderline){
1221 this.selected_orderline.set_selected(false);
1223 this.selected_orderline = line;
1224 this.selected_orderline.set_selected(true);
1227 this.selected_orderline = undefined;
1230 deselectLine: function(){
1231 if(this.selected_orderline){
1232 this.selected_orderline.set_selected(false);
1233 this.selected_orderline = undefined;
1236 selectPaymentline: function(line){
1237 if(line !== this.selected_paymentline){
1238 if(this.selected_paymentline){
1239 this.selected_paymentline.set_selected(false);
1241 this.selected_paymentline = line;
1242 if(this.selected_paymentline){
1243 this.selected_paymentline.set_selected(true);
1245 this.trigger('change:selected_paymentline',this.selected_paymentline);
1250 module.OrderCollection = Backbone.Collection.extend({
1251 model: module.Order,
1255 The numpad handles both the choice of the property currently being modified
1256 (quantity, price or discount) and the edition of the corresponding numeric value.
1258 module.NumpadState = Backbone.Model.extend({
1263 appendNewChar: function(newChar) {
1265 oldBuffer = this.get('buffer');
1266 if (oldBuffer === '0') {
1270 } else if (oldBuffer === '-0') {
1272 buffer: "-" + newChar
1276 buffer: (this.get('buffer')) + newChar
1279 this.trigger('set_value',this.get('buffer'));
1281 deleteLastChar: function() {
1282 if(this.get('buffer') === ""){
1283 if(this.get('mode') === 'quantity'){
1284 this.trigger('set_value','remove');
1286 this.trigger('set_value',this.get('buffer'));
1289 var newBuffer = this.get('buffer').slice(0,-1) || "";
1290 this.set({ buffer: newBuffer });
1291 this.trigger('set_value',this.get('buffer'));
1294 switchSign: function() {
1296 oldBuffer = this.get('buffer');
1298 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1300 this.trigger('set_value',this.get('buffer'));
1302 changeMode: function(newMode) {
1314 resetValue: function(){
1315 this.set({buffer:'0'});