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, patterns: {}}); // 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 this.order_sequence = 1;
52 window.posmodel = this;
54 // these dynamic attributes can be watched for change by other models or widgets
56 'synch': { state:'connected', pending:0 },
57 'orders': new module.OrderCollection(),
58 'selectedOrder': null,
61 this.bind('change:synch',function(pos,synch){
62 clearTimeout(self.synch_timeout);
63 self.synch_timeout = setTimeout(function(){
64 if(synch.state !== 'disconnected' && synch.pending > 0){
65 self.set('synch',{state:'disconnected', pending:synch.pending});
70 this.get('orders').bind('remove', function(order,_unused_,options){
71 self.on_removed_order(order,options.index,options.reason);
74 // We fetch the backend data on the server asynchronously. this is done only when the pos user interface is launched,
75 // Any change on this data made on the server is thus not reflected on the point of sale until it is relaunched.
76 // when all the data has loaded, we compute some stuff, and declare the Pos ready to be used.
77 this.ready = this.load_server_data()
79 if(self.config.use_proxy){
80 return self.connect_to_proxy();
86 // releases ressources holds by the model at the end of life of the posmodel
88 // FIXME, should wait for flushing, return a deferred to indicate successfull destruction
91 this.barcode_reader.disconnect();
92 this.barcode_reader.disconnect_from_proxy();
94 connect_to_proxy: function(){
96 var done = new $.Deferred();
97 this.barcode_reader.disconnect_from_proxy();
98 this.pos_widget.loading_message(_t('Connecting to the PosBox'),0);
99 this.pos_widget.loading_skip(function(){
100 self.proxy.stop_searching();
102 this.proxy.autoconnect({
103 force_ip: self.config.proxy_ip || undefined,
104 progress: function(prog){
105 self.pos_widget.loading_progress(prog);
108 if(self.config.iface_scan_via_proxy){
109 self.barcode_reader.connect_to_proxy();
111 }).always(function(){
117 // helper function to load data from the server
118 fetch: function(model, fields, domain, ctx){
119 this._load_progress = (this._load_progress || 0) + 0.05;
120 this.pos_widget.loading_message(_t('Loading')+' '+model,this._load_progress);
121 return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
124 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
125 load_server_data: function(){
128 var loaded = self.fetch('res.users',['name','company_id'],[['id','=',this.session.uid]])
129 .then(function(users){
130 self.user = users[0];
132 return self.fetch('res.company',
143 [['id','=',users[0].company_id[0]]],
144 {show_address_only: true});
145 }).then(function(companies){
146 self.company = companies[0];
148 return self.fetch('product.uom', null, null);
149 }).then(function(units){
151 var units_by_id = {};
152 for(var i = 0, len = units.length; i < len; i++){
153 units_by_id[units[i].id] = units[i];
154 units[i].groupable = ( units[i].category_id[0] === 1 );
155 units[i].is_unit = ( units[i].id === 1 );
157 self.units_by_id = units_by_id;
159 return self.fetch('res.users', ['name','ean13'], [['ean13', '!=', false]]);
160 }).then(function(users){
163 return self.fetch('res.partner', ['name','street','city','country_id','phone','zip','mobile','email','ean13']);
164 }).then(function(partners){
165 self.partners = partners;
166 self.db.add_partners(partners);
168 return self.fetch('account.tax', ['name','amount', 'price_include', 'type']);
169 }).then(function(taxes){
174 ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number'],
175 [['state', '=', 'opened'], ['user_id', '=', self.session.uid]]
177 }).then(function(pos_sessions){
178 self.pos_session = pos_sessions[0];
180 return self.fetch('pos.config',[],[['id','=', self.pos_session.config_id[0]]]);
181 }).then(function(configs){
182 self.config = configs[0];
183 self.config.use_proxy = self.config.iface_payment_terminal ||
184 self.config.iface_electronic_scale ||
185 self.config.iface_print_via_proxy ||
186 self.config.iface_scan_via_proxy ||
187 self.config.iface_cashdrawer;
189 self.barcode_reader.add_barcode_patterns({
190 'product': self.config.barcode_product,
191 'cashier': self.config.barcode_cashier,
192 'client': self.config.barcode_customer,
193 'weight': self.config.barcode_weight,
194 'discount': self.config.barcode_discount,
195 'price': self.config.barcode_price,
197 return self.fetch('stock.location',[],[['id','=', self.config.stock_location_id[0]]]);
198 }).then(function(shops){
199 self.shop = shops[0];
201 return self.fetch('product.pricelist',['currency_id'],[['id','=',self.config.pricelist_id[0]]]);
202 }).then(function(pricelists){
203 self.pricelist = pricelists[0];
205 return self.fetch('res.currency',['symbol','position','rounding','accuracy'],[['id','=',self.pricelist.currency_id[0]]]);
206 }).then(function(currencies){
207 self.currency = currencies[0];
209 return self.fetch('product.packaging',['ean','product_tmpl_id']);
210 }).then(function(packagings){
211 self.db.add_packagings(packagings);
213 return self.fetch('pos.category', ['id','name','parent_id','child_id','image']);
214 }).then(function(categories){
215 self.db.add_categories(categories);
219 ['name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code', 'variants',
220 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
222 [['sale_ok','=',true],['available_in_pos','=',true]],
223 {pricelist: self.pricelist.id} // context for price
225 }).then(function(products){
226 self.db.add_products(products);
229 'account.bank.statement',
230 ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
231 [['state','=','open'],['pos_session_id', '=', self.pos_session.id]]
233 }).then(function(bankstatements){
235 _.each(bankstatements,function(statement) {
236 journals.push(statement.journal_id[0]);
238 self.bankstatements = bankstatements;
239 return self.fetch('account.journal', undefined, [['id','in', journals]]);
240 }).then(function(journals){
241 self.journals = journals;
243 // associate the bank statements with their journals.
244 var bankstatements = self.bankstatements;
245 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
246 for(var j = 0, jlen = journals.length; j < jlen; j++){
247 if(bankstatements[i].journal_id[0] === journals[j].id){
248 bankstatements[i].journal = journals[j];
249 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
253 self.cashregisters = bankstatements;
255 // Load the company Logo
257 self.company_logo = new Image();
258 self.company_logo.crossOrigin = 'anonymous';
259 var logo_loaded = new $.Deferred();
260 self.company_logo.onload = function(){
261 var img = self.company_logo;
263 var targetwidth = 300;
265 if( img.width !== targetwidth ){
266 ratio = targetwidth / img.width;
268 if( img.height * ratio > maxheight ){
269 ratio = maxheight / img.height;
271 var width = Math.floor(img.width * ratio);
272 var height = Math.floor(img.height * ratio);
273 var c = document.createElement('canvas');
276 var ctx = c.getContext('2d');
277 ctx.drawImage(self.company_logo,0,0, width, height);
279 self.company_logo_base64 = c.toDataURL();
280 window.logo64 = self.company_logo_base64;
281 logo_loaded.resolve();
283 self.company_logo.onerror = function(){
284 logo_loaded.reject();
286 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
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' || removed_order.temporary) && 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 get_order: function(){
315 return this.get('selectedOrder');
318 //removes the current order
319 delete_current_order: function(){
320 this.get('selectedOrder').destroy({'reason':'abandon'});
323 // saves the order locally and try to send it to the backend.
324 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
325 push_order: function(order) {
327 this.proxy.log('push_order',order.export_as_JSON());
328 var order_id = this.db.add_order(order.export_as_JSON());
329 var pushed = new $.Deferred();
331 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
333 this.flush_mutex.exec(function(){
334 var flushed = self._flush_all_orders();
336 flushed.always(function(){
345 // saves the order locally and try to send it to the backend and make an invoice
346 // returns a deferred that succeeds when the order has been posted and successfully generated
347 // an invoice. This method can fail in various ways:
348 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
349 // this error is solved
350 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
351 // the network connection is up
353 push_and_invoice_order: function(order){
355 var invoiced = new $.Deferred();
357 if(!order.get_client()){
358 invoiced.reject('error-no-client');
362 var order_id = this.db.add_order(order.export_as_JSON());
364 this.set('synch',{state:'connecting', pending:self.db.get_orders().length});
366 this.flush_mutex.exec(function(){
367 var done = new $.Deferred(); // holds the mutex
369 // send the order to the server
370 // we have a 30 seconds timeout on this push.
371 // FIXME: if the server takes more than 30 seconds to accept the order,
372 // the client will believe it wasn't successfully sent, and very bad
373 // things will happen as a duplicate will be sent next time
374 // so we must make sure the server detects and ignores duplicated orders
376 var transfer = self._flush_order(order_id, {timeout:30000, to_invoice:true});
378 transfer.fail(function(){
379 invoiced.reject('error-transfer');
383 // on success, get the order id generated by the server
384 transfer.pipe(function(order_server_id){
385 // generate the pdf and download it
386 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
387 active_ids:order_server_id,
400 // attemps to send all pending orders ( stored in the pos_db ) to the server,
401 // and remove the successfully sent ones from the db once
402 // it has been confirmed that they have been sent correctly.
405 var flushed = new $.Deferred();
407 this.flush_mutex.exec(function(){
408 var done = new $.Deferred();
410 self._flush_all_orders()
411 .done( function(){ flushed.resolve();})
412 .fail( function(){ flushed.reject(); })
413 .always(function(){ done.resolve(); });
421 // attempts to send the locally stored order of id 'order_id'
422 // the sending is asynchronous and can take some time to decide if it is successful or not
423 // it is therefore important to only call this method from inside a mutex
424 // this method returns a deferred indicating wether the sending was successful or not
425 // there is a timeout parameter which is set to 2 seconds by default.
426 _flush_order: function( order_id, options) {
427 return this._flush_all_orders([this.db.get_order(order_id)], options);
430 // attempts to send all the locally stored orders. As with _flush_order, it should only be
431 // called from within a mutex.
432 // this method returns a deferred that always succeeds when all orders have been tried to be sent,
433 // even if none of them could actually be sent.
434 _flush_all_orders: function () {
438 pending: self.get('synch').pending
440 return self._save_to_server(self.db.get_orders()).done(function () {
441 var pending = self.db.get_orders().length;
443 state: pending ? 'connecting' : 'connected',
449 // send an array of orders to the server
450 // available options:
451 // - timeout: timeout for the rpc call in ms
452 _save_to_server: function (orders, options) {
453 if (!orders || !orders.length) {
454 var result = $.Deferred();
459 options = options || {};
462 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
464 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
465 // then we want to notify the user that we are waiting on something )
466 var posOrderModel = new instance.web.Model('pos.order');
467 return posOrderModel.call('create_from_ui',
468 [_.map(orders, function (order) {
469 order.to_invoice = options.to_invoice || false;
474 shadow: !options.to_invoice,
478 _.each(orders, function (order) {
479 self.db.remove_order(order.id);
481 }).fail(function (unused, event){
482 // prevent an error popup creation by the rpc failure
483 // we want the failure to be silent as we send the orders in the background
484 event.preventDefault();
485 console.error('Failed to send orders:', orders);
489 scan_product: function(parsed_code){
491 var selectedOrder = this.get('selectedOrder');
492 if(parsed_code.encoding === 'ean13'){
493 var product = this.db.get_product_by_ean13(parsed_code.base_code);
494 }else if(parsed_code.encoding === 'reference'){
495 var product = this.db.get_product_by_reference(parsed_code.code);
502 if(parsed_code.type === 'price'){
503 selectedOrder.addProduct(product, {price:parsed_code.value});
504 }else if(parsed_code.type === 'weight'){
505 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
506 }else if(parsed_code.type === 'discount'){
507 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
509 selectedOrder.addProduct(product);
515 var orderline_id = 1;
517 // An orderline represent one element of the content of a client's shopping cart.
518 // An orderline contains a product, its quantity, its price, discount. etc.
519 // An Order contains zero or more Orderlines.
520 module.Orderline = Backbone.Model.extend({
521 initialize: function(attr,options){
522 this.pos = options.pos;
523 this.order = options.order;
524 this.product = options.product;
525 this.price = options.product.price;
527 this.quantityStr = '1';
529 this.discountStr = '0';
531 this.selected = false;
532 this.id = orderline_id++;
535 var orderline = new module.Orderline({},{
538 product: this.product,
541 orderline.quantity = this.quantity;
542 orderline.quantityStr = this.quantityStr;
543 orderline.discount = this.discount;
544 orderline.type = this.type;
545 orderline.selected = false;
548 // sets a discount [0,100]%
549 set_discount: function(discount){
550 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
551 this.discount = disc;
552 this.discountStr = '' + disc;
553 this.trigger('change',this);
555 // returns the discount [0,100]%
556 get_discount: function(){
557 return this.discount;
559 get_discount_str: function(){
560 return this.discountStr;
562 get_product_type: function(){
565 // sets the quantity of the product. The quantity will be rounded according to the
566 // product's unity of measure properties. Quantities greater than zero will not get
568 set_quantity: function(quantity){
569 if(quantity === 'remove'){
570 this.order.removeOrderline(this);
573 var quant = parseFloat(quantity) || 0;
574 var unit = this.get_unit();
576 this.quantity = round_pr(quant, unit.rounding);
577 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
579 this.quantity = quant;
580 this.quantityStr = '' + this.quantity;
583 this.trigger('change',this);
585 // return the quantity of product
586 get_quantity: function(){
587 return this.quantity;
589 get_quantity_str: function(){
590 return this.quantityStr;
592 get_quantity_str_with_unit: function(){
593 var unit = this.get_unit();
594 if(unit && !unit.is_unit){
595 return this.quantityStr + ' ' + unit.name;
597 return this.quantityStr;
600 // return the unit of measure of the product
601 get_unit: function(){
602 var unit_id = (this.product.uos_id || this.product.uom_id);
606 unit_id = unit_id[0];
610 return this.pos.units_by_id[unit_id];
612 // return the product of this orderline
613 get_product: function(){
616 // selects or deselects this orderline
617 set_selected: function(selected){
618 this.selected = selected;
619 this.trigger('change',this);
621 // returns true if this orderline is selected
622 is_selected: function(){
623 return this.selected;
625 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
626 // in the orderline. This returns true if it makes sense to merge the two
627 can_be_merged_with: function(orderline){
628 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
630 }else if(!this.get_unit() || !this.get_unit().groupable){
632 }else if(this.get_product_type() !== orderline.get_product_type()){
634 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
636 }else if(this.price !== orderline.price){
642 merge: function(orderline){
643 this.set_quantity(this.get_quantity() + orderline.get_quantity());
645 export_as_JSON: function() {
647 qty: this.get_quantity(),
648 price_unit: this.get_unit_price(),
649 discount: this.get_discount(),
650 product_id: this.get_product().id,
653 //used to create a json of the ticket, to be sent to the printer
654 export_for_printing: function(){
656 quantity: this.get_quantity(),
657 unit_name: this.get_unit().name,
658 price: this.get_unit_price(),
659 discount: this.get_discount(),
660 product_name: this.get_product().name,
661 price_display : this.get_display_price(),
662 price_with_tax : this.get_price_with_tax(),
663 price_without_tax: this.get_price_without_tax(),
665 product_description: this.get_product().description,
666 product_description_sale: this.get_product().description_sale,
669 // changes the base price of the product for this orderline
670 set_unit_price: function(price){
671 this.price = round_di(parseFloat(price) || 0, 2);
672 this.trigger('change',this);
674 get_unit_price: function(){
675 var rounding = this.pos.currency.rounding;
676 return round_pr(this.price,rounding);
678 get_display_price: function(){
679 var rounding = this.pos.currency.rounding;
680 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
682 get_price_without_tax: function(){
683 return this.get_all_prices().priceWithoutTax;
685 get_price_with_tax: function(){
686 return this.get_all_prices().priceWithTax;
689 return this.get_all_prices().tax;
691 get_tax_details: function(){
692 return this.get_all_prices().taxDetails;
694 get_all_prices: function(){
696 var currency_rounding = this.pos.currency.rounding;
697 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
699 var totalNoTax = base;
701 var product = this.get_product();
702 var taxes_ids = product.taxes_id;
703 var taxes = self.pos.taxes;
706 _.each(taxes_ids, function(el) {
707 var tax = _.detect(taxes, function(t) {return t.id === el;});
708 if (tax.price_include) {
710 if (tax.type === "percent") {
711 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
712 } else if (tax.type === "fixed") {
713 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
715 throw "This type of tax is not supported by the point of sale: " + tax.type;
717 tmp = round_pr(tmp,currency_rounding);
720 taxdetail[tax.id] = tmp;
723 if (tax.type === "percent") {
724 tmp = tax.amount * base;
725 } else if (tax.type === "fixed") {
726 tmp = tax.amount * self.get_quantity();
728 throw "This type of tax is not supported by the point of sale: " + tax.type;
730 tmp = round_pr(tmp,currency_rounding);
733 taxdetail[tax.id] = tmp;
737 "priceWithTax": totalTax,
738 "priceWithoutTax": totalNoTax,
740 "taxDetails": taxdetail,
745 module.OrderlineCollection = Backbone.Collection.extend({
746 model: module.Orderline,
749 // Every Paymentline contains a cashregister and an amount of money.
750 module.Paymentline = Backbone.Model.extend({
751 initialize: function(attributes, options) {
753 this.cashregister = options.cashregister;
754 this.name = this.cashregister.journal_id[1];
755 this.selected = false;
757 //sets the amount of money on this payment line
758 set_amount: function(value){
759 this.amount = round_di(parseFloat(value) || 0, 2);
760 this.trigger('change:amount',this);
762 // returns the amount of money on this paymentline
763 get_amount: function(){
766 set_selected: function(selected){
767 if(this.selected !== selected){
768 this.selected = selected;
769 this.trigger('change:selected',this);
772 // returns the associated cashregister
773 //exports as JSON for server communication
774 export_as_JSON: function(){
776 name: instance.web.datetime_to_str(new Date()),
777 statement_id: this.cashregister.id,
778 account_id: this.cashregister.account_id[0],
779 journal_id: this.cashregister.journal_id[0],
780 amount: this.get_amount()
783 //exports as JSON for receipt printing
784 export_for_printing: function(){
786 amount: this.get_amount(),
787 journal: this.cashregister.journal_id[1],
792 module.PaymentlineCollection = Backbone.Collection.extend({
793 model: module.Paymentline,
797 // An order more or less represents the content of a client's shopping cart (the OrderLines)
798 // plus the associated payment information (the Paymentlines)
799 // there is always an active ('selected') order in the Pos, a new one is created
800 // automaticaly once an order is completed and sent to the server.
801 module.Order = Backbone.Model.extend({
802 initialize: function(attributes){
803 Backbone.Model.prototype.initialize.apply(this, arguments);
804 this.uid = this.generateUniqueId();
806 creationDate: new Date(),
807 orderLines: new module.OrderlineCollection(),
808 paymentLines: new module.PaymentlineCollection(),
809 name: "Order " + this.uid,
812 this.pos = attributes.pos;
813 this.selected_orderline = undefined;
814 this.selected_paymentline = undefined;
815 this.screen_data = {}; // see ScreenSelector
816 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
817 this.temporary = attributes.temporary || false;
818 this.sequence_number = this.pos.pos_session.sequence_number++;
821 is_empty: function(){
822 return (this.get('orderLines').models.length === 0);
824 generateUniqueId: function() {
825 return new Date().getTime();
827 addOrderline: function(line){
829 order.removeOrderline(line);
832 this.get('orderLines').add(line);
833 this.selectLine(this.getLastOrderline());
835 addProduct: function(product, options){
836 options = options || {};
837 var attr = JSON.parse(JSON.stringify(product));
840 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
842 if(options.quantity !== undefined){
843 line.set_quantity(options.quantity);
845 if(options.price !== undefined){
846 line.set_unit_price(options.price);
848 if(options.discount !== undefined){
849 line.set_discount(options.discount);
852 var last_orderline = this.getLastOrderline();
853 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
854 last_orderline.merge(line);
856 this.get('orderLines').add(line);
858 this.selectLine(this.getLastOrderline());
860 removeOrderline: function( line ){
861 this.get('orderLines').remove(line);
862 this.selectLine(this.getLastOrderline());
864 getOrderline: function(id){
865 var orderlines = this.get('orderLines').models;
866 for(var i = 0; i < orderlines.length; i++){
867 if(orderlines[i].id === id){
868 return orderlines[i];
873 getLastOrderline: function(){
874 return this.get('orderLines').at(this.get('orderLines').length -1);
876 addPaymentline: function(cashregister) {
877 var paymentLines = this.get('paymentLines');
878 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
879 if(cashregister.journal.type !== 'cash'){
880 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
882 paymentLines.add(newPaymentline);
883 this.selectPaymentline(newPaymentline);
886 removePaymentline: function(line){
887 if(this.selected_paymentline === line){
888 this.selectPaymentline(undefined);
890 this.get('paymentLines').remove(line);
892 getName: function() {
893 return this.get('name');
895 getSubtotal : function(){
896 return (this.get('orderLines')).reduce((function(sum, orderLine){
897 return sum + orderLine.get_display_price();
900 getTotalTaxIncluded: function() {
901 return (this.get('orderLines')).reduce((function(sum, orderLine) {
902 return sum + orderLine.get_price_with_tax();
905 getDiscountTotal: function() {
906 return (this.get('orderLines')).reduce((function(sum, orderLine) {
907 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
910 getTotalTaxExcluded: function() {
911 return (this.get('orderLines')).reduce((function(sum, orderLine) {
912 return sum + orderLine.get_price_without_tax();
916 return (this.get('orderLines')).reduce((function(sum, orderLine) {
917 return sum + orderLine.get_tax();
920 getTaxDetails: function(){
922 var fulldetails = [];
923 var taxes_by_id = {};
925 for(var i = 0; i < this.pos.taxes.length; i++){
926 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
929 this.get('orderLines').each(function(line){
930 var ldetails = line.get_tax_details();
931 for(var id in ldetails){
932 if(ldetails.hasOwnProperty(id)){
933 details[id] = (details[id] || 0) + ldetails[id];
938 for(var id in details){
939 if(details.hasOwnProperty(id)){
940 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
946 getPaidTotal: function() {
947 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
948 return sum + paymentLine.get_amount();
951 getChange: function() {
952 return this.getPaidTotal() - this.getTotalTaxIncluded();
954 getDueLeft: function() {
955 return this.getTotalTaxIncluded() - this.getPaidTotal();
957 // sets the type of receipt 'receipt'(default) or 'invoice'
958 set_receipt_type: function(type){
959 this.receipt_type = type;
961 get_receipt_type: function(){
962 return this.receipt_type;
964 // the client related to the current order.
965 set_client: function(client){
966 this.set('client',client);
968 get_client: function(){
969 return this.get('client');
971 get_client_name: function(){
972 var client = this.get('client');
973 return client ? client.name : "";
975 // the order also stores the screen status, as the PoS supports
976 // different active screens per order. This method is used to
977 // store the screen status.
978 set_screen_data: function(key,value){
979 if(arguments.length === 2){
980 this.screen_data[key] = value;
981 }else if(arguments.length === 1){
982 for(key in arguments[0]){
983 this.screen_data[key] = arguments[0][key];
987 //see set_screen_data
988 get_screen_data: function(key){
989 return this.screen_data[key];
991 // exports a JSON for receipt printing
992 export_for_printing: function(){
994 this.get('orderLines').each(function(orderline){
995 orderlines.push(orderline.export_for_printing());
998 var paymentlines = [];
999 this.get('paymentLines').each(function(paymentline){
1000 paymentlines.push(paymentline.export_for_printing());
1002 var client = this.get('client');
1003 var cashier = this.pos.cashier || this.pos.user;
1004 var company = this.pos.company;
1005 var shop = this.pos.shop;
1006 var date = new Date();
1009 orderlines: orderlines,
1010 paymentlines: paymentlines,
1011 subtotal: this.getSubtotal(),
1012 total_with_tax: this.getTotalTaxIncluded(),
1013 total_without_tax: this.getTotalTaxExcluded(),
1014 total_tax: this.getTax(),
1015 total_paid: this.getPaidTotal(),
1016 total_discount: this.getDiscountTotal(),
1017 tax_details: this.getTaxDetails(),
1018 change: this.getChange(),
1019 name : this.getName(),
1020 client: client ? client.name : null ,
1021 invoice_id: null, //TODO
1022 cashier: cashier ? cashier.name : null,
1023 header: this.pos.config.receipt_header || '',
1024 footer: this.pos.config.receipt_footer || '',
1031 year: date.getFullYear(),
1032 month: date.getMonth(),
1033 date: date.getDate(), // day of the month
1034 day: date.getDay(), // day of the week
1035 hour: date.getHours(),
1036 minute: date.getMinutes() ,
1037 isostring: date.toISOString(),
1038 localestring: date.toLocaleString(),
1041 email: company.email,
1042 website: company.website,
1043 company_registry: company.company_registry,
1044 contact_address: company.partner_id[1],
1047 phone: company.phone,
1048 logo: this.pos.company_logo_base64,
1053 currency: this.pos.currency,
1056 export_as_JSON: function() {
1057 var orderLines, paymentLines;
1059 (this.get('orderLines')).each(_.bind( function(item) {
1060 return orderLines.push([0, 0, item.export_as_JSON()]);
1063 (this.get('paymentLines')).each(_.bind( function(item) {
1064 return paymentLines.push([0, 0, item.export_as_JSON()]);
1067 name: this.getName(),
1068 amount_paid: this.getPaidTotal(),
1069 amount_total: this.getTotalTaxIncluded(),
1070 amount_tax: this.getTax(),
1071 amount_return: this.getChange(),
1073 statement_ids: paymentLines,
1074 pos_session_id: this.pos.pos_session.id,
1075 partner_id: this.get_client() ? this.get_client().id : false,
1076 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1078 sequence_number: this.sequence_number,
1081 getSelectedLine: function(){
1082 return this.selected_orderline;
1084 selectLine: function(line){
1086 if(line !== this.selected_orderline){
1087 if(this.selected_orderline){
1088 this.selected_orderline.set_selected(false);
1090 this.selected_orderline = line;
1091 this.selected_orderline.set_selected(true);
1094 this.selected_orderline = undefined;
1097 deselectLine: function(){
1098 if(this.selected_orderline){
1099 this.selected_orderline.set_selected(false);
1100 this.selected_orderline = undefined;
1103 selectPaymentline: function(line){
1104 if(line !== this.selected_paymentline){
1105 if(this.selected_paymentline){
1106 this.selected_paymentline.set_selected(false);
1108 this.selected_paymentline = line;
1109 if(this.selected_paymentline){
1110 this.selected_paymentline.set_selected(true);
1112 this.trigger('change:selected_paymentline',this.selected_paymentline);
1117 module.OrderCollection = Backbone.Collection.extend({
1118 model: module.Order,
1122 The numpad handles both the choice of the property currently being modified
1123 (quantity, price or discount) and the edition of the corresponding numeric value.
1125 module.NumpadState = Backbone.Model.extend({
1130 appendNewChar: function(newChar) {
1132 oldBuffer = this.get('buffer');
1133 if (oldBuffer === '0') {
1137 } else if (oldBuffer === '-0') {
1139 buffer: "-" + newChar
1143 buffer: (this.get('buffer')) + newChar
1146 this.trigger('set_value',this.get('buffer'));
1148 deleteLastChar: function() {
1149 if(this.get('buffer') === ""){
1150 if(this.get('mode') === 'quantity'){
1151 this.trigger('set_value','remove');
1153 this.trigger('set_value',this.get('buffer'));
1156 var newBuffer = this.get('buffer').slice(0,-1) || "";
1157 this.set({ buffer: newBuffer });
1158 this.trigger('set_value',this.get('buffer'));
1161 switchSign: function() {
1163 oldBuffer = this.get('buffer');
1165 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1167 this.trigger('set_value',this.get('buffer'));
1169 changeMode: function(newMode) {
1181 resetValue: function(){
1182 this.set({buffer:'0'});