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', 'variants',
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 var logo_loaded = new $.Deferred();
261 self.company_logo.onload = function(){
262 var img = self.company_logo;
264 var targetwidth = 300;
266 if( img.width !== targetwidth ){
267 ratio = targetwidth / img.width;
269 if( img.height * ratio > maxheight ){
270 ratio = maxheight / img.height;
272 var width = Math.floor(img.width * ratio);
273 var height = Math.floor(img.height * ratio);
274 var c = document.createElement('canvas');
277 var ctx = c.getContext('2d');
278 ctx.drawImage(self.company_logo,0,0, width, height);
280 self.company_logo_base64 = c.toDataURL();
281 logo_loaded.resolve();
283 self.company_logo.onerror = function(){
284 logo_loaded.reject();
286 self.company_logo.src = '/web/binary/company_logo'+'?_'+Math.random();
294 // this is called when an order is removed from the order collection. It ensures that there is always an existing
295 // order and a valid selected order
296 on_removed_order: function(removed_order,index,reason){
297 if(reason === 'abandon' && this.get('orders').size() > 0){
298 // when we intentionally remove an unfinished order, and there is another existing one
299 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
301 // when the order was automatically removed after completion,
302 // or when we intentionally delete the only concurrent order
303 this.add_new_order();
307 //creates a new empty order and sets it as the current order
308 add_new_order: function(){
309 var order = new module.Order({pos:this});
310 this.get('orders').add(order);
311 this.set('selectedOrder', order);
314 //removes the current order
315 delete_current_order: function(){
316 this.get('selectedOrder').destroy({'reason':'abandon'});
319 // saves the order locally and try to send it to the backend.
320 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
321 push_order: function(order) {
323 this.proxy.log('push_order',order.export_as_JSON());
324 var order_id = this.db.add_order(order.export_as_JSON());
325 var pushed = new $.Deferred();
327 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
329 this.flush_mutex.exec(function(){
330 var flushed = self._flush_all_orders();
332 flushed.always(function(){
341 // saves the order locally and try to send it to the backend and make an invoice
342 // returns a deferred that succeeds when the order has been posted and successfully generated
343 // an invoice. This method can fail in various ways:
344 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
345 // this error is solved
346 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
347 // the network connection is up
349 push_and_invoice_order: function(order){
351 var invoiced = new $.Deferred();
353 if(!order.get_client()){
354 invoiced.reject('error-no-client');
358 var order_id = this.db.add_order(order.export_as_JSON());
360 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
362 this.flush_mutex.exec(function(){
363 var done = new $.Deferred(); // holds the mutex
365 // send the order to the server
366 // we have a 30 seconds timeout on this push.
367 // FIXME: if the server takes more than 30 seconds to accept the order,
368 // the client will believe it wasn't successfully sent, and very bad
369 // things will happen as a duplicate will be sent next time
370 // so we must make sure the server detects and ignores duplicated orders
372 var transfer = self._flush_order(order_id, {timeout:30000, to_invoice:true});
374 transfer.fail(function(){
375 invoiced.reject('error-transfer');
379 // on success, get the order id generated by the server
380 transfer.pipe(function(order_server_id){
381 // generate the pdf and download it
382 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
383 active_ids:order_server_id,
396 // attemps to send all pending orders ( stored in the pos_db ) to the server,
397 // and remove the successfully sent ones from the db once
398 // it has been confirmed that they have been sent correctly.
401 var flushed = new $.Deferred();
403 this.flush_mutex.exec(function(){
404 var done = new $.Deferred();
406 self._flush_all_orders()
407 .done( function(){ flushed.resolve();})
408 .fail( function(){ flushed.reject(); })
409 .always(function(){ done.resolve(); });
417 // attempts to send the locally stored order of id 'order_id'
418 // the sending is asynchronous and can take some time to decide if it is successful or not
419 // it is therefore important to only call this method from inside a mutex
420 // this method returns a deferred indicating wether the sending was successful or not
421 // there is a timeout parameter which is set to 2 seconds by default.
422 _flush_order: function( order_id, options) {
423 return this._flush_all_orders([this.db.get_order(order_id)], options);
426 // attempts to send all the locally stored orders. As with _flush_order, it should only be
427 // called from within a mutex.
428 // this method returns a deferred that always succeeds when all orders have been tried to be sent,
429 // even if none of them could actually be sent.
430 _flush_all_orders: function ( order, options) {
432 orders = order || self.db.get_orders()
435 pending: self.get('synch').pending
437 return self._save_to_server( orders, options).done(function () {
438 var pending = orders.length;
440 state: pending ? 'connecting' : 'connected',
446 // send an array of orders to the server
447 // available options:
448 // - timeout: timeout for the rpc call in ms
449 _save_to_server: function (orders, options) {
450 if (!orders || !orders.length) {
451 var result = $.Deferred();
456 options = options || {};
459 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
461 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
462 // then we want to notify the user that we are waiting on something )
463 var posOrderModel = new instance.web.Model('pos.order');
464 return posOrderModel.call('create_from_ui',
465 [_.map(orders, function (order) {
466 order.to_invoice = options.to_invoice || false;
471 shadow: !options.to_invoice,
475 _.each(orders, function (order) {
476 self.db.remove_order(order.id);
478 }).fail(function (unused, event){
479 // prevent an error popup creation by the rpc failure
480 // we want the failure to be silent as we send the orders in the background
481 event.preventDefault();
482 console.error('Failed to send orders:', orders);
486 scan_product: function(parsed_code){
488 var selectedOrder = this.get('selectedOrder');
489 if(parsed_code.encoding === 'ean13'){
490 var product = this.db.get_product_by_ean13(parsed_code.base_code);
491 }else if(parsed_code.encoding === 'reference'){
492 var product = this.db.get_product_by_reference(parsed_code.code);
499 if(parsed_code.type === 'price'){
500 selectedOrder.addProduct(product, {price:parsed_code.value});
501 }else if(parsed_code.type === 'weight'){
502 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
504 selectedOrder.addProduct(product);
510 // An orderline represent one element of the content of a client's shopping cart.
511 // An orderline contains a product, its quantity, its price, discount. etc.
512 // An Order contains zero or more Orderlines.
513 module.Orderline = Backbone.Model.extend({
514 initialize: function(attr,options){
515 this.pos = options.pos;
516 this.order = options.order;
517 this.product = options.product;
518 this.price = options.product.price;
520 this.quantityStr = '1';
522 this.discountStr = '0';
524 this.selected = false;
526 // sets a discount [0,100]%
527 set_discount: function(discount){
528 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
529 this.discount = disc;
530 this.discountStr = '' + disc;
531 this.trigger('change',this);
533 // returns the discount [0,100]%
534 get_discount: function(){
535 return this.discount;
537 get_discount_str: function(){
538 return this.discountStr;
540 get_product_type: function(){
543 // sets the quantity of the product. The quantity will be rounded according to the
544 // product's unity of measure properties. Quantities greater than zero will not get
546 set_quantity: function(quantity){
547 if(quantity === 'remove'){
548 this.order.removeOrderline(this);
551 var quant = Math.max(parseFloat(quantity) || 0, 0);
552 var unit = this.get_unit();
554 this.quantity = Math.max(unit.rounding, round_pr(quant, unit.rounding));
555 this.quantityStr = this.quantity.toFixed(Math.max(0,Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10))));
557 this.quantity = quant;
558 this.quantityStr = '' + this.quantity;
561 this.trigger('change',this);
563 // return the quantity of product
564 get_quantity: function(){
565 return this.quantity;
567 get_quantity_str: function(){
568 return this.quantityStr;
570 get_quantity_str_with_unit: function(){
571 var unit = this.get_unit();
572 if(unit && unit.name !== 'Unit(s)'){
573 return this.quantityStr + ' ' + unit.name;
575 return this.quantityStr;
578 // return the unit of measure of the product
579 get_unit: function(){
580 var unit_id = (this.product.uos_id || this.product.uom_id);
584 unit_id = unit_id[0];
588 return this.pos.units_by_id[unit_id];
590 // return the product of this orderline
591 get_product: function(){
594 // selects or deselects this orderline
595 set_selected: function(selected){
596 this.selected = selected;
597 this.trigger('change',this);
599 // returns true if this orderline is selected
600 is_selected: function(){
601 return this.selected;
603 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
604 // in the orderline. This returns true if it makes sense to merge the two
605 can_be_merged_with: function(orderline){
606 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
608 }else if(this.get_product_type() !== orderline.get_product_type()){
610 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
612 }else if(this.price !== orderline.price){
618 merge: function(orderline){
619 this.set_quantity(this.get_quantity() + orderline.get_quantity());
621 export_as_JSON: function() {
623 qty: this.get_quantity(),
624 price_unit: this.get_unit_price(),
625 discount: this.get_discount(),
626 product_id: this.get_product().id,
629 //used to create a json of the ticket, to be sent to the printer
630 export_for_printing: function(){
632 quantity: this.get_quantity(),
633 unit_name: this.get_unit().name,
634 price: this.get_unit_price(),
635 discount: this.get_discount(),
636 product_name: this.get_product().name,
637 price_display : this.get_display_price(),
638 price_with_tax : this.get_price_with_tax(),
639 price_without_tax: this.get_price_without_tax(),
641 product_description: this.get_product().description,
642 product_description_sale: this.get_product().description_sale,
645 // changes the base price of the product for this orderline
646 set_unit_price: function(price){
647 this.price = round_di(parseFloat(price) || 0, 2);
648 this.trigger('change',this);
650 get_unit_price: function(){
651 var rounding = this.pos.currency.rounding;
652 return round_pr(this.price,rounding);
654 get_display_price: function(){
655 var rounding = this.pos.currency.rounding;
656 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
658 get_price_without_tax: function(){
659 return this.get_all_prices().priceWithoutTax;
661 get_price_with_tax: function(){
662 return this.get_all_prices().priceWithTax;
665 return this.get_all_prices().tax;
667 get_tax_details: function(){
668 return this.get_all_prices().taxDetails;
670 get_all_prices: function(){
672 var currency_rounding = this.pos.currency.rounding;
673 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
675 var totalNoTax = base;
677 var product = this.get_product();
678 var taxes_ids = product.taxes_id;
679 var taxes = self.pos.taxes;
682 _.each(taxes_ids, function(el) {
683 var tax = _.detect(taxes, function(t) {return t.id === el;});
684 if (tax.price_include) {
686 if (tax.type === "percent") {
687 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
688 } else if (tax.type === "fixed") {
689 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
691 throw "This type of tax is not supported by the point of sale: " + tax.type;
693 tmp = round_pr(tmp,currency_rounding);
696 taxdetail[tax.id] = tmp;
699 if (tax.type === "percent") {
700 tmp = tax.amount * base;
701 } else if (tax.type === "fixed") {
702 tmp = tax.amount * self.get_quantity();
704 throw "This type of tax is not supported by the point of sale: " + tax.type;
706 tmp = round_pr(tmp,currency_rounding);
709 taxdetail[tax.id] = tmp;
713 "priceWithTax": totalTax,
714 "priceWithoutTax": totalNoTax,
716 "taxDetails": taxdetail,
721 module.OrderlineCollection = Backbone.Collection.extend({
722 model: module.Orderline,
725 // Every Paymentline contains a cashregister and an amount of money.
726 module.Paymentline = Backbone.Model.extend({
727 initialize: function(attributes, options) {
729 this.cashregister = options.cashregister;
730 this.name = this.cashregister.journal_id[1];
731 this.selected = false;
733 //sets the amount of money on this payment line
734 set_amount: function(value){
735 this.amount = round_di(parseFloat(value) || 0, 2);
736 this.trigger('change:amount',this);
738 // returns the amount of money on this paymentline
739 get_amount: function(){
742 set_selected: function(selected){
743 if(this.selected !== selected){
744 this.selected = selected;
745 this.trigger('change:selected',this);
748 // returns the associated cashregister
749 //exports as JSON for server communication
750 export_as_JSON: function(){
752 name: instance.web.datetime_to_str(new Date()),
753 statement_id: this.cashregister.id,
754 account_id: this.cashregister.account_id[0],
755 journal_id: this.cashregister.journal_id[0],
756 amount: this.get_amount()
759 //exports as JSON for receipt printing
760 export_for_printing: function(){
762 amount: this.get_amount(),
763 journal: this.cashregister.journal_id[1],
768 module.PaymentlineCollection = Backbone.Collection.extend({
769 model: module.Paymentline,
773 // An order more or less represents the content of a client's shopping cart (the OrderLines)
774 // plus the associated payment information (the Paymentlines)
775 // there is always an active ('selected') order in the Pos, a new one is created
776 // automaticaly once an order is completed and sent to the server.
777 module.Order = Backbone.Model.extend({
778 initialize: function(attributes){
779 Backbone.Model.prototype.initialize.apply(this, arguments);
780 this.uid = this.generateUniqueId();
782 creationDate: new Date(),
783 orderLines: new module.OrderlineCollection(),
784 paymentLines: new module.PaymentlineCollection(),
785 name: "Order " + this.uid,
788 this.pos = attributes.pos;
789 this.selected_orderline = undefined;
790 this.selected_paymentline = undefined;
791 this.screen_data = {}; // see ScreenSelector
792 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
795 generateUniqueId: function() {
796 return new Date().getTime();
798 addProduct: function(product, options){
799 options = options || {};
800 var attr = JSON.parse(JSON.stringify(product));
803 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
805 if(options.quantity !== undefined){
806 line.set_quantity(options.quantity);
808 if(options.price !== undefined){
809 line.set_unit_price(options.price);
812 var last_orderline = this.getLastOrderline();
813 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
814 last_orderline.merge(line);
816 this.get('orderLines').add(line);
818 this.selectLine(this.getLastOrderline());
820 removeOrderline: function( line ){
821 this.get('orderLines').remove(line);
822 this.selectLine(this.getLastOrderline());
824 getLastOrderline: function(){
825 return this.get('orderLines').at(this.get('orderLines').length -1);
827 addPaymentline: function(cashregister) {
828 var paymentLines = this.get('paymentLines');
829 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
830 if(cashregister.journal.type !== 'cash'){
831 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
833 paymentLines.add(newPaymentline);
834 this.selectPaymentline(newPaymentline);
837 removePaymentline: function(line){
838 if(this.selected_paymentline === line){
839 this.selectPaymentline(undefined);
841 this.get('paymentLines').remove(line);
843 getName: function() {
844 return this.get('name');
846 getSubtotal : function(){
847 return (this.get('orderLines')).reduce((function(sum, orderLine){
848 return sum + orderLine.get_display_price();
851 getTotalTaxIncluded: function() {
852 return (this.get('orderLines')).reduce((function(sum, orderLine) {
853 return sum + orderLine.get_price_with_tax();
856 getDiscountTotal: function() {
857 return (this.get('orderLines')).reduce((function(sum, orderLine) {
858 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
861 getTotalTaxExcluded: function() {
862 return (this.get('orderLines')).reduce((function(sum, orderLine) {
863 return sum + orderLine.get_price_without_tax();
867 return (this.get('orderLines')).reduce((function(sum, orderLine) {
868 return sum + orderLine.get_tax();
871 getTaxDetails: function(){
873 var fulldetails = [];
874 var taxes_by_id = {};
876 for(var i = 0; i < this.pos.taxes.length; i++){
877 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
880 this.get('orderLines').each(function(line){
881 var ldetails = line.get_tax_details();
882 for(var id in ldetails){
883 if(ldetails.hasOwnProperty(id)){
884 details[id] = (details[id] || 0) + ldetails[id];
889 for(var id in details){
890 if(details.hasOwnProperty(id)){
891 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
897 getPaidTotal: function() {
898 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
899 return sum + paymentLine.get_amount();
902 getChange: function() {
903 return this.getPaidTotal() - this.getTotalTaxIncluded();
905 getDueLeft: function() {
906 return this.getTotalTaxIncluded() - this.getPaidTotal();
908 // sets the type of receipt 'receipt'(default) or 'invoice'
909 set_receipt_type: function(type){
910 this.receipt_type = type;
912 get_receipt_type: function(){
913 return this.receipt_type;
915 // the client related to the current order.
916 set_client: function(client){
917 this.set('client',client);
919 get_client: function(){
920 return this.get('client');
922 get_client_name: function(){
923 var client = this.get('client');
924 return client ? client.name : "";
926 // the order also stores the screen status, as the PoS supports
927 // different active screens per order. This method is used to
928 // store the screen status.
929 set_screen_data: function(key,value){
930 if(arguments.length === 2){
931 this.screen_data[key] = value;
932 }else if(arguments.length === 1){
933 for(key in arguments[0]){
934 this.screen_data[key] = arguments[0][key];
938 //see set_screen_data
939 get_screen_data: function(key){
940 return this.screen_data[key];
942 // exports a JSON for receipt printing
943 export_for_printing: function(){
945 this.get('orderLines').each(function(orderline){
946 orderlines.push(orderline.export_for_printing());
949 var paymentlines = [];
950 this.get('paymentLines').each(function(paymentline){
951 paymentlines.push(paymentline.export_for_printing());
953 var client = this.get('client');
954 var cashier = this.pos.cashier || this.pos.user;
955 var company = this.pos.company;
956 var shop = this.pos.shop;
957 var date = new Date();
960 orderlines: orderlines,
961 paymentlines: paymentlines,
962 subtotal: this.getSubtotal(),
963 total_with_tax: this.getTotalTaxIncluded(),
964 total_without_tax: this.getTotalTaxExcluded(),
965 total_tax: this.getTax(),
966 total_paid: this.getPaidTotal(),
967 total_discount: this.getDiscountTotal(),
968 tax_details: this.getTaxDetails(),
969 change: this.getChange(),
970 name : this.getName(),
971 client: client ? client.name : null ,
972 invoice_id: null, //TODO
973 cashier: cashier ? cashier.name : null,
974 header: this.pos.config.receipt_header || '',
975 footer: this.pos.config.receipt_footer || '',
982 year: date.getFullYear(),
983 month: date.getMonth(),
984 date: date.getDate(), // day of the month
985 day: date.getDay(), // day of the week
986 hour: date.getHours(),
987 minute: date.getMinutes() ,
988 isostring: date.toISOString(),
991 email: company.email,
992 website: company.website,
993 company_registry: company.company_registry,
994 contact_address: company.partner_id[1],
997 phone: company.phone,
998 logo: this.pos.company_logo_base64,
1003 currency: this.pos.currency,
1006 export_as_JSON: function() {
1007 var orderLines, paymentLines;
1009 (this.get('orderLines')).each(_.bind( function(item) {
1010 return orderLines.push([0, 0, item.export_as_JSON()]);
1013 (this.get('paymentLines')).each(_.bind( function(item) {
1014 return paymentLines.push([0, 0, item.export_as_JSON()]);
1017 name: this.getName(),
1018 amount_paid: this.getPaidTotal(),
1019 amount_total: this.getTotalTaxIncluded(),
1020 amount_tax: this.getTax(),
1021 amount_return: this.getChange(),
1023 statement_ids: paymentLines,
1024 pos_session_id: this.pos.pos_session.id,
1025 partner_id: this.get_client() ? this.get_client().id : false,
1026 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1030 getSelectedLine: function(){
1031 return this.selected_orderline;
1033 selectLine: function(line){
1035 if(line !== this.selected_orderline){
1036 if(this.selected_orderline){
1037 this.selected_orderline.set_selected(false);
1039 this.selected_orderline = line;
1040 this.selected_orderline.set_selected(true);
1043 this.selected_orderline = undefined;
1046 deselectLine: function(){
1047 if(this.selected_orderline){
1048 this.selected_orderline.set_selected(false);
1049 this.selected_orderline = undefined;
1052 selectPaymentline: function(line){
1053 if(line !== this.selected_paymentline){
1054 if(this.selected_paymentline){
1055 this.selected_paymentline.set_selected(false);
1057 this.selected_paymentline = line;
1058 if(this.selected_paymentline){
1059 this.selected_paymentline.set_selected(true);
1061 this.trigger('change:selected_paymentline',this.selected_paymentline);
1066 module.OrderCollection = Backbone.Collection.extend({
1067 model: module.Order,
1071 The numpad handles both the choice of the property currently being modified
1072 (quantity, price or discount) and the edition of the corresponding numeric value.
1074 module.NumpadState = Backbone.Model.extend({
1079 appendNewChar: function(newChar) {
1081 oldBuffer = this.get('buffer');
1082 if (oldBuffer === '0') {
1086 } else if (oldBuffer === '-0') {
1088 buffer: "-" + newChar
1092 buffer: (this.get('buffer')) + newChar
1095 this.trigger('set_value',this.get('buffer'));
1097 deleteLastChar: function() {
1098 if(this.get('buffer') === ""){
1099 if(this.get('mode') === 'quantity'){
1100 this.trigger('set_value','remove');
1102 this.trigger('set_value',this.get('buffer'));
1105 var newBuffer = this.get('buffer').slice(0,-1) || "";
1106 this.set({ buffer: newBuffer });
1107 this.trigger('set_value',this.get('buffer'));
1110 switchSign: function() {
1112 oldBuffer = this.get('buffer');
1114 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1116 this.trigger('set_value',this.get('buffer'));
1118 changeMode: function(newMode) {
1130 resetValue: function(){
1131 this.set({buffer:'0'});