screens.js 25.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright (C) 2020 - Today: GRAP (http://www.grap.coop)
// @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
// License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

odoo.define("pos_meal_voucher.screens", function (require) {
    "use strict";

    var screens = require("point_of_sale.screens");
    var core = require('web.core');
10
    var formats = require('web.formats');
11
    var _t = core._t;
12
    var QWeb = core.qweb;
13 14
    var Model = require('web.DataModel');
    var config_parameter = new Model('ir.config_parameter');
15 16
    var utils = require("web.utils");
    var round_pr = utils.round_precision;
17 18 19

    screens.ScreenWidget.include({
        barcode_meal_voucher_payment_action: function (code) {
20 21
            var order = this.pos.get_order();
            if(!order.paper_meal_vouche_number_already_used(code.code)){
22 23 24
                // Display the payment screen, if it is not the current one.
                if (this.pos.gui.current_screen.template !== "PaymentScreenWidget"){
                    this.gui.show_screen("payment");
25
                }
26 27
                var paymentScreen = this.pos.gui.current_screen;
                var amount = code.value;
28 29 30 31 32

                // Check if the total amount is OK regarding to max amounts
                var total_eligible = order.get_total_meal_voucher_eligible();
                var max_amount = this.pos.config.max_meal_voucher_amount;
                var total_received = order.get_total_meal_voucher_received() + amount;
33
                let order_due = order.get_due();  
34 35

                // Display info popup if amount is too high
36 37 38
                // bug fix below : as order_due deduces previous paiement lines from initial due,
                // it must be compared to amount of current line only and not to total_received
                if (/*total_received*/amount > order_due) {
39 40 41 42 43 44
                    this.gui.show_popup("alert", {
                        'title': _t("Impossible d'utiliser ce Titre Restaurant"),
                        'body':  _t("Vous ne pouvez pas ajouter ce ticket restaurant car le montant total est supérieur au montant restant dû de la commande")
                    });
                    return;
                }
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
                if (total_received > total_eligible) {
                    this.gui.show_popup("alert", {
                        'title': _t("Impossible d'utiliser ce Titre Restaurant"),
                        'body':  _t("Vous ne pouvez pas ajouter ce ticket restaurant car le montant total est supérieur au montant éligible en titres restaurant")
                    });
                    return;
                } 
                if (total_received > max_amount && max_amount > 0) {
                    this.gui.show_popup("alert", {
                        'title': _t("Impossible d'utiliser ce Titre Restaurant"),
                        'body':  _t("Vous ne pouvez pas ajouter ce ticket restaurant car le montant total est supérieur au montant maximum autorisé")
                    });
                    return;
                } 

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
                var cashregister = null;
                // find a meal voucher cash register, if exist
                for ( var i = 0; i < this.pos.cashregisters.length; i++ ) {
                    if ( this.pos.cashregisters[i].journal.meal_voucher_type === "paper" ){
                        cashregister = this.pos.cashregisters[i];
                        break;
                    }
                }
                if (!cashregister){
                    return;
                }

                // Add new payment line with the amount found in the barcode
                this.pos.get_order().add_paymentline(cashregister);
                paymentScreen.reset_input()
                order.selected_paymentline.set_amount(amount);
                order.selected_paymentline.statement_note = code.code;
                paymentScreen.order_changes();
                paymentScreen.render_paymentlines();
                paymentScreen.$(".paymentline.selected .edit").text(paymentScreen.format_currency_no_symbol(amount));
                
            }else{
                this.gui.show_popup("alert", {
83 84 85
                    'title': _t("Titre restaurant déjà scanné"),
                    'body':  _t("Le ticket restaurant ") +
                    code.code + _t(" a déjà été scanné")
86
                });
87 88 89 90 91 92 93 94 95 96 97 98 99 100
            }
        },

        // Setup the callback action for the "meal_voucher_payment" barcodes.
        show: function () {
            this._super();
            this.pos.barcode_reader.set_action_callback(
                "meal_voucher_payment",
                _.bind(this.barcode_meal_voucher_payment_action, this));
        },
    });


    screens.OrderWidget.include({
101
        //check if POS if configured to accept payment in meal voucher
102
        meal_voucher_activated: function() {
103 104 105
          var is_meal_voucher_method = this.pos.cashregisters.map(function(cash_register) {
            if (cash_register.journal.meal_voucher_type === "paper" || cash_register.journal.meal_voucher_type === "dematerialized") {
              return true
106
            }
107
          })
108 109 110
          return is_meal_voucher_method.includes(true);
        },

111 112 113
        update_summary: function () {
            this._super.apply(this, arguments);
            var order = this.pos.get_order();
114 115

            if (!this.meal_voucher_activated()) {
116 117 118 119 120
              const meal_voucher_summary = this.el.querySelector(".summary .meal-voucher");
              if (meal_voucher_summary != null) {
                meal_voucher_summary.style.display = 'none';
              }
              // this.el.querySelector(".summary .meal-voucher").style.display = 'none';
121 122
              return;
            }
123 124 125 126 127 128 129 130 131
            if (!order.get_orderlines().length) {
                return;
            }
            this.el.querySelector(".summary .meal-voucher .value").textContent = this.format_currency(order.get_total_meal_voucher_eligible());
        },
    });


    screens.PaymentScreenWidget.include({
132 133 134 135 136 137 138 139 140
        //check if POS if configured to accept payment in meal voucher
        meal_voucher_activated: function() {
          var is_meal_voucher_method = this.pos.cashregisters.map(function(cash_register) {
            if (cash_register.journal.meal_voucher_type === "paper" || cash_register.journal.meal_voucher_type === "dematerialized") {
              return true
            }
          })
          return is_meal_voucher_method.includes(true);
        },
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

        // odoo/addons/point_of_sale/static/src/js/screens.js
        // We need to change the default behaviour of locking input with 
        // popup bcause of the papar meal voucher
        init: function(parent, options) {
            var self = this;
            this._super(parent, options);
            
            // This is a keydown handler that prevents backspace from
            // doing a back navigation. It also makes sure that keys that
            // do not generate a keypress in Chrom{e,ium} (eg. delete,
            // backspace, ...) get passed to the keypress handler.
            this.keyboard_keydown_handler = function(event){
                // We overight the expected behaviour if a popup is open
                if (self.gui.has_popup()) {
                    
                }
                else if (event.keyCode === 8 || event.keyCode === 46) { // Backspace and Delete
                    event.preventDefault();
                    console.log('keyboard_keydown_handler')
                    // These do not generate keypress events in
                    // Chrom{e,ium}. Even if they did, we just called
                    // preventDefault which will cancel any keypress that
                    // would normally follow. So we call keyboard_handler
                    // explicitly with this keydown event.
                    self.keyboard_handler(event);
                }
            };
            
            // This keyboard handler listens for keypress events. It is
            // also called explicitly to handle some keydown events that
            // do not generate keypress events.
            this.keyboard_handler = function(event){
                var key = '';
                // We overight the expected behaviour if a popup is open
                if (self.gui.has_popup()) {
                    
                }
                else{
                    if (event.type === "keypress") {
                        if (event.keyCode === 13) { // Enter
                            self.validate_order();
                        } else if ( event.keyCode === 190 || // Dot
                                    event.keyCode === 110 ||  // Decimal point (numpad)
                                    event.keyCode === 188 ||  // Comma
                                    event.keyCode === 46 ) {  // Numpad dot
                            key = self.decimal_point;
                        } else if (event.keyCode >= 48 && event.keyCode <= 57) { // Numbers
                            key = '' + (event.keyCode - 48);
                        } else if (event.keyCode === 45) { // Minus
                            key = '-';
                        } else if (event.keyCode === 43) { // Plus
                            key = '+';
                        }
                    } else { // keyup/keydown
                        if (event.keyCode === 46) { // Delete
                            key = 'CLEAR';
                        } else if (event.keyCode === 8) { // Backspace
                            key = 'BACKSPACE';
                        }
                    }
        
                    self.payment_input(key);
                    event.preventDefault();
                }
                
                
            };
209

210
            this.meal_voucher_issuers = [];
211 212 213
            // get meal voucher issuers from config
            config_parameter.call('get_param', ['pos_meal_voucher.meal_voucher_issuers'])
                .then( function(value){
214 215 216 217 218 219 220 221
                    try {
                        self.meal_voucher_issuers = JSON.parse(value);
                    } catch (error) {
                        self.gui.show_popup("alert", {
                            'title': _t("Problème de configuration du POS"),
                            'body':  _t("Le paramètre des émetteurs de CB déj est mal formatté dans la configuration d'Odoo. Veuillez demander à un.e salarié.e de régler ce problème (Configuration > Paramètres systèmes > pos_meal_voucher.meal_voucher_issuers). Vous pouvez continuer à utiliser la caisse.")
                        });
                    }
222
                });
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        },

        payment_input: function(input) {
            var newbuf = this.gui.numpad_input(this.inputbuffer, input, {'firstinput': this.firstinput});

            this.firstinput = (newbuf.length === 0);
    
            if (newbuf !== this.inputbuffer) {
                this.inputbuffer = newbuf;
                var order = this.pos.get_order();
                // We choose to unactivated the editing of the amount for the paper meal voucher
                if (order.selected_paymentline && !order.selected_paymentline.is_paper_meal_voucher()) {
                    var amount = this.inputbuffer;
    
                    if (this.inputbuffer !== "-") {
                        amount = formats.parse_value(this.inputbuffer, {type: "float"}, 0.0);
                    }
    
                    order.selected_paymentline.set_amount(amount);
                    this.order_changes();
                    this.render_paymentlines();
                    this.$('.paymentline.selected .edit').text(this.format_currency_no_symbol(amount));
                }
            }

            var order = this.pos.get_order();

            if(order.selected_paymentline && order.selected_paymentline.is_dematerialized_meal_voucher()){
                var total_eligible = order.get_total_meal_voucher_eligible();
                var total_received = order.get_total_meal_voucher_received();
                var max_amount = this.pos.config.max_meal_voucher_amount;
                var current_max = total_eligible;
                if (max_amount) {
                    current_max = Math.min(total_eligible, max_amount);
                }
258 259 260 261 262 263 264 265 266

                // If there is change -> the amount of last payment line was above the order remaining due amount
                let order_change = order.get_change();
                if (order_change > 0) {
                    let last_line_amount = order.selected_paymentline.get_amount();
                    let limit_amount = round_pr(last_line_amount - order_change, this.pos.currency.rounding)
                    current_max = Math.min(current_max, limit_amount);
                }
                
267 268 269
                if (total_received > current_max){
                    this.gui.show_popup("alert", {
                        'title': _t("Meal Voucher Amount incorrect"),
270
                        'body':  _t("Le montant saisi est supérieur au maximum éligible/au montant restant dû de ") +
271 272
                           this.format_currency(current_max),
                    });
273 274
                    const max_current_amount = current_max-total_received+order.selected_paymentline.get_amount() ;
                    order.selected_paymentline.set_amount(max_current_amount);
275 276
                    this.order_changes();
                    this.render_paymentlines();
277
                    this.$('.paymentline.selected .edit').text(this.format_currency_no_symbol(max_current_amount));
278 279 280 281 282 283
                    this.inputbuffer = "";
                }

            }
        },

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        click_paymentmethods_meal_voucher_mixed: function(id) {
            var cashregister = null;
            for ( var i = 0; i < this.pos.cashregisters.length; i++ ) {
                if ( this.pos.cashregisters[i].journal_id[0] === id ){
                    cashregister = this.pos.cashregisters[i];
                    break;
                }
            }
            this.pos.get_order().add_paymentline( cashregister );
            // manually set meal voucher
            this.pos.get_order().selected_paymentline.manual_meal_voucher = true;
            this.reset_input();
            this.render_paymentlines();
        },
        render_paymentmethods: function() {
            var self = this;
            var methods = this._super.apply(this, arguments);
            methods.on('click','.paymentmethod-meal-voucher-mixed',function(){
                self.click_paymentmethods_meal_voucher_mixed($(this).data('id'));
            });
            return methods;
        },
306 307 308 309 310 311
        remove_selected_paymentline: function(order) {
            this.pos.get_order().remove_paymentline(order.selected_paymentline);
            var paymentScreen = this.pos.gui.current_screen;
            paymentScreen.reset_input();
            paymentScreen.render_paymentlines();
        },
Etienne Freiss committed
312 313 314 315 316 317 318
        click_paymentmethods: function(id) {
            var self = this;
            var methods = this._super.apply(this, arguments);


            var paymentScreen = this.pos.gui.current_screen;
            var order = this.pos.get_order();
319

320 321 322 323 324 325 326 327
            if (
                order.selected_paymentline.is_meal_voucher()
                && order.get_total_meal_voucher_eligible() == 0
            ) {
                this.gui.show_popup("alert", {
                    'title': _t("Impossible de payer en titre restaurant"),
                    'body':  _t("Aucun article du panier n'est éligible en titres restaurants (Montant éligible : 0€)."),
                    cancel: function() {
328
                        self.remove_selected_paymentline(order);
329 330
                    }
                });
Etienne Freiss committed
331

332 333
                return false;
            }
334
                        
335
            // if user choose card meal voucher
336
            if(order.selected_paymentline.is_meal_voucher() && order.selected_paymentline.is_dematerialized_meal_voucher()){
337 338 339 340 341 342
                // Set selected payment line amount to 0 before any further check
                order.selected_paymentline.set_amount(0);
                paymentScreen.order_changes();
                paymentScreen.render_paymentlines();
                paymentScreen.$(".paymentline.selected .edit").text(paymentScreen.format_currency_no_symbol(0));

343 344 345
                // update selected (last) payment line & order with meal voucher data
                function update_order_meal_voucher_data(issuer = '') {
                    var total_eligible = order.get_total_meal_voucher_eligible();
346 347 348 349 350 351 352

                    // Function defined in module "lacagette_mona", that may not be activated.
                    // If said module is activated, consider this eligible amount.
                    if (typeof order.get_total_meal_vouchers_eligible_including_mona === "function") {
                        total_eligible = order.get_total_meal_vouchers_eligible_including_mona();
                    }

353 354 355 356 357 358 359 360 361
                    var total_received = order.get_total_meal_voucher_received();
                    var max_amount = self.pos.config.max_meal_voucher_amount;
                    var current_max = total_eligible;
                    if (max_amount) {
                        current_max = Math.min(total_eligible, max_amount);
                    }

                    // Check how much is still possible to pay with meal voucher
                    // The selected line is "by default" set to the rest to pay of the order
362 363 364 365 366
                    let max_current_amount = current_max-total_received +order.selected_paymentline.get_amount();

                    // Limit the amount paid to the remaining due amount
                    const order_due_amount = order.get_due();
                    max_current_amount = Math.min(max_current_amount, order_due_amount);
367
            
368
                    order.selected_paymentline.set_amount(max_current_amount);
369 370 371 372
                    order.selected_paymentline.set_meal_voucher_issuer(issuer);

                    paymentScreen.order_changes();
                    paymentScreen.render_paymentlines();
373
                    paymentScreen.$(".paymentline.selected .edit").text(paymentScreen.format_currency_no_symbol(max_current_amount));
Etienne Freiss committed
374 375
                }

376 377
                // If required by the config, ask for the meal voucher issuer
                if (this.pos.config.meal_voucher_ask_for_issuer) {
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
                    let select_data = [{
                        'val': "",
                        'text': "- Choississez un émetteur"
                    }];

                    for (let issuer of this.meal_voucher_issuers) {
                        select_data.push({
                            "val": issuer,
                            "text": issuer
                        });
                    }

                    this.gui.show_popup("select-or-textinput", {
                        'title': _t("Émetteur du titre restaurant"),
                        'body':  _t("Si l'émetteur n'est pas dans la liste ci-dessus, veuillez le noter dans le champs ci-dessous : "),
                        'selectText':  _t("Veuillez sélectionner l'émetteur de CB déj dans la liste ci-dessous : "),
                        'selectData': select_data,
395 396 397 398 399 400 401 402 403 404 405
                        confirm: function(value) {
                            let issuer = value;
                            update_order_meal_voucher_data(issuer)
                        },
                        cancel: function(value) {
                            self.remove_selected_paymentline(order);
                        },
                    });
                } else {
                    update_order_meal_voucher_data();
                }
Etienne Freiss committed
406
            }
407 408 409 410
            
            // If user choose paper meal voucher
            // Open a popup asking for the number of the meal voucher
            if(order.selected_paymentline.is_meal_voucher() && order.selected_paymentline.is_paper_meal_voucher()){
411 412 413 414 415 416
                // Maybe not needed but cleaner : Set selected payment line amount to 0 before any further check
                order.selected_paymentline.set_amount(0);
                paymentScreen.order_changes();
                paymentScreen.render_paymentlines();
                paymentScreen.$(".paymentline.selected .edit").text(paymentScreen.format_currency_no_symbol(0));

417
                this.gui.show_popup("textinput", {
418 419
                    'title': _t("Chèque Restaurant"),
                    'body':  _t("Pour ajouter un chèque restaurant, merci de scanner le code barre du chèque. Si le chèque est illisible, veuillez rentrer le code à la main."),
420 421 422 423 424 425 426 427
                    confirm: function(value) {
                        this.pos.get_order().remove_paymentline(order.selected_paymentline);
                        var paymentScreen = this.pos.gui.current_screen;
                        paymentScreen.reset_input();
                        paymentScreen.render_paymentlines();
                        var core = '';
                        odoo.define('coreservice', function(require){core=require('web.core');})
                        core.bus.trigger('barcode_scanned', value)
428

429 430
                    },
                    cancel: function(vaue) {
431
                        self.remove_selected_paymentline(order);
432 433
                    },
                });
434 435
            }
        },
436 437
        render_paymentlines: function() {
            var self  = this;
Etienne Freiss committed
438
            
439 440 441 442 443
            this._super.apply(this, arguments);
            var order = this.pos.get_order();
            if (!order) {
                return;
            }
444

445 446 447
            // Update meal voucher summary
            var total_eligible = order.get_total_meal_voucher_eligible();
            var max_amount = this.pos.config.max_meal_voucher_amount;
448 449 450

            this.el.querySelector("#meal-voucher-eligible-amount").textContent = this.format_currency(Math.min(total_eligible,max_amount));

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
            var total_received = order.get_total_meal_voucher_received();
            this.el.querySelector("#meal-voucher-received-amount").textContent = this.format_currency(total_received);

            // Display warnings
            if (total_received > total_eligible) {
                this.$("#meal-voucher-eligible-warning").removeClass("oe_hidden");
            } else {
                this.$("#meal-voucher-eligible-warning").addClass("oe_hidden");
            }
            if (total_received > max_amount) {
                this.$("#meal-voucher-max-warning").removeClass("oe_hidden");
            } else {
                this.$("#meal-voucher-max-warning").addClass("oe_hidden");
            }

466 467 468
            if (!this.meal_voucher_activated()) {
              this.$(".meal-voucher-summary").addClass("oe_hidden");
            }
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
        },

        order_is_valid: function(force_validation) {
            var self = this;
            var order = this.pos.get_order();

            var total_eligible = order.get_total_meal_voucher_eligible();
            var total_received = order.get_total_meal_voucher_received();
            var max_amount = this.pos.config.max_meal_voucher_amount;

            var current_max = total_eligible;
            if (max_amount) {
                current_max = Math.min(total_eligible, max_amount);
            }

484 485
            // if the change is too large, it's probably an input error, if giving change is accepted make the user confirm.
            if (!force_validation && (total_received > current_max) && this.pos.config.meal_voucher_change_accepted) {
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
                this.gui.show_popup("confirm", {
                    'title': _t("Please Confirm Meal Voucher Amount"),
                    'body':  _t("You are about to validate a meal voucher payment of ") +
                           this.format_currency(total_received) +
                           _t(", when the maximum amount is ") +
                           this.format_currency(current_max) +
                           _t(".\n\n Clicking 'Confirm' will validate the payment."),
                    confirm: function() {
                        // Note: Due to the bad design of the original function
                        // the check "Large Amount" will be skipped in that case.
                        self.validate_order("confirm");
                    },
                });
                return false;
            }
501 502 503 504 505 506 507 508 509 510 511 512
            //else force user to correct
            else if (!force_validation && (total_received > current_max) && !this.pos.config.meal_voucher_change_accepted) {
                this.gui.show_popup("alert", {
                    'title': _t("Meal Voucher Amount incorrect"),
                    'body':  _t("Warning, the maximum amount of meal voucher accepted ( ") +
                           this.format_currency(current_max) +
                           _t(" ) is under the amount input ( ") +
                           this.format_currency(total_received) +
                           _t(")"),
                });
                return false;
            }
513 514 515 516
            return this._super.apply(this, arguments);
        },
    });

517 518 519
    /* point_of_sale/statis/src/js/screens.js */
    screens.ReceiptScreenWidget.include({
        render_receipt: function() {
520
            var order = this.pos.get_order();            
521
            order.meal_voucher_used = order.is_meal_voucher_used();
522

523 524 525 526
            this.$('.pos-receipt-container').html(QWeb.render('PosTicket',{
                widget:this,
                order: order,
                receipt: order.export_for_printing(),
527 528
                orderlines: order.get_orderlines(),
                paymentlines: order.get_paymentlines()
529
            }));
530 531
        }
    });
532
});