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}); // 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 = '';
42 this.cashregisters = [];
43 this.bankstatements = [];
45 this.pos_session = null;
48 this.units_by_id = {};
49 this.pricelist = null;
50 window.posmodel = this;
52 // these dynamic attributes can be watched for change by other models or widgets
54 'synch': { state:'connected', pending:0 },
55 'orders': new module.OrderCollection(),
56 'selectedOrder': null,
59 this.bind('change:synch',function(pos,synch){
60 clearTimeout(self.synch_timeout);
61 self.synch_timeout = setTimeout(function(){
62 if(synch.state !== 'disconnected' && synch.pending > 0){
63 self.set('synch',{state:'disconnected', pending:synch.pending});
68 this.get('orders').bind('remove', function(order,_unused_,options){
69 self.on_removed_order(order,options.index,options.reason);
72 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
73 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
74 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
75 this.ready = this.load_server_data()
77 if(self.config.use_proxy){
78 return self.connect_to_proxy();
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();
90 this.barcode_reader.disconnect_from_proxy();
92 connect_to_proxy: function(){
94 var done = new $.Deferred();
95 this.barcode_reader.disconnect_from_proxy();
96 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
97 this.pos_widget.loading_skip(function(){
98 self.proxy.stop_searching();
100 this.proxy.autoconnect({
101 force_ip: self.config.proxy_ip || undefined,
102 progress: function(prog){
103 self.pos_widget.loading_progress(prog);
106 if(self.config.iface_scan_via_proxy){
107 self.barcode_reader.connect_to_proxy();
109 }).always(function(){
115 // helper function to load data from the server
116 fetch: function(model, fields, domain, ctx){
117 this._load_progress = (this._load_progress || 0) + 0.05;
118 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
119 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
121 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
122 load_server_data: function(){
125 var loaded = self.fetch('res.users',['name','company_id'],[['id','=',this.session.uid]])
126 .then(function(users){
127 self.user = users[0];
129 return self.fetch('res.company',
140 [['id','=',users[0].company_id[0]]],
141 {show_address_only: true});
142 }).then(function(companies){
143 self.company = companies[0];
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','journal_id','pricelist_id',
177 'iface_self_checkout', 'iface_led', 'iface_cashdrawer',
178 'iface_payment_terminal', 'iface_electronic_scale', 'iface_barscan',
179 'iface_vkeyboard','iface_print_via_proxy','iface_scan_via_proxy',
180 'iface_cashdrawer','iface_invoicing','iface_big_scrollbars',
181 'receipt_header','receipt_footer','proxy_ip',
182 'state','sequence_id','session_ids'],
183 [['id','=', self.pos_session.config_id[0]]]
185 }).then(function(configs){
186 self.config = configs[0];
187 self.config.use_proxy = self.config.iface_payment_terminal ||
188 self.config.iface_electronic_scale ||
189 self.config.iface_print_via_proxy ||
190 self.config.iface_scan_via_proxy ||
191 self.config.iface_cashdrawer;
193 return self.fetch('product.pricelist',['currency_id'],[['id','=',self.config.pricelist_id[0]]]);
194 }).then(function(pricelists){
195 self.pricelist = pricelists[0];
197 return self.fetch('res.currency',['symbol','position','rounding','accuracy'],[['id','=',self.pricelist.currency_id[0]]]);
198 }).then(function(currencies){
199 self.currency = currencies[0];
202 return (new instance.web.Model('decimal.precision')).call('get_precision',[['Account']]);
203 }).then(function(precision){
204 self.accounting_precision = precision;
205 console.log("PRECISION",precision);
207 return self.fetch('product.packaging',['ean','product_id']);
208 }).then(function(packagings){
209 self.db.add_packagings(packagings);
211 return self.fetch('product.public.category', ['id','name','parent_id','child_id','image'])
212 }).then(function(categories){
213 self.db.add_categories(categories);
217 ['name', 'list_price','price','public_categ_id', 'taxes_id', 'ean13', 'default_code', 'variants',
218 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description'],
219 [['sale_ok','=',true],['available_in_pos','=',true]],
220 {pricelist: self.pricelist.id} // context for price
222 }).then(function(products){
223 self.db.add_products(products);
226 'account.bank.statement',
227 ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
228 [['state','=','open'],['pos_session_id', '=', self.pos_session.id]]
230 }).then(function(bankstatements){
232 _.each(bankstatements,function(statement) {
233 journals.push(statement.journal_id[0])
235 self.bankstatements = bankstatements;
236 return self.fetch('account.journal', undefined, [['id','in', journals]]);
237 }).then(function(journals){
238 self.journals = journals;
240 // associate the bank statements with their journals.
241 var bankstatements = self.bankstatements
242 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
243 for(var j = 0, jlen = journals.length; j < jlen; j++){
244 if(bankstatements[i].journal_id[0] === journals[j].id){
245 bankstatements[i].journal = journals[j];
246 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
250 self.cashregisters = bankstatements;
252 // Load the company Logo
254 self.company_logo = new Image();
255 self.company_logo.crossOrigin = 'anonymous';
256 var logo_loaded = new $.Deferred();
257 self.company_logo.onload = function(){
258 var img = self.company_logo;
260 var targetwidth = 300;
262 if( img.width !== targetwidth ){
263 ratio = targetwidth / img.width;
265 if( img.height * ratio > maxheight ){
266 ratio = maxheight / img.height;
268 var width = Math.floor(img.width * ratio);
269 var height = Math.floor(img.height * ratio);
270 var c = document.createElement('canvas');
273 var ctx = c.getContext('2d');
274 ctx.drawImage(self.company_logo,0,0, width, height);
276 self.company_logo_base64 = c.toDataURL();
277 window.logo64 = self.company_logo_base64;
278 logo_loaded.resolve();
280 self.company_logo.onerror = function(){
281 logo_loaded.reject();
283 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
291 // this is called when an order is removed from the order collection. It ensures that there is always an existing
292 // order and a valid selected order
293 on_removed_order: function(removed_order,index,reason){
294 if(reason === 'abandon' && this.get('orders').size() > 0){
295 // when we intentionally remove an unfinished order, and there is another existing one
296 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
298 // when the order was automatically removed after completion,
299 // or when we intentionally delete the only concurrent order
300 this.add_new_order();
304 //creates a new empty order and sets it as the current order
305 add_new_order: function(){
306 var order = new module.Order({pos:this});
307 this.get('orders').add(order);
308 this.set('selectedOrder', order);
311 //removes the current order
312 delete_current_order: function(){
313 this.get('selectedOrder').destroy({'reason':'abandon'});
316 // saves the order locally and try to send it to the backend.
317 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
318 push_order: function(order) {
320 this.proxy.log('push_order',order.export_as_JSON());
321 var order_id = this.db.add_order(order.export_as_JSON());
322 var pushed = new $.Deferred();
324 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
326 this.flush_mutex.exec(function(){
327 var flushed = self._flush_all_orders();
329 flushed.always(function(){
338 // saves the order locally and try to send it to the backend and make an invoice
339 // returns a deferred that succeeds when the order has been posted and successfully generated
340 // an invoice. This method can fail in various ways:
341 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
342 // this error is solved
343 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
344 // the network connection is up
346 push_and_invoice_order: function(order){
348 var invoiced = new $.Deferred();
350 if(!order.get_client()){
351 invoiced.reject('error-no-client');
355 var order_id = this.db.add_order(order.export_as_JSON());
357 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
359 this.flush_mutex.exec(function(){
360 var done = new $.Deferred(); // holds the mutex
362 // send the order to the server
363 // we have a 30 seconds timeout on this push.
364 // FIXME: if the server takes more than 30 seconds to accept the order,
365 // the client will believe it wasn't successfully sent, and very bad
366 // things will happen as a duplicate will be sent next time
367 // so we must make sure the server detects and ignores duplicated orders
369 var transfer = self._flush_order(order_id, {timeout:30000, to_invoice:true});
371 transfer.fail(function(){
372 invoiced.reject('error-transfer');
376 // on success, get the order id generated by the server
377 transfer.pipe(function(order_server_id){
378 // generate the pdf and download it
379 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
380 active_ids:order_server_id,
393 // attemps to send all pending orders ( stored in the pos_db ) to the server,
394 // and remove the successfully sent ones from the db once
395 // it has been confirmed that they have been sent correctly.
398 var flushed = new $.Deferred();
400 this.flush_mutex.exec(function(){
401 var done = new $.Deferred();
403 self._flush_all_orders()
404 .done( function(){ flushed.resolve();})
405 .fail( function(){ flushed.reject(); })
406 .always(function(){ done.resolve(); });
414 // attempts to send the locally stored order of id 'order_id'
415 // the sending is asynchronous and can take some time to decide if it is successful or not
416 // it is therefore important to only call this method from inside a mutex
417 // this method returns a deferred indicating wether the sending was successful or not
418 // there is a timeout parameter which is set to 2 seconds by default.
419 _flush_order: function( order_id, options) {
420 return this._flush_all_orders([this.db.get_order(order_id)], options);
423 // attempts to send all the locally stored orders. As with _flush_order, it should only be
424 // called from within a mutex.
425 // this method returns a deferred that always succeeds when all orders have been tried to be sent,
426 // even if none of them could actually be sent.
427 _flush_all_orders: function () {
431 pending: self.get('synch').pending
433 return self._save_to_server(self.db.get_orders()).done(function () {
434 var pending = self.db.get_orders().length;
436 state: pending ? 'connecting' : 'connected',
442 // send an array of orders to the server
443 // available options:
444 // - timeout: timeout for the rpc call in ms
445 _save_to_server: function (orders, options) {
446 if (!orders || !orders.length) {
447 var result = $.Deferred();
452 options = options || {};
455 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
457 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
458 // then we want to notify the user that we are waiting on something )
459 var posOrderModel = new instance.web.Model('pos.order');
460 return posOrderModel.call('create_from_ui',
461 [_.map(orders, function (order) {
462 order.to_invoice = options.to_invoice || false;
467 shadow: !options.to_invoice,
471 _.each(orders, function (order) {
472 self.db.remove_order(order.id);
474 }).fail(function (unused, event){
475 // prevent an error popup creation by the rpc failure
476 // we want the failure to be silent as we send the orders in the background
477 event.preventDefault();
478 console.error('Failed to send orders:', orders);
482 scan_product: function(parsed_code){
484 var selectedOrder = this.get('selectedOrder');
485 if(parsed_code.encoding === 'ean13'){
486 var product = this.db.get_product_by_ean13(parsed_code.base_code);
487 }else if(parsed_code.encoding === 'reference'){
488 var product = this.db.get_product_by_reference(parsed_code.code);
495 if(parsed_code.type === 'price'){
496 selectedOrder.addProduct(product, {price:parsed_code.value});
497 }else if(parsed_code.type === 'weight'){
498 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
500 selectedOrder.addProduct(product);
506 // An orderline represent one element of the content of a client's shopping cart.
507 // An orderline contains a product, its quantity, its price, discount. etc.
508 // An Order contains zero or more Orderlines.
509 module.Orderline = Backbone.Model.extend({
510 initialize: function(attr,options){
511 this.pos = options.pos;
512 this.order = options.order;
513 this.product = options.product;
514 this.price = options.product.price;
516 this.quantityStr = '1';
518 this.discountStr = '0';
520 this.selected = false;
522 // sets a discount [0,100]%
523 set_discount: function(discount){
524 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
525 this.discount = disc;
526 this.discountStr = '' + disc;
527 this.trigger('change',this);
529 // returns the discount [0,100]%
530 get_discount: function(){
531 return this.discount;
533 get_discount_str: function(){
534 return this.discountStr;
536 get_product_type: function(){
539 // sets the quantity of the product. The quantity will be rounded according to the
540 // product's unity of measure properties. Quantities greater than zero will not get
542 set_quantity: function(quantity){
543 if(quantity === 'remove'){
544 this.order.removeOrderline(this);
547 var quant = parseFloat(quantity) || 0;
548 var unit = this.get_unit();
550 this.quantity = round_pr(quant, unit.rounding);
551 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
553 this.quantity = quant;
554 this.quantityStr = '' + this.quantity;
557 this.trigger('change',this);
559 // return the quantity of product
560 get_quantity: function(){
561 return this.quantity;
563 get_quantity_str: function(){
564 return this.quantityStr;
566 get_quantity_str_with_unit: function(){
567 var unit = this.get_unit();
568 if(unit && unit.name !== 'Unit(s)'){
569 return this.quantityStr + ' ' + unit.name;
571 return this.quantityStr;
574 // return the unit of measure of the product
575 get_unit: function(){
576 var unit_id = (this.product.uos_id || this.product.uom_id);
580 unit_id = unit_id[0];
584 return this.pos.units_by_id[unit_id];
586 // return the product of this orderline
587 get_product: function(){
590 // selects or deselects this orderline
591 set_selected: function(selected){
592 this.selected = selected;
593 this.trigger('change',this);
595 // returns true if this orderline is selected
596 is_selected: function(){
597 return this.selected;
599 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
600 // in the orderline. This returns true if it makes sense to merge the two
601 can_be_merged_with: function(orderline){
602 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
604 }else if(this.get_product_type() !== orderline.get_product_type()){
606 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
608 }else if(this.price !== orderline.price){
614 merge: function(orderline){
615 this.set_quantity(this.get_quantity() + orderline.get_quantity());
617 export_as_JSON: function() {
619 qty: this.get_quantity(),
620 price_unit: this.get_unit_price(),
621 discount: this.get_discount(),
622 product_id: this.get_product().id,
625 //used to create a json of the ticket, to be sent to the printer
626 export_for_printing: function(){
628 quantity: this.get_quantity(),
629 unit_name: this.get_unit().name,
630 price: this.get_unit_price(),
631 discount: this.get_discount(),
632 product_name: this.get_product().name,
633 price_display : this.get_display_price(),
634 price_with_tax : this.get_price_with_tax(),
635 price_without_tax: this.get_price_without_tax(),
637 product_description: this.get_product().description,
638 product_description_sale: this.get_product().description_sale,
641 // changes the base price of the product for this orderline
642 set_unit_price: function(price){
643 this.price = round_di(parseFloat(price) || 0, 2);
644 this.trigger('change',this);
646 get_unit_price: function(){
647 var rounding = this.pos.currency.rounding;
648 return round_pr(this.price,rounding);
650 get_display_price: function(){
651 var rounding = this.pos.currency.rounding;
652 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
654 get_price_without_tax: function(){
655 return this.get_all_prices().priceWithoutTax;
657 get_price_with_tax: function(){
658 return this.get_all_prices().priceWithTax;
661 return this.get_all_prices().tax;
663 get_tax_details: function(){
664 return this.get_all_prices().taxDetails;
666 get_all_prices: function(){
668 var currency_rounding = this.pos.currency.rounding;
669 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
671 var totalNoTax = base;
673 var product = this.get_product();
674 var taxes_ids = product.taxes_id;
675 var taxes = self.pos.taxes;
678 _.each(taxes_ids, function(el) {
679 var tax = _.detect(taxes, function(t) {return t.id === el;});
680 if (tax.price_include) {
682 if (tax.type === "percent") {
683 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
684 } else if (tax.type === "fixed") {
685 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
687 throw "This type of tax is not supported by the point of sale: " + tax.type;
689 tmp = round_pr(tmp,currency_rounding);
692 taxdetail[tax.id] = tmp;
695 if (tax.type === "percent") {
696 tmp = tax.amount * base;
697 } else if (tax.type === "fixed") {
698 tmp = tax.amount * self.get_quantity();
700 throw "This type of tax is not supported by the point of sale: " + tax.type;
702 tmp = round_pr(tmp,currency_rounding);
705 taxdetail[tax.id] = tmp;
709 "priceWithTax": totalTax,
710 "priceWithoutTax": totalNoTax,
712 "taxDetails": taxdetail,
717 module.OrderlineCollection = Backbone.Collection.extend({
718 model: module.Orderline,
721 // Every Paymentline contains a cashregister and an amount of money.
722 module.Paymentline = Backbone.Model.extend({
723 initialize: function(attributes, options) {
725 this.cashregister = options.cashregister;
726 this.name = this.cashregister.journal_id[1];
727 this.selected = false;
729 //sets the amount of money on this payment line
730 set_amount: function(value){
731 this.amount = round_di(parseFloat(value) || 0, 2);
732 this.trigger('change:amount',this);
734 // returns the amount of money on this paymentline
735 get_amount: function(){
738 set_selected: function(selected){
739 if(this.selected !== selected){
740 this.selected = selected;
741 this.trigger('change:selected',this);
744 // returns the associated cashregister
745 //exports as JSON for server communication
746 export_as_JSON: function(){
748 name: instance.web.datetime_to_str(new Date()),
749 statement_id: this.cashregister.id,
750 account_id: this.cashregister.account_id[0],
751 journal_id: this.cashregister.journal_id[0],
752 amount: this.get_amount()
755 //exports as JSON for receipt printing
756 export_for_printing: function(){
758 amount: this.get_amount(),
759 journal: this.cashregister.journal_id[1],
764 module.PaymentlineCollection = Backbone.Collection.extend({
765 model: module.Paymentline,
769 // An order more or less represents the content of a client's shopping cart (the OrderLines)
770 // plus the associated payment information (the Paymentlines)
771 // there is always an active ('selected') order in the Pos, a new one is created
772 // automaticaly once an order is completed and sent to the server.
773 module.Order = Backbone.Model.extend({
774 initialize: function(attributes){
775 Backbone.Model.prototype.initialize.apply(this, arguments);
776 this.uid = this.generateUniqueId();
778 creationDate: new Date(),
779 orderLines: new module.OrderlineCollection(),
780 paymentLines: new module.PaymentlineCollection(),
781 name: "Order " + this.uid,
784 this.pos = attributes.pos;
785 this.selected_orderline = undefined;
786 this.selected_paymentline = undefined;
787 this.screen_data = {}; // see ScreenSelector
788 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
791 generateUniqueId: function() {
792 return new Date().getTime();
794 addProduct: function(product, options){
795 options = options || {};
796 var attr = JSON.parse(JSON.stringify(product));
799 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
801 if(options.quantity !== undefined){
802 line.set_quantity(options.quantity);
804 if(options.price !== undefined){
805 line.set_unit_price(options.price);
808 var last_orderline = this.getLastOrderline();
809 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
810 last_orderline.merge(line);
812 this.get('orderLines').add(line);
814 this.selectLine(this.getLastOrderline());
816 removeOrderline: function( line ){
817 this.get('orderLines').remove(line);
818 this.selectLine(this.getLastOrderline());
820 getLastOrderline: function(){
821 return this.get('orderLines').at(this.get('orderLines').length -1);
823 addPaymentline: function(cashregister) {
824 var paymentLines = this.get('paymentLines');
825 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
826 if(cashregister.journal.type !== 'cash'){
827 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
829 paymentLines.add(newPaymentline);
830 this.selectPaymentline(newPaymentline);
833 removePaymentline: function(line){
834 if(this.selected_paymentline === line){
835 this.selectPaymentline(undefined);
837 this.get('paymentLines').remove(line);
839 getName: function() {
840 return this.get('name');
842 getSubtotal : function(){
843 return (this.get('orderLines')).reduce((function(sum, orderLine){
844 return sum + orderLine.get_display_price();
847 getTotalTaxIncluded: function() {
848 return (this.get('orderLines')).reduce((function(sum, orderLine) {
849 return sum + orderLine.get_price_with_tax();
852 getDiscountTotal: function() {
853 return (this.get('orderLines')).reduce((function(sum, orderLine) {
854 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
857 getTotalTaxExcluded: function() {
858 return (this.get('orderLines')).reduce((function(sum, orderLine) {
859 return sum + orderLine.get_price_without_tax();
863 return (this.get('orderLines')).reduce((function(sum, orderLine) {
864 return sum + orderLine.get_tax();
867 getTaxDetails: function(){
869 var fulldetails = [];
870 var taxes_by_id = {};
872 for(var i = 0; i < this.pos.taxes.length; i++){
873 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
876 this.get('orderLines').each(function(line){
877 var ldetails = line.get_tax_details();
878 for(var id in ldetails){
879 if(ldetails.hasOwnProperty(id)){
880 details[id] = (details[id] || 0) + ldetails[id];
885 for(var id in details){
886 if(details.hasOwnProperty(id)){
887 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
893 getPaidTotal: function() {
894 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
895 return sum + paymentLine.get_amount();
898 getChange: function() {
899 return this.getPaidTotal() - this.getTotalTaxIncluded();
901 getDueLeft: function() {
902 return this.getTotalTaxIncluded() - this.getPaidTotal();
904 // sets the type of receipt 'receipt'(default) or 'invoice'
905 set_receipt_type: function(type){
906 this.receipt_type = type;
908 get_receipt_type: function(){
909 return this.receipt_type;
911 // the client related to the current order.
912 set_client: function(client){
913 this.set('client',client);
915 get_client: function(){
916 return this.get('client');
918 get_client_name: function(){
919 var client = this.get('client');
920 return client ? client.name : "";
922 // the order also stores the screen status, as the PoS supports
923 // different active screens per order. This method is used to
924 // store the screen status.
925 set_screen_data: function(key,value){
926 if(arguments.length === 2){
927 this.screen_data[key] = value;
928 }else if(arguments.length === 1){
929 for(key in arguments[0]){
930 this.screen_data[key] = arguments[0][key];
934 //see set_screen_data
935 get_screen_data: function(key){
936 return this.screen_data[key];
938 // exports a JSON for receipt printing
939 export_for_printing: function(){
941 this.get('orderLines').each(function(orderline){
942 orderlines.push(orderline.export_for_printing());
945 var paymentlines = [];
946 this.get('paymentLines').each(function(paymentline){
947 paymentlines.push(paymentline.export_for_printing());
949 var client = this.get('client');
950 var cashier = this.pos.cashier || this.pos.user;
951 var company = this.pos.company;
952 var date = new Date();
955 orderlines: orderlines,
956 paymentlines: paymentlines,
957 subtotal: this.getSubtotal(),
958 total_with_tax: this.getTotalTaxIncluded(),
959 total_without_tax: this.getTotalTaxExcluded(),
960 total_tax: this.getTax(),
961 total_paid: this.getPaidTotal(),
962 total_discount: this.getDiscountTotal(),
963 tax_details: this.getTaxDetails(),
964 change: this.getChange(),
965 name : this.getName(),
966 client: client ? client.name : null ,
967 invoice_id: null, //TODO
968 cashier: cashier ? cashier.name : null,
969 header: this.pos.config.receipt_header || '',
970 footer: this.pos.config.receipt_footer || '',
977 year: date.getFullYear(),
978 month: date.getMonth(),
979 date: date.getDate(), // day of the month
980 day: date.getDay(), // day of the week
981 hour: date.getHours(),
982 minute: date.getMinutes() ,
983 isostring: date.toISOString(),
984 localestring: date.toLocaleString(),
987 email: company.email,
988 website: company.website,
989 company_registry: company.company_registry,
990 contact_address: company.partner_id[1],
993 phone: company.phone,
994 logo: this.pos.company_logo_base64,
996 currency: this.pos.currency,
999 export_as_JSON: function() {
1000 var orderLines, paymentLines;
1002 (this.get('orderLines')).each(_.bind( function(item) {
1003 return orderLines.push([0, 0, item.export_as_JSON()]);
1006 (this.get('paymentLines')).each(_.bind( function(item) {
1007 return paymentLines.push([0, 0, item.export_as_JSON()]);
1010 name: this.getName(),
1011 amount_paid: this.getPaidTotal(),
1012 amount_total: this.getTotalTaxIncluded(),
1013 amount_tax: this.getTax(),
1014 amount_return: this.getChange(),
1016 statement_ids: paymentLines,
1017 pos_session_id: this.pos.pos_session.id,
1018 partner_id: this.get_client() ? this.get_client().id : false,
1019 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1023 getSelectedLine: function(){
1024 return this.selected_orderline;
1026 selectLine: function(line){
1028 if(line !== this.selected_orderline){
1029 if(this.selected_orderline){
1030 this.selected_orderline.set_selected(false);
1032 this.selected_orderline = line;
1033 this.selected_orderline.set_selected(true);
1036 this.selected_orderline = undefined;
1039 deselectLine: function(){
1040 if(this.selected_orderline){
1041 this.selected_orderline.set_selected(false);
1042 this.selected_orderline = undefined;
1045 selectPaymentline: function(line){
1046 if(line !== this.selected_paymentline){
1047 if(this.selected_paymentline){
1048 this.selected_paymentline.set_selected(false);
1050 this.selected_paymentline = line;
1051 if(this.selected_paymentline){
1052 this.selected_paymentline.set_selected(true);
1054 this.trigger('change:selected_paymentline',this.selected_paymentline);
1059 module.OrderCollection = Backbone.Collection.extend({
1060 model: module.Order,
1064 The numpad handles both the choice of the property currently being modified
1065 (quantity, price or discount) and the edition of the corresponding numeric value.
1067 module.NumpadState = Backbone.Model.extend({
1072 appendNewChar: function(newChar) {
1074 oldBuffer = this.get('buffer');
1075 if (oldBuffer === '0') {
1079 } else if (oldBuffer === '-0') {
1081 buffer: "-" + newChar
1085 buffer: (this.get('buffer')) + newChar
1088 this.trigger('set_value',this.get('buffer'));
1090 deleteLastChar: function() {
1091 if(this.get('buffer') === ""){
1092 if(this.get('mode') === 'quantity'){
1093 this.trigger('set_value','remove');
1095 this.trigger('set_value',this.get('buffer'));
1098 var newBuffer = this.get('buffer').slice(0,-1) || "";
1099 this.set({ buffer: newBuffer });
1100 this.trigger('set_value',this.get('buffer'));
1103 switchSign: function() {
1104 console.log('switchsing');
1106 oldBuffer = this.get('buffer');
1108 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1110 this.trigger('set_value',this.get('buffer'));
1112 changeMode: function(newMode) {
1124 resetValue: function(){
1125 this.set({buffer:'0'});