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'],
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'],
176 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
177 loaded: function(self,pos_sessions){ self.pos_session = pos_sessions[0]; },
181 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
182 loaded: function(self,configs){
183 self.config = configs[0];
184 self.config.use_proxy = self.config.iface_payment_terminal ||
185 self.config.iface_electronic_scale ||
186 self.config.iface_print_via_proxy ||
187 self.config.iface_scan_via_proxy ||
188 self.config.iface_cashdrawer;
190 self.barcode_reader.add_barcode_patterns({
191 'product': self.config.barcode_product,
192 'cashier': self.config.barcode_cashier,
193 'client': self.config.barcode_customer,
194 'weight': self.config.barcode_weight,
195 'discount': self.config.barcode_discount,
196 'price': self.config.barcode_price,
200 model: 'stock.location',
202 domain: function(self){ return [['id','=', self.config.stock_location_id[0]]]; },
203 loaded: function(self, locations){ self.shop = locations[0]; },
205 model: 'product.pricelist',
206 fields: ['currency_id'],
207 domain: function(self){ return [['id','=',self.config.pricelist_id[0]]]; },
208 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
210 model: 'res.currency',
211 fields: ['symbol','position','rounding','accuracy'],
212 domain: function(self){ return [['id','=',self.pricelist.currency_id[0]]]; },
213 loaded: function(self, currencies){
214 self.currency = currencies[0];
217 model: 'product.packaging',
218 fields: ['ean','product_tmpl_id'],
220 loaded: function(self, packagings){
221 self.db.add_packagings(packagings);
224 model: 'pos.category',
225 fields: ['id','name','parent_id','child_id','image'],
227 loaded: function(self, categories){
228 self.db.add_categories(categories);
231 model: 'product.product',
232 fields: ['name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code', 'variants',
233 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
235 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
236 context: function(self){ return { pricelist: self.pricelist.id }; },
237 loaded: function(self, products){
238 self.db.add_products(products);
241 model: 'account.bank.statement',
242 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
243 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
244 loaded: function(self, bankstatements, tmp){
245 self.bankstatements = bankstatements;
248 _.each(bankstatements,function(statement){
249 tmp.journals.push(statement.journal_id[0]);
253 model: 'account.journal',
255 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
256 loaded: function(self, journals){
257 self.journals = journals;
259 // associate the bank statements with their journals.
260 var bankstatements = self.bankstatements;
261 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
262 for(var j = 0, jlen = journals.length; j < jlen; j++){
263 if(bankstatements[i].journal_id[0] === journals[j].id){
264 bankstatements[i].journal = journals[j];
265 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
269 self.cashregisters = bankstatements;
272 loaded: function(self){
273 self.company_logo = new Image();
274 self.company_logo.crossOrigin = 'anonymous';
275 var logo_loaded = new $.Deferred();
276 self.company_logo.onload = function(){
277 var img = self.company_logo;
279 var targetwidth = 300;
281 if( img.width !== targetwidth ){
282 ratio = targetwidth / img.width;
284 if( img.height * ratio > maxheight ){
285 ratio = maxheight / img.height;
287 var width = Math.floor(img.width * ratio);
288 var height = Math.floor(img.height * ratio);
289 var c = document.createElement('canvas');
292 var ctx = c.getContext('2d');
293 ctx.drawImage(self.company_logo,0,0, width, height);
295 self.company_logo_base64 = c.toDataURL();
296 window.logo64 = self.company_logo_base64;
297 logo_loaded.resolve();
299 self.company_logo.onerror = function(){
300 logo_loaded.reject();
302 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
309 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
310 load_server_data: function(){
312 var loaded = new $.Deferred();
314 var progress_step = 1.0 / self.models.length;
315 var tmp = {}; // this is used to share a temporary state between models loaders
317 function load_model(index){
318 if(index >= self.models.length){
321 var model = self.models[index];
322 self.pos_widget.loading_message(_t('Loading')+' '+(model.model || ''), progress);
323 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
324 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
325 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
326 progress += progress_step;
329 new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
330 .then(function(result){
331 $.when(model.loaded(self,result,tmp))
332 .then(function(){ load_model(index + 1); },
333 function(err){ loaded.reject(err); });
337 }else if( model.loaded ){
338 $.when(model.loaded(self,tmp))
339 .then( function(){ load_model(index +1); },
340 function(err){ loaded.reject(err); });
342 load_model(index + 1);
352 // this is called when an order is removed from the order collection. It ensures that there is always an existing
353 // order and a valid selected order
354 on_removed_order: function(removed_order,index,reason){
355 if( (reason === 'abandon' || removed_order.temporary) && this.get('orders').size() > 0){
356 // when we intentionally remove an unfinished order, and there is another existing one
357 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
359 // when the order was automatically removed after completion,
360 // or when we intentionally delete the only concurrent order
361 this.add_new_order();
365 //creates a new empty order and sets it as the current order
366 add_new_order: function(){
367 var order = new module.Order({pos:this});
368 this.get('orders').add(order);
369 this.set('selectedOrder', order);
372 get_order: function(){
373 return this.get('selectedOrder');
376 //removes the current order
377 delete_current_order: function(){
378 this.get('selectedOrder').destroy({'reason':'abandon'});
381 // saves the order locally and try to send it to the backend.
382 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
383 push_order: function(order) {
387 this.proxy.log('push_order',order.export_as_JSON());
388 this.db.add_order(order.export_as_JSON());
391 var pushed = new $.Deferred();
393 this.flush_mutex.exec(function(){
394 var flushed = self._flush_orders(self.db.get_orders());
396 flushed.always(function(ids){
397 console.log('pushed orders:',ids);
404 // saves the order locally and try to send it to the backend and make an invoice
405 // returns a deferred that succeeds when the order has been posted and successfully generated
406 // an invoice. This method can fail in various ways:
407 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
408 // this error is solved
409 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
410 // the network connection is up
412 push_and_invoice_order: function(order){
414 var invoiced = new $.Deferred();
416 if(!order.get_client()){
417 invoiced.reject('error-no-client');
421 var order_id = this.db.add_order(order.export_as_JSON());
423 this.flush_mutex.exec(function(){
424 var done = new $.Deferred(); // holds the mutex
426 // send the order to the server
427 // we have a 30 seconds timeout on this push.
428 // FIXME: if the server takes more than 30 seconds to accept the order,
429 // the client will believe it wasn't successfully sent, and very bad
430 // things will happen as a duplicate will be sent next time
431 // so we must make sure the server detects and ignores duplicated orders
433 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
435 transfer.fail(function(){
436 invoiced.reject('error-transfer');
440 // on success, get the order id generated by the server
441 transfer.pipe(function(order_server_id){
443 // generate the pdf and download it
444 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
445 active_ids:order_server_id,
459 // wrapper around the _save_to_server that updates the synch status widget
460 _flush_orders: function(orders, options) {
463 this.set('synch',{ state: 'connecting', pending: orders.length});
465 return self._save_to_server(orders, options).done(function (server_ids) {
466 var pending = self.db.get_orders().length;
469 state: pending ? 'connecting' : 'connected',
477 // send an array of orders to the server
478 // available options:
479 // - timeout: timeout for the rpc call in ms
480 // returns a deferred that resolves with the list of
481 // server generated ids for the sent orders
482 _save_to_server: function (orders, options) {
483 if (!orders || !orders.length) {
484 var result = $.Deferred();
489 options = options || {};
492 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
494 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
495 // then we want to notify the user that we are waiting on something )
496 var posOrderModel = new instance.web.Model('pos.order');
497 return posOrderModel.call('create_from_ui',
498 [_.map(orders, function (order) {
499 order.to_invoice = options.to_invoice || false;
504 shadow: !options.to_invoice,
507 ).then(function (server_ids) {
508 _.each(orders, function (order) {
509 self.db.remove_order(order.id);
512 }).fail(function (error, event){
513 if(error.code === 200 ){ // Business Logic Error, not a connection problem
514 self.pos_widget.screen_selector.show_popup('error-traceback',{
515 message: error.data.message,
516 comment: error.data.debug
519 // prevent an error popup creation by the rpc failure
520 // we want the failure to be silent as we send the orders in the background
521 event.preventDefault();
522 console.error('Failed to send orders:', orders);
526 scan_product: function(parsed_code){
528 var selectedOrder = this.get('selectedOrder');
529 if(parsed_code.encoding === 'ean13'){
530 var product = this.db.get_product_by_ean13(parsed_code.base_code);
531 }else if(parsed_code.encoding === 'reference'){
532 var product = this.db.get_product_by_reference(parsed_code.code);
539 if(parsed_code.type === 'price'){
540 selectedOrder.addProduct(product, {price:parsed_code.value});
541 }else if(parsed_code.type === 'weight'){
542 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
543 }else if(parsed_code.type === 'discount'){
544 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
546 selectedOrder.addProduct(product);
552 var orderline_id = 1;
554 // An orderline represent one element of the content of a client's shopping cart.
555 // An orderline contains a product, its quantity, its price, discount. etc.
556 // An Order contains zero or more Orderlines.
557 module.Orderline = Backbone.Model.extend({
558 initialize: function(attr,options){
559 this.pos = options.pos;
560 this.order = options.order;
561 this.product = options.product;
562 this.price = options.product.price;
564 this.quantityStr = '1';
566 this.discountStr = '0';
568 this.selected = false;
569 this.id = orderline_id++;
572 var orderline = new module.Orderline({},{
575 product: this.product,
578 orderline.quantity = this.quantity;
579 orderline.quantityStr = this.quantityStr;
580 orderline.discount = this.discount;
581 orderline.type = this.type;
582 orderline.selected = false;
585 // sets a discount [0,100]%
586 set_discount: function(discount){
587 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
588 this.discount = disc;
589 this.discountStr = '' + disc;
590 this.trigger('change',this);
592 // returns the discount [0,100]%
593 get_discount: function(){
594 return this.discount;
596 get_discount_str: function(){
597 return this.discountStr;
599 get_product_type: function(){
602 // sets the quantity of the product. The quantity will be rounded according to the
603 // product's unity of measure properties. Quantities greater than zero will not get
605 set_quantity: function(quantity){
606 if(quantity === 'remove'){
607 this.order.removeOrderline(this);
610 var quant = parseFloat(quantity) || 0;
611 var unit = this.get_unit();
613 this.quantity = round_pr(quant, unit.rounding);
614 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
616 this.quantity = quant;
617 this.quantityStr = '' + this.quantity;
620 this.trigger('change',this);
622 // return the quantity of product
623 get_quantity: function(){
624 return this.quantity;
626 get_quantity_str: function(){
627 return this.quantityStr;
629 get_quantity_str_with_unit: function(){
630 var unit = this.get_unit();
631 if(unit && !unit.is_unit){
632 return this.quantityStr + ' ' + unit.name;
634 return this.quantityStr;
637 // return the unit of measure of the product
638 get_unit: function(){
639 var unit_id = (this.product.uos_id || this.product.uom_id);
643 unit_id = unit_id[0];
647 return this.pos.units_by_id[unit_id];
649 // return the product of this orderline
650 get_product: function(){
653 // selects or deselects this orderline
654 set_selected: function(selected){
655 this.selected = selected;
656 this.trigger('change',this);
658 // returns true if this orderline is selected
659 is_selected: function(){
660 return this.selected;
662 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
663 // in the orderline. This returns true if it makes sense to merge the two
664 can_be_merged_with: function(orderline){
665 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
667 }else if(!this.get_unit() || !this.get_unit().groupable){
669 }else if(this.get_product_type() !== orderline.get_product_type()){
671 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
673 }else if(this.price !== orderline.price){
679 merge: function(orderline){
680 this.set_quantity(this.get_quantity() + orderline.get_quantity());
682 export_as_JSON: function() {
684 qty: this.get_quantity(),
685 price_unit: this.get_unit_price(),
686 discount: this.get_discount(),
687 product_id: this.get_product().id,
690 //used to create a json of the ticket, to be sent to the printer
691 export_for_printing: function(){
693 quantity: this.get_quantity(),
694 unit_name: this.get_unit().name,
695 price: this.get_unit_price(),
696 discount: this.get_discount(),
697 product_name: this.get_product().name,
698 price_display : this.get_display_price(),
699 price_with_tax : this.get_price_with_tax(),
700 price_without_tax: this.get_price_without_tax(),
702 product_description: this.get_product().description,
703 product_description_sale: this.get_product().description_sale,
706 // changes the base price of the product for this orderline
707 set_unit_price: function(price){
708 this.price = round_di(parseFloat(price) || 0, 2);
709 this.trigger('change',this);
711 get_unit_price: function(){
712 var rounding = this.pos.currency.rounding;
713 return round_pr(this.price,rounding);
715 get_display_price: function(){
716 var rounding = this.pos.currency.rounding;
717 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
719 get_price_without_tax: function(){
720 return this.get_all_prices().priceWithoutTax;
722 get_price_with_tax: function(){
723 return this.get_all_prices().priceWithTax;
726 return this.get_all_prices().tax;
728 get_tax_details: function(){
729 return this.get_all_prices().taxDetails;
731 get_all_prices: function(){
733 var currency_rounding = this.pos.currency.rounding;
734 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
736 var totalNoTax = base;
738 var product = this.get_product();
739 var taxes_ids = product.taxes_id;
740 var taxes = self.pos.taxes;
743 _.each(taxes_ids, function(el) {
744 var tax = _.detect(taxes, function(t) {return t.id === el;});
745 if (tax.price_include) {
747 if (tax.type === "percent") {
748 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
749 } else if (tax.type === "fixed") {
750 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
752 throw "This type of tax is not supported by the point of sale: " + tax.type;
754 tmp = round_pr(tmp,currency_rounding);
757 taxdetail[tax.id] = tmp;
760 if (tax.type === "percent") {
761 tmp = tax.amount * base;
762 } else if (tax.type === "fixed") {
763 tmp = tax.amount * self.get_quantity();
765 throw "This type of tax is not supported by the point of sale: " + tax.type;
767 tmp = round_pr(tmp,currency_rounding);
770 taxdetail[tax.id] = tmp;
774 "priceWithTax": totalTax,
775 "priceWithoutTax": totalNoTax,
777 "taxDetails": taxdetail,
782 module.OrderlineCollection = Backbone.Collection.extend({
783 model: module.Orderline,
786 // Every Paymentline contains a cashregister and an amount of money.
787 module.Paymentline = Backbone.Model.extend({
788 initialize: function(attributes, options) {
790 this.cashregister = options.cashregister;
791 this.name = this.cashregister.journal_id[1];
792 this.selected = false;
794 //sets the amount of money on this payment line
795 set_amount: function(value){
796 this.amount = round_di(parseFloat(value) || 0, 2);
797 this.trigger('change:amount',this);
799 // returns the amount of money on this paymentline
800 get_amount: function(){
803 set_selected: function(selected){
804 if(this.selected !== selected){
805 this.selected = selected;
806 this.trigger('change:selected',this);
809 // returns the associated cashregister
810 //exports as JSON for server communication
811 export_as_JSON: function(){
813 name: instance.web.datetime_to_str(new Date()),
814 statement_id: this.cashregister.id,
815 account_id: this.cashregister.account_id[0],
816 journal_id: this.cashregister.journal_id[0],
817 amount: this.get_amount()
820 //exports as JSON for receipt printing
821 export_for_printing: function(){
823 amount: this.get_amount(),
824 journal: this.cashregister.journal_id[1],
829 module.PaymentlineCollection = Backbone.Collection.extend({
830 model: module.Paymentline,
834 // An order more or less represents the content of a client's shopping cart (the OrderLines)
835 // plus the associated payment information (the Paymentlines)
836 // there is always an active ('selected') order in the Pos, a new one is created
837 // automaticaly once an order is completed and sent to the server.
838 module.Order = Backbone.Model.extend({
839 initialize: function(attributes){
840 Backbone.Model.prototype.initialize.apply(this, arguments);
841 this.uid = this.generateUniqueId();
843 creationDate: new Date(),
844 orderLines: new module.OrderlineCollection(),
845 paymentLines: new module.PaymentlineCollection(),
846 name: "Order " + this.uid,
849 this.pos = attributes.pos;
850 this.selected_orderline = undefined;
851 this.selected_paymentline = undefined;
852 this.screen_data = {}; // see ScreenSelector
853 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
854 this.temporary = attributes.temporary || false;
855 this.sequence_number = this.pos.pos_session.sequence_number++;
858 is_empty: function(){
859 return (this.get('orderLines').models.length === 0);
861 generateUniqueId: function() {
862 return new Date().getTime();
864 addOrderline: function(line){
866 order.removeOrderline(line);
869 this.get('orderLines').add(line);
870 this.selectLine(this.getLastOrderline());
872 addProduct: function(product, options){
873 options = options || {};
874 var attr = JSON.parse(JSON.stringify(product));
877 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
879 if(options.quantity !== undefined){
880 line.set_quantity(options.quantity);
882 if(options.price !== undefined){
883 line.set_unit_price(options.price);
885 if(options.discount !== undefined){
886 line.set_discount(options.discount);
889 var last_orderline = this.getLastOrderline();
890 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
891 last_orderline.merge(line);
893 this.get('orderLines').add(line);
895 this.selectLine(this.getLastOrderline());
897 removeOrderline: function( line ){
898 this.get('orderLines').remove(line);
899 this.selectLine(this.getLastOrderline());
901 getOrderline: function(id){
902 var orderlines = this.get('orderLines').models;
903 for(var i = 0; i < orderlines.length; i++){
904 if(orderlines[i].id === id){
905 return orderlines[i];
910 getLastOrderline: function(){
911 return this.get('orderLines').at(this.get('orderLines').length -1);
913 addPaymentline: function(cashregister) {
914 var paymentLines = this.get('paymentLines');
915 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
916 if(cashregister.journal.type !== 'cash'){
917 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
919 paymentLines.add(newPaymentline);
920 this.selectPaymentline(newPaymentline);
923 removePaymentline: function(line){
924 if(this.selected_paymentline === line){
925 this.selectPaymentline(undefined);
927 this.get('paymentLines').remove(line);
929 getName: function() {
930 return this.get('name');
932 getSubtotal : function(){
933 return (this.get('orderLines')).reduce((function(sum, orderLine){
934 return sum + orderLine.get_display_price();
937 getTotalTaxIncluded: function() {
938 return (this.get('orderLines')).reduce((function(sum, orderLine) {
939 return sum + orderLine.get_price_with_tax();
942 getDiscountTotal: function() {
943 return (this.get('orderLines')).reduce((function(sum, orderLine) {
944 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
947 getTotalTaxExcluded: function() {
948 return (this.get('orderLines')).reduce((function(sum, orderLine) {
949 return sum + orderLine.get_price_without_tax();
953 return (this.get('orderLines')).reduce((function(sum, orderLine) {
954 return sum + orderLine.get_tax();
957 getTaxDetails: function(){
959 var fulldetails = [];
960 var taxes_by_id = {};
962 for(var i = 0; i < this.pos.taxes.length; i++){
963 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
966 this.get('orderLines').each(function(line){
967 var ldetails = line.get_tax_details();
968 for(var id in ldetails){
969 if(ldetails.hasOwnProperty(id)){
970 details[id] = (details[id] || 0) + ldetails[id];
975 for(var id in details){
976 if(details.hasOwnProperty(id)){
977 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
983 getPaidTotal: function() {
984 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
985 return sum + paymentLine.get_amount();
988 getChange: function() {
989 return this.getPaidTotal() - this.getTotalTaxIncluded();
991 getDueLeft: function() {
992 return this.getTotalTaxIncluded() - this.getPaidTotal();
994 // sets the type of receipt 'receipt'(default) or 'invoice'
995 set_receipt_type: function(type){
996 this.receipt_type = type;
998 get_receipt_type: function(){
999 return this.receipt_type;
1001 // the client related to the current order.
1002 set_client: function(client){
1003 this.set('client',client);
1005 get_client: function(){
1006 return this.get('client');
1008 get_client_name: function(){
1009 var client = this.get('client');
1010 return client ? client.name : "";
1012 // the order also stores the screen status, as the PoS supports
1013 // different active screens per order. This method is used to
1014 // store the screen status.
1015 set_screen_data: function(key,value){
1016 if(arguments.length === 2){
1017 this.screen_data[key] = value;
1018 }else if(arguments.length === 1){
1019 for(key in arguments[0]){
1020 this.screen_data[key] = arguments[0][key];
1024 //see set_screen_data
1025 get_screen_data: function(key){
1026 return this.screen_data[key];
1028 // exports a JSON for receipt printing
1029 export_for_printing: function(){
1030 var orderlines = [];
1031 this.get('orderLines').each(function(orderline){
1032 orderlines.push(orderline.export_for_printing());
1035 var paymentlines = [];
1036 this.get('paymentLines').each(function(paymentline){
1037 paymentlines.push(paymentline.export_for_printing());
1039 var client = this.get('client');
1040 var cashier = this.pos.cashier || this.pos.user;
1041 var company = this.pos.company;
1042 var shop = this.pos.shop;
1043 var date = new Date();
1046 orderlines: orderlines,
1047 paymentlines: paymentlines,
1048 subtotal: this.getSubtotal(),
1049 total_with_tax: this.getTotalTaxIncluded(),
1050 total_without_tax: this.getTotalTaxExcluded(),
1051 total_tax: this.getTax(),
1052 total_paid: this.getPaidTotal(),
1053 total_discount: this.getDiscountTotal(),
1054 tax_details: this.getTaxDetails(),
1055 change: this.getChange(),
1056 name : this.getName(),
1057 client: client ? client.name : null ,
1058 invoice_id: null, //TODO
1059 cashier: cashier ? cashier.name : null,
1060 header: this.pos.config.receipt_header || '',
1061 footer: this.pos.config.receipt_footer || '',
1068 year: date.getFullYear(),
1069 month: date.getMonth(),
1070 date: date.getDate(), // day of the month
1071 day: date.getDay(), // day of the week
1072 hour: date.getHours(),
1073 minute: date.getMinutes() ,
1074 isostring: date.toISOString(),
1075 localestring: date.toLocaleString(),
1078 email: company.email,
1079 website: company.website,
1080 company_registry: company.company_registry,
1081 contact_address: company.partner_id[1],
1084 phone: company.phone,
1085 logo: this.pos.company_logo_base64,
1090 currency: this.pos.currency,
1093 export_as_JSON: function() {
1094 var orderLines, paymentLines;
1096 (this.get('orderLines')).each(_.bind( function(item) {
1097 return orderLines.push([0, 0, item.export_as_JSON()]);
1100 (this.get('paymentLines')).each(_.bind( function(item) {
1101 return paymentLines.push([0, 0, item.export_as_JSON()]);
1104 name: this.getName(),
1105 amount_paid: this.getPaidTotal(),
1106 amount_total: this.getTotalTaxIncluded(),
1107 amount_tax: this.getTax(),
1108 amount_return: this.getChange(),
1110 statement_ids: paymentLines,
1111 pos_session_id: this.pos.pos_session.id,
1112 partner_id: this.get_client() ? this.get_client().id : false,
1113 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1115 sequence_number: this.sequence_number,
1118 getSelectedLine: function(){
1119 return this.selected_orderline;
1121 selectLine: function(line){
1123 if(line !== this.selected_orderline){
1124 if(this.selected_orderline){
1125 this.selected_orderline.set_selected(false);
1127 this.selected_orderline = line;
1128 this.selected_orderline.set_selected(true);
1131 this.selected_orderline = undefined;
1134 deselectLine: function(){
1135 if(this.selected_orderline){
1136 this.selected_orderline.set_selected(false);
1137 this.selected_orderline = undefined;
1140 selectPaymentline: function(line){
1141 if(line !== this.selected_paymentline){
1142 if(this.selected_paymentline){
1143 this.selected_paymentline.set_selected(false);
1145 this.selected_paymentline = line;
1146 if(this.selected_paymentline){
1147 this.selected_paymentline.set_selected(true);
1149 this.trigger('change:selected_paymentline',this.selected_paymentline);
1154 module.OrderCollection = Backbone.Collection.extend({
1155 model: module.Order,
1159 The numpad handles both the choice of the property currently being modified
1160 (quantity, price or discount) and the edition of the corresponding numeric value.
1162 module.NumpadState = Backbone.Model.extend({
1167 appendNewChar: function(newChar) {
1169 oldBuffer = this.get('buffer');
1170 if (oldBuffer === '0') {
1174 } else if (oldBuffer === '-0') {
1176 buffer: "-" + newChar
1180 buffer: (this.get('buffer')) + newChar
1183 this.trigger('set_value',this.get('buffer'));
1185 deleteLastChar: function() {
1186 if(this.get('buffer') === ""){
1187 if(this.get('mode') === 'quantity'){
1188 this.trigger('set_value','remove');
1190 this.trigger('set_value',this.get('buffer'));
1193 var newBuffer = this.get('buffer').slice(0,-1) || "";
1194 this.set({ buffer: newBuffer });
1195 this.trigger('set_value',this.get('buffer'));
1198 switchSign: function() {
1200 oldBuffer = this.get('buffer');
1202 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1204 this.trigger('set_value',this.get('buffer'));
1206 changeMode: function(newMode) {
1218 resetValue: function(){
1219 this.set({buffer:'0'});