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){
178 self.pos_session = pos_sessions[0];
179 self.pos_session_id = parseInt(self.pos_session.name.split('/')[1]);
181 var orders = self.db.get_orders();
182 for (var i = 0; i < orders.length; i++) {
183 self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
189 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
190 loaded: function(self,configs){
191 self.config = configs[0];
192 self.config.use_proxy = self.config.iface_payment_terminal ||
193 self.config.iface_electronic_scale ||
194 self.config.iface_print_via_proxy ||
195 self.config.iface_scan_via_proxy ||
196 self.config.iface_cashdrawer;
198 self.barcode_reader.add_barcode_patterns({
199 'product': self.config.barcode_product,
200 'cashier': self.config.barcode_cashier,
201 'client': self.config.barcode_customer,
202 'weight': self.config.barcode_weight,
203 'discount': self.config.barcode_discount,
204 'price': self.config.barcode_price,
208 model: 'stock.location',
210 domain: function(self){ return [['id','=', self.config.stock_location_id[0]]]; },
211 loaded: function(self, locations){ self.shop = locations[0]; },
213 model: 'product.pricelist',
214 fields: ['currency_id'],
215 domain: function(self){ return [['id','=',self.config.pricelist_id[0]]]; },
216 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
218 model: 'res.currency',
219 fields: ['symbol','position','rounding','accuracy'],
220 domain: function(self){ return [['id','=',self.pricelist.currency_id[0]]]; },
221 loaded: function(self, currencies){
222 self.currency = currencies[0];
225 model: 'product.packaging',
226 fields: ['ean','product_tmpl_id'],
228 loaded: function(self, packagings){
229 self.db.add_packagings(packagings);
232 model: 'pos.category',
233 fields: ['id','name','parent_id','child_id','image'],
235 loaded: function(self, categories){
236 self.db.add_categories(categories);
239 model: 'product.product',
240 fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
241 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
243 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
244 context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
245 loaded: function(self, products){
246 self.db.add_products(products);
249 model: 'account.bank.statement',
250 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
251 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
252 loaded: function(self, bankstatements, tmp){
253 self.bankstatements = bankstatements;
256 _.each(bankstatements,function(statement){
257 tmp.journals.push(statement.journal_id[0]);
261 model: 'account.journal',
263 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
264 loaded: function(self, journals){
265 self.journals = journals;
267 // associate the bank statements with their journals.
268 var bankstatements = self.bankstatements;
269 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
270 for(var j = 0, jlen = journals.length; j < jlen; j++){
271 if(bankstatements[i].journal_id[0] === journals[j].id){
272 bankstatements[i].journal = journals[j];
273 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
277 self.cashregisters = bankstatements;
280 loaded: function(self){
281 self.company_logo = new Image();
282 self.company_logo.crossOrigin = 'anonymous';
283 var logo_loaded = new $.Deferred();
284 self.company_logo.onload = function(){
285 var img = self.company_logo;
287 var targetwidth = 300;
289 if( img.width !== targetwidth ){
290 ratio = targetwidth / img.width;
292 if( img.height * ratio > maxheight ){
293 ratio = maxheight / img.height;
295 var width = Math.floor(img.width * ratio);
296 var height = Math.floor(img.height * ratio);
297 var c = document.createElement('canvas');
300 var ctx = c.getContext('2d');
301 ctx.drawImage(self.company_logo,0,0, width, height);
303 self.company_logo_base64 = c.toDataURL();
304 window.logo64 = self.company_logo_base64;
305 logo_loaded.resolve();
307 self.company_logo.onerror = function(){
308 logo_loaded.reject();
310 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
317 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
318 load_server_data: function(){
320 var loaded = new $.Deferred();
322 var progress_step = 1.0 / self.models.length;
323 var tmp = {}; // this is used to share a temporary state between models loaders
325 function load_model(index){
326 if(index >= self.models.length){
329 var model = self.models[index];
330 self.pos_widget.loading_message(_t('Loading')+' '+(model.model || ''), progress);
331 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
332 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
333 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
334 progress += progress_step;
337 new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
338 .then(function(result){
339 try{ // catching exceptions in model.loaded(...)
340 $.when(model.loaded(self,result,tmp))
341 .then(function(){ load_model(index + 1); },
342 function(err){ loaded.reject(err); });
349 }else if( model.loaded ){
350 try{ // catching exceptions in model.loaded(...)
351 $.when(model.loaded(self,tmp))
352 .then( function(){ load_model(index +1); },
353 function(err){ loaded.reject(err); });
358 load_model(index + 1);
372 // this is called when an order is removed from the order collection. It ensures that there is always an existing
373 // order and a valid selected order
374 on_removed_order: function(removed_order,index,reason){
375 if( (reason === 'abandon' || removed_order.temporary) && this.get('orders').size() > 0){
376 // when we intentionally remove an unfinished order, and there is another existing one
377 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
379 // when the order was automatically removed after completion,
380 // or when we intentionally delete the only concurrent order
381 this.add_new_order();
385 //creates a new empty order and sets it as the current order
386 add_new_order: function(){
387 var order = new module.Order({pos:this});
388 this.get('orders').add(order);
389 this.set('selectedOrder', order);
392 get_order: function(){
393 return this.get('selectedOrder');
396 //removes the current order
397 delete_current_order: function(){
398 this.get('selectedOrder').destroy({'reason':'abandon'});
401 // saves the order locally and try to send it to the backend.
402 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
403 push_order: function(order) {
407 this.proxy.log('push_order',order.export_as_JSON());
408 this.db.add_order(order.export_as_JSON());
411 var pushed = new $.Deferred();
413 this.flush_mutex.exec(function(){
414 var flushed = self._flush_orders(self.db.get_orders());
416 flushed.always(function(ids){
423 // saves the order locally and try to send it to the backend and make an invoice
424 // returns a deferred that succeeds when the order has been posted and successfully generated
425 // an invoice. This method can fail in various ways:
426 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
427 // this error is solved
428 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
429 // the network connection is up
431 push_and_invoice_order: function(order){
433 var invoiced = new $.Deferred();
435 if(!order.get_client()){
436 invoiced.reject('error-no-client');
440 var order_id = this.db.add_order(order.export_as_JSON());
442 this.flush_mutex.exec(function(){
443 var done = new $.Deferred(); // holds the mutex
445 // send the order to the server
446 // we have a 30 seconds timeout on this push.
447 // FIXME: if the server takes more than 30 seconds to accept the order,
448 // the client will believe it wasn't successfully sent, and very bad
449 // things will happen as a duplicate will be sent next time
450 // so we must make sure the server detects and ignores duplicated orders
452 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
454 transfer.fail(function(){
455 invoiced.reject('error-transfer');
459 // on success, get the order id generated by the server
460 transfer.pipe(function(order_server_id){
462 // generate the pdf and download it
463 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
464 active_ids:order_server_id,
478 // wrapper around the _save_to_server that updates the synch status widget
479 _flush_orders: function(orders, options) {
482 this.set('synch',{ state: 'connecting', pending: orders.length});
484 return self._save_to_server(orders, options).done(function (server_ids) {
485 var pending = self.db.get_orders().length;
488 state: pending ? 'connecting' : 'connected',
496 // send an array of orders to the server
497 // available options:
498 // - timeout: timeout for the rpc call in ms
499 // returns a deferred that resolves with the list of
500 // server generated ids for the sent orders
501 _save_to_server: function (orders, options) {
502 if (!orders || !orders.length) {
503 var result = $.Deferred();
508 options = options || {};
511 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
513 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
514 // then we want to notify the user that we are waiting on something )
515 var posOrderModel = new instance.web.Model('pos.order');
516 return posOrderModel.call('create_from_ui',
517 [_.map(orders, function (order) {
518 order.to_invoice = options.to_invoice || false;
523 shadow: !options.to_invoice,
526 ).then(function (server_ids) {
527 _.each(orders, function (order) {
528 self.db.remove_order(order.id);
531 }).fail(function (error, event){
532 if(error.code === 200 ){ // Business Logic Error, not a connection problem
533 self.pos_widget.screen_selector.show_popup('error-traceback',{
534 message: error.data.message,
535 comment: error.data.debug
538 // prevent an error popup creation by the rpc failure
539 // we want the failure to be silent as we send the orders in the background
540 event.preventDefault();
541 console.error('Failed to send orders:', orders);
545 scan_product: function(parsed_code){
547 var selectedOrder = this.get('selectedOrder');
548 if(parsed_code.encoding === 'ean13'){
549 var product = this.db.get_product_by_ean13(parsed_code.base_code);
550 }else if(parsed_code.encoding === 'reference'){
551 var product = this.db.get_product_by_reference(parsed_code.code);
558 if(parsed_code.type === 'price'){
559 selectedOrder.addProduct(product, {price:parsed_code.value});
560 }else if(parsed_code.type === 'weight'){
561 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
562 }else if(parsed_code.type === 'discount'){
563 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
565 selectedOrder.addProduct(product);
571 var orderline_id = 1;
573 // An orderline represent one element of the content of a client's shopping cart.
574 // An orderline contains a product, its quantity, its price, discount. etc.
575 // An Order contains zero or more Orderlines.
576 module.Orderline = Backbone.Model.extend({
577 initialize: function(attr,options){
578 this.pos = options.pos;
579 this.order = options.order;
580 this.product = options.product;
581 this.price = options.product.price;
583 this.quantityStr = '1';
585 this.discountStr = '0';
587 this.selected = false;
588 this.id = orderline_id++;
591 var orderline = new module.Orderline({},{
594 product: this.product,
597 orderline.quantity = this.quantity;
598 orderline.quantityStr = this.quantityStr;
599 orderline.discount = this.discount;
600 orderline.type = this.type;
601 orderline.selected = false;
604 // sets a discount [0,100]%
605 set_discount: function(discount){
606 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
607 this.discount = disc;
608 this.discountStr = '' + disc;
609 this.trigger('change',this);
611 // returns the discount [0,100]%
612 get_discount: function(){
613 return this.discount;
615 get_discount_str: function(){
616 return this.discountStr;
618 get_product_type: function(){
621 // sets the quantity of the product. The quantity will be rounded according to the
622 // product's unity of measure properties. Quantities greater than zero will not get
624 set_quantity: function(quantity){
625 if(quantity === 'remove'){
626 this.order.removeOrderline(this);
629 var quant = parseFloat(quantity) || 0;
630 var unit = this.get_unit();
632 this.quantity = round_pr(quant, unit.rounding);
633 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
635 this.quantity = quant;
636 this.quantityStr = '' + this.quantity;
639 this.trigger('change',this);
641 // return the quantity of product
642 get_quantity: function(){
643 return this.quantity;
645 get_quantity_str: function(){
646 return this.quantityStr;
648 get_quantity_str_with_unit: function(){
649 var unit = this.get_unit();
650 if(unit && !unit.is_unit){
651 return this.quantityStr + ' ' + unit.name;
653 return this.quantityStr;
656 // return the unit of measure of the product
657 get_unit: function(){
658 var unit_id = (this.product.uos_id || this.product.uom_id);
662 unit_id = unit_id[0];
666 return this.pos.units_by_id[unit_id];
668 // return the product of this orderline
669 get_product: function(){
672 // selects or deselects this orderline
673 set_selected: function(selected){
674 this.selected = selected;
675 this.trigger('change',this);
677 // returns true if this orderline is selected
678 is_selected: function(){
679 return this.selected;
681 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
682 // in the orderline. This returns true if it makes sense to merge the two
683 can_be_merged_with: function(orderline){
684 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
686 }else if(!this.get_unit() || !this.get_unit().groupable){
688 }else if(this.get_product_type() !== orderline.get_product_type()){
690 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
692 }else if(this.price !== orderline.price){
698 merge: function(orderline){
699 this.set_quantity(this.get_quantity() + orderline.get_quantity());
701 export_as_JSON: function() {
703 qty: this.get_quantity(),
704 price_unit: this.get_unit_price(),
705 discount: this.get_discount(),
706 product_id: this.get_product().id,
709 //used to create a json of the ticket, to be sent to the printer
710 export_for_printing: function(){
712 quantity: this.get_quantity(),
713 unit_name: this.get_unit().name,
714 price: this.get_unit_price(),
715 discount: this.get_discount(),
716 product_name: this.get_product().display_name,
717 price_display : this.get_display_price(),
718 price_with_tax : this.get_price_with_tax(),
719 price_without_tax: this.get_price_without_tax(),
721 product_description: this.get_product().description,
722 product_description_sale: this.get_product().description_sale,
725 // changes the base price of the product for this orderline
726 set_unit_price: function(price){
727 this.price = round_di(parseFloat(price) || 0, 2);
728 this.trigger('change',this);
730 get_unit_price: function(){
731 var rounding = this.pos.currency.rounding;
732 return round_pr(this.price,rounding);
734 get_display_price: function(){
735 var rounding = this.pos.currency.rounding;
736 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
738 get_price_without_tax: function(){
739 return this.get_all_prices().priceWithoutTax;
741 get_price_with_tax: function(){
742 return this.get_all_prices().priceWithTax;
745 return this.get_all_prices().tax;
747 get_tax_details: function(){
748 return this.get_all_prices().taxDetails;
750 get_all_prices: function(){
752 var currency_rounding = this.pos.currency.rounding;
753 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
755 var totalNoTax = base;
757 var product = this.get_product();
758 var taxes_ids = product.taxes_id;
759 var taxes = self.pos.taxes;
762 _.each(taxes_ids, function(el) {
763 var tax = _.detect(taxes, function(t) {return t.id === el;});
764 if (tax.price_include) {
766 if (tax.type === "percent") {
767 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
768 } else if (tax.type === "fixed") {
769 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
771 throw "This type of tax is not supported by the point of sale: " + tax.type;
773 tmp = round_pr(tmp,currency_rounding);
776 taxdetail[tax.id] = tmp;
779 if (tax.type === "percent") {
780 tmp = tax.amount * base;
781 } else if (tax.type === "fixed") {
782 tmp = tax.amount * self.get_quantity();
784 throw "This type of tax is not supported by the point of sale: " + tax.type;
786 tmp = round_pr(tmp,currency_rounding);
789 taxdetail[tax.id] = tmp;
793 "priceWithTax": totalTax,
794 "priceWithoutTax": totalNoTax,
796 "taxDetails": taxdetail,
801 module.OrderlineCollection = Backbone.Collection.extend({
802 model: module.Orderline,
805 // Every Paymentline contains a cashregister and an amount of money.
806 module.Paymentline = Backbone.Model.extend({
807 initialize: function(attributes, options) {
809 this.cashregister = options.cashregister;
810 this.name = this.cashregister.journal_id[1];
811 this.selected = false;
813 //sets the amount of money on this payment line
814 set_amount: function(value){
815 this.amount = round_di(parseFloat(value) || 0, 2);
816 this.trigger('change:amount',this);
818 // returns the amount of money on this paymentline
819 get_amount: function(){
822 set_selected: function(selected){
823 if(this.selected !== selected){
824 this.selected = selected;
825 this.trigger('change:selected',this);
828 // returns the associated cashregister
829 //exports as JSON for server communication
830 export_as_JSON: function(){
832 name: instance.web.datetime_to_str(new Date()),
833 statement_id: this.cashregister.id,
834 account_id: this.cashregister.account_id[0],
835 journal_id: this.cashregister.journal_id[0],
836 amount: this.get_amount()
839 //exports as JSON for receipt printing
840 export_for_printing: function(){
842 amount: this.get_amount(),
843 journal: this.cashregister.journal_id[1],
848 module.PaymentlineCollection = Backbone.Collection.extend({
849 model: module.Paymentline,
853 // An order more or less represents the content of a client's shopping cart (the OrderLines)
854 // plus the associated payment information (the Paymentlines)
855 // there is always an active ('selected') order in the Pos, a new one is created
856 // automaticaly once an order is completed and sent to the server.
857 module.Order = Backbone.Model.extend({
858 initialize: function(attributes){
859 Backbone.Model.prototype.initialize.apply(this, arguments);
860 this.pos = attributes.pos;
861 this.sequence_number = this.pos.pos_session.sequence_number++;
862 this.uid = this.generateUniqueId();
864 creationDate: new Date(),
865 orderLines: new module.OrderlineCollection(),
866 paymentLines: new module.PaymentlineCollection(),
867 name: "Order " + this.uid,
870 this.selected_orderline = undefined;
871 this.selected_paymentline = undefined;
872 this.screen_data = {}; // see ScreenSelector
873 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
874 this.temporary = attributes.temporary || false;
877 is_empty: function(){
878 return (this.get('orderLines').models.length === 0);
880 // Generates a public identification number for the order.
881 // The generated number must be unique and sequential. They are made 12 digit long
882 // to fit into EAN-13 barcodes.
883 generateUniqueId: function() {
884 function zero_pad(num,size){
886 while (s.length < size) {
891 return zero_pad(this.pos.pos_session_id,6) + zero_pad(this.sequence_number,6);
893 addOrderline: function(line){
895 order.removeOrderline(line);
898 this.get('orderLines').add(line);
899 this.selectLine(this.getLastOrderline());
901 addProduct: function(product, options){
902 options = options || {};
903 var attr = JSON.parse(JSON.stringify(product));
906 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
908 if(options.quantity !== undefined){
909 line.set_quantity(options.quantity);
911 if(options.price !== undefined){
912 line.set_unit_price(options.price);
914 if(options.discount !== undefined){
915 line.set_discount(options.discount);
918 var last_orderline = this.getLastOrderline();
919 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
920 last_orderline.merge(line);
922 this.get('orderLines').add(line);
924 this.selectLine(this.getLastOrderline());
926 removeOrderline: function( line ){
927 this.get('orderLines').remove(line);
928 this.selectLine(this.getLastOrderline());
930 getOrderline: function(id){
931 var orderlines = this.get('orderLines').models;
932 for(var i = 0; i < orderlines.length; i++){
933 if(orderlines[i].id === id){
934 return orderlines[i];
939 getLastOrderline: function(){
940 return this.get('orderLines').at(this.get('orderLines').length -1);
942 addPaymentline: function(cashregister) {
943 var paymentLines = this.get('paymentLines');
944 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
945 if(cashregister.journal.type !== 'cash'){
946 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
948 paymentLines.add(newPaymentline);
949 this.selectPaymentline(newPaymentline);
952 removePaymentline: function(line){
953 if(this.selected_paymentline === line){
954 this.selectPaymentline(undefined);
956 this.get('paymentLines').remove(line);
958 getName: function() {
959 return this.get('name');
961 getSubtotal : function(){
962 return (this.get('orderLines')).reduce((function(sum, orderLine){
963 return sum + orderLine.get_display_price();
966 getTotalTaxIncluded: function() {
967 return (this.get('orderLines')).reduce((function(sum, orderLine) {
968 return sum + orderLine.get_price_with_tax();
971 getDiscountTotal: function() {
972 return (this.get('orderLines')).reduce((function(sum, orderLine) {
973 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
976 getTotalTaxExcluded: function() {
977 return (this.get('orderLines')).reduce((function(sum, orderLine) {
978 return sum + orderLine.get_price_without_tax();
982 return (this.get('orderLines')).reduce((function(sum, orderLine) {
983 return sum + orderLine.get_tax();
986 getTaxDetails: function(){
988 var fulldetails = [];
989 var taxes_by_id = {};
991 for(var i = 0; i < this.pos.taxes.length; i++){
992 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
995 this.get('orderLines').each(function(line){
996 var ldetails = line.get_tax_details();
997 for(var id in ldetails){
998 if(ldetails.hasOwnProperty(id)){
999 details[id] = (details[id] || 0) + ldetails[id];
1004 for(var id in details){
1005 if(details.hasOwnProperty(id)){
1006 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
1012 getPaidTotal: function() {
1013 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
1014 return sum + paymentLine.get_amount();
1017 getChange: function() {
1018 return this.getPaidTotal() - this.getTotalTaxIncluded();
1020 getDueLeft: function() {
1021 return this.getTotalTaxIncluded() - this.getPaidTotal();
1023 // sets the type of receipt 'receipt'(default) or 'invoice'
1024 set_receipt_type: function(type){
1025 this.receipt_type = type;
1027 get_receipt_type: function(){
1028 return this.receipt_type;
1030 // the client related to the current order.
1031 set_client: function(client){
1032 this.set('client',client);
1034 get_client: function(){
1035 return this.get('client');
1037 get_client_name: function(){
1038 var client = this.get('client');
1039 return client ? client.name : "";
1041 // the order also stores the screen status, as the PoS supports
1042 // different active screens per order. This method is used to
1043 // store the screen status.
1044 set_screen_data: function(key,value){
1045 if(arguments.length === 2){
1046 this.screen_data[key] = value;
1047 }else if(arguments.length === 1){
1048 for(key in arguments[0]){
1049 this.screen_data[key] = arguments[0][key];
1053 //see set_screen_data
1054 get_screen_data: function(key){
1055 return this.screen_data[key];
1057 // exports a JSON for receipt printing
1058 export_for_printing: function(){
1059 var orderlines = [];
1060 this.get('orderLines').each(function(orderline){
1061 orderlines.push(orderline.export_for_printing());
1064 var paymentlines = [];
1065 this.get('paymentLines').each(function(paymentline){
1066 paymentlines.push(paymentline.export_for_printing());
1068 var client = this.get('client');
1069 var cashier = this.pos.cashier || this.pos.user;
1070 var company = this.pos.company;
1071 var shop = this.pos.shop;
1072 var date = new Date();
1075 orderlines: orderlines,
1076 paymentlines: paymentlines,
1077 subtotal: this.getSubtotal(),
1078 total_with_tax: this.getTotalTaxIncluded(),
1079 total_without_tax: this.getTotalTaxExcluded(),
1080 total_tax: this.getTax(),
1081 total_paid: this.getPaidTotal(),
1082 total_discount: this.getDiscountTotal(),
1083 tax_details: this.getTaxDetails(),
1084 change: this.getChange(),
1085 name : this.getName(),
1086 client: client ? client.name : null ,
1087 invoice_id: null, //TODO
1088 cashier: cashier ? cashier.name : null,
1089 header: this.pos.config.receipt_header || '',
1090 footer: this.pos.config.receipt_footer || '',
1097 year: date.getFullYear(),
1098 month: date.getMonth(),
1099 date: date.getDate(), // day of the month
1100 day: date.getDay(), // day of the week
1101 hour: date.getHours(),
1102 minute: date.getMinutes() ,
1103 isostring: date.toISOString(),
1104 localestring: date.toLocaleString(),
1107 email: company.email,
1108 website: company.website,
1109 company_registry: company.company_registry,
1110 contact_address: company.partner_id[1],
1113 phone: company.phone,
1114 logo: this.pos.company_logo_base64,
1119 currency: this.pos.currency,
1122 export_as_JSON: function() {
1123 var orderLines, paymentLines;
1125 (this.get('orderLines')).each(_.bind( function(item) {
1126 return orderLines.push([0, 0, item.export_as_JSON()]);
1129 (this.get('paymentLines')).each(_.bind( function(item) {
1130 return paymentLines.push([0, 0, item.export_as_JSON()]);
1133 name: this.getName(),
1134 amount_paid: this.getPaidTotal(),
1135 amount_total: this.getTotalTaxIncluded(),
1136 amount_tax: this.getTax(),
1137 amount_return: this.getChange(),
1139 statement_ids: paymentLines,
1140 pos_session_id: this.pos.pos_session.id,
1141 partner_id: this.get_client() ? this.get_client().id : false,
1142 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1144 sequence_number: this.sequence_number,
1147 getSelectedLine: function(){
1148 return this.selected_orderline;
1150 selectLine: function(line){
1152 if(line !== this.selected_orderline){
1153 if(this.selected_orderline){
1154 this.selected_orderline.set_selected(false);
1156 this.selected_orderline = line;
1157 this.selected_orderline.set_selected(true);
1160 this.selected_orderline = undefined;
1163 deselectLine: function(){
1164 if(this.selected_orderline){
1165 this.selected_orderline.set_selected(false);
1166 this.selected_orderline = undefined;
1169 selectPaymentline: function(line){
1170 if(line !== this.selected_paymentline){
1171 if(this.selected_paymentline){
1172 this.selected_paymentline.set_selected(false);
1174 this.selected_paymentline = line;
1175 if(this.selected_paymentline){
1176 this.selected_paymentline.set_selected(true);
1178 this.trigger('change:selected_paymentline',this.selected_paymentline);
1183 module.OrderCollection = Backbone.Collection.extend({
1184 model: module.Order,
1188 The numpad handles both the choice of the property currently being modified
1189 (quantity, price or discount) and the edition of the corresponding numeric value.
1191 module.NumpadState = Backbone.Model.extend({
1196 appendNewChar: function(newChar) {
1198 oldBuffer = this.get('buffer');
1199 if (oldBuffer === '0') {
1203 } else if (oldBuffer === '-0') {
1205 buffer: "-" + newChar
1209 buffer: (this.get('buffer')) + newChar
1212 this.trigger('set_value',this.get('buffer'));
1214 deleteLastChar: function() {
1215 if(this.get('buffer') === ""){
1216 if(this.get('mode') === 'quantity'){
1217 this.trigger('set_value','remove');
1219 this.trigger('set_value',this.get('buffer'));
1222 var newBuffer = this.get('buffer').slice(0,-1) || "";
1223 this.set({ buffer: newBuffer });
1224 this.trigger('set_value',this.get('buffer'));
1227 switchSign: function() {
1229 oldBuffer = this.get('buffer');
1231 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1233 this.trigger('set_value',this.get('buffer'));
1235 changeMode: function(newMode) {
1247 resetValue: function(){
1248 this.set({buffer:'0'});