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 try{ // catching exceptions in model.loaded(...)
332 $.when(model.loaded(self,result,tmp))
333 .then(function(){ load_model(index + 1); },
334 function(err){ loaded.reject(err); });
341 }else if( model.loaded ){
342 try{ // catching exceptions in model.loaded(...)
343 $.when(model.loaded(self,tmp))
344 .then( function(){ load_model(index +1); },
345 function(err){ loaded.reject(err); });
350 load_model(index + 1);
364 // this is called when an order is removed from the order collection. It ensures that there is always an existing
365 // order and a valid selected order
366 on_removed_order: function(removed_order,index,reason){
367 if( (reason === 'abandon' || removed_order.temporary) && this.get('orders').size() > 0){
368 // when we intentionally remove an unfinished order, and there is another existing one
369 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
371 // when the order was automatically removed after completion,
372 // or when we intentionally delete the only concurrent order
373 this.add_new_order();
377 //creates a new empty order and sets it as the current order
378 add_new_order: function(){
379 var order = new module.Order({pos:this});
380 this.get('orders').add(order);
381 this.set('selectedOrder', order);
384 get_order: function(){
385 return this.get('selectedOrder');
388 //removes the current order
389 delete_current_order: function(){
390 this.get('selectedOrder').destroy({'reason':'abandon'});
393 // saves the order locally and try to send it to the backend.
394 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
395 push_order: function(order) {
399 this.proxy.log('push_order',order.export_as_JSON());
400 this.db.add_order(order.export_as_JSON());
403 var pushed = new $.Deferred();
405 this.flush_mutex.exec(function(){
406 var flushed = self._flush_orders(self.db.get_orders());
408 flushed.always(function(ids){
409 console.log('pushed orders:',ids);
416 // saves the order locally and try to send it to the backend and make an invoice
417 // returns a deferred that succeeds when the order has been posted and successfully generated
418 // an invoice. This method can fail in various ways:
419 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
420 // this error is solved
421 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
422 // the network connection is up
424 push_and_invoice_order: function(order){
426 var invoiced = new $.Deferred();
428 if(!order.get_client()){
429 invoiced.reject('error-no-client');
433 var order_id = this.db.add_order(order.export_as_JSON());
435 this.flush_mutex.exec(function(){
436 var done = new $.Deferred(); // holds the mutex
438 // send the order to the server
439 // we have a 30 seconds timeout on this push.
440 // FIXME: if the server takes more than 30 seconds to accept the order,
441 // the client will believe it wasn't successfully sent, and very bad
442 // things will happen as a duplicate will be sent next time
443 // so we must make sure the server detects and ignores duplicated orders
445 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
447 transfer.fail(function(){
448 invoiced.reject('error-transfer');
452 // on success, get the order id generated by the server
453 transfer.pipe(function(order_server_id){
455 // generate the pdf and download it
456 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
457 active_ids:order_server_id,
471 // wrapper around the _save_to_server that updates the synch status widget
472 _flush_orders: function(orders, options) {
475 this.set('synch',{ state: 'connecting', pending: orders.length});
477 return self._save_to_server(orders, options).done(function (server_ids) {
478 var pending = self.db.get_orders().length;
481 state: pending ? 'connecting' : 'connected',
489 // send an array of orders to the server
490 // available options:
491 // - timeout: timeout for the rpc call in ms
492 // returns a deferred that resolves with the list of
493 // server generated ids for the sent orders
494 _save_to_server: function (orders, options) {
495 if (!orders || !orders.length) {
496 var result = $.Deferred();
501 options = options || {};
504 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
506 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
507 // then we want to notify the user that we are waiting on something )
508 var posOrderModel = new instance.web.Model('pos.order');
509 return posOrderModel.call('create_from_ui',
510 [_.map(orders, function (order) {
511 order.to_invoice = options.to_invoice || false;
516 shadow: !options.to_invoice,
519 ).then(function (server_ids) {
520 _.each(orders, function (order) {
521 self.db.remove_order(order.id);
524 }).fail(function (error, event){
525 if(error.code === 200 ){ // Business Logic Error, not a connection problem
526 self.pos_widget.screen_selector.show_popup('error-traceback',{
527 message: error.data.message,
528 comment: error.data.debug
531 // prevent an error popup creation by the rpc failure
532 // we want the failure to be silent as we send the orders in the background
533 event.preventDefault();
534 console.error('Failed to send orders:', orders);
538 scan_product: function(parsed_code){
540 var selectedOrder = this.get('selectedOrder');
541 if(parsed_code.encoding === 'ean13'){
542 var product = this.db.get_product_by_ean13(parsed_code.base_code);
543 }else if(parsed_code.encoding === 'reference'){
544 var product = this.db.get_product_by_reference(parsed_code.code);
551 if(parsed_code.type === 'price'){
552 selectedOrder.addProduct(product, {price:parsed_code.value});
553 }else if(parsed_code.type === 'weight'){
554 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
555 }else if(parsed_code.type === 'discount'){
556 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
558 selectedOrder.addProduct(product);
564 var orderline_id = 1;
566 // An orderline represent one element of the content of a client's shopping cart.
567 // An orderline contains a product, its quantity, its price, discount. etc.
568 // An Order contains zero or more Orderlines.
569 module.Orderline = Backbone.Model.extend({
570 initialize: function(attr,options){
571 this.pos = options.pos;
572 this.order = options.order;
573 this.product = options.product;
574 this.price = options.product.price;
576 this.quantityStr = '1';
578 this.discountStr = '0';
580 this.selected = false;
581 this.id = orderline_id++;
584 var orderline = new module.Orderline({},{
587 product: this.product,
590 orderline.quantity = this.quantity;
591 orderline.quantityStr = this.quantityStr;
592 orderline.discount = this.discount;
593 orderline.type = this.type;
594 orderline.selected = false;
597 // sets a discount [0,100]%
598 set_discount: function(discount){
599 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
600 this.discount = disc;
601 this.discountStr = '' + disc;
602 this.trigger('change',this);
604 // returns the discount [0,100]%
605 get_discount: function(){
606 return this.discount;
608 get_discount_str: function(){
609 return this.discountStr;
611 get_product_type: function(){
614 // sets the quantity of the product. The quantity will be rounded according to the
615 // product's unity of measure properties. Quantities greater than zero will not get
617 set_quantity: function(quantity){
618 if(quantity === 'remove'){
619 this.order.removeOrderline(this);
622 var quant = parseFloat(quantity) || 0;
623 var unit = this.get_unit();
625 this.quantity = round_pr(quant, unit.rounding);
626 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
628 this.quantity = quant;
629 this.quantityStr = '' + this.quantity;
632 this.trigger('change',this);
634 // return the quantity of product
635 get_quantity: function(){
636 return this.quantity;
638 get_quantity_str: function(){
639 return this.quantityStr;
641 get_quantity_str_with_unit: function(){
642 var unit = this.get_unit();
643 if(unit && !unit.is_unit){
644 return this.quantityStr + ' ' + unit.name;
646 return this.quantityStr;
649 // return the unit of measure of the product
650 get_unit: function(){
651 var unit_id = (this.product.uos_id || this.product.uom_id);
655 unit_id = unit_id[0];
659 return this.pos.units_by_id[unit_id];
661 // return the product of this orderline
662 get_product: function(){
665 // selects or deselects this orderline
666 set_selected: function(selected){
667 this.selected = selected;
668 this.trigger('change',this);
670 // returns true if this orderline is selected
671 is_selected: function(){
672 return this.selected;
674 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
675 // in the orderline. This returns true if it makes sense to merge the two
676 can_be_merged_with: function(orderline){
677 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
679 }else if(!this.get_unit() || !this.get_unit().groupable){
681 }else if(this.get_product_type() !== orderline.get_product_type()){
683 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
685 }else if(this.price !== orderline.price){
691 merge: function(orderline){
692 this.set_quantity(this.get_quantity() + orderline.get_quantity());
694 export_as_JSON: function() {
696 qty: this.get_quantity(),
697 price_unit: this.get_unit_price(),
698 discount: this.get_discount(),
699 product_id: this.get_product().id,
702 //used to create a json of the ticket, to be sent to the printer
703 export_for_printing: function(){
705 quantity: this.get_quantity(),
706 unit_name: this.get_unit().name,
707 price: this.get_unit_price(),
708 discount: this.get_discount(),
709 product_name: this.get_product().name,
710 price_display : this.get_display_price(),
711 price_with_tax : this.get_price_with_tax(),
712 price_without_tax: this.get_price_without_tax(),
714 product_description: this.get_product().description,
715 product_description_sale: this.get_product().description_sale,
718 // changes the base price of the product for this orderline
719 set_unit_price: function(price){
720 this.price = round_di(parseFloat(price) || 0, 2);
721 this.trigger('change',this);
723 get_unit_price: function(){
724 var rounding = this.pos.currency.rounding;
725 return round_pr(this.price,rounding);
727 get_display_price: function(){
728 var rounding = this.pos.currency.rounding;
729 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
731 get_price_without_tax: function(){
732 return this.get_all_prices().priceWithoutTax;
734 get_price_with_tax: function(){
735 return this.get_all_prices().priceWithTax;
738 return this.get_all_prices().tax;
740 get_tax_details: function(){
741 return this.get_all_prices().taxDetails;
743 get_all_prices: function(){
745 var currency_rounding = this.pos.currency.rounding;
746 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
748 var totalNoTax = base;
750 var product = this.get_product();
751 var taxes_ids = product.taxes_id;
752 var taxes = self.pos.taxes;
755 _.each(taxes_ids, function(el) {
756 var tax = _.detect(taxes, function(t) {return t.id === el;});
757 if (tax.price_include) {
759 if (tax.type === "percent") {
760 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
761 } else if (tax.type === "fixed") {
762 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
764 throw "This type of tax is not supported by the point of sale: " + tax.type;
766 tmp = round_pr(tmp,currency_rounding);
769 taxdetail[tax.id] = tmp;
772 if (tax.type === "percent") {
773 tmp = tax.amount * base;
774 } else if (tax.type === "fixed") {
775 tmp = tax.amount * self.get_quantity();
777 throw "This type of tax is not supported by the point of sale: " + tax.type;
779 tmp = round_pr(tmp,currency_rounding);
782 taxdetail[tax.id] = tmp;
786 "priceWithTax": totalTax,
787 "priceWithoutTax": totalNoTax,
789 "taxDetails": taxdetail,
794 module.OrderlineCollection = Backbone.Collection.extend({
795 model: module.Orderline,
798 // Every Paymentline contains a cashregister and an amount of money.
799 module.Paymentline = Backbone.Model.extend({
800 initialize: function(attributes, options) {
802 this.cashregister = options.cashregister;
803 this.name = this.cashregister.journal_id[1];
804 this.selected = false;
806 //sets the amount of money on this payment line
807 set_amount: function(value){
808 this.amount = round_di(parseFloat(value) || 0, 2);
809 this.trigger('change:amount',this);
811 // returns the amount of money on this paymentline
812 get_amount: function(){
815 set_selected: function(selected){
816 if(this.selected !== selected){
817 this.selected = selected;
818 this.trigger('change:selected',this);
821 // returns the associated cashregister
822 //exports as JSON for server communication
823 export_as_JSON: function(){
825 name: instance.web.datetime_to_str(new Date()),
826 statement_id: this.cashregister.id,
827 account_id: this.cashregister.account_id[0],
828 journal_id: this.cashregister.journal_id[0],
829 amount: this.get_amount()
832 //exports as JSON for receipt printing
833 export_for_printing: function(){
835 amount: this.get_amount(),
836 journal: this.cashregister.journal_id[1],
841 module.PaymentlineCollection = Backbone.Collection.extend({
842 model: module.Paymentline,
846 // An order more or less represents the content of a client's shopping cart (the OrderLines)
847 // plus the associated payment information (the Paymentlines)
848 // there is always an active ('selected') order in the Pos, a new one is created
849 // automaticaly once an order is completed and sent to the server.
850 module.Order = Backbone.Model.extend({
851 initialize: function(attributes){
852 Backbone.Model.prototype.initialize.apply(this, arguments);
853 this.uid = this.generateUniqueId();
855 creationDate: new Date(),
856 orderLines: new module.OrderlineCollection(),
857 paymentLines: new module.PaymentlineCollection(),
858 name: "Order " + this.uid,
861 this.pos = attributes.pos;
862 this.selected_orderline = undefined;
863 this.selected_paymentline = undefined;
864 this.screen_data = {}; // see ScreenSelector
865 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
866 this.temporary = attributes.temporary || false;
867 this.sequence_number = this.pos.pos_session.sequence_number++;
870 is_empty: function(){
871 return (this.get('orderLines').models.length === 0);
873 generateUniqueId: function() {
874 return new Date().getTime();
876 addOrderline: function(line){
878 order.removeOrderline(line);
881 this.get('orderLines').add(line);
882 this.selectLine(this.getLastOrderline());
884 addProduct: function(product, options){
885 options = options || {};
886 var attr = JSON.parse(JSON.stringify(product));
889 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
891 if(options.quantity !== undefined){
892 line.set_quantity(options.quantity);
894 if(options.price !== undefined){
895 line.set_unit_price(options.price);
897 if(options.discount !== undefined){
898 line.set_discount(options.discount);
901 var last_orderline = this.getLastOrderline();
902 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
903 last_orderline.merge(line);
905 this.get('orderLines').add(line);
907 this.selectLine(this.getLastOrderline());
909 removeOrderline: function( line ){
910 this.get('orderLines').remove(line);
911 this.selectLine(this.getLastOrderline());
913 getOrderline: function(id){
914 var orderlines = this.get('orderLines').models;
915 for(var i = 0; i < orderlines.length; i++){
916 if(orderlines[i].id === id){
917 return orderlines[i];
922 getLastOrderline: function(){
923 return this.get('orderLines').at(this.get('orderLines').length -1);
925 addPaymentline: function(cashregister) {
926 var paymentLines = this.get('paymentLines');
927 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
928 if(cashregister.journal.type !== 'cash'){
929 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
931 paymentLines.add(newPaymentline);
932 this.selectPaymentline(newPaymentline);
935 removePaymentline: function(line){
936 if(this.selected_paymentline === line){
937 this.selectPaymentline(undefined);
939 this.get('paymentLines').remove(line);
941 getName: function() {
942 return this.get('name');
944 getSubtotal : function(){
945 return (this.get('orderLines')).reduce((function(sum, orderLine){
946 return sum + orderLine.get_display_price();
949 getTotalTaxIncluded: function() {
950 return (this.get('orderLines')).reduce((function(sum, orderLine) {
951 return sum + orderLine.get_price_with_tax();
954 getDiscountTotal: function() {
955 return (this.get('orderLines')).reduce((function(sum, orderLine) {
956 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
959 getTotalTaxExcluded: function() {
960 return (this.get('orderLines')).reduce((function(sum, orderLine) {
961 return sum + orderLine.get_price_without_tax();
965 return (this.get('orderLines')).reduce((function(sum, orderLine) {
966 return sum + orderLine.get_tax();
969 getTaxDetails: function(){
971 var fulldetails = [];
972 var taxes_by_id = {};
974 for(var i = 0; i < this.pos.taxes.length; i++){
975 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
978 this.get('orderLines').each(function(line){
979 var ldetails = line.get_tax_details();
980 for(var id in ldetails){
981 if(ldetails.hasOwnProperty(id)){
982 details[id] = (details[id] || 0) + ldetails[id];
987 for(var id in details){
988 if(details.hasOwnProperty(id)){
989 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
995 getPaidTotal: function() {
996 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
997 return sum + paymentLine.get_amount();
1000 getChange: function() {
1001 return this.getPaidTotal() - this.getTotalTaxIncluded();
1003 getDueLeft: function() {
1004 return this.getTotalTaxIncluded() - this.getPaidTotal();
1006 // sets the type of receipt 'receipt'(default) or 'invoice'
1007 set_receipt_type: function(type){
1008 this.receipt_type = type;
1010 get_receipt_type: function(){
1011 return this.receipt_type;
1013 // the client related to the current order.
1014 set_client: function(client){
1015 this.set('client',client);
1017 get_client: function(){
1018 return this.get('client');
1020 get_client_name: function(){
1021 var client = this.get('client');
1022 return client ? client.name : "";
1024 // the order also stores the screen status, as the PoS supports
1025 // different active screens per order. This method is used to
1026 // store the screen status.
1027 set_screen_data: function(key,value){
1028 if(arguments.length === 2){
1029 this.screen_data[key] = value;
1030 }else if(arguments.length === 1){
1031 for(key in arguments[0]){
1032 this.screen_data[key] = arguments[0][key];
1036 //see set_screen_data
1037 get_screen_data: function(key){
1038 return this.screen_data[key];
1040 // exports a JSON for receipt printing
1041 export_for_printing: function(){
1042 var orderlines = [];
1043 this.get('orderLines').each(function(orderline){
1044 orderlines.push(orderline.export_for_printing());
1047 var paymentlines = [];
1048 this.get('paymentLines').each(function(paymentline){
1049 paymentlines.push(paymentline.export_for_printing());
1051 var client = this.get('client');
1052 var cashier = this.pos.cashier || this.pos.user;
1053 var company = this.pos.company;
1054 var shop = this.pos.shop;
1055 var date = new Date();
1058 orderlines: orderlines,
1059 paymentlines: paymentlines,
1060 subtotal: this.getSubtotal(),
1061 total_with_tax: this.getTotalTaxIncluded(),
1062 total_without_tax: this.getTotalTaxExcluded(),
1063 total_tax: this.getTax(),
1064 total_paid: this.getPaidTotal(),
1065 total_discount: this.getDiscountTotal(),
1066 tax_details: this.getTaxDetails(),
1067 change: this.getChange(),
1068 name : this.getName(),
1069 client: client ? client.name : null ,
1070 invoice_id: null, //TODO
1071 cashier: cashier ? cashier.name : null,
1072 header: this.pos.config.receipt_header || '',
1073 footer: this.pos.config.receipt_footer || '',
1080 year: date.getFullYear(),
1081 month: date.getMonth(),
1082 date: date.getDate(), // day of the month
1083 day: date.getDay(), // day of the week
1084 hour: date.getHours(),
1085 minute: date.getMinutes() ,
1086 isostring: date.toISOString(),
1087 localestring: date.toLocaleString(),
1090 email: company.email,
1091 website: company.website,
1092 company_registry: company.company_registry,
1093 contact_address: company.partner_id[1],
1096 phone: company.phone,
1097 logo: this.pos.company_logo_base64,
1102 currency: this.pos.currency,
1105 export_as_JSON: function() {
1106 var orderLines, paymentLines;
1108 (this.get('orderLines')).each(_.bind( function(item) {
1109 return orderLines.push([0, 0, item.export_as_JSON()]);
1112 (this.get('paymentLines')).each(_.bind( function(item) {
1113 return paymentLines.push([0, 0, item.export_as_JSON()]);
1116 name: this.getName(),
1117 amount_paid: this.getPaidTotal(),
1118 amount_total: this.getTotalTaxIncluded(),
1119 amount_tax: this.getTax(),
1120 amount_return: this.getChange(),
1122 statement_ids: paymentLines,
1123 pos_session_id: this.pos.pos_session.id,
1124 partner_id: this.get_client() ? this.get_client().id : false,
1125 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1127 sequence_number: this.sequence_number,
1130 getSelectedLine: function(){
1131 return this.selected_orderline;
1133 selectLine: function(line){
1135 if(line !== this.selected_orderline){
1136 if(this.selected_orderline){
1137 this.selected_orderline.set_selected(false);
1139 this.selected_orderline = line;
1140 this.selected_orderline.set_selected(true);
1143 this.selected_orderline = undefined;
1146 deselectLine: function(){
1147 if(this.selected_orderline){
1148 this.selected_orderline.set_selected(false);
1149 this.selected_orderline = undefined;
1152 selectPaymentline: function(line){
1153 if(line !== this.selected_paymentline){
1154 if(this.selected_paymentline){
1155 this.selected_paymentline.set_selected(false);
1157 this.selected_paymentline = line;
1158 if(this.selected_paymentline){
1159 this.selected_paymentline.set_selected(true);
1161 this.trigger('change:selected_paymentline',this.selected_paymentline);
1166 module.OrderCollection = Backbone.Collection.extend({
1167 model: module.Order,
1171 The numpad handles both the choice of the property currently being modified
1172 (quantity, price or discount) and the edition of the corresponding numeric value.
1174 module.NumpadState = Backbone.Model.extend({
1179 appendNewChar: function(newChar) {
1181 oldBuffer = this.get('buffer');
1182 if (oldBuffer === '0') {
1186 } else if (oldBuffer === '-0') {
1188 buffer: "-" + newChar
1192 buffer: (this.get('buffer')) + newChar
1195 this.trigger('set_value',this.get('buffer'));
1197 deleteLastChar: function() {
1198 if(this.get('buffer') === ""){
1199 if(this.get('mode') === 'quantity'){
1200 this.trigger('set_value','remove');
1202 this.trigger('set_value',this.get('buffer'));
1205 var newBuffer = this.get('buffer').slice(0,-1) || "";
1206 this.set({ buffer: newBuffer });
1207 this.trigger('set_value',this.get('buffer'));
1210 switchSign: function() {
1212 oldBuffer = this.get('buffer');
1214 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1216 this.trigger('set_value',this.get('buffer'));
1218 changeMode: function(newMode) {
1230 resetValue: function(){
1231 this.set({buffer:'0'});