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 = '';
43 this.cashregisters = [];
44 this.bankstatements = [];
46 this.pos_session = null;
49 this.units_by_id = {};
50 this.pricelist = null;
51 window.posmodel = this;
53 // these dynamic attributes can be watched for change by other models or widgets
55 'synch': { state:'connected', pending:0 },
56 'orders': new module.OrderCollection(),
57 'selectedOrder': null,
60 this.bind('change:synch',function(pos,synch){
61 clearTimeout(self.synch_timeout);
62 self.synch_timeout = setTimeout(function(){
63 if(synch.state !== 'disconnected' && synch.pending > 0){
64 self.set('synch',{state:'disconnected', pending:synch.pending});
69 this.get('orders').bind('remove', function(order,_unused_,options){
70 self.on_removed_order(order,options.index,options.reason);
73 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
74 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
75 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
76 this.ready = this.load_server_data()
78 if(self.config.use_proxy){
79 return self.connect_to_proxy();
85 // releases ressources holds by the model at the end of life of the posmodel
87 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
90 this.barcode_reader.disconnect();
91 this.barcode_reader.disconnect_from_proxy();
93 connect_to_proxy: function(){
95 var done = new $.Deferred();
96 this.barcode_reader.disconnect_from_proxy();
97 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
98 this.pos_widget.loading_skip(function(){
99 self.proxy.stop_searching();
101 this.proxy.autoconnect({
102 force_ip: self.config.proxy_ip || undefined,
103 progress: function(prog){
104 self.pos_widget.loading_progress(prog);
107 if(self.config.iface_scan_via_proxy){
108 self.barcode_reader.connect_to_proxy();
110 }).always(function(){
116 // helper function to load data from the server
117 fetch: function(model, fields, domain, ctx){
118 this._load_progress = (this._load_progress || 0) + 0.05;
119 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
120 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
122 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
123 load_server_data: function(){
126 var loaded = self.fetch('res.users',['name','company_id'],[['id','=',this.session.uid]])
127 .then(function(users){
128 self.user = users[0];
130 return self.fetch('res.company',
141 [['id','=',users[0].company_id[0]]],
142 {show_address_only: true});
143 }).then(function(companies){
144 self.company = companies[0];
146 return self.fetch('product.uom', null, null);
147 }).then(function(units){
149 var units_by_id = {};
150 for(var i = 0, len = units.length; i < len; i++){
151 units_by_id[units[i].id] = units[i];
153 self.units_by_id = units_by_id;
155 return self.fetch('res.users', ['name','ean13'], [['ean13', '!=', false]]);
156 }).then(function(users){
159 return self.fetch('res.partner', ['name','ean13'], [['ean13', '!=', false]]);
160 }).then(function(partners){
161 self.partners = partners;
163 return self.fetch('account.tax', ['name','amount', 'price_include', 'type']);
164 }).then(function(taxes){
169 ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at'],
170 [['state', '=', 'opened'], ['user_id', '=', self.session.uid]]
172 }).then(function(pos_sessions){
173 self.pos_session = pos_sessions[0];
177 ['name','journal_ids','warehouse_id','journal_id','pricelist_id',
178 'iface_self_checkout', 'iface_led', 'iface_cashdrawer',
179 'iface_payment_terminal', 'iface_electronic_scale', 'iface_barscan',
180 'iface_vkeyboard','iface_print_via_proxy','iface_scan_via_proxy',
181 'iface_cashdrawer','iface_invoicing','iface_big_scrollbars',
182 'receipt_header','receipt_footer','proxy_ip',
183 'state','sequence_id','session_ids'],
184 [['id','=', self.pos_session.config_id[0]]]
186 }).then(function(configs){
187 self.config = configs[0];
188 self.config.use_proxy = self.config.iface_payment_terminal ||
189 self.config.iface_electronic_scale ||
190 self.config.iface_print_via_proxy ||
191 self.config.iface_scan_via_proxy ||
192 self.config.iface_cashdrawer;
194 return self.fetch('stock.warehouse',[],[['id','=', self.config.warehouse_id[0]]]);
195 }).then(function(shops){
196 self.shop = shops[0];
198 return self.fetch('product.pricelist',['currency_id'],[['id','=',self.config.pricelist_id[0]]]);
199 }).then(function(pricelists){
200 self.pricelist = pricelists[0];
202 return self.fetch('res.currency',['symbol','position','rounding','accuracy'],[['id','=',self.pricelist.currency_id[0]]]);
203 }).then(function(currencies){
204 self.currency = currencies[0];
207 return (new instance.web.Model('decimal.precision')).call('get_precision',[['Account']]);
208 }).then(function(precision){
209 self.accounting_precision = precision;
210 console.log("PRECISION",precision);
212 return self.fetch('product.packaging',['ean','product_id']);
213 }).then(function(packagings){
214 self.db.add_packagings(packagings);
216 return self.fetch('product.public.category', ['id','name','parent_id','child_id','image'])
217 }).then(function(categories){
218 self.db.add_categories(categories);
222 ['name', 'list_price','price','public_categ_id', 'taxes_id', 'ean13', 'default_code',
223 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description'],
224 [['sale_ok','=',true],['available_in_pos','=',true]],
225 {pricelist: self.pricelist.id} // context for price
227 }).then(function(products){
228 self.db.add_products(products);
231 'account.bank.statement',
232 ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
233 [['state','=','open'],['pos_session_id', '=', self.pos_session.id]]
235 }).then(function(bankstatements){
237 _.each(bankstatements,function(statement) {
238 journals.push(statement.journal_id[0])
240 self.bankstatements = bankstatements;
241 return self.fetch('account.journal', undefined, [['id','in', journals]]);
242 }).then(function(journals){
243 self.journals = journals;
245 // associate the bank statements with their journals.
246 var bankstatements = self.bankstatements
247 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
248 for(var j = 0, jlen = journals.length; j < jlen; j++){
249 if(bankstatements[i].journal_id[0] === journals[j].id){
250 bankstatements[i].journal = journals[j];
251 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
255 self.cashregisters = bankstatements;
257 // Load the company Logo
259 self.company_logo = new Image();
260 self.company_logo.crossOrigin = 'anonymous';
261 var logo_loaded = new $.Deferred();
262 self.company_logo.onload = function(){
263 var img = self.company_logo;
265 var targetwidth = 300;
267 if( img.width !== targetwidth ){
268 ratio = targetwidth / img.width;
270 if( img.height * ratio > maxheight ){
271 ratio = maxheight / img.height;
273 var width = Math.floor(img.width * ratio);
274 var height = Math.floor(img.height * ratio);
275 var c = document.createElement('canvas');
278 var ctx = c.getContext('2d');
279 ctx.drawImage(self.company_logo,0,0, width, height);
281 self.company_logo_base64 = c.toDataURL();
282 window.logo64 = self.company_logo_base64;
283 logo_loaded.resolve();
285 self.company_logo.onerror = function(){
286 logo_loaded.reject();
288 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
296 // this is called when an order is removed from the order collection. It ensures that there is always an existing
297 // order and a valid selected order
298 on_removed_order: function(removed_order,index,reason){
299 if(reason === 'abandon' && this.get('orders').size() > 0){
300 // when we intentionally remove an unfinished order, and there is another existing one
301 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
303 // when the order was automatically removed after completion,
304 // or when we intentionally delete the only concurrent order
305 this.add_new_order();
309 //creates a new empty order and sets it as the current order
310 add_new_order: function(){
311 var order = new module.Order({pos:this});
312 this.get('orders').add(order);
313 this.set('selectedOrder', order);
316 //removes the current order
317 delete_current_order: function(){
318 this.get('selectedOrder').destroy({'reason':'abandon'});
321 // saves the order locally and try to send it to the backend.
322 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
323 push_order: function(order) {
325 this.proxy.log('push_order',order.export_as_JSON());
326 var order_id = this.db.add_order(order.export_as_JSON());
327 var pushed = new $.Deferred();
329 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
331 this.flush_mutex.exec(function(){
332 var flushed = self._flush_all_orders();
334 flushed.always(function(){
343 // saves the order locally and try to send it to the backend and make an invoice
344 // returns a deferred that succeeds when the order has been posted and successfully generated
345 // an invoice. This method can fail in various ways:
346 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
347 // this error is solved
348 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
349 // the network connection is up
351 push_and_invoice_order: function(order){
353 var invoiced = new $.Deferred();
355 if(!order.get_client()){
356 invoiced.reject('error-no-client');
360 var order_id = this.db.add_order(order.export_as_JSON());
362 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
364 this.flush_mutex.exec(function(){
365 var done = new $.Deferred(); // holds the mutex
367 // send the order to the server
368 // we have a 30 seconds timeout on this push.
369 // FIXME: if the server takes more than 30 seconds to accept the order,
370 // the client will believe it wasn't successfully sent, and very bad
371 // things will happen as a duplicate will be sent next time
372 // so we must make sure the server detects and ignores duplicated orders
374 var transfer = self._flush_order(order_id, {timeout:30000, to_invoice:true});
376 transfer.fail(function(){
377 invoiced.reject('error-transfer');
381 // on success, get the order id generated by the server
382 transfer.pipe(function(order_server_id){
383 // generate the pdf and download it
384 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
385 active_ids:order_server_id,
398 // attemps to send all pending orders ( stored in the pos_db ) to the server,
399 // and remove the successfully sent ones from the db once
400 // it has been confirmed that they have been sent correctly.
403 var flushed = new $.Deferred();
405 this.flush_mutex.exec(function(){
406 var done = new $.Deferred();
408 self._flush_all_orders()
409 .done( function(){ flushed.resolve();})
410 .fail( function(){ flushed.reject(); })
411 .always(function(){ done.resolve(); });
419 // attempts to send the locally stored order of id 'order_id'
420 // the sending is asynchronous and can take some time to decide if it is successful or not
421 // it is therefore important to only call this method from inside a mutex
422 // this method returns a deferred indicating wether the sending was successful or not
423 // there is a timeout parameter which is set to 2 seconds by default.
424 _flush_order: function( order_id, options) {
425 return this._flush_all_orders([this.db.get_order(order_id)], options);
428 // attempts to send all the locally stored orders. As with _flush_order, it should only be
429 // called from within a mutex.
430 // this method returns a deferred that always succeeds when all orders have been tried to be sent,
431 // even if none of them could actually be sent.
432 _flush_all_orders: function () {
436 pending: self.get('synch').pending
438 return self._save_to_server(self.db.get_orders()).done(function () {
439 var pending = self.db.get_orders().length;
441 state: pending ? 'connecting' : 'connected',
447 // send an array of orders to the server
448 // available options:
449 // - timeout: timeout for the rpc call in ms
450 _save_to_server: function (orders, options) {
451 if (!orders || !orders.length) {
452 var result = $.Deferred();
457 options = options || {};
460 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500;
462 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
463 // then we want to notify the user that we are waiting on something )
464 var posOrderModel = new instance.web.Model('pos.order');
465 return posOrderModel.call('create_from_ui',
466 [_.map(orders, function (order) {
467 order.to_invoice = options.to_invoice || false;
472 shadow: !options.to_invoice,
476 _.each(orders, function (order) {
477 self.db.remove_order(order.id);
479 }).fail(function (unused, event){
480 // prevent an error popup creation by the rpc failure
481 // we want the failure to be silent as we send the orders in the background
482 event.preventDefault();
483 console.error('Failed to send orders:', orders);
487 scan_product: function(parsed_code){
489 var selectedOrder = this.get('selectedOrder');
490 if(parsed_code.encoding === 'ean13'){
491 var product = this.db.get_product_by_ean13(parsed_code.base_code);
492 }else if(parsed_code.encoding === 'reference'){
493 var product = this.db.get_product_by_reference(parsed_code.code);
500 if(parsed_code.type === 'price'){
501 selectedOrder.addProduct(product, {price:parsed_code.value});
502 }else if(parsed_code.type === 'weight'){
503 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
505 selectedOrder.addProduct(product);
511 // An orderline represent one element of the content of a client's shopping cart.
512 // An orderline contains a product, its quantity, its price, discount. etc.
513 // An Order contains zero or more Orderlines.
514 module.Orderline = Backbone.Model.extend({
515 initialize: function(attr,options){
516 this.pos = options.pos;
517 this.order = options.order;
518 this.product = options.product;
519 this.price = options.product.price;
521 this.quantityStr = '1';
523 this.discountStr = '0';
525 this.selected = false;
527 // sets a discount [0,100]%
528 set_discount: function(discount){
529 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
530 this.discount = disc;
531 this.discountStr = '' + disc;
532 this.trigger('change',this);
534 // returns the discount [0,100]%
535 get_discount: function(){
536 return this.discount;
538 get_discount_str: function(){
539 return this.discountStr;
541 get_product_type: function(){
544 // sets the quantity of the product. The quantity will be rounded according to the
545 // product's unity of measure properties. Quantities greater than zero will not get
547 set_quantity: function(quantity){
548 if(quantity === 'remove'){
549 this.order.removeOrderline(this);
552 var quant = Math.max(parseFloat(quantity) || 0, 0);
553 var unit = this.get_unit();
555 this.quantity = Math.max(unit.rounding, round_pr(quant, unit.rounding));
556 this.quantityStr = this.quantity.toFixed(Math.max(0,Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10))));
558 this.quantity = quant;
559 this.quantityStr = '' + this.quantity;
562 this.trigger('change',this);
564 // return the quantity of product
565 get_quantity: function(){
566 return this.quantity;
568 get_quantity_str: function(){
569 return this.quantityStr;
571 get_quantity_str_with_unit: function(){
572 var unit = this.get_unit();
573 if(unit && unit.name !== 'Unit(s)'){
574 return this.quantityStr + ' ' + unit.name;
576 return this.quantityStr;
579 // return the unit of measure of the product
580 get_unit: function(){
581 var unit_id = (this.product.uos_id || this.product.uom_id);
585 unit_id = unit_id[0];
589 return this.pos.units_by_id[unit_id];
591 // return the product of this orderline
592 get_product: function(){
595 // selects or deselects this orderline
596 set_selected: function(selected){
597 this.selected = selected;
598 this.trigger('change',this);
600 // returns true if this orderline is selected
601 is_selected: function(){
602 return this.selected;
604 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
605 // in the orderline. This returns true if it makes sense to merge the two
606 can_be_merged_with: function(orderline){
607 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
609 }else if(this.get_product_type() !== orderline.get_product_type()){
611 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
613 }else if(this.price !== orderline.price){
619 merge: function(orderline){
620 this.set_quantity(this.get_quantity() + orderline.get_quantity());
622 export_as_JSON: function() {
624 qty: this.get_quantity(),
625 price_unit: this.get_unit_price(),
626 discount: this.get_discount(),
627 product_id: this.get_product().id,
630 //used to create a json of the ticket, to be sent to the printer
631 export_for_printing: function(){
633 quantity: this.get_quantity(),
634 unit_name: this.get_unit().name,
635 price: this.get_unit_price(),
636 discount: this.get_discount(),
637 product_name: this.get_product().name,
638 price_display : this.get_display_price(),
639 price_with_tax : this.get_price_with_tax(),
640 price_without_tax: this.get_price_without_tax(),
642 product_description: this.get_product().description,
643 product_description_sale: this.get_product().description_sale,
646 // changes the base price of the product for this orderline
647 set_unit_price: function(price){
648 this.price = round_di(parseFloat(price) || 0, 2);
649 this.trigger('change',this);
651 get_unit_price: function(){
652 var rounding = this.pos.currency.rounding;
653 return round_pr(this.price,rounding);
655 get_display_price: function(){
656 var rounding = this.pos.currency.rounding;
657 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
659 get_price_without_tax: function(){
660 return this.get_all_prices().priceWithoutTax;
662 get_price_with_tax: function(){
663 return this.get_all_prices().priceWithTax;
666 return this.get_all_prices().tax;
668 get_tax_details: function(){
669 return this.get_all_prices().taxDetails;
671 get_all_prices: function(){
673 var currency_rounding = this.pos.currency.rounding;
674 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
676 var totalNoTax = base;
678 var product = this.get_product();
679 var taxes_ids = product.taxes_id;
680 var taxes = self.pos.taxes;
683 _.each(taxes_ids, function(el) {
684 var tax = _.detect(taxes, function(t) {return t.id === el;});
685 if (tax.price_include) {
687 if (tax.type === "percent") {
688 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
689 } else if (tax.type === "fixed") {
690 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
692 throw "This type of tax is not supported by the point of sale: " + tax.type;
694 tmp = round_pr(tmp,currency_rounding);
697 taxdetail[tax.id] = tmp;
700 if (tax.type === "percent") {
701 tmp = tax.amount * base;
702 } else if (tax.type === "fixed") {
703 tmp = tax.amount * self.get_quantity();
705 throw "This type of tax is not supported by the point of sale: " + tax.type;
707 tmp = round_pr(tmp,currency_rounding);
710 taxdetail[tax.id] = tmp;
714 "priceWithTax": totalTax,
715 "priceWithoutTax": totalNoTax,
717 "taxDetails": taxdetail,
722 module.OrderlineCollection = Backbone.Collection.extend({
723 model: module.Orderline,
726 // Every Paymentline contains a cashregister and an amount of money.
727 module.Paymentline = Backbone.Model.extend({
728 initialize: function(attributes, options) {
730 this.cashregister = options.cashregister;
731 this.name = this.cashregister.journal_id[1];
732 this.selected = false;
734 //sets the amount of money on this payment line
735 set_amount: function(value){
736 this.amount = round_di(parseFloat(value) || 0, 2);
737 this.trigger('change:amount',this);
739 // returns the amount of money on this paymentline
740 get_amount: function(){
743 set_selected: function(selected){
744 if(this.selected !== selected){
745 this.selected = selected;
746 this.trigger('change:selected',this);
749 // returns the associated cashregister
750 //exports as JSON for server communication
751 export_as_JSON: function(){
753 name: instance.web.datetime_to_str(new Date()),
754 statement_id: this.cashregister.id,
755 account_id: this.cashregister.account_id[0],
756 journal_id: this.cashregister.journal_id[0],
757 amount: this.get_amount()
760 //exports as JSON for receipt printing
761 export_for_printing: function(){
763 amount: this.get_amount(),
764 journal: this.cashregister.journal_id[1],
769 module.PaymentlineCollection = Backbone.Collection.extend({
770 model: module.Paymentline,
774 // An order more or less represents the content of a client's shopping cart (the OrderLines)
775 // plus the associated payment information (the Paymentlines)
776 // there is always an active ('selected') order in the Pos, a new one is created
777 // automaticaly once an order is completed and sent to the server.
778 module.Order = Backbone.Model.extend({
779 initialize: function(attributes){
780 Backbone.Model.prototype.initialize.apply(this, arguments);
781 this.uid = this.generateUniqueId();
783 creationDate: new Date(),
784 orderLines: new module.OrderlineCollection(),
785 paymentLines: new module.PaymentlineCollection(),
786 name: "Order " + this.uid,
789 this.pos = attributes.pos;
790 this.selected_orderline = undefined;
791 this.selected_paymentline = undefined;
792 this.screen_data = {}; // see ScreenSelector
793 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
796 generateUniqueId: function() {
797 return new Date().getTime();
799 addProduct: function(product, options){
800 options = options || {};
801 var attr = JSON.parse(JSON.stringify(product));
804 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
806 if(options.quantity !== undefined){
807 line.set_quantity(options.quantity);
809 if(options.price !== undefined){
810 line.set_unit_price(options.price);
813 var last_orderline = this.getLastOrderline();
814 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
815 last_orderline.merge(line);
817 this.get('orderLines').add(line);
819 this.selectLine(this.getLastOrderline());
821 removeOrderline: function( line ){
822 this.get('orderLines').remove(line);
823 this.selectLine(this.getLastOrderline());
825 getLastOrderline: function(){
826 return this.get('orderLines').at(this.get('orderLines').length -1);
828 addPaymentline: function(cashregister) {
829 var paymentLines = this.get('paymentLines');
830 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
831 if(cashregister.journal.type !== 'cash'){
832 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
834 paymentLines.add(newPaymentline);
835 this.selectPaymentline(newPaymentline);
838 removePaymentline: function(line){
839 if(this.selected_paymentline === line){
840 this.selectPaymentline(undefined);
842 this.get('paymentLines').remove(line);
844 getName: function() {
845 return this.get('name');
847 getSubtotal : function(){
848 return (this.get('orderLines')).reduce((function(sum, orderLine){
849 return sum + orderLine.get_display_price();
852 getTotalTaxIncluded: function() {
853 return (this.get('orderLines')).reduce((function(sum, orderLine) {
854 return sum + orderLine.get_price_with_tax();
857 getDiscountTotal: function() {
858 return (this.get('orderLines')).reduce((function(sum, orderLine) {
859 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
862 getTotalTaxExcluded: function() {
863 return (this.get('orderLines')).reduce((function(sum, orderLine) {
864 return sum + orderLine.get_price_without_tax();
868 return (this.get('orderLines')).reduce((function(sum, orderLine) {
869 return sum + orderLine.get_tax();
872 getTaxDetails: function(){
874 var fulldetails = [];
875 var taxes_by_id = {};
877 for(var i = 0; i < this.pos.taxes.length; i++){
878 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
881 this.get('orderLines').each(function(line){
882 var ldetails = line.get_tax_details();
883 for(var id in ldetails){
884 if(ldetails.hasOwnProperty(id)){
885 details[id] = (details[id] || 0) + ldetails[id];
890 for(var id in details){
891 if(details.hasOwnProperty(id)){
892 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
898 getPaidTotal: function() {
899 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
900 return sum + paymentLine.get_amount();
903 getChange: function() {
904 return this.getPaidTotal() - this.getTotalTaxIncluded();
906 getDueLeft: function() {
907 return this.getTotalTaxIncluded() - this.getPaidTotal();
909 // sets the type of receipt 'receipt'(default) or 'invoice'
910 set_receipt_type: function(type){
911 this.receipt_type = type;
913 get_receipt_type: function(){
914 return this.receipt_type;
916 // the client related to the current order.
917 set_client: function(client){
918 this.set('client',client);
920 get_client: function(){
921 return this.get('client');
923 get_client_name: function(){
924 var client = this.get('client');
925 return client ? client.name : "";
927 // the order also stores the screen status, as the PoS supports
928 // different active screens per order. This method is used to
929 // store the screen status.
930 set_screen_data: function(key,value){
931 if(arguments.length === 2){
932 this.screen_data[key] = value;
933 }else if(arguments.length === 1){
934 for(key in arguments[0]){
935 this.screen_data[key] = arguments[0][key];
939 //see set_screen_data
940 get_screen_data: function(key){
941 return this.screen_data[key];
943 // exports a JSON for receipt printing
944 export_for_printing: function(){
946 this.get('orderLines').each(function(orderline){
947 orderlines.push(orderline.export_for_printing());
950 var paymentlines = [];
951 this.get('paymentLines').each(function(paymentline){
952 paymentlines.push(paymentline.export_for_printing());
954 var client = this.get('client');
955 var cashier = this.pos.cashier || this.pos.user;
956 var company = this.pos.company;
957 var shop = this.pos.shop;
958 var date = new Date();
961 orderlines: orderlines,
962 paymentlines: paymentlines,
963 subtotal: this.getSubtotal(),
964 total_with_tax: this.getTotalTaxIncluded(),
965 total_without_tax: this.getTotalTaxExcluded(),
966 total_tax: this.getTax(),
967 total_paid: this.getPaidTotal(),
968 total_discount: this.getDiscountTotal(),
969 tax_details: this.getTaxDetails(),
970 change: this.getChange(),
971 name : this.getName(),
972 client: client ? client.name : null ,
973 invoice_id: null, //TODO
974 cashier: cashier ? cashier.name : null,
975 header: this.pos.config.receipt_header || '',
976 footer: this.pos.config.receipt_footer || '',
983 year: date.getFullYear(),
984 month: date.getMonth(),
985 date: date.getDate(), // day of the month
986 day: date.getDay(), // day of the week
987 hour: date.getHours(),
988 minute: date.getMinutes() ,
989 isostring: date.toISOString(),
992 email: company.email,
993 website: company.website,
994 company_registry: company.company_registry,
995 contact_address: company.partner_id[1],
998 phone: company.phone,
999 logo: this.pos.company_logo_base64,
1004 currency: this.pos.currency,
1007 export_as_JSON: function() {
1008 var orderLines, paymentLines;
1010 (this.get('orderLines')).each(_.bind( function(item) {
1011 return orderLines.push([0, 0, item.export_as_JSON()]);
1014 (this.get('paymentLines')).each(_.bind( function(item) {
1015 return paymentLines.push([0, 0, item.export_as_JSON()]);
1018 name: this.getName(),
1019 amount_paid: this.getPaidTotal(),
1020 amount_total: this.getTotalTaxIncluded(),
1021 amount_tax: this.getTax(),
1022 amount_return: this.getChange(),
1024 statement_ids: paymentLines,
1025 pos_session_id: this.pos.pos_session.id,
1026 partner_id: this.get_client() ? this.get_client().id : false,
1027 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1031 getSelectedLine: function(){
1032 return this.selected_orderline;
1034 selectLine: function(line){
1036 if(line !== this.selected_orderline){
1037 if(this.selected_orderline){
1038 this.selected_orderline.set_selected(false);
1040 this.selected_orderline = line;
1041 this.selected_orderline.set_selected(true);
1044 this.selected_orderline = undefined;
1047 deselectLine: function(){
1048 if(this.selected_orderline){
1049 this.selected_orderline.set_selected(false);
1050 this.selected_orderline = undefined;
1053 selectPaymentline: function(line){
1054 if(line !== this.selected_paymentline){
1055 if(this.selected_paymentline){
1056 this.selected_paymentline.set_selected(false);
1058 this.selected_paymentline = line;
1059 if(this.selected_paymentline){
1060 this.selected_paymentline.set_selected(true);
1062 this.trigger('change:selected_paymentline',this.selected_paymentline);
1067 module.OrderCollection = Backbone.Collection.extend({
1068 model: module.Order,
1072 The numpad handles both the choice of the property currently being modified
1073 (quantity, price or discount) and the edition of the corresponding numeric value.
1075 module.NumpadState = Backbone.Model.extend({
1080 appendNewChar: function(newChar) {
1082 oldBuffer = this.get('buffer');
1083 if (oldBuffer === '0') {
1087 } else if (oldBuffer === '-0') {
1089 buffer: "-" + newChar
1093 buffer: (this.get('buffer')) + newChar
1096 this.trigger('set_value',this.get('buffer'));
1098 deleteLastChar: function() {
1099 if(this.get('buffer') === ""){
1100 if(this.get('mode') === 'quantity'){
1101 this.trigger('set_value','remove');
1103 this.trigger('set_value',this.get('buffer'));
1106 var newBuffer = this.get('buffer').slice(0,-1) || "";
1107 this.set({ buffer: newBuffer });
1108 this.trigger('set_value',this.get('buffer'));
1111 switchSign: function() {
1113 oldBuffer = this.get('buffer');
1115 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1117 this.trigger('set_value',this.get('buffer'));
1119 changeMode: function(newMode) {
1131 resetValue: function(){
1132 this.set({buffer:'0'});