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_tmpl_id']);
208 }).then(function(packagings){
209 self.db.add_packagings(packagings);
211 return self.fetch('pos.category', ['id','name','parent_id','child_id','image']);
212 }).then(function(categories){
213 self.db.add_categories(categories);
217 ['name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code', 'variants',
218 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
220 [['sale_ok','=',true],['available_in_pos','=',true]],
221 {pricelist: self.pricelist.id} // context for price
223 }).then(function(products){
224 self.db.add_products(products);
227 'account.bank.statement',
228 ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
229 [['state','=','open'],['pos_session_id', '=', self.pos_session.id]]
231 }).then(function(bankstatements){
233 _.each(bankstatements,function(statement) {
234 journals.push(statement.journal_id[0]);
236 self.bankstatements = bankstatements;
237 return self.fetch('account.journal', undefined, [['id','in', journals]]);
238 }).then(function(journals){
239 self.journals = journals;
241 // associate the bank statements with their journals.
242 var bankstatements = self.bankstatements;
243 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
244 for(var j = 0, jlen = journals.length; j < jlen; j++){
245 if(bankstatements[i].journal_id[0] === journals[j].id){
246 bankstatements[i].journal = journals[j];
247 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
251 self.cashregisters = bankstatements;
253 // Load the company Logo
255 self.company_logo = new Image();
256 self.company_logo.crossOrigin = 'anonymous';
257 var logo_loaded = new $.Deferred();
258 self.company_logo.onload = function(){
259 var img = self.company_logo;
261 var targetwidth = 300;
263 if( img.width !== targetwidth ){
264 ratio = targetwidth / img.width;
266 if( img.height * ratio > maxheight ){
267 ratio = maxheight / img.height;
269 var width = Math.floor(img.width * ratio);
270 var height = Math.floor(img.height * ratio);
271 var c = document.createElement('canvas');
274 var ctx = c.getContext('2d');
275 ctx.drawImage(self.company_logo,0,0, width, height);
277 self.company_logo_base64 = c.toDataURL();
278 window.logo64 = self.company_logo_base64;
279 logo_loaded.resolve();
281 self.company_logo.onerror = function(){
282 logo_loaded.reject();
284 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
292 // this is called when an order is removed from the order collection. It ensures that there is always an existing
293 // order and a valid selected order
294 on_removed_order: function(removed_order,index,reason){
295 if(reason === 'abandon' && this.get('orders').size() > 0){
296 // when we intentionally remove an unfinished order, and there is another existing one
297 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
299 // when the order was automatically removed after completion,
300 // or when we intentionally delete the only concurrent order
301 this.add_new_order();
305 //creates a new empty order and sets it as the current order
306 add_new_order: function(){
307 var order = new module.Order({pos:this});
308 this.get('orders').add(order);
309 this.set('selectedOrder', order);
312 //removes the current order
313 delete_current_order: function(){
314 this.get('selectedOrder').destroy({'reason':'abandon'});
317 // saves the order locally and try to send it to the backend.
318 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
319 push_order: function(order) {
321 this.proxy.log('push_order',order.export_as_JSON());
322 var order_id = this.db.add_order(order.export_as_JSON());
323 var pushed = new $.Deferred();
325 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
327 this.flush_mutex.exec(function(){
328 var flushed = self._flush_all_orders();
330 flushed.always(function(){
339 // saves the order locally and try to send it to the backend and make an invoice
340 // returns a deferred that succeeds when the order has been posted and successfully generated
341 // an invoice. This method can fail in various ways:
342 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
343 // this error is solved
344 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
345 // the network connection is up
347 push_and_invoice_order: function(order){
349 var invoiced = new $.Deferred();
351 if(!order.get_client()){
352 invoiced.reject('error-no-client');
356 var order_id = this.db.add_order(order.export_as_JSON());
358 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
360 this.flush_mutex.exec(function(){
361 var done = new $.Deferred(); // holds the mutex
363 // send the order to the server
364 // we have a 30 seconds timeout on this push.
365 // FIXME: if the server takes more than 30 seconds to accept the order,
366 // the client will believe it wasn't successfully sent, and very bad
367 // things will happen as a duplicate will be sent next time
368 // so we must make sure the server detects and ignores duplicated orders
370 var transfer = self._flush_order(order_id, {timeout:30000, to_invoice:true});
372 transfer.fail(function(){
373 invoiced.reject('error-transfer');
377 // on success, get the order id generated by the server
378 transfer.pipe(function(order_server_id){
379 // generate the pdf and download it
380 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
381 active_ids:order_server_id,
394 // attemps to send all pending orders ( stored in the pos_db ) to the server,
395 // and remove the successfully sent ones from the db once
396 // it has been confirmed that they have been sent correctly.
399 var flushed = new $.Deferred();
401 this.flush_mutex.exec(function(){
402 var done = new $.Deferred();
404 self._flush_all_orders()
405 .done( function(){ flushed.resolve();})
406 .fail( function(){ flushed.reject(); })
407 .always(function(){ done.resolve(); });
415 // attempts to send the locally stored order of id 'order_id'
416 // the sending is asynchronous and can take some time to decide if it is successful or not
417 // it is therefore important to only call this method from inside a mutex
418 // this method returns a deferred indicating wether the sending was successful or not
419 // there is a timeout parameter which is set to 2 seconds by default.
420 _flush_order: function( order_id, options) {
421 return this._flush_all_orders([this.db.get_order(order_id)], options);
424 // attempts to send all the locally stored orders. As with _flush_order, it should only be
425 // called from within a mutex.
426 // this method returns a deferred that always succeeds when all orders have been tried to be sent,
427 // even if none of them could actually be sent.
428 _flush_all_orders: function () {
432 pending: self.get('synch').pending
434 return self._save_to_server(self.db.get_orders()).done(function () {
435 var pending = self.db.get_orders().length;
437 state: pending ? 'connecting' : 'connected',
443 // send an array of orders to the server
444 // available options:
445 // - timeout: timeout for the rpc call in ms
446 _save_to_server: function (orders, options) {
447 if (!orders || !orders.length) {
448 var result = $.Deferred();
453 options = options || {};
456 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
458 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
459 // then we want to notify the user that we are waiting on something )
460 var posOrderModel = new instance.web.Model('pos.order');
461 return posOrderModel.call('create_from_ui',
462 [_.map(orders, function (order) {
463 order.to_invoice = options.to_invoice || false;
468 shadow: !options.to_invoice,
472 _.each(orders, function (order) {
473 self.db.remove_order(order.id);
475 }).fail(function (unused, event){
476 // prevent an error popup creation by the rpc failure
477 // we want the failure to be silent as we send the orders in the background
478 event.preventDefault();
479 console.error('Failed to send orders:', orders);
483 scan_product: function(parsed_code){
485 var selectedOrder = this.get('selectedOrder');
486 if(parsed_code.encoding === 'ean13'){
487 var product = this.db.get_product_by_ean13(parsed_code.base_code);
488 }else if(parsed_code.encoding === 'reference'){
489 var product = this.db.get_product_by_reference(parsed_code.code);
496 if(parsed_code.type === 'price'){
497 selectedOrder.addProduct(product, {price:parsed_code.value});
498 }else if(parsed_code.type === 'weight'){
499 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
501 selectedOrder.addProduct(product);
507 // An orderline represent one element of the content of a client's shopping cart.
508 // An orderline contains a product, its quantity, its price, discount. etc.
509 // An Order contains zero or more Orderlines.
510 module.Orderline = Backbone.Model.extend({
511 initialize: function(attr,options){
512 this.pos = options.pos;
513 this.order = options.order;
514 this.product = options.product;
515 this.price = options.product.price;
517 this.quantityStr = '1';
519 this.discountStr = '0';
521 this.selected = false;
523 // sets a discount [0,100]%
524 set_discount: function(discount){
525 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
526 this.discount = disc;
527 this.discountStr = '' + disc;
528 this.trigger('change',this);
530 // returns the discount [0,100]%
531 get_discount: function(){
532 return this.discount;
534 get_discount_str: function(){
535 return this.discountStr;
537 get_product_type: function(){
540 // sets the quantity of the product. The quantity will be rounded according to the
541 // product's unity of measure properties. Quantities greater than zero will not get
543 set_quantity: function(quantity){
544 if(quantity === 'remove'){
545 this.order.removeOrderline(this);
548 var quant = parseFloat(quantity) || 0;
549 var unit = this.get_unit();
551 this.quantity = round_pr(quant, unit.rounding);
552 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
554 this.quantity = quant;
555 this.quantityStr = '' + this.quantity;
558 this.trigger('change',this);
560 // return the quantity of product
561 get_quantity: function(){
562 return this.quantity;
564 get_quantity_str: function(){
565 return this.quantityStr;
567 get_quantity_str_with_unit: function(){
568 var unit = this.get_unit();
569 if(unit && unit.name !== 'Unit(s)'){
570 return this.quantityStr + ' ' + unit.name;
572 return this.quantityStr;
575 // return the unit of measure of the product
576 get_unit: function(){
577 var unit_id = (this.product.uos_id || this.product.uom_id);
581 unit_id = unit_id[0];
585 return this.pos.units_by_id[unit_id];
587 // return the product of this orderline
588 get_product: function(){
591 // selects or deselects this orderline
592 set_selected: function(selected){
593 this.selected = selected;
594 this.trigger('change',this);
596 // returns true if this orderline is selected
597 is_selected: function(){
598 return this.selected;
600 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
601 // in the orderline. This returns true if it makes sense to merge the two
602 can_be_merged_with: function(orderline){
603 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
605 }else if(this.get_product_type() !== orderline.get_product_type()){
607 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
609 }else if(this.price !== orderline.price){
615 merge: function(orderline){
616 this.set_quantity(this.get_quantity() + orderline.get_quantity());
618 export_as_JSON: function() {
620 qty: this.get_quantity(),
621 price_unit: this.get_unit_price(),
622 discount: this.get_discount(),
623 product_id: this.get_product().id,
626 //used to create a json of the ticket, to be sent to the printer
627 export_for_printing: function(){
629 quantity: this.get_quantity(),
630 unit_name: this.get_unit().name,
631 price: this.get_unit_price(),
632 discount: this.get_discount(),
633 product_name: this.get_product().name,
634 price_display : this.get_display_price(),
635 price_with_tax : this.get_price_with_tax(),
636 price_without_tax: this.get_price_without_tax(),
638 product_description: this.get_product().description,
639 product_description_sale: this.get_product().description_sale,
642 // changes the base price of the product for this orderline
643 set_unit_price: function(price){
644 this.price = round_di(parseFloat(price) || 0, 2);
645 this.trigger('change',this);
647 get_unit_price: function(){
648 var rounding = this.pos.currency.rounding;
649 return round_pr(this.price,rounding);
651 get_display_price: function(){
652 var rounding = this.pos.currency.rounding;
653 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
655 get_price_without_tax: function(){
656 return this.get_all_prices().priceWithoutTax;
658 get_price_with_tax: function(){
659 return this.get_all_prices().priceWithTax;
662 return this.get_all_prices().tax;
664 get_tax_details: function(){
665 return this.get_all_prices().taxDetails;
667 get_all_prices: function(){
669 var currency_rounding = this.pos.currency.rounding;
670 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
672 var totalNoTax = base;
674 var product = this.get_product();
675 var taxes_ids = product.taxes_id;
676 var taxes = self.pos.taxes;
679 _.each(taxes_ids, function(el) {
680 var tax = _.detect(taxes, function(t) {return t.id === el;});
681 if (tax.price_include) {
683 if (tax.type === "percent") {
684 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
685 } else if (tax.type === "fixed") {
686 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
688 throw "This type of tax is not supported by the point of sale: " + tax.type;
690 tmp = round_pr(tmp,currency_rounding);
693 taxdetail[tax.id] = tmp;
696 if (tax.type === "percent") {
697 tmp = tax.amount * base;
698 } else if (tax.type === "fixed") {
699 tmp = tax.amount * self.get_quantity();
701 throw "This type of tax is not supported by the point of sale: " + tax.type;
703 tmp = round_pr(tmp,currency_rounding);
706 taxdetail[tax.id] = tmp;
710 "priceWithTax": totalTax,
711 "priceWithoutTax": totalNoTax,
713 "taxDetails": taxdetail,
718 module.OrderlineCollection = Backbone.Collection.extend({
719 model: module.Orderline,
722 // Every Paymentline contains a cashregister and an amount of money.
723 module.Paymentline = Backbone.Model.extend({
724 initialize: function(attributes, options) {
726 this.cashregister = options.cashregister;
727 this.name = this.cashregister.journal_id[1];
728 this.selected = false;
730 //sets the amount of money on this payment line
731 set_amount: function(value){
732 this.amount = round_di(parseFloat(value) || 0, 2);
733 this.trigger('change:amount',this);
735 // returns the amount of money on this paymentline
736 get_amount: function(){
739 set_selected: function(selected){
740 if(this.selected !== selected){
741 this.selected = selected;
742 this.trigger('change:selected',this);
745 // returns the associated cashregister
746 //exports as JSON for server communication
747 export_as_JSON: function(){
749 name: instance.web.datetime_to_str(new Date()),
750 statement_id: this.cashregister.id,
751 account_id: this.cashregister.account_id[0],
752 journal_id: this.cashregister.journal_id[0],
753 amount: this.get_amount()
756 //exports as JSON for receipt printing
757 export_for_printing: function(){
759 amount: this.get_amount(),
760 journal: this.cashregister.journal_id[1],
765 module.PaymentlineCollection = Backbone.Collection.extend({
766 model: module.Paymentline,
770 // An order more or less represents the content of a client's shopping cart (the OrderLines)
771 // plus the associated payment information (the Paymentlines)
772 // there is always an active ('selected') order in the Pos, a new one is created
773 // automaticaly once an order is completed and sent to the server.
774 module.Order = Backbone.Model.extend({
775 initialize: function(attributes){
776 Backbone.Model.prototype.initialize.apply(this, arguments);
777 this.uid = this.generateUniqueId();
779 creationDate: new Date(),
780 orderLines: new module.OrderlineCollection(),
781 paymentLines: new module.PaymentlineCollection(),
782 name: "Order " + this.uid,
785 this.pos = attributes.pos;
786 this.selected_orderline = undefined;
787 this.selected_paymentline = undefined;
788 this.screen_data = {}; // see ScreenSelector
789 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
792 generateUniqueId: function() {
793 return new Date().getTime();
795 addProduct: function(product, options){
796 options = options || {};
797 var attr = JSON.parse(JSON.stringify(product));
800 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
802 if(options.quantity !== undefined){
803 line.set_quantity(options.quantity);
805 if(options.price !== undefined){
806 line.set_unit_price(options.price);
809 var last_orderline = this.getLastOrderline();
810 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
811 last_orderline.merge(line);
813 this.get('orderLines').add(line);
815 this.selectLine(this.getLastOrderline());
817 removeOrderline: function( line ){
818 this.get('orderLines').remove(line);
819 this.selectLine(this.getLastOrderline());
821 getLastOrderline: function(){
822 return this.get('orderLines').at(this.get('orderLines').length -1);
824 addPaymentline: function(cashregister) {
825 var paymentLines = this.get('paymentLines');
826 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
827 if(cashregister.journal.type !== 'cash'){
828 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
830 paymentLines.add(newPaymentline);
831 this.selectPaymentline(newPaymentline);
834 removePaymentline: function(line){
835 if(this.selected_paymentline === line){
836 this.selectPaymentline(undefined);
838 this.get('paymentLines').remove(line);
840 getName: function() {
841 return this.get('name');
843 getSubtotal : function(){
844 return (this.get('orderLines')).reduce((function(sum, orderLine){
845 return sum + orderLine.get_display_price();
848 getTotalTaxIncluded: function() {
849 return (this.get('orderLines')).reduce((function(sum, orderLine) {
850 return sum + orderLine.get_price_with_tax();
853 getDiscountTotal: function() {
854 return (this.get('orderLines')).reduce((function(sum, orderLine) {
855 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
858 getTotalTaxExcluded: function() {
859 return (this.get('orderLines')).reduce((function(sum, orderLine) {
860 return sum + orderLine.get_price_without_tax();
864 return (this.get('orderLines')).reduce((function(sum, orderLine) {
865 return sum + orderLine.get_tax();
868 getTaxDetails: function(){
870 var fulldetails = [];
871 var taxes_by_id = {};
873 for(var i = 0; i < this.pos.taxes.length; i++){
874 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
877 this.get('orderLines').each(function(line){
878 var ldetails = line.get_tax_details();
879 for(var id in ldetails){
880 if(ldetails.hasOwnProperty(id)){
881 details[id] = (details[id] || 0) + ldetails[id];
886 for(var id in details){
887 if(details.hasOwnProperty(id)){
888 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
894 getPaidTotal: function() {
895 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
896 return sum + paymentLine.get_amount();
899 getChange: function() {
900 return this.getPaidTotal() - this.getTotalTaxIncluded();
902 getDueLeft: function() {
903 return this.getTotalTaxIncluded() - this.getPaidTotal();
905 // sets the type of receipt 'receipt'(default) or 'invoice'
906 set_receipt_type: function(type){
907 this.receipt_type = type;
909 get_receipt_type: function(){
910 return this.receipt_type;
912 // the client related to the current order.
913 set_client: function(client){
914 this.set('client',client);
916 get_client: function(){
917 return this.get('client');
919 get_client_name: function(){
920 var client = this.get('client');
921 return client ? client.name : "";
923 // the order also stores the screen status, as the PoS supports
924 // different active screens per order. This method is used to
925 // store the screen status.
926 set_screen_data: function(key,value){
927 if(arguments.length === 2){
928 this.screen_data[key] = value;
929 }else if(arguments.length === 1){
930 for(key in arguments[0]){
931 this.screen_data[key] = arguments[0][key];
935 //see set_screen_data
936 get_screen_data: function(key){
937 return this.screen_data[key];
939 // exports a JSON for receipt printing
940 export_for_printing: function(){
942 this.get('orderLines').each(function(orderline){
943 orderlines.push(orderline.export_for_printing());
946 var paymentlines = [];
947 this.get('paymentLines').each(function(paymentline){
948 paymentlines.push(paymentline.export_for_printing());
950 var client = this.get('client');
951 var cashier = this.pos.cashier || this.pos.user;
952 var company = this.pos.company;
953 var date = new Date();
956 orderlines: orderlines,
957 paymentlines: paymentlines,
958 subtotal: this.getSubtotal(),
959 total_with_tax: this.getTotalTaxIncluded(),
960 total_without_tax: this.getTotalTaxExcluded(),
961 total_tax: this.getTax(),
962 total_paid: this.getPaidTotal(),
963 total_discount: this.getDiscountTotal(),
964 tax_details: this.getTaxDetails(),
965 change: this.getChange(),
966 name : this.getName(),
967 client: client ? client.name : null ,
968 invoice_id: null, //TODO
969 cashier: cashier ? cashier.name : null,
970 header: this.pos.config.receipt_header || '',
971 footer: this.pos.config.receipt_footer || '',
978 year: date.getFullYear(),
979 month: date.getMonth(),
980 date: date.getDate(), // day of the month
981 day: date.getDay(), // day of the week
982 hour: date.getHours(),
983 minute: date.getMinutes() ,
984 isostring: date.toISOString(),
985 localestring: date.toLocaleString(),
988 email: company.email,
989 website: company.website,
990 company_registry: company.company_registry,
991 contact_address: company.partner_id[1],
994 phone: company.phone,
995 logo: this.pos.company_logo_base64,
997 currency: this.pos.currency,
1000 export_as_JSON: function() {
1001 var orderLines, paymentLines;
1003 (this.get('orderLines')).each(_.bind( function(item) {
1004 return orderLines.push([0, 0, item.export_as_JSON()]);
1007 (this.get('paymentLines')).each(_.bind( function(item) {
1008 return paymentLines.push([0, 0, item.export_as_JSON()]);
1011 name: this.getName(),
1012 amount_paid: this.getPaidTotal(),
1013 amount_total: this.getTotalTaxIncluded(),
1014 amount_tax: this.getTax(),
1015 amount_return: this.getChange(),
1017 statement_ids: paymentLines,
1018 pos_session_id: this.pos.pos_session.id,
1019 partner_id: this.get_client() ? this.get_client().id : false,
1020 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1024 getSelectedLine: function(){
1025 return this.selected_orderline;
1027 selectLine: function(line){
1029 if(line !== this.selected_orderline){
1030 if(this.selected_orderline){
1031 this.selected_orderline.set_selected(false);
1033 this.selected_orderline = line;
1034 this.selected_orderline.set_selected(true);
1037 this.selected_orderline = undefined;
1040 deselectLine: function(){
1041 if(this.selected_orderline){
1042 this.selected_orderline.set_selected(false);
1043 this.selected_orderline = undefined;
1046 selectPaymentline: function(line){
1047 if(line !== this.selected_paymentline){
1048 if(this.selected_paymentline){
1049 this.selected_paymentline.set_selected(false);
1051 this.selected_paymentline = line;
1052 if(this.selected_paymentline){
1053 this.selected_paymentline.set_selected(true);
1055 this.trigger('change:selected_paymentline',this.selected_paymentline);
1060 module.OrderCollection = Backbone.Collection.extend({
1061 model: module.Order,
1065 The numpad handles both the choice of the property currently being modified
1066 (quantity, price or discount) and the edition of the corresponding numeric value.
1068 module.NumpadState = Backbone.Model.extend({
1073 appendNewChar: function(newChar) {
1075 oldBuffer = this.get('buffer');
1076 if (oldBuffer === '0') {
1080 } else if (oldBuffer === '-0') {
1082 buffer: "-" + newChar
1086 buffer: (this.get('buffer')) + newChar
1089 this.trigger('set_value',this.get('buffer'));
1091 deleteLastChar: function() {
1092 if(this.get('buffer') === ""){
1093 if(this.get('mode') === 'quantity'){
1094 this.trigger('set_value','remove');
1096 this.trigger('set_value',this.get('buffer'));
1099 var newBuffer = this.get('buffer').slice(0,-1) || "";
1100 this.set({ buffer: newBuffer });
1101 this.trigger('set_value',this.get('buffer'));
1104 switchSign: function() {
1105 console.log('switchsing');
1107 oldBuffer = this.get('buffer');
1109 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1111 this.trigger('set_value',this.get('buffer'));
1113 changeMode: function(newMode) {
1125 resetValue: function(){
1126 this.set({buffer:'0'});