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('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'],
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 var logo_loaded = new $.Deferred();
256 self.company_logo.onload = function(){
257 var img = self.company_logo;
259 var targetwidth = 300;
261 if( img.width !== targetwidth ){
262 ratio = targetwidth / img.width;
264 if( img.height * ratio > maxheight ){
265 ratio = maxheight / img.height;
267 var width = Math.floor(img.width * ratio);
268 var height = Math.floor(img.height * ratio);
269 var c = document.createElement('canvas');
272 var ctx = c.getContext('2d');
273 ctx.drawImage(self.company_logo,0,0, width, height);
275 self.company_logo_base64 = c.toDataURL();
276 logo_loaded.resolve();
278 self.company_logo.onerror = function(){
279 logo_loaded.reject();
281 self.company_logo.src = '/web/binary/company_logo'+'?_'+Math.random();
289 // this is called when an order is removed from the order collection. It ensures that there is always an existing
290 // order and a valid selected order
291 on_removed_order: function(removed_order,index,reason){
292 if(reason === 'abandon' && this.get('orders').size() > 0){
293 // when we intentionally remove an unfinished order, and there is another existing one
294 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
296 // when the order was automatically removed after completion,
297 // or when we intentionally delete the only concurrent order
298 this.add_new_order();
302 //creates a new empty order and sets it as the current order
303 add_new_order: function(){
304 var order = new module.Order({pos:this});
305 this.get('orders').add(order);
306 this.set('selectedOrder', order);
309 //removes the current order
310 delete_current_order: function(){
311 this.get('selectedOrder').destroy({'reason':'abandon'});
314 // saves the order locally and try to send it to the backend.
315 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
316 push_order: function(order) {
318 this.proxy.log('push_order',order.export_as_JSON());
319 var order_id = this.db.add_order(order.export_as_JSON());
320 var pushed = new $.Deferred();
322 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
324 this.flush_mutex.exec(function(){
325 var flushed = self._flush_all_orders();
327 flushed.always(function(){
336 // saves the order locally and try to send it to the backend and make an invoice
337 // returns a deferred that succeeds when the order has been posted and successfully generated
338 // an invoice. This method can fail in various ways:
339 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
340 // this error is solved
341 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
342 // the network connection is up
344 push_and_invoice_order: function(order){
346 var invoiced = new $.Deferred();
348 if(!order.get_client()){
349 invoiced.reject('error-no-client');
353 var order_id = this.db.add_order(order.export_as_JSON());
355 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
357 this.flush_mutex.exec(function(){
358 var done = new $.Deferred(); // holds the mutex
360 // send the order to the server
361 // we have a 30 seconds timeout on this push.
362 // FIXME: if the server takes more than 30 seconds to accept the order,
363 // the client will believe it wasn't successfully sent, and very bad
364 // things will happen as a duplicate will be sent next time
365 // so we must make sure the server detects and ignores duplicated orders
367 var transfer = self._flush_order(order_id, {timeout:30000, to_invoice:true});
369 transfer.fail(function(){
370 invoiced.reject('error-transfer');
374 // on success, get the order id generated by the server
375 transfer.pipe(function(order_server_id){
376 // generate the pdf and download it
377 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
378 active_ids:order_server_id,
391 // attemps to send all pending orders ( stored in the pos_db ) to the server,
392 // and remove the successfully sent ones from the db once
393 // it has been confirmed that they have been sent correctly.
396 var flushed = new $.Deferred();
398 this.flush_mutex.exec(function(){
399 var done = new $.Deferred();
401 self._flush_all_orders()
402 .done( function(){ flushed.resolve();})
403 .fail( function(){ flushed.reject(); })
404 .always(function(){ done.resolve(); });
412 // attempts to send the locally stored order of id 'order_id'
413 // the sending is asynchronous and can take some time to decide if it is successful or not
414 // it is therefore important to only call this method from inside a mutex
415 // this method returns a deferred indicating wether the sending was successful or not
416 // there is a timeout parameter which is set to 2 seconds by default.
417 _flush_order: function( order_id, options) {
418 return this._flush_all_orders([this.db.get_order(order_id)], options);
421 // attempts to send all the locally stored orders. As with _flush_order, it should only be
422 // called from within a mutex.
423 // this method returns a deferred that always succeeds when all orders have been tried to be sent,
424 // even if none of them could actually be sent.
425 _flush_all_orders: function () {
429 pending: self.get('synch').pending
431 return self._save_to_server(self.db.get_orders()).done(function () {
432 var pending = self.db.get_orders().length;
434 state: pending ? 'connecting' : 'connected',
440 // send an array of orders to the server
441 // available options:
442 // - timeout: timeout for the rpc call in ms
443 _save_to_server: function (orders, options) {
444 if (!orders || !orders.length) {
445 var result = $.Deferred();
450 options = options || {};
453 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
455 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
456 // then we want to notify the user that we are waiting on something )
457 var posOrderModel = new instance.web.Model('pos.order');
458 return posOrderModel.call('create_from_ui',
459 [_.map(orders, function (order) {
460 order.to_invoice = options.to_invoice || false;
465 shadow: !options.to_invoice,
469 _.each(orders, function (order) {
470 self.db.remove_order(order.id);
472 }).fail(function (unused, event){
473 // prevent an error popup creation by the rpc failure
474 // we want the failure to be silent as we send the orders in the background
475 event.preventDefault();
476 console.error('Failed to send orders:', orders);
480 scan_product: function(parsed_code){
482 var selectedOrder = this.get('selectedOrder');
483 if(parsed_code.encoding === 'ean13'){
484 var product = this.db.get_product_by_ean13(parsed_code.base_code);
485 }else if(parsed_code.encoding === 'reference'){
486 var product = this.db.get_product_by_reference(parsed_code.code);
493 if(parsed_code.type === 'price'){
494 selectedOrder.addProduct(product, {price:parsed_code.value});
495 }else if(parsed_code.type === 'weight'){
496 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
498 selectedOrder.addProduct(product);
504 // An orderline represent one element of the content of a client's shopping cart.
505 // An orderline contains a product, its quantity, its price, discount. etc.
506 // An Order contains zero or more Orderlines.
507 module.Orderline = Backbone.Model.extend({
508 initialize: function(attr,options){
509 this.pos = options.pos;
510 this.order = options.order;
511 this.product = options.product;
512 this.price = options.product.price;
514 this.quantityStr = '1';
516 this.discountStr = '0';
518 this.selected = false;
520 // sets a discount [0,100]%
521 set_discount: function(discount){
522 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
523 this.discount = disc;
524 this.discountStr = '' + disc;
525 this.trigger('change',this);
527 // returns the discount [0,100]%
528 get_discount: function(){
529 return this.discount;
531 get_discount_str: function(){
532 return this.discountStr;
534 get_product_type: function(){
537 // sets the quantity of the product. The quantity will be rounded according to the
538 // product's unity of measure properties. Quantities greater than zero will not get
540 set_quantity: function(quantity){
541 if(quantity === 'remove'){
542 this.order.removeOrderline(this);
545 var quant = parseFloat(quantity) || 0;
546 var unit = this.get_unit();
548 this.quantity = round_pr(quant, unit.rounding);
549 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
551 this.quantity = quant;
552 this.quantityStr = '' + this.quantity;
555 this.trigger('change',this);
557 // return the quantity of product
558 get_quantity: function(){
559 return this.quantity;
561 get_quantity_str: function(){
562 return this.quantityStr;
564 get_quantity_str_with_unit: function(){
565 var unit = this.get_unit();
566 if(unit && unit.name !== 'Unit(s)'){
567 return this.quantityStr + ' ' + unit.name;
569 return this.quantityStr;
572 // return the unit of measure of the product
573 get_unit: function(){
574 var unit_id = (this.product.uos_id || this.product.uom_id);
578 unit_id = unit_id[0];
582 return this.pos.units_by_id[unit_id];
584 // return the product of this orderline
585 get_product: function(){
588 // selects or deselects this orderline
589 set_selected: function(selected){
590 this.selected = selected;
591 this.trigger('change',this);
593 // returns true if this orderline is selected
594 is_selected: function(){
595 return this.selected;
597 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
598 // in the orderline. This returns true if it makes sense to merge the two
599 can_be_merged_with: function(orderline){
600 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
602 }else if(this.get_product_type() !== orderline.get_product_type()){
604 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
606 }else if(this.price !== orderline.price){
612 merge: function(orderline){
613 this.set_quantity(this.get_quantity() + orderline.get_quantity());
615 export_as_JSON: function() {
617 qty: this.get_quantity(),
618 price_unit: this.get_unit_price(),
619 discount: this.get_discount(),
620 product_id: this.get_product().id,
623 //used to create a json of the ticket, to be sent to the printer
624 export_for_printing: function(){
626 quantity: this.get_quantity(),
627 unit_name: this.get_unit().name,
628 price: this.get_unit_price(),
629 discount: this.get_discount(),
630 product_name: this.get_product().name,
631 price_display : this.get_display_price(),
632 price_with_tax : this.get_price_with_tax(),
633 price_without_tax: this.get_price_without_tax(),
635 product_description: this.get_product().description,
636 product_description_sale: this.get_product().description_sale,
639 // changes the base price of the product for this orderline
640 set_unit_price: function(price){
641 this.price = round_di(parseFloat(price) || 0, 2);
642 this.trigger('change',this);
644 get_unit_price: function(){
645 var rounding = this.pos.currency.rounding;
646 return round_pr(this.price,rounding);
648 get_display_price: function(){
649 var rounding = this.pos.currency.rounding;
650 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
652 get_price_without_tax: function(){
653 return this.get_all_prices().priceWithoutTax;
655 get_price_with_tax: function(){
656 return this.get_all_prices().priceWithTax;
659 return this.get_all_prices().tax;
661 get_tax_details: function(){
662 return this.get_all_prices().taxDetails;
664 get_all_prices: function(){
666 var currency_rounding = this.pos.currency.rounding;
667 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
669 var totalNoTax = base;
671 var product = this.get_product();
672 var taxes_ids = product.taxes_id;
673 var taxes = self.pos.taxes;
676 _.each(taxes_ids, function(el) {
677 var tax = _.detect(taxes, function(t) {return t.id === el;});
678 if (tax.price_include) {
680 if (tax.type === "percent") {
681 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
682 } else if (tax.type === "fixed") {
683 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
685 throw "This type of tax is not supported by the point of sale: " + tax.type;
687 tmp = round_pr(tmp,currency_rounding);
690 taxdetail[tax.id] = tmp;
693 if (tax.type === "percent") {
694 tmp = tax.amount * base;
695 } else if (tax.type === "fixed") {
696 tmp = tax.amount * self.get_quantity();
698 throw "This type of tax is not supported by the point of sale: " + tax.type;
700 tmp = round_pr(tmp,currency_rounding);
703 taxdetail[tax.id] = tmp;
707 "priceWithTax": totalTax,
708 "priceWithoutTax": totalNoTax,
710 "taxDetails": taxdetail,
715 module.OrderlineCollection = Backbone.Collection.extend({
716 model: module.Orderline,
719 // Every Paymentline contains a cashregister and an amount of money.
720 module.Paymentline = Backbone.Model.extend({
721 initialize: function(attributes, options) {
723 this.cashregister = options.cashregister;
724 this.name = this.cashregister.journal_id[1];
725 this.selected = false;
727 //sets the amount of money on this payment line
728 set_amount: function(value){
729 this.amount = round_di(parseFloat(value) || 0, 2);
730 this.trigger('change:amount',this);
732 // returns the amount of money on this paymentline
733 get_amount: function(){
736 set_selected: function(selected){
737 if(this.selected !== selected){
738 this.selected = selected;
739 this.trigger('change:selected',this);
742 // returns the associated cashregister
743 //exports as JSON for server communication
744 export_as_JSON: function(){
746 name: instance.web.datetime_to_str(new Date()),
747 statement_id: this.cashregister.id,
748 account_id: this.cashregister.account_id[0],
749 journal_id: this.cashregister.journal_id[0],
750 amount: this.get_amount()
753 //exports as JSON for receipt printing
754 export_for_printing: function(){
756 amount: this.get_amount(),
757 journal: this.cashregister.journal_id[1],
762 module.PaymentlineCollection = Backbone.Collection.extend({
763 model: module.Paymentline,
767 // An order more or less represents the content of a client's shopping cart (the OrderLines)
768 // plus the associated payment information (the Paymentlines)
769 // there is always an active ('selected') order in the Pos, a new one is created
770 // automaticaly once an order is completed and sent to the server.
771 module.Order = Backbone.Model.extend({
772 initialize: function(attributes){
773 Backbone.Model.prototype.initialize.apply(this, arguments);
774 this.uid = this.generateUniqueId();
776 creationDate: new Date(),
777 orderLines: new module.OrderlineCollection(),
778 paymentLines: new module.PaymentlineCollection(),
779 name: "Order " + this.uid,
782 this.pos = attributes.pos;
783 this.selected_orderline = undefined;
784 this.selected_paymentline = undefined;
785 this.screen_data = {}; // see ScreenSelector
786 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
789 generateUniqueId: function() {
790 return new Date().getTime();
792 addProduct: function(product, options){
793 options = options || {};
794 var attr = JSON.parse(JSON.stringify(product));
797 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
799 if(options.quantity !== undefined){
800 line.set_quantity(options.quantity);
802 if(options.price !== undefined){
803 line.set_unit_price(options.price);
806 var last_orderline = this.getLastOrderline();
807 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
808 last_orderline.merge(line);
810 this.get('orderLines').add(line);
812 this.selectLine(this.getLastOrderline());
814 removeOrderline: function( line ){
815 this.get('orderLines').remove(line);
816 this.selectLine(this.getLastOrderline());
818 getLastOrderline: function(){
819 return this.get('orderLines').at(this.get('orderLines').length -1);
821 addPaymentline: function(cashregister) {
822 var paymentLines = this.get('paymentLines');
823 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
824 if(cashregister.journal.type !== 'cash'){
825 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
827 paymentLines.add(newPaymentline);
828 this.selectPaymentline(newPaymentline);
831 removePaymentline: function(line){
832 if(this.selected_paymentline === line){
833 this.selectPaymentline(undefined);
835 this.get('paymentLines').remove(line);
837 getName: function() {
838 return this.get('name');
840 getSubtotal : function(){
841 return (this.get('orderLines')).reduce((function(sum, orderLine){
842 return sum + orderLine.get_display_price();
845 getTotalTaxIncluded: function() {
846 return (this.get('orderLines')).reduce((function(sum, orderLine) {
847 return sum + orderLine.get_price_with_tax();
850 getDiscountTotal: function() {
851 return (this.get('orderLines')).reduce((function(sum, orderLine) {
852 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
855 getTotalTaxExcluded: function() {
856 return (this.get('orderLines')).reduce((function(sum, orderLine) {
857 return sum + orderLine.get_price_without_tax();
861 return (this.get('orderLines')).reduce((function(sum, orderLine) {
862 return sum + orderLine.get_tax();
865 getTaxDetails: function(){
867 var fulldetails = [];
868 var taxes_by_id = {};
870 for(var i = 0; i < this.pos.taxes.length; i++){
871 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
874 this.get('orderLines').each(function(line){
875 var ldetails = line.get_tax_details();
876 for(var id in ldetails){
877 if(ldetails.hasOwnProperty(id)){
878 details[id] = (details[id] || 0) + ldetails[id];
883 for(var id in details){
884 if(details.hasOwnProperty(id)){
885 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
891 getPaidTotal: function() {
892 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
893 return sum + paymentLine.get_amount();
896 getChange: function() {
897 return this.getPaidTotal() - this.getTotalTaxIncluded();
899 getDueLeft: function() {
900 return this.getTotalTaxIncluded() - this.getPaidTotal();
902 // sets the type of receipt 'receipt'(default) or 'invoice'
903 set_receipt_type: function(type){
904 this.receipt_type = type;
906 get_receipt_type: function(){
907 return this.receipt_type;
909 // the client related to the current order.
910 set_client: function(client){
911 this.set('client',client);
913 get_client: function(){
914 return this.get('client');
916 get_client_name: function(){
917 var client = this.get('client');
918 return client ? client.name : "";
920 // the order also stores the screen status, as the PoS supports
921 // different active screens per order. This method is used to
922 // store the screen status.
923 set_screen_data: function(key,value){
924 if(arguments.length === 2){
925 this.screen_data[key] = value;
926 }else if(arguments.length === 1){
927 for(key in arguments[0]){
928 this.screen_data[key] = arguments[0][key];
932 //see set_screen_data
933 get_screen_data: function(key){
934 return this.screen_data[key];
936 // exports a JSON for receipt printing
937 export_for_printing: function(){
939 this.get('orderLines').each(function(orderline){
940 orderlines.push(orderline.export_for_printing());
943 var paymentlines = [];
944 this.get('paymentLines').each(function(paymentline){
945 paymentlines.push(paymentline.export_for_printing());
947 var client = this.get('client');
948 var cashier = this.pos.cashier || this.pos.user;
949 var company = this.pos.company;
950 var date = new Date();
953 orderlines: orderlines,
954 paymentlines: paymentlines,
955 subtotal: this.getSubtotal(),
956 total_with_tax: this.getTotalTaxIncluded(),
957 total_without_tax: this.getTotalTaxExcluded(),
958 total_tax: this.getTax(),
959 total_paid: this.getPaidTotal(),
960 total_discount: this.getDiscountTotal(),
961 tax_details: this.getTaxDetails(),
962 change: this.getChange(),
963 name : this.getName(),
964 client: client ? client.name : null ,
965 invoice_id: null, //TODO
966 cashier: cashier ? cashier.name : null,
967 header: this.pos.config.receipt_header || '',
968 footer: this.pos.config.receipt_footer || '',
975 year: date.getFullYear(),
976 month: date.getMonth(),
977 date: date.getDate(), // day of the month
978 day: date.getDay(), // day of the week
979 hour: date.getHours(),
980 minute: date.getMinutes() ,
981 isostring: date.toISOString(),
982 localestring: date.toLocaleString(),
985 email: company.email,
986 website: company.website,
987 company_registry: company.company_registry,
988 contact_address: company.partner_id[1],
991 phone: company.phone,
992 logo: this.pos.company_logo_base64,
994 currency: this.pos.currency,
997 export_as_JSON: function() {
998 var orderLines, paymentLines;
1000 (this.get('orderLines')).each(_.bind( function(item) {
1001 return orderLines.push([0, 0, item.export_as_JSON()]);
1004 (this.get('paymentLines')).each(_.bind( function(item) {
1005 return paymentLines.push([0, 0, item.export_as_JSON()]);
1008 name: this.getName(),
1009 amount_paid: this.getPaidTotal(),
1010 amount_total: this.getTotalTaxIncluded(),
1011 amount_tax: this.getTax(),
1012 amount_return: this.getChange(),
1014 statement_ids: paymentLines,
1015 pos_session_id: this.pos.pos_session.id,
1016 partner_id: this.get_client() ? this.get_client().id : false,
1017 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1021 getSelectedLine: function(){
1022 return this.selected_orderline;
1024 selectLine: function(line){
1026 if(line !== this.selected_orderline){
1027 if(this.selected_orderline){
1028 this.selected_orderline.set_selected(false);
1030 this.selected_orderline = line;
1031 this.selected_orderline.set_selected(true);
1034 this.selected_orderline = undefined;
1037 deselectLine: function(){
1038 if(this.selected_orderline){
1039 this.selected_orderline.set_selected(false);
1040 this.selected_orderline = undefined;
1043 selectPaymentline: function(line){
1044 if(line !== this.selected_paymentline){
1045 if(this.selected_paymentline){
1046 this.selected_paymentline.set_selected(false);
1048 this.selected_paymentline = line;
1049 if(this.selected_paymentline){
1050 this.selected_paymentline.set_selected(true);
1052 this.trigger('change:selected_paymentline',this.selected_paymentline);
1057 module.OrderCollection = Backbone.Collection.extend({
1058 model: module.Order,
1062 The numpad handles both the choice of the property currently being modified
1063 (quantity, price or discount) and the edition of the corresponding numeric value.
1065 module.NumpadState = Backbone.Model.extend({
1070 appendNewChar: function(newChar) {
1072 oldBuffer = this.get('buffer');
1073 if (oldBuffer === '0') {
1077 } else if (oldBuffer === '-0') {
1079 buffer: "-" + newChar
1083 buffer: (this.get('buffer')) + newChar
1086 this.trigger('set_value',this.get('buffer'));
1088 deleteLastChar: function() {
1089 if(this.get('buffer') === ""){
1090 if(this.get('mode') === 'quantity'){
1091 this.trigger('set_value','remove');
1093 this.trigger('set_value',this.get('buffer'));
1096 var newBuffer = this.get('buffer').slice(0,-1) || "";
1097 this.set({ buffer: newBuffer });
1098 this.trigger('set_value',this.get('buffer'));
1101 switchSign: function() {
1102 console.log('switchsing');
1104 oldBuffer = this.get('buffer');
1106 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1108 this.trigger('set_value',this.get('buffer'));
1110 changeMode: function(newMode) {
1122 resetValue: function(){
1123 this.set({buffer:'0'});