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. Obsolete use the models loader below.
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 // Server side model loaders. This is the list of the models that need to be loaded from
125 // the server. The models are loaded one by one by this list's order. The 'loaded' callback
126 // is used to store the data in the appropriate place once it has been loaded. This callback
127 // can return a deferred that will pause the loading of the next module.
128 // a shared temporary dictionary is available for loaders to communicate private variables
129 // used during loading such as object ids, etc.
133 fields: ['name','company_id'],
134 domain: function(self){ return [['id','=',self.session.uid]]; },
135 loaded: function(self,users){ self.user = users[0]; },
137 model: 'res.company',
138 fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' ],
139 domain: function(self){ return [['id','=',self.user.company_id[0]]]; },
140 loaded: function(self,companies){ self.company = companies[0]; },
142 model: 'product.uom',
145 loaded: function(self,units){
147 var units_by_id = {};
148 for(var i = 0, len = units.length; i < len; i++){
149 units_by_id[units[i].id] = units[i];
150 units[i].groupable = ( units[i].category_id[0] === 1 );
151 units[i].is_unit = ( units[i].id === 1 );
153 self.units_by_id = units_by_id;
157 fields: ['name','ean13'],
159 loaded: function(self,users){ self.users = users; },
161 model: 'res.partner',
162 fields: ['name','street','city','country_id','phone','zip','mobile','email','ean13'],
164 loaded: function(self,partners){
165 self.partners = partners;
166 self.db.add_partners(partners);
169 model: 'account.tax',
170 fields: ['name','amount', 'price_include', 'type'],
172 loaded: function(self,taxes){ self.taxes = taxes; },
174 model: 'pos.session',
175 fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number'],
176 domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
177 loaded: function(self,pos_sessions){ self.pos_session = pos_sessions[0]; },
181 domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
182 loaded: function(self,configs){
183 self.config = configs[0];
184 self.config.use_proxy = self.config.iface_payment_terminal ||
185 self.config.iface_electronic_scale ||
186 self.config.iface_print_via_proxy ||
187 self.config.iface_scan_via_proxy ||
188 self.config.iface_cashdrawer;
190 self.barcode_reader.add_barcode_patterns({
191 'product': self.config.barcode_product,
192 'cashier': self.config.barcode_cashier,
193 'client': self.config.barcode_customer,
194 'weight': self.config.barcode_weight,
195 'discount': self.config.barcode_discount,
196 'price': self.config.barcode_price,
200 model: 'stock.location',
202 domain: function(self){ return [['id','=', self.config.stock_location_id[0]]]; },
203 loaded: function(self, locations){ self.shop = locations[0]; },
205 model: 'product.pricelist',
206 fields: ['currency_id'],
207 domain: function(self){ return [['id','=',self.config.pricelist_id[0]]]; },
208 loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
210 model: 'res.currency',
211 fields: ['symbol','position','rounding','accuracy'],
212 domain: function(self){ return [['id','=',self.pricelist.currency_id[0]]]; },
213 loaded: function(self, currencies){
214 self.currency = currencies[0];
217 model: 'product.packaging',
218 fields: ['ean','product_tmpl_id'],
220 loaded: function(self, packagings){
221 self.db.add_packagings(packagings);
224 model: 'pos.category',
225 fields: ['id','name','parent_id','child_id','image'],
227 loaded: function(self, categories){
228 self.db.add_categories(categories);
231 model: 'product.product',
232 fields: ['name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code', 'variants',
233 'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
235 domain: function(self){ return [['sale_ok','=',true],['available_in_pos','=',true]]; },
236 context: function(self){ return { pricelist: self.pricelist.id }; },
237 loaded: function(self, products){
238 self.db.add_products(products);
241 model: 'account.bank.statement',
242 fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
243 domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
244 loaded: function(self, bankstatements, tmp){
245 self.bankstatements = bankstatements;
248 _.each(bankstatements,function(statement){
249 tmp.journals.push(statement.journal_id[0]);
253 model: 'account.journal',
255 domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
256 loaded: function(self, journals){
257 self.journals = journals;
259 // associate the bank statements with their journals.
260 var bankstatements = self.bankstatements;
261 for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
262 for(var j = 0, jlen = journals.length; j < jlen; j++){
263 if(bankstatements[i].journal_id[0] === journals[j].id){
264 bankstatements[i].journal = journals[j];
265 bankstatements[i].self_checkout_payment_method = journals[j].self_checkout_payment_method;
269 self.cashregisters = bankstatements;
272 loaded: function(self){
273 self.company_logo = new Image();
274 self.company_logo.crossOrigin = 'anonymous';
275 var logo_loaded = new $.Deferred();
276 self.company_logo.onload = function(){
277 var img = self.company_logo;
279 var targetwidth = 300;
281 if( img.width !== targetwidth ){
282 ratio = targetwidth / img.width;
284 if( img.height * ratio > maxheight ){
285 ratio = maxheight / img.height;
287 var width = Math.floor(img.width * ratio);
288 var height = Math.floor(img.height * ratio);
289 var c = document.createElement('canvas');
292 var ctx = c.getContext('2d');
293 ctx.drawImage(self.company_logo,0,0, width, height);
295 self.company_logo_base64 = c.toDataURL();
296 window.logo64 = self.company_logo_base64;
297 logo_loaded.resolve();
299 self.company_logo.onerror = function(){
300 logo_loaded.reject();
302 self.company_logo.src = window.location.origin + '/web/binary/company_logo';
309 // loads all the needed data on the sever. returns a deferred indicating when all the data has loaded.
310 load_server_data: function(){
312 var loaded = new $.Deferred();
314 var progress_step = 1.0 / self.models.length;
315 var tmp = {}; // this is used to share a temporary state between models loaders
317 function load_model(index){
318 if(index >= self.models.length){
321 var model = self.models[index];
322 self.pos_widget.loading_message(_t('Loading')+' '+(model.model || ''), progress);
323 var fields = typeof model.fields === 'function' ? model.fields(self,tmp) : model.fields;
324 var domain = typeof model.domain === 'function' ? model.domain(self,tmp) : model.domain;
325 var context = typeof model.context === 'function' ? model.context(self,tmp) : model.context;
326 progress += progress_step;
329 new instance.web.Model(model.model).query(fields).filter(domain).context(context).all()
330 .then(function(result){
331 try{ // catching exceptions in model.loaded(...)
332 $.when(model.loaded(self,result,tmp))
333 .then(function(){ load_model(index + 1); },
334 function(err){ loaded.reject(err); });
341 }else if( model.loaded ){
342 try{ // catching exceptions in model.loaded(...)
343 $.when(model.loaded(self,tmp))
344 .then( function(){ load_model(index +1); },
345 function(err){ loaded.reject(err); });
350 load_model(index + 1);
364 // this is called when an order is removed from the order collection. It ensures that there is always an existing
365 // order and a valid selected order
366 on_removed_order: function(removed_order,index,reason){
367 if( (reason === 'abandon' || removed_order.temporary) && this.get('orders').size() > 0){
368 // when we intentionally remove an unfinished order, and there is another existing one
369 this.set({'selectedOrder' : this.get('orders').at(index) || this.get('orders').last()});
371 // when the order was automatically removed after completion,
372 // or when we intentionally delete the only concurrent order
373 this.add_new_order();
377 //creates a new empty order and sets it as the current order
378 add_new_order: function(){
379 var order = new module.Order({pos:this});
380 this.get('orders').add(order);
381 this.set('selectedOrder', order);
384 get_order: function(){
385 return this.get('selectedOrder');
388 //removes the current order
389 delete_current_order: function(){
390 this.get('selectedOrder').destroy({'reason':'abandon'});
393 // saves the order locally and try to send it to the backend.
394 // it returns a deferred that succeeds after having tried to send the order and all the other pending orders.
395 push_order: function(order) {
399 this.proxy.log('push_order',order.export_as_JSON());
400 this.db.add_order(order.export_as_JSON());
403 var pushed = new $.Deferred();
405 this.flush_mutex.exec(function(){
406 var flushed = self._flush_orders(self.db.get_orders());
408 flushed.always(function(ids){
415 // saves the order locally and try to send it to the backend and make an invoice
416 // returns a deferred that succeeds when the order has been posted and successfully generated
417 // an invoice. This method can fail in various ways:
418 // error-no-client: the order must have an associated partner_id. You can retry to make an invoice once
419 // this error is solved
420 // error-transfer: there was a connection error during the transfer. You can retry to make the invoice once
421 // the network connection is up
423 push_and_invoice_order: function(order){
425 var invoiced = new $.Deferred();
427 if(!order.get_client()){
428 invoiced.reject('error-no-client');
432 var order_id = this.db.add_order(order.export_as_JSON());
434 this.flush_mutex.exec(function(){
435 var done = new $.Deferred(); // holds the mutex
437 // send the order to the server
438 // we have a 30 seconds timeout on this push.
439 // FIXME: if the server takes more than 30 seconds to accept the order,
440 // the client will believe it wasn't successfully sent, and very bad
441 // things will happen as a duplicate will be sent next time
442 // so we must make sure the server detects and ignores duplicated orders
444 var transfer = self._flush_orders([self.db.get_order(order_id)], {timeout:30000, to_invoice:true});
446 transfer.fail(function(){
447 invoiced.reject('error-transfer');
451 // on success, get the order id generated by the server
452 transfer.pipe(function(order_server_id){
454 // generate the pdf and download it
455 self.pos_widget.do_action('point_of_sale.pos_invoice_report',{additional_context:{
456 active_ids:order_server_id,
470 // wrapper around the _save_to_server that updates the synch status widget
471 _flush_orders: function(orders, options) {
474 this.set('synch',{ state: 'connecting', pending: orders.length});
476 return self._save_to_server(orders, options).done(function (server_ids) {
477 var pending = self.db.get_orders().length;
480 state: pending ? 'connecting' : 'connected',
488 // send an array of orders to the server
489 // available options:
490 // - timeout: timeout for the rpc call in ms
491 // returns a deferred that resolves with the list of
492 // server generated ids for the sent orders
493 _save_to_server: function (orders, options) {
494 if (!orders || !orders.length) {
495 var result = $.Deferred();
500 options = options || {};
503 var timeout = typeof options.timeout === 'number' ? options.timeout : 7500 * orders.length;
505 // we try to send the order. shadow prevents a spinner if it takes too long. (unless we are sending an invoice,
506 // then we want to notify the user that we are waiting on something )
507 var posOrderModel = new instance.web.Model('pos.order');
508 return posOrderModel.call('create_from_ui',
509 [_.map(orders, function (order) {
510 order.to_invoice = options.to_invoice || false;
515 shadow: !options.to_invoice,
518 ).then(function (server_ids) {
519 _.each(orders, function (order) {
520 self.db.remove_order(order.id);
523 }).fail(function (error, event){
524 if(error.code === 200 ){ // Business Logic Error, not a connection problem
525 self.pos_widget.screen_selector.show_popup('error-traceback',{
526 message: error.data.message,
527 comment: error.data.debug
530 // prevent an error popup creation by the rpc failure
531 // we want the failure to be silent as we send the orders in the background
532 event.preventDefault();
533 console.error('Failed to send orders:', orders);
537 scan_product: function(parsed_code){
539 var selectedOrder = this.get('selectedOrder');
540 if(parsed_code.encoding === 'ean13'){
541 var product = this.db.get_product_by_ean13(parsed_code.base_code);
542 }else if(parsed_code.encoding === 'reference'){
543 var product = this.db.get_product_by_reference(parsed_code.code);
550 if(parsed_code.type === 'price'){
551 selectedOrder.addProduct(product, {price:parsed_code.value});
552 }else if(parsed_code.type === 'weight'){
553 selectedOrder.addProduct(product, {quantity:parsed_code.value, merge:false});
554 }else if(parsed_code.type === 'discount'){
555 selectedOrder.addProduct(product, {discount:parsed_code.value, merge:false});
557 selectedOrder.addProduct(product);
563 var orderline_id = 1;
565 // An orderline represent one element of the content of a client's shopping cart.
566 // An orderline contains a product, its quantity, its price, discount. etc.
567 // An Order contains zero or more Orderlines.
568 module.Orderline = Backbone.Model.extend({
569 initialize: function(attr,options){
570 this.pos = options.pos;
571 this.order = options.order;
572 this.product = options.product;
573 this.price = options.product.price;
575 this.quantityStr = '1';
577 this.discountStr = '0';
579 this.selected = false;
580 this.id = orderline_id++;
583 var orderline = new module.Orderline({},{
586 product: this.product,
589 orderline.quantity = this.quantity;
590 orderline.quantityStr = this.quantityStr;
591 orderline.discount = this.discount;
592 orderline.type = this.type;
593 orderline.selected = false;
596 // sets a discount [0,100]%
597 set_discount: function(discount){
598 var disc = Math.min(Math.max(parseFloat(discount) || 0, 0),100);
599 this.discount = disc;
600 this.discountStr = '' + disc;
601 this.trigger('change',this);
603 // returns the discount [0,100]%
604 get_discount: function(){
605 return this.discount;
607 get_discount_str: function(){
608 return this.discountStr;
610 get_product_type: function(){
613 // sets the quantity of the product. The quantity will be rounded according to the
614 // product's unity of measure properties. Quantities greater than zero will not get
616 set_quantity: function(quantity){
617 if(quantity === 'remove'){
618 this.order.removeOrderline(this);
621 var quant = parseFloat(quantity) || 0;
622 var unit = this.get_unit();
624 this.quantity = round_pr(quant, unit.rounding);
625 this.quantityStr = this.quantity.toFixed(Math.ceil(Math.log(1.0 / unit.rounding) / Math.log(10)));
627 this.quantity = quant;
628 this.quantityStr = '' + this.quantity;
631 this.trigger('change',this);
633 // return the quantity of product
634 get_quantity: function(){
635 return this.quantity;
637 get_quantity_str: function(){
638 return this.quantityStr;
640 get_quantity_str_with_unit: function(){
641 var unit = this.get_unit();
642 if(unit && !unit.is_unit){
643 return this.quantityStr + ' ' + unit.name;
645 return this.quantityStr;
648 // return the unit of measure of the product
649 get_unit: function(){
650 var unit_id = (this.product.uos_id || this.product.uom_id);
654 unit_id = unit_id[0];
658 return this.pos.units_by_id[unit_id];
660 // return the product of this orderline
661 get_product: function(){
664 // selects or deselects this orderline
665 set_selected: function(selected){
666 this.selected = selected;
667 this.trigger('change',this);
669 // returns true if this orderline is selected
670 is_selected: function(){
671 return this.selected;
673 // when we add an new orderline we want to merge it with the last line to see reduce the number of items
674 // in the orderline. This returns true if it makes sense to merge the two
675 can_be_merged_with: function(orderline){
676 if( this.get_product().id !== orderline.get_product().id){ //only orderline of the same product can be merged
678 }else if(!this.get_unit() || !this.get_unit().groupable){
680 }else if(this.get_product_type() !== orderline.get_product_type()){
682 }else if(this.get_discount() > 0){ // we don't merge discounted orderlines
684 }else if(this.price !== orderline.price){
690 merge: function(orderline){
691 this.set_quantity(this.get_quantity() + orderline.get_quantity());
693 export_as_JSON: function() {
695 qty: this.get_quantity(),
696 price_unit: this.get_unit_price(),
697 discount: this.get_discount(),
698 product_id: this.get_product().id,
701 //used to create a json of the ticket, to be sent to the printer
702 export_for_printing: function(){
704 quantity: this.get_quantity(),
705 unit_name: this.get_unit().name,
706 price: this.get_unit_price(),
707 discount: this.get_discount(),
708 product_name: this.get_product().name,
709 price_display : this.get_display_price(),
710 price_with_tax : this.get_price_with_tax(),
711 price_without_tax: this.get_price_without_tax(),
713 product_description: this.get_product().description,
714 product_description_sale: this.get_product().description_sale,
717 // changes the base price of the product for this orderline
718 set_unit_price: function(price){
719 this.price = round_di(parseFloat(price) || 0, 2);
720 this.trigger('change',this);
722 get_unit_price: function(){
723 var rounding = this.pos.currency.rounding;
724 return round_pr(this.price,rounding);
726 get_display_price: function(){
727 var rounding = this.pos.currency.rounding;
728 return round_pr(round_pr(this.get_unit_price() * this.get_quantity(),rounding) * (1- this.get_discount()/100.0),rounding);
730 get_price_without_tax: function(){
731 return this.get_all_prices().priceWithoutTax;
733 get_price_with_tax: function(){
734 return this.get_all_prices().priceWithTax;
737 return this.get_all_prices().tax;
739 get_tax_details: function(){
740 return this.get_all_prices().taxDetails;
742 get_all_prices: function(){
744 var currency_rounding = this.pos.currency.rounding;
745 var base = round_pr(this.get_quantity() * this.get_unit_price() * (1.0 - (this.get_discount() / 100.0)), currency_rounding);
747 var totalNoTax = base;
749 var product = this.get_product();
750 var taxes_ids = product.taxes_id;
751 var taxes = self.pos.taxes;
754 _.each(taxes_ids, function(el) {
755 var tax = _.detect(taxes, function(t) {return t.id === el;});
756 if (tax.price_include) {
758 if (tax.type === "percent") {
759 tmp = base - round_pr(base / (1 + tax.amount),currency_rounding);
760 } else if (tax.type === "fixed") {
761 tmp = round_pr(tax.amount * self.get_quantity(),currency_rounding);
763 throw "This type of tax is not supported by the point of sale: " + tax.type;
765 tmp = round_pr(tmp,currency_rounding);
768 taxdetail[tax.id] = tmp;
771 if (tax.type === "percent") {
772 tmp = tax.amount * base;
773 } else if (tax.type === "fixed") {
774 tmp = tax.amount * self.get_quantity();
776 throw "This type of tax is not supported by the point of sale: " + tax.type;
778 tmp = round_pr(tmp,currency_rounding);
781 taxdetail[tax.id] = tmp;
785 "priceWithTax": totalTax,
786 "priceWithoutTax": totalNoTax,
788 "taxDetails": taxdetail,
793 module.OrderlineCollection = Backbone.Collection.extend({
794 model: module.Orderline,
797 // Every Paymentline contains a cashregister and an amount of money.
798 module.Paymentline = Backbone.Model.extend({
799 initialize: function(attributes, options) {
801 this.cashregister = options.cashregister;
802 this.name = this.cashregister.journal_id[1];
803 this.selected = false;
805 //sets the amount of money on this payment line
806 set_amount: function(value){
807 this.amount = round_di(parseFloat(value) || 0, 2);
808 this.trigger('change:amount',this);
810 // returns the amount of money on this paymentline
811 get_amount: function(){
814 set_selected: function(selected){
815 if(this.selected !== selected){
816 this.selected = selected;
817 this.trigger('change:selected',this);
820 // returns the associated cashregister
821 //exports as JSON for server communication
822 export_as_JSON: function(){
824 name: instance.web.datetime_to_str(new Date()),
825 statement_id: this.cashregister.id,
826 account_id: this.cashregister.account_id[0],
827 journal_id: this.cashregister.journal_id[0],
828 amount: this.get_amount()
831 //exports as JSON for receipt printing
832 export_for_printing: function(){
834 amount: this.get_amount(),
835 journal: this.cashregister.journal_id[1],
840 module.PaymentlineCollection = Backbone.Collection.extend({
841 model: module.Paymentline,
845 // An order more or less represents the content of a client's shopping cart (the OrderLines)
846 // plus the associated payment information (the Paymentlines)
847 // there is always an active ('selected') order in the Pos, a new one is created
848 // automaticaly once an order is completed and sent to the server.
849 module.Order = Backbone.Model.extend({
850 initialize: function(attributes){
851 Backbone.Model.prototype.initialize.apply(this, arguments);
852 this.uid = this.generateUniqueId();
854 creationDate: new Date(),
855 orderLines: new module.OrderlineCollection(),
856 paymentLines: new module.PaymentlineCollection(),
857 name: "Order " + this.uid,
860 this.pos = attributes.pos;
861 this.selected_orderline = undefined;
862 this.selected_paymentline = undefined;
863 this.screen_data = {}; // see ScreenSelector
864 this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
865 this.temporary = attributes.temporary || false;
866 this.sequence_number = this.pos.pos_session.sequence_number++;
869 is_empty: function(){
870 return (this.get('orderLines').models.length === 0);
872 generateUniqueId: function() {
873 return new Date().getTime();
875 addOrderline: function(line){
877 order.removeOrderline(line);
880 this.get('orderLines').add(line);
881 this.selectLine(this.getLastOrderline());
883 addProduct: function(product, options){
884 options = options || {};
885 var attr = JSON.parse(JSON.stringify(product));
888 var line = new module.Orderline({}, {pos: this.pos, order: this, product: product});
890 if(options.quantity !== undefined){
891 line.set_quantity(options.quantity);
893 if(options.price !== undefined){
894 line.set_unit_price(options.price);
896 if(options.discount !== undefined){
897 line.set_discount(options.discount);
900 var last_orderline = this.getLastOrderline();
901 if( last_orderline && last_orderline.can_be_merged_with(line) && options.merge !== false){
902 last_orderline.merge(line);
904 this.get('orderLines').add(line);
906 this.selectLine(this.getLastOrderline());
908 removeOrderline: function( line ){
909 this.get('orderLines').remove(line);
910 this.selectLine(this.getLastOrderline());
912 getOrderline: function(id){
913 var orderlines = this.get('orderLines').models;
914 for(var i = 0; i < orderlines.length; i++){
915 if(orderlines[i].id === id){
916 return orderlines[i];
921 getLastOrderline: function(){
922 return this.get('orderLines').at(this.get('orderLines').length -1);
924 addPaymentline: function(cashregister) {
925 var paymentLines = this.get('paymentLines');
926 var newPaymentline = new module.Paymentline({},{cashregister:cashregister});
927 if(cashregister.journal.type !== 'cash'){
928 newPaymentline.set_amount( Math.max(this.getDueLeft(),0) );
930 paymentLines.add(newPaymentline);
931 this.selectPaymentline(newPaymentline);
934 removePaymentline: function(line){
935 if(this.selected_paymentline === line){
936 this.selectPaymentline(undefined);
938 this.get('paymentLines').remove(line);
940 getName: function() {
941 return this.get('name');
943 getSubtotal : function(){
944 return (this.get('orderLines')).reduce((function(sum, orderLine){
945 return sum + orderLine.get_display_price();
948 getTotalTaxIncluded: function() {
949 return (this.get('orderLines')).reduce((function(sum, orderLine) {
950 return sum + orderLine.get_price_with_tax();
953 getDiscountTotal: function() {
954 return (this.get('orderLines')).reduce((function(sum, orderLine) {
955 return sum + (orderLine.get_unit_price() * (orderLine.get_discount()/100) * orderLine.get_quantity());
958 getTotalTaxExcluded: function() {
959 return (this.get('orderLines')).reduce((function(sum, orderLine) {
960 return sum + orderLine.get_price_without_tax();
964 return (this.get('orderLines')).reduce((function(sum, orderLine) {
965 return sum + orderLine.get_tax();
968 getTaxDetails: function(){
970 var fulldetails = [];
971 var taxes_by_id = {};
973 for(var i = 0; i < this.pos.taxes.length; i++){
974 taxes_by_id[this.pos.taxes[i].id] = this.pos.taxes[i];
977 this.get('orderLines').each(function(line){
978 var ldetails = line.get_tax_details();
979 for(var id in ldetails){
980 if(ldetails.hasOwnProperty(id)){
981 details[id] = (details[id] || 0) + ldetails[id];
986 for(var id in details){
987 if(details.hasOwnProperty(id)){
988 fulldetails.push({amount: details[id], tax: taxes_by_id[id]});
994 getPaidTotal: function() {
995 return (this.get('paymentLines')).reduce((function(sum, paymentLine) {
996 return sum + paymentLine.get_amount();
999 getChange: function() {
1000 return this.getPaidTotal() - this.getTotalTaxIncluded();
1002 getDueLeft: function() {
1003 return this.getTotalTaxIncluded() - this.getPaidTotal();
1005 // sets the type of receipt 'receipt'(default) or 'invoice'
1006 set_receipt_type: function(type){
1007 this.receipt_type = type;
1009 get_receipt_type: function(){
1010 return this.receipt_type;
1012 // the client related to the current order.
1013 set_client: function(client){
1014 this.set('client',client);
1016 get_client: function(){
1017 return this.get('client');
1019 get_client_name: function(){
1020 var client = this.get('client');
1021 return client ? client.name : "";
1023 // the order also stores the screen status, as the PoS supports
1024 // different active screens per order. This method is used to
1025 // store the screen status.
1026 set_screen_data: function(key,value){
1027 if(arguments.length === 2){
1028 this.screen_data[key] = value;
1029 }else if(arguments.length === 1){
1030 for(key in arguments[0]){
1031 this.screen_data[key] = arguments[0][key];
1035 //see set_screen_data
1036 get_screen_data: function(key){
1037 return this.screen_data[key];
1039 // exports a JSON for receipt printing
1040 export_for_printing: function(){
1041 var orderlines = [];
1042 this.get('orderLines').each(function(orderline){
1043 orderlines.push(orderline.export_for_printing());
1046 var paymentlines = [];
1047 this.get('paymentLines').each(function(paymentline){
1048 paymentlines.push(paymentline.export_for_printing());
1050 var client = this.get('client');
1051 var cashier = this.pos.cashier || this.pos.user;
1052 var company = this.pos.company;
1053 var shop = this.pos.shop;
1054 var date = new Date();
1057 orderlines: orderlines,
1058 paymentlines: paymentlines,
1059 subtotal: this.getSubtotal(),
1060 total_with_tax: this.getTotalTaxIncluded(),
1061 total_without_tax: this.getTotalTaxExcluded(),
1062 total_tax: this.getTax(),
1063 total_paid: this.getPaidTotal(),
1064 total_discount: this.getDiscountTotal(),
1065 tax_details: this.getTaxDetails(),
1066 change: this.getChange(),
1067 name : this.getName(),
1068 client: client ? client.name : null ,
1069 invoice_id: null, //TODO
1070 cashier: cashier ? cashier.name : null,
1071 header: this.pos.config.receipt_header || '',
1072 footer: this.pos.config.receipt_footer || '',
1079 year: date.getFullYear(),
1080 month: date.getMonth(),
1081 date: date.getDate(), // day of the month
1082 day: date.getDay(), // day of the week
1083 hour: date.getHours(),
1084 minute: date.getMinutes() ,
1085 isostring: date.toISOString(),
1086 localestring: date.toLocaleString(),
1089 email: company.email,
1090 website: company.website,
1091 company_registry: company.company_registry,
1092 contact_address: company.partner_id[1],
1095 phone: company.phone,
1096 logo: this.pos.company_logo_base64,
1101 currency: this.pos.currency,
1104 export_as_JSON: function() {
1105 var orderLines, paymentLines;
1107 (this.get('orderLines')).each(_.bind( function(item) {
1108 return orderLines.push([0, 0, item.export_as_JSON()]);
1111 (this.get('paymentLines')).each(_.bind( function(item) {
1112 return paymentLines.push([0, 0, item.export_as_JSON()]);
1115 name: this.getName(),
1116 amount_paid: this.getPaidTotal(),
1117 amount_total: this.getTotalTaxIncluded(),
1118 amount_tax: this.getTax(),
1119 amount_return: this.getChange(),
1121 statement_ids: paymentLines,
1122 pos_session_id: this.pos.pos_session.id,
1123 partner_id: this.get_client() ? this.get_client().id : false,
1124 user_id: this.pos.cashier ? this.pos.cashier.id : this.pos.user.id,
1126 sequence_number: this.sequence_number,
1129 getSelectedLine: function(){
1130 return this.selected_orderline;
1132 selectLine: function(line){
1134 if(line !== this.selected_orderline){
1135 if(this.selected_orderline){
1136 this.selected_orderline.set_selected(false);
1138 this.selected_orderline = line;
1139 this.selected_orderline.set_selected(true);
1142 this.selected_orderline = undefined;
1145 deselectLine: function(){
1146 if(this.selected_orderline){
1147 this.selected_orderline.set_selected(false);
1148 this.selected_orderline = undefined;
1151 selectPaymentline: function(line){
1152 if(line !== this.selected_paymentline){
1153 if(this.selected_paymentline){
1154 this.selected_paymentline.set_selected(false);
1156 this.selected_paymentline = line;
1157 if(this.selected_paymentline){
1158 this.selected_paymentline.set_selected(true);
1160 this.trigger('change:selected_paymentline',this.selected_paymentline);
1165 module.OrderCollection = Backbone.Collection.extend({
1166 model: module.Order,
1170 The numpad handles both the choice of the property currently being modified
1171 (quantity, price or discount) and the edition of the corresponding numeric value.
1173 module.NumpadState = Backbone.Model.extend({
1178 appendNewChar: function(newChar) {
1180 oldBuffer = this.get('buffer');
1181 if (oldBuffer === '0') {
1185 } else if (oldBuffer === '-0') {
1187 buffer: "-" + newChar
1191 buffer: (this.get('buffer')) + newChar
1194 this.trigger('set_value',this.get('buffer'));
1196 deleteLastChar: function() {
1197 if(this.get('buffer') === ""){
1198 if(this.get('mode') === 'quantity'){
1199 this.trigger('set_value','remove');
1201 this.trigger('set_value',this.get('buffer'));
1204 var newBuffer = this.get('buffer').slice(0,-1) || "";
1205 this.set({ buffer: newBuffer });
1206 this.trigger('set_value',this.get('buffer'));
1209 switchSign: function() {
1211 oldBuffer = this.get('buffer');
1213 buffer: oldBuffer[0] === '-' ? oldBuffer.substr(1) : "-" + oldBuffer
1215 this.trigger('set_value',this.get('buffer'));
1217 changeMode: function(newMode) {
1229 resetValue: function(){
1230 this.set({buffer:'0'});