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(); // used to communicate to the hardware devices via a local proxy
27 this.barcode_reader = new module.BarcodeReader({'pos': this, proxy:this.proxy}); // used to read barcodes
28 this.barcode_reader.connect_to_proxy();
29 this.proxy_queue = new module.JobQueue(); // used to prevent parallels communications to the proxy
30 this.db = new module.PosDB(); // a local database used to search trough products and categories & store pending orders
31 this.debug = jQuery.deparam(jQuery.param.querystring()).debug !== undefined; //debug mode
33 // Business data; loaded from the server at launch
34 this.accounting_precision = 2; //TODO
35 this.company_logo = null;
36 this.company_logo_base64 = '';
44 this.cashregisters = [];
45 this.bankstatements = [];
47 this.pos_session = null;
50 this.units_by_id = {};
51 this.pricelist = null;
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 return self.connect_to_posbox();
84 // releases ressources holds by the model at the end of life of the posmodel
86 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
89 this.barcode_reader.disconnect();
92 connect_to_posbox: function(){
94 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
96 this.pos_widget.loading_skip(function(){
97 self.proxy.stop_searching();
100 return this.proxy.find_proxy({
101 force_ip: self.config.proxy_ip || undefined,
102 progress: function(prog){
103 self.pos_widget.loading_progress(prog);
105 }).then(function(proxies){
106 if(proxies.length > 0){
107 self.proxy.connect(proxies[0]);
112 // helper function to load data from the server
113 fetch: function(model, fields, domain, ctx){
114 this._load_progress = (this._load_progress || 0) + 0.05;
115 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
116 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
118 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
119 load_server_data: function(){
122 var loaded = self.fetch('res.users',['name','company_id'],[['id','=',this.session.uid]])
123 .then(function(users){
124 self.user = users[0];
126 return self.fetch('res.company',
137 [['id','=',users[0].company_id[0]]]);
138 }).then(function(companies){
139 self.company = companies[0];
141 return self.fetch('res.partner',['contact_address'],[['id','=',companies[0].partner_id[0]]]);
142 }).then(function(company_partners){
143 self.company.contact_address = company_partners[0].contact_address;
145 return self.fetch('product.uom', null, null);
146 }).then(function(units){
148 var units_by_id = {};
149 for(var i = 0, len = units.length; i < len; i++){
150 units_by_id[units[i].id] = units[i];
152 self.units_by_id = units_by_id;
154 return self.fetch('res.users', ['name','ean13'], [['ean13', '!=', false]]);
155 }).then(function(users){
158 return self.fetch('res.partner', ['name','ean13'], [['ean13', '!=', false]]);
159 }).then(function(partners){
160 self.partners = partners;
162 return self.fetch('account.tax', ['name','amount', 'price_include', 'type']);
163 }).then(function(taxes){
168 ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at'],
169 [['state', '=', 'opened'], ['user_id', '=', self.session.uid]]
171 }).then(function(pos_sessions){
172 self.pos_session = pos_sessions[0];
176 ['name','journal_ids','warehouse_id','journal_id','pricelist_id',
177 'iface_self_checkout', 'iface_led', 'iface_cashdrawer',
178 'iface_payment_terminal', 'iface_electronic_scale', 'iface_barscan', 'iface_vkeyboard',
179 'iface_print_via_proxy','iface_cashdrawer','iface_invoicing','iface_big_scrollbars',
180 'receipt_header','receipt_footer','proxy_ip',
181 'state','sequence_id','session_ids'],
182 [['id','=', self.pos_session.config_id[0]]]
184 }).then(function(configs){
185 self.config = configs[0];
187 return self.fetch('stock.warehouse',[],[['id','=', self.config.warehouse_id[0]]]);
188 }).then(function(shops){
189 self.shop = shops[0];
191 return self.fetch('product.pricelist',['currency_id'],[['id','=',self.config.pricelist_id[0]]]);
192 }).then(function(pricelists){
193 self.pricelist = pricelists[0];
195 return self.fetch('res.currency',['symbol','position','rounding','accuracy'],[['id','=',self.pricelist.currency_id[0]]]);
196 }).then(function(currencies){
197 self.currency = currencies[0];
200 return (new instance.web.Model('decimal.precision')).call('get_precision',[['Account']]);
201 }).then(function(precision){
202 self.accounting_precision = precision;
203 console.log("PRECISION",precision);
205 return self.fetch('product.packaging',['ean','product_id']);
206 }).then(function(packagings){
207 self.db.add_packagings(packagings);
209 return self.fetch('pos.category', ['id','name','parent_id','child_id','image'])
210 }).then(function(categories){
211 self.db.add_categories(categories);
215 ['name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
216 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description'],
217 [['sale_ok','=',true],['available_in_pos','=',true]],
218 {pricelist: self.pricelist.id} // context for price
220 }).then(function(products){
221 self.db.add_products(products);
224 'account.bank.statement',
225 ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
226 [['state','=','open'],['pos_session_id', '=', self.pos_session.id]]
228 }).then(function(bankstatements){
230 _.each(bankstatements,function(statement) {
231 journals.push(statement.journal_id[0])
233 self.bankstatements = bankstatements;
234 return self.fetch('account.journal', undefined, [['id','in', journals]]);
235 }).then(function(journals){
236 self.journals = journals;
238 // associate the bank statements with their journals.
239 var bankstatements = self.bankstatements
240 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
241 for(var j = 0, jlen = journals.length; j < jlen; j++){
242 if(bankstatements[i].journal_id[0] === journals[j].id){
243 bankstatements[i].journal = journals[j];
244 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
248 self.cashregisters = bankstatements;
250 // Load the company Logo
252 self.company_logo = new Image();
253 self.company_logo.crossOrigin = 'anonymous';
254 var logo_loaded = new $.Deferred();
255 self.company_logo.onload = function(){
256 var c = document.createElement('canvas');
257 c.width = self.company_logo.width;
258 c.height = self.company_logo.height;
259 var ctx = c.getContext('2d');
260 ctx.drawImage(self.company_logo,0,0);
261 self.company_logo_base64 = c.toDataURL();
262 logo_loaded.resolve();
264 self.company_logo.onerror = function(){
265 logo_loaded.reject();
267 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
275 // this is called when an order is removed from the order collection. It ensures that there is always an existing
276 // order and a valid selected order
277 on_removed_order: function(removed_order,index,reason){
278 if(reason === 'abandon' && this.get('orders').size() > 0){
279 // when we intentionally remove an unfinished order, and there is another existing one
280 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
282 // when the order was automatically removed after completion,
283 // or when we intentionally delete the only concurrent order
284 this.add_new_order();
288 //creates a new empty order and sets it as the current order
289 add_new_order: function(){
290 var order = new module.Order({pos:this});
291 this.get('orders').add(order);
292 this.set('selectedOrder', order);
295 //removes the current order
296 delete_current_order: function(){
297 this.get('selectedOrder').destroy({'reason':'abandon'});
300 // saves the order locally and try to send it to the backend.
301 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
302 push_order: function(order) {
304 this.proxy.log('push_order',order.export_as_JSON());
305 var order_id = this.db.add_order(order.export_as_JSON());
306 var pushed = new $.Deferred();
308 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
310 this.flush_mutex.exec(function(){
311 var flushed = self._flush_all_orders();
313 flushed.always(function(){
322 // saves the order locally and try to send it to the backend and make an invoice
323 // returns a deferred that succeeds when the order has been posted and successfully generated
324 // an invoice. This method can fail in various ways:
325 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
326 // this error is solved
327 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
328 // the network connection is up
330 push_and_invoice_order: function(order){
332 var invoiced = new $.Deferred();
334 if(!order.get_client()){
335 invoiced.reject('error-no-client');
339 var order_id = this.db.add_order(order.export_as_JSON());
341 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
343 this.flush_mutex.exec(function(){
344 var done = new $.Deferred(); // holds the mutex
346 // send the order to the server
347 // we have a 30 seconds timeout on this push.
348 // FIXME: if the server takes more than 30 seconds to accept the order,
349 // the client will believe it wasn't successfully sent, and very bad
350 // things will happen as a duplicate will be sent next time
351 // so we must make sure the server detects and ignores duplicated orders
353 var transfer = self._flush_order(order_id, {timeout:30000, to_invoice:true});
355 transfer.fail(function(){
356 invoiced.reject('error-transfer');
360 // on success, get the order id generated by the server
361 transfer.pipe(function(order_server_id){
362 // generate the pdf and download it
363 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
364 active_ids:order_server_id,
377 // attemps to send all pending orders ( stored in the pos_db ) to the server,
378 // and remove the successfully sent ones from the db once
379 // it has been confirmed that they have been sent correctly.
382 var flushed = new $.Deferred();
384 this.flush_mutex.exec(function(){
385 var done = new $.Deferred();
387 self._flush_all_orders()
388 .done( function(){ flushed.resolve();})
389 .fail( function(){ flushed.reject(); })
390 .always(function(){ done.resolve(); });
398 // attempts to send the locally stored order of id 'order_id'
399 // the sending is asynchronous and can take some time to decide if it is successful or not
400 // it is therefore important to only call this method from inside a mutex
401 // this method returns a deferred indicating wether the sending was successful or not
402 // there is a timeout parameter which is set to 2 seconds by default.
403 _flush_order: function(order_id, options){
405 options = options || {};
406 timeout = typeof options.timeout === 'number' ? options.timeout : 7500;
408 this.set('synch',{state:'connecting', pending: this.get('synch').pending});
410 var order = this.db.get_order(order_id);
411 order.to_invoice = options.to_invoice || false;
414 // flushing a non existing order always fails
415 return (new $.Deferred()).reject();
418 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
419 // then we want to notify the user that we are waiting on something )
420 var rpc = (new instance.web.Model('pos.order')).call('create_from_ui',[[order]],undefined,{shadow: !options.to_invoice, timeout:timeout});
422 rpc.fail(function(unused,event){
423 // prevent an error popup creation by the rpc failure
424 // we want the failure to be silent as we send the orders in the background
425 event.preventDefault();
426 console.error('Failed to send order:',order);
430 self.db.remove_order(order_id);
431 var pending = self.db.get_orders().length;
432 self.set('synch',{state: pending ? 'connecting' : 'connected', pending:pending});
438 // attempts to send all the locally stored orders. As with _flush_order, it should only be
439 // called from within a mutex.
440 // this method returns a deferred that always succeeds when all orders have been tried to be sent,
441 // even if none of them could actually be sent.
442 _flush_all_orders: function(){
444 var orders = this.db.get_orders();
445 var tried_all = new $.Deferred();
447 function rec_flush(index){
448 if(index < orders.length){
449 self._flush_order(orders[index].id).always(function(){
461 scan_product: function(parsed_code){
463 var selectedOrder = this.get('selectedOrder');
464 if(parsed_code.encoding === 'ean13'){
465 var product = this.db.get_product_by_ean13(parsed_code.base_code);
466 }else if(parsed_code.encoding === 'reference'){
467 var product = this.db.get_product_by_reference(parsed_code.code);
474 if(parsed_code.type === 'price'){
475 selectedOrder.addProduct(product, {price:parsed_code.value});
476 }else if(parsed_code.type === 'weight'){
477 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
479 selectedOrder.addProduct(product);
485 // An orderline represent one element of the content of a client's shopping cart.
486 // An orderline contains a product, its quantity, its price, discount. etc.
487 // An Order contains zero or more Orderlines.
488 module.Orderline = Backbone.Model.extend({
489 initialize: function(attr,options){
490 this.pos = options.pos;
491 this.order = options.order;
492 this.product = options.product;
493 this.price = options.product.price;
495 this.quantityStr = '1';
497 this.discountStr = '0';
499 this.selected = false;
501 // sets a discount [0,100]%
502 set_discount: function(discount){
503 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
504 this.discount = disc;
505 this.discountStr = '' + disc;
506 this.trigger('change',this);
508 // returns the discount [0,100]%
509 get_discount: function(){
510 return this.discount;
512 get_discount_str: function(){
513 return this.discountStr;
515 get_product_type: function(){
518 // sets the quantity of the product. The quantity will be rounded according to the
519 // product's unity of measure properties. Quantities greater than zero will not get
521 set_quantity: function(quantity){
522 if(quantity === 'remove'){
523 this.order.removeOrderline(this);
526 var quant = Math.max(parseFloat(quantity) || 0, 0);
527 var unit = this.get_unit();
529 this.quantity = Math.max(unit.rounding, round_pr(quant, unit.rounding));
530 this.quantityStr = this.quantity.toFixed(Math.max(0,Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10))));
532 this.quantity = quant;
533 this.quantityStr = '' + this.quantity;
536 this.trigger('change',this);
538 // return the quantity of product
539 get_quantity: function(){
540 return this.quantity;
542 get_quantity_str: function(){
543 return this.quantityStr;
545 get_quantity_str_with_unit: function(){
546 var unit = this.get_unit();
547 if(unit && unit.name !== 'Unit(s)'){
548 return this.quantityStr + ' ' + unit.name;
550 return this.quantityStr;
553 // return the unit of measure of the product
554 get_unit: function(){
555 var unit_id = (this.product.uos_id || this.product.uom_id);
559 unit_id = unit_id[0];
563 return this.pos.units_by_id[unit_id];
565 // return the product of this orderline
566 get_product: function(){
569 // selects or deselects this orderline
570 set_selected: function(selected){
571 this.selected = selected;
572 this.trigger('change',this);
574 // returns true if this orderline is selected
575 is_selected: function(){
576 return this.selected;
578 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
579 // in the orderline. This returns true if it makes sense to merge the two
580 can_be_merged_with: function(orderline){
581 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
583 }else if(this.get_product_type() !== orderline.get_product_type()){
585 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
587 }else if(this.price !== orderline.price){
593 merge: function(orderline){
594 this.set_quantity(this.get_quantity() + orderline.get_quantity());
596 export_as_JSON: function() {
598 qty: this.get_quantity(),
599 price_unit: this.get_unit_price(),
600 discount: this.get_discount(),
601 product_id: this.get_product().id,
604 //used to create a json of the ticket, to be sent to the printer
605 export_for_printing: function(){
607 quantity: this.get_quantity(),
608 unit_name: this.get_unit().name,
609 price: this.get_unit_price(),
610 discount: this.get_discount(),
611 product_name: this.get_product().name,
612 price_display : this.get_display_price(),
613 price_with_tax : this.get_price_with_tax(),
614 price_without_tax: this.get_price_without_tax(),
616 product_description: this.get_product().description,
617 product_description_sale: this.get_product().description_sale,
620 // changes the base price of the product for this orderline
621 set_unit_price: function(price){
622 this.price = round_di(parseFloat(price) || 0, 2);
623 this.trigger('change',this);
625 get_unit_price: function(){
626 var rounding = this.pos.currency.rounding;
627 return round_pr(this.price,rounding);
629 get_display_price: function(){
630 var rounding = this.pos.currency.rounding;
631 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
633 get_price_without_tax: function(){
634 return this.get_all_prices().priceWithoutTax;
636 get_price_with_tax: function(){
637 return this.get_all_prices().priceWithTax;
640 return this.get_all_prices().tax;
642 get_tax_details: function(){
643 return this.get_all_prices().taxDetails;
645 get_all_prices: function(){
647 var currency_rounding = this.pos.currency.rounding;
648 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
650 var totalNoTax = base;
652 var product = this.get_product();
653 var taxes_ids = product.taxes_id;
654 var taxes = self.pos.taxes;
657 _.each(taxes_ids, function(el) {
658 var tax = _.detect(taxes, function(t) {return t.id === el;});
659 if (tax.price_include) {
661 if (tax.type === "percent") {
662 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
663 } else if (tax.type === "fixed") {
664 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
666 throw "This type of tax is not supported by the point of sale: " + tax.type;
668 tmp = round_pr(tmp,currency_rounding);
671 taxdetail[tax.id] = tmp;
674 if (tax.type === "percent") {
675 tmp = tax.amount * base;
676 } else if (tax.type === "fixed") {
677 tmp = tax.amount * self.get_quantity();
679 throw "This type of tax is not supported by the point of sale: " + tax.type;
681 tmp = round_pr(tmp,currency_rounding);
684 taxdetail[tax.id] = tmp;
688 "priceWithTax": totalTax,
689 "priceWithoutTax": totalNoTax,
691 "taxDetails": taxdetail,
696 module.OrderlineCollection = Backbone.Collection.extend({
697 model: module.Orderline,
700 // Every Paymentline contains a cashregister and an amount of money.
701 module.Paymentline = Backbone.Model.extend({
702 initialize: function(attributes, options) {
704 this.cashregister = options.cashregister;
705 this.name = this.cashregister.journal_id[1];
706 this.selected = false;
708 //sets the amount of money on this payment line
709 set_amount: function(value){
710 this.amount = round_di(parseFloat(value) || 0, 2);
711 this.trigger('change:amount',this);
713 // returns the amount of money on this paymentline
714 get_amount: function(){
717 set_selected: function(selected){
718 if(this.selected !== selected){
719 this.selected = selected;
720 this.trigger('change:selected',this);
723 // returns the associated cashregister
724 //exports as JSON for server communication
725 export_as_JSON: function(){
727 name: instance.web.datetime_to_str(new Date()),
728 statement_id: this.cashregister.id,
729 account_id: this.cashregister.account_id[0],
730 journal_id: this.cashregister.journal_id[0],
731 amount: this.get_amount()
734 //exports as JSON for receipt printing
735 export_for_printing: function(){
737 amount: this.get_amount(),
738 journal: this.cashregister.journal_id[1],
743 module.PaymentlineCollection = Backbone.Collection.extend({
744 model: module.Paymentline,
748 // An order more or less represents the content of a client's shopping cart (the OrderLines)
749 // plus the associated payment information (the Paymentlines)
750 // there is always an active ('selected') order in the Pos, a new one is created
751 // automaticaly once an order is completed and sent to the server.
752 module.Order = Backbone.Model.extend({
753 initialize: function(attributes){
754 Backbone.Model.prototype.initialize.apply(this, arguments);
755 this.uid = this.generateUniqueId();
757 creationDate: new Date(),
758 orderLines: new module.OrderlineCollection(),
759 paymentLines: new module.PaymentlineCollection(),
760 name: "Order " + this.uid,
763 this.pos = attributes.pos;
764 this.selected_orderline = undefined;
765 this.selected_paymentline = undefined;
766 this.screen_data = {}; // see ScreenSelector
767 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
770 generateUniqueId: function() {
771 return new Date().getTime();
773 addProduct: function(product, options){
774 options = options || {};
775 var attr = JSON.parse(JSON.stringify(product));
778 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
780 if(options.quantity !== undefined){
781 line.set_quantity(options.quantity);
783 if(options.price !== undefined){
784 line.set_unit_price(options.price);
787 var last_orderline = this.getLastOrderline();
788 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
789 last_orderline.merge(line);
791 this.get('orderLines').add(line);
793 this.selectLine(this.getLastOrderline());
795 removeOrderline: function( line ){
796 this.get('orderLines').remove(line);
797 this.selectLine(this.getLastOrderline());
799 getLastOrderline: function(){
800 return this.get('orderLines').at(this.get('orderLines').length -1);
802 addPaymentline: function(cashregister) {
803 var paymentLines = this.get('paymentLines');
804 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
805 if(cashregister.journal.type !== 'cash'){
806 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
808 paymentLines.add(newPaymentline);
809 this.selectPaymentline(newPaymentline);
812 removePaymentline: function(line){
813 if(this.selected_paymentline === line){
814 this.selectPaymentline(undefined);
816 this.get('paymentLines').remove(line);
818 getName: function() {
819 return this.get('name');
821 getSubtotal : function(){
822 return (this.get('orderLines')).reduce((function(sum, orderLine){
823 return sum + orderLine.get_display_price();
826 getTotalTaxIncluded: function() {
827 return (this.get('orderLines')).reduce((function(sum, orderLine) {
828 return sum + orderLine.get_price_with_tax();
831 getDiscountTotal: function() {
832 return (this.get('orderLines')).reduce((function(sum, orderLine) {
833 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
836 getTotalTaxExcluded: function() {
837 return (this.get('orderLines')).reduce((function(sum, orderLine) {
838 return sum + orderLine.get_price_without_tax();
842 return (this.get('orderLines')).reduce((function(sum, orderLine) {
843 return sum + orderLine.get_tax();
846 getTaxDetails: function(){
848 var fulldetails = [];
849 var taxes_by_id = {};
851 for(var i = 0; i < this.pos.taxes.length; i++){
852 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
855 this.get('orderLines').each(function(line){
856 var ldetails = line.get_tax_details();
857 for(var id in ldetails){
858 if(ldetails.hasOwnProperty(id)){
859 details[id] = (details[id] || 0) + ldetails[id];
864 for(var id in details){
865 if(details.hasOwnProperty(id)){
866 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
872 getPaidTotal: function() {
873 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
874 return sum + paymentLine.get_amount();
877 getChange: function() {
878 return this.getPaidTotal() - this.getTotalTaxIncluded();
880 getDueLeft: function() {
881 return this.getTotalTaxIncluded() - this.getPaidTotal();
883 // sets the type of receipt 'receipt'(default) or 'invoice'
884 set_receipt_type: function(type){
885 this.receipt_type = type;
887 get_receipt_type: function(){
888 return this.receipt_type;
890 // the client related to the current order.
891 set_client: function(client){
892 this.set('client',client);
894 get_client: function(){
895 return this.get('client');
897 get_client_name: function(){
898 var client = this.get('client');
899 return client ? client.name : "";
901 // the order also stores the screen status, as the PoS supports
902 // different active screens per order. This method is used to
903 // store the screen status.
904 set_screen_data: function(key,value){
905 if(arguments.length === 2){
906 this.screen_data[key] = value;
907 }else if(arguments.length === 1){
908 for(key in arguments[0]){
909 this.screen_data[key] = arguments[0][key];
913 //see set_screen_data
914 get_screen_data: function(key){
915 return this.screen_data[key];
917 // exports a JSON for receipt printing
918 export_for_printing: function(){
920 this.get('orderLines').each(function(orderline){
921 orderlines.push(orderline.export_for_printing());
924 var paymentlines = [];
925 this.get('paymentLines').each(function(paymentline){
926 paymentlines.push(paymentline.export_for_printing());
928 var client = this.get('client');
929 var cashier = this.pos.cashier || this.pos.user;
930 var company = this.pos.company;
931 var shop = this.pos.shop;
932 var date = new Date();
935 orderlines: orderlines,
936 paymentlines: paymentlines,
937 subtotal: this.getSubtotal(),
938 total_with_tax: this.getTotalTaxIncluded(),
939 total_without_tax: this.getTotalTaxExcluded(),
940 total_tax: this.getTax(),
941 total_paid: this.getPaidTotal(),
942 total_discount: this.getDiscountTotal(),
943 tax_details: this.getTaxDetails(),
944 change: this.getChange(),
945 name : this.getName(),
946 client: client ? client.name : null ,
947 invoice_id: null, //TODO
948 cashier: cashier ? cashier.name : null,
949 header: this.pos.config.receipt_header || '',
950 footer: this.pos.config.receipt_footer || '',
957 year: date.getFullYear(),
958 month: date.getMonth(),
959 date: date.getDate(), // day of the month
960 day: date.getDay(), // day of the week
961 hour: date.getHours(),
962 minute: date.getMinutes() ,
963 isostring: date.toISOString(),
966 email: company.email,
967 website: company.website,
968 company_registry: company.company_registry,
969 contact_address: company.contact_address,
972 phone: company.phone,
973 logo: this.pos.company_logo_base64,
978 currency: this.pos.currency,
981 export_as_JSON: function() {
982 var orderLines, paymentLines;
984 (this.get('orderLines')).each(_.bind( function(item) {
985 return orderLines.push([0, 0, item.export_as_JSON()]);
988 (this.get('paymentLines')).each(_.bind( function(item) {
989 return paymentLines.push([0, 0, item.export_as_JSON()]);
992 name: this.getName(),
993 amount_paid: this.getPaidTotal(),
994 amount_total: this.getTotalTaxIncluded(),
995 amount_tax: this.getTax(),
996 amount_return: this.getChange(),
998 statement_ids: paymentLines,
999 pos_session_id: this.pos.pos_session.id,
1000 partner_id: this.get_client() ? this.get_client().id : false,
1001 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1005 getSelectedLine: function(){
1006 return this.selected_orderline;
1008 selectLine: function(line){
1010 if(line !== this.selected_orderline){
1011 if(this.selected_orderline){
1012 this.selected_orderline.set_selected(false);
1014 this.selected_orderline = line;
1015 this.selected_orderline.set_selected(true);
1018 this.selected_orderline = undefined;
1021 deselectLine: function(){
1022 if(this.selected_orderline){
1023 this.selected_orderline.set_selected(false);
1024 this.selected_orderline = undefined;
1027 selectPaymentline: function(line){
1028 if(line !== this.selected_paymentline){
1029 if(this.selected_paymentline){
1030 this.selected_paymentline.set_selected(false);
1032 this.selected_paymentline = line;
1033 if(this.selected_paymentline){
1034 this.selected_paymentline.set_selected(true);
1036 this.trigger('change:selected_paymentline',this.selected_paymentline);
1041 module.OrderCollection = Backbone.Collection.extend({
1042 model: module.Order,
1046 The numpad handles both the choice of the property currently being modified
1047 (quantity, price or discount) and the edition of the corresponding numeric value.
1049 module.NumpadState = Backbone.Model.extend({
1054 appendNewChar: function(newChar) {
1056 oldBuffer = this.get('buffer');
1057 if (oldBuffer === '0') {
1061 } else if (oldBuffer === '-0') {
1063 buffer: "-" + newChar
1067 buffer: (this.get('buffer')) + newChar
1070 this.trigger('set_value',this.get('buffer'));
1072 deleteLastChar: function() {
1073 if(this.get('buffer') === ""){
1074 if(this.get('mode') === 'quantity'){
1075 this.trigger('set_value','remove');
1077 this.trigger('set_value',this.get('buffer'));
1080 var newBuffer = this.get('buffer').slice(0,-1) || "";
1081 this.set({ buffer: newBuffer });
1082 this.trigger('set_value',this.get('buffer'));
1085 switchSign: function() {
1087 oldBuffer = this.get('buffer');
1089 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1091 this.trigger('set_value',this.get('buffer'));
1093 changeMode: function(newMode) {
1105 resetValue: function(){
1106 this.set({buffer:'0'});