reception_produits.js 106 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
Logique :
Cette page peut avoir à traiter un groupe de commandes ou une unique commande.
Pour garder une unique logique, une commande unique sera considérée comme
  un groupe de une commande.

Sémantiquement, ici :
  list_to_process représente la liste des produits à réceptionner
  list_processed la liste des produit déjà réceptionnés
*/

/**
* Associative array of current order(s)
* If more than 1 element: group of orders
* If 1 element: single order
*/
17
var orders = {},
18 19
    group_ids = [],
    product_coeffs = [];
20

Damien Moulard committed
21
var reception_status = null,
22 23
    list_to_process = [],
    list_processed = [],
Damien Moulard committed
24 25
    table_to_process = null,
    table_processed = null,
26
    editing_product = null, // Store the product currently being edited
Damien Moulard committed
27
    editing_origin = null, // Keep track of where editing_product comes from
28 29 30 31
    processed_row_counter = 0, // Order in which products were added in processed list
    user_comments = "",
    updatedProducts = [], // Keep record of updated products
    validProducts = [], // Keep record of directly validated products
32
    updateType = "", // step 1: qty_valid; step2: br_valid
33
    barcodes = null, // Barcodes stored locally
34 35
    priceToWeightIsCorrect = true,
    suppliers_products = [], // All products of current order(s) supplier(s)
36 37
    products_to_add = [], // Products to add to order
    re_editing_qty = false; // During prices edition, edit qty mode enabled
Administrator committed
38

39
var dbc = null,
40 41
    sync = null,
    fingerprint = null;
Administrator committed
42

43 44
let lastKeypressTime = 0;

Administrator committed
45 46 47
/* UTILS */

function back() {
48
    document.location.href = "/reception";
Administrator committed
49 50
}

51 52 53 54 55 56 57 58 59 60 61 62 63 64
/**
 * Dingle order or grouped orders?
 * @returns Boolean
 */
function is_grouped_order() {
    return Object.keys(orders).length > 1;
}

/**
 * Get distinct suppliers id of current orders
 * @returns Boolean
 */
function get_suppliers_id() {
    let suppliers_id = [];
65

66
    for (var order_id in orders) {
67
        if ('partner_id' in orders[order_id]) { // check for versions transition
68 69 70
            suppliers_id.push(orders[order_id].partner_id);
        }
    }
71

72 73 74
    return suppliers_id;
}

Administrator committed
75 76 77 78
/** Search if the product being edited is already in the updated products.
  * Returns its index or -1.
  */
function searchUpdatedProduct() {
79 80 81 82 83 84 85
    try {
        if (editing_product != null) {
            for (var i=0; i < updatedProducts.length; i++) {
                if (updatedProducts[i].product_id[0] == editing_product.product_id[0]) {
                    return i;
                }
            }
Administrator committed
86
        }
87 88 89 90
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'searchUpdatedProduct'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
91 92
    }

93
    return -1;
Administrator committed
94 95 96 97
}

// Directly send a line to edition when barcode is read
function select_product_from_bc(barcode) {
98 99
    try {
        if (editing_product == null) {
100
            var scannedProduct = barcodes.get_corresponding_odoo_product(barcode);
101

102 103 104
            priceToWeightIsCorrect = true;

            if (scannedProduct == null) {
105
                alert("Le code-barre " + barcode + " ne correspond à aucun article connu.");
106 107 108 109

                return -1;
            }

110
            var foundProduct = {data: null, place: null};
Administrator committed
111

112
            // Does the product come from to_process ?
113
            $.each(list_to_process, function(i, e) {
114 115 116
                if (e.product_id[0] == scannedProduct.data[barcodes['keys']['id']]) {
                    foundProduct.data = e;
                    foundProduct.place = 'to_process';
117 118
                }
            });
Administrator committed
119

120
            // Does the product come from processed ?
121
            if (foundProduct.data == null) {
122
                $.each(list_processed, function(i, e) {
123 124
                    if (e.product_id[0] == scannedProduct.data[barcodes['keys']['id']]) {
                        foundProduct.data = JSON.parse(JSON.stringify(e));
Damien Moulard committed
125
                        foundProduct.data.product_qty = null; // Set qty to null from product already scanned
126
                        foundProduct.place = 'processed';
127 128 129
                    }
                });
            }
130

131 132 133 134
            if (foundProduct.data !== null) {
                if (foundProduct.data.product_uom[0] == 21) { //if qty is in weight
                    if (scannedProduct.rule === 'weight') {
                        editing_product = foundProduct.data;
Damien Moulard committed
135
                        foundProduct.weightAddition = true; // product weight is directly added
136 137 138 139 140 141 142
                        editProductInfo(foundProduct.data, scannedProduct.qty);
                        editing_product = null;
                    } else if (scannedProduct.rule === 'price_to_weight') {
                        openModal($('#templates #modal_confirm_price_to_weight').html(), price_to_weight_is_wrong, 'Non', false, true, price_to_weight_confirmed_callback(foundProduct, scannedProduct));
                        setupPopUpBtnStyle(scannedProduct);
                    }
                }
143

144 145
                if (scannedProduct.rule !== 'price_to_weight') {
                    if (foundProduct.data.product_uom[0] != 21) {
146 147
                        setLineEdition(foundProduct.data);
                    }
Damien Moulard committed
148

149 150 151 152
                    if (foundProduct.place === 'to_process') {
                        let row = table_to_process.row($('#'+foundProduct.data.product_id[0]));

                        remove_from_toProcess(row, foundProduct.data);
153
                    }
154
                    // Don't remove product from processed list
155 156
                }
            }
Administrator committed
157
        }
158 159 160 161
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'select_product_from_bc'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
162
    }
Damien Moulard committed
163 164

    return 0;
Administrator committed
165 166
}

167 168
/**
 * Update couchdb order
Damien Moulard committed
169
 * @param {int} order_id
170 171
 */
function update_distant_order(order_id) {
172 173
    orders[order_id].last_update = {
        timestamp: Date.now(),
Damien Moulard committed
174
        fingerprint: fingerprint
175
    };
176

Damien Moulard committed
177
    dbc.put(orders[order_id], (err, result) => {
178 179 180 181 182 183 184 185 186
        if (!err && result !== undefined) {
            orders[order_id]._rev = result.rev;
        } else {
            alert("Erreur lors de la sauvegarde de la commande... Si l'erreur persiste contactez un administrateur svp.");
            console.log(err);
        }
    });
}

187 188 189 190
/**
 * Update distant orders with local data
 * @param {int} order_id
 */
Damien Moulard committed
191
function update_distant_orders() {
192 193 194
    for (let order_id in orders) {
        orders[order_id].last_update = {
            timestamp: Date.now(),
Damien Moulard committed
195
            fingerprint: fingerprint
196 197 198 199 200 201 202
        };
    }

    dbc.bulkDocs(Object.values(orders)).then((response) => {
        // Update rev of current orders after their update
        for (let doc of response) {
            let order_id = doc.id.split('_')[1];
Damien Moulard committed
203 204

            orders[order_id]._rev = doc.rev;
205 206
        }
    })
Damien Moulard committed
207 208 209
        .catch((err) => {
            console.log(err);
        });
210 211
}

212 213 214 215 216 217 218 219 220 221 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 258 259 260 261 262 263 264 265 266 267 268 269 270
function price_to_weight_confirmed_callback(foundProduct, scannedProduct) {
    return function() {
        let newQty = null;

        if (priceToWeightIsCorrect) {
            newQty = scannedProduct.qty;
        } else {
            let tmp = Number((scannedProduct.value/document.getElementById("new_price_to_weight").value).toFixed(3));

            if (isFinite(tmp)) {
                newQty = tmp;
            }
        }

        if (foundProduct.data !== null && newQty != null) {
            if (foundProduct.place === 'to_process') {
                let row = table_to_process.row($('#'+foundProduct.data.product_id[0]));

                remove_from_toProcess(row, foundProduct.data);
            }
            editing_product = foundProduct.data;
            editProductInfo(foundProduct.data, newQty);
            editing_product = null;
            resetPopUpButtons();
        }
    };
}

function price_to_weight_is_wrong() {
    document.getElementById("new_price_to_weight").style.display = "";
    document.getElementsByClassName("btn--success")[0].style.display = "none";
    document.querySelector('#modal_closebtn_bottom').innerHTML = 'OK';
    priceToWeightIsCorrect = false;
}

function setupPopUpBtnStyle(p) {
    //On inverse en quelque sorte les boutons succes et d'annulation en mettant "Oui" sur le btn d'annulation
    // et "Non" sur le bouton de reussite.
    //Cela nous permet de reecrire moins de code puisque si la reponse est Oui on ne veut
    //rien modifier et sortir du pop up, ce qui correspond au comportement du bouton annulation
    //(ou aussi appeler cancel button)

    document.querySelector('#modal_closebtn_bottom').innerHTML = 'Oui';
    document.getElementById("modal_closebtn_bottom").style.backgroundColor = "green";
    document.getElementsByClassName("btn--success")[0].style.backgroundColor = "red";

    document.querySelector('#product_to_verify').innerHTML = p.data[0];
    document.querySelector('#price_to_verify').innerHTML = p.data[6];

    document.getElementById("new_price_to_weight").style.display = "none";
    document.getElementsByClassName("btn--success")[0].style.display = "";
}

function resetPopUpButtons() {
    document.getElementsByClassName("btn--success")[0].style.display = "";
    document.getElementsByClassName("btn--success")[0].style.backgroundColor = "";
    document.querySelector('#modal_closebtn_bottom').style.backgroundColor = "";
}

271
/* FETCH SERVER DATA */
Administrator committed
272

273
function store_received_product_coeffs(coeffs) {
274 275 276
    for (let i=0; i<coeffs.length; i++) {
        if (product_coeffs.indexOf(coeffs[i]) == -1)
            product_coeffs.push(coeffs[i]);
277 278 279
    }
}

280 281 282 283 284 285 286
/**
 * Get order(s) data from server
 * @param {Array} po_ids if set, fetch data for these po only
 */
function fetch_data(po_ids = null) {
    let po_to_fetch = (po_ids === null) ? group_ids : po_ids;

287 288 289 290 291 292 293
    try {
        $.ajax({
            type: 'POST',
            url: '../get_orders_lines',
            dataType:"json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
294
            data: JSON.stringify({'po_ids' : po_to_fetch}),
295 296 297
            success: function(data) {
                // for each order
                for (order_data of data.orders) {
298
                    store_received_product_coeffs(order_data.used_coeffs);
299 300
                    // for each product in order
                    for (i in order_data.po) {
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
                        // If in step 2, find old qty in previous step data
                        if (
                            reception_status == 'qty_valid'
                            && "previous_steps_data" in orders[order_data.id_po]
                            && "False" in orders[order_data.id_po]["previous_steps_data"]
                            && "updated_products" in orders[order_data.id_po]["previous_steps_data"]["False"] // extra + secturity
                        ) {
                            // For each updated product in step 1
                            for (let step1_updated_product of orders[order_data.id_po]["previous_steps_data"]["False"]["updated_products"]) {
                                // If product found
                                if (step1_updated_product["product_id"][0] === order_data.po[i]["product_id"][0]) {
                                    // Add old qty
                                    order_data.po[i].old_qty = step1_updated_product.old_qty;
                                }
                            }
                        }

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
                        // Does product already exists in list_to_process?
                        var existing_index = null;

                        for (var j = 0; j < list_to_process.length; j++) {
                            if (order_data.po[i].product_id[0] == list_to_process[j].product_id[0]) {
                                existing_index = j;
                                break;
                            }
                        }

                        // Products already exists: it is present in different orders
                        if (existing_index != null) {
                            // Add order id and product id to product list for other orders data
                            if (!('other_orders_data' in list_to_process[existing_index])) {
                                list_to_process[existing_index]['other_orders_data'] = [];
                            }

                            list_to_process[existing_index].other_orders_data.push({
                                id_po : order_data.id_po,
                                id_product : order_data.po[i].id,
                                initial_qty : order_data.po[i].product_qty
                            });

                            // If in step 1, concatenate qty in list_to_process
                            if (reception_status == 'False') {
                                list_to_process[existing_index].product_qty += order_data.po[i].product_qty;
                                list_to_process[existing_index].package_qty += order_data.po[i].package_qty;
                                list_to_process[existing_index].product_qty_package += order_data.po[i].product_qty_package;
                            }

                        } else {
349 350 351 352 353
                            // Add order key in products
                            let order_full_data = orders[order_data.id_po];

                            order_data.po[i].order_key = order_full_data.key;

354 355 356 357 358 359 360 361
                            // Add product to list_to_process
                            list_to_process.push(order_data.po[i]);

                            // Save order id to keep track of where product comes from
                            list_to_process[list_to_process.length-1]['id_po'] = order_data.id_po;
                        }
                    }
                }
Administrator committed
362

363 364 365 366
                initLists();
            },
            error: function() {
                alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.');
Administrator committed
367
            }
368 369 370 371 372 373
        });
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'fetch_data'};
        console.error(err);
        report_JS_error(err, 'reception');
    }
Administrator committed
374 375
}

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
// Load barcodes at page loading, then barcodes are stored locally
var get_barcodes = async function() {
    if (barcodes == null) barcodes = await init_barcodes();
};

// Get labels to print for current orders from server
function get_pdf_labels() {
    try {
        if (is_time_to('print_pdf_labels', 10000)) {
            // Concatenate orders id into a string, separated with comas, to retrieve
            oids = group_ids.join(',');

            // Send request & diret download pdf
            var filename = "codebarres_" + group_ids[0] + ".pdf";

            $.ajax({
                url: "../../orders/get_pdf_labels?oids=" + oids,
                success: download.bind(true, "pdf", filename)
            });
        } else {
            alert("Vous avez cliqué il y a moins de 10s... Patience, la demande est en cours de traitement.");
        }
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'get_pdf_labels'};
        console.error(err);
        report_JS_error(err, 'reception');
    }
}

/**
 * Get products of order(s) supplier(s) if not already fetched
 */
function fetch_suppliers_products() {
    if (suppliers_products.length === 0) {
        openModal();
411

412
        let suppliers_id = get_suppliers_id();
413

414 415 416 417 418 419 420 421 422 423 424 425
        // Fetch supplier products
        $.ajax({
            type: 'GET',
            url: "/orders/get_supplier_products",
            data: {
                sids: suppliers_id
            },
            dataType:"json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                suppliers_products = data.res.products;
426 427 428 429 430

                // Filter supplier products on products already in orders
                suppliers_products = suppliers_products.filter(p => list_to_process.findIndex(ptp => ptp.product_id[1] === p.name) === -1);
                suppliers_products = suppliers_products.filter(p => list_processed.findIndex(pp => pp.product_id[1] === p.name) === -1);

431 432 433 434 435 436 437 438 439
                closeModal();
                set_add_products_modal();
            },
            error: function(data) {
                err = {msg: "erreur serveur lors de la récupération des produits du fournisseur", ctx: 'get_supplier_products'};
                if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                    err.msg += ' : ' + data.responseJSON.error;
                }
                report_JS_error(err, 'reception');
440

441 442 443 444 445 446 447 448
                closeModal();
                alert('Erreur lors de la récupération des produits, réessayer plus tard.');
            }
        });
    } else {
        set_add_products_modal();
    }
}
Administrator committed
449 450 451 452

/* LISTS HANDLING */

// Init Data & listeners
453 454
function initLists() {
    try {
455 456 457 458 459 460 461 462 463 464 465
        // Set action buttons for remaining items
        if (
            add_all_left_is_good_qties === "True" && reception_status == "False"
            ||
            add_all_left_is_good_prices === "True" && reception_status == "qty_valid"
        ) {
            $("#remaining_lines_actions_area").addClass("connected_actions");
            $("#all_left_is_good").show();
        }

        // Enable validation buttons now the data's here
466 467 468 469 470 471 472
        if (reception_status == "False") {
            document.getElementById("valid_qty").disabled = false;
            document.getElementById("valid_all_qties").disabled = false;
        } else if (reception_status == "qty_valid") {
            document.getElementById("valid_uprice").disabled = false;
            document.getElementById("valid_all_uprices").disabled = false;
        }
Administrator committed
473

474
        // Set processed and to_process lists based on saved data
475
        for (var i = 0; i < updatedProducts.length; i++) {
476
            let product = updatedProducts[i];
Administrator committed
477

478 479
            product['row_counter'] = -1;
            list_processed.push(product);
480
            let toProcess_index = list_to_process.findIndex(x => x.id == updatedProducts[i]['id']);
Administrator committed
481

482 483
            if (toProcess_index > -1) {
                list_to_process.splice(toProcess_index, 1);
Administrator committed
484 485 486
            }
        }

487 488
        for (var j = 0; j < validProducts.length; j++) {
            let toProcess_index = list_to_process.findIndex(x => x.id == validProducts[j]);
489 490

            if (toProcess_index > -1) {
491
                let product = list_to_process[toProcess_index];
492 493 494 495

                product['row_counter'] = -1;
                list_processed.push(product);
                list_to_process.splice(toProcess_index, 1);
Administrator committed
496
            }
497
        }
Administrator committed
498

499 500 501 502
        let columns_to_process = [];
        let columns_processed = [];

        // In case of group orders, add "Order" as first column for ordering
503
        if (is_grouped_order()) {
504
            columns_to_process.push({
505
                data:"order_key", title: "n°", className: "dt-body-center",
506
                width: "15px"
507 508
            });
        }
509

510 511 512 513 514 515 516
        // Titles for Qty column
        const base_qty_title = "Qté";
        const qty_title_tooltip = `<div class="tooltip tt_twolines">
                                    Qté
                                    <span class="tooltiptext">Qté comptée / Qté commandée</span>
                                </div>`;

517 518
        columns_to_process = columns_to_process.concat([
            {data:"product_id.0", title: "id", visible: false},
519
            {data:"shelf_sortorder", title: "Rayon", className: "dt-body-center", width: "4%"},
520 521 522 523 524 525 526 527 528
            {
                data:"product_id.1",
                title:"Produit",
                render: function (data, type, full) {
                    // Add tooltip with barcode over product name
                    let display_barcode = "Aucun";

                    if ('barcode' in full) {
                        display_barcode = full.barcode;
529
                    }
530
                    let supplier_code = "Aucune";
531

532 533 534
                    if ('supplier_code' in full && full.supplier_code) {
                        supplier_code = full.supplier_code;
                    }
535
                    return '<div class="tooltip">' + data
536 537 538 539
                        + ' <span class="tooltiptext tooltip-lg tt_twolines">Code barre : '
                        + display_barcode
                        + ' Réf. fournisseur : '
                        + supplier_code + '</span> </div>';
540 541
                }
            },
Damien Moulard committed
542 543 544
            { data:"product_uom.1",
                title: "Unité vente",
                className:"dt-body-center",
545
                orderable: false,
546
                width: "5%",
547
                render: function (data) {
548
                    if (display_autres === "True" && data.toLowerCase().indexOf('unit') === 0) {
549 550 551 552 553 554
                        return "U";
                    } else {
                        return data;
                    }
                }
            },
555 556
            {
                data:"product_qty",
557 558
                title: (reception_status == "qty_valid") ? qty_title_tooltip : base_qty_title,
                className: (reception_status == "qty_valid") ? "dt-body-center product_qty_cell" : "dt-body-center",
559
                width: "5%",
560 561 562 563 564 565 566 567 568
                render: function (data, type, full) {
                    if (reception_status == "False") {
                        return data;
                    } else if ("old_qty" in full) {
                        return `${data}/${full.old_qty}`;
                    } else {
                        return `${data}/${data}`;
                    }
                }
569 570 571 572 573
            },
            {
                data:"price_unit",
                title:"Prix unit.",
                className:"dt-body-center",
574 575
                visible: (reception_status == "qty_valid"),
                width: "5%"
576 577 578
            },
            {
                title:"Editer",
579
                defaultContent: "<a class='btn toProcess_line_edit' href='#'><i class='far fa-edit'></i></a>",
580
                className:"dt-body-center",
581 582
                orderable: false,
                width: "5%"
583 584 585
            },
            {
                title:"Valider",
586
                defaultContent: "<a class='btn toProcess_line_valid' href='#'><i class='far fa-check-square'></i></a>",
587
                className:"dt-body-center",
588 589
                orderable: false,
                width: "5%"
590 591
            },
            {
592
                title:"",
593 594 595
                defaultContent: "<select class='select_product_action'><option value=''></option><option value='supplier_shortage'>Rupture fournisseur</option></select>",
                className:"dt-body-center",
                orderable: false,
596 597
                visible: display_autres === "True",
                width: "5%"
598 599 600 601 602
            }
        ]);

        columns_processed = [
            {data:"row_counter", title:"row_counter", visible: false}, // Hidden counter to display last row first
603
            {data:"shelf_sortorder", title: "Rayon", className:"dt-body-center", width: "4%"},
604 605 606
            {
                data:"product_id.1",
                title:"Produit",
607
                // width: "55%",
608 609 610 611 612 613 614
                render: function (data, type, full) {
                    // Add tooltip with barcode over product name
                    let display_barcode = "Aucun";

                    if ('barcode' in full) {
                        display_barcode = full.barcode;
                    }
615 616 617 618 619
                    let supplier_code = "Aucune";

                    if ('supplier_code' in full && full.supplier_code) {
                        supplier_code = full.supplier_code;
                    }
620 621

                    let display = '<div class="tooltip">' + data
622 623 624 625
                                  + ' <span class="tooltiptext tooltip-lg tt_twolines">Code barre : '
                                  + display_barcode
                                  + ' Réf. fournisseur : '
                                  + supplier_code + '</span> </div>';
626 627 628 629 630 631 632 633 634 635

                    if (full.supplier_shortage) {
                        display += ' <div class="tooltip"><i class="fas fa-info-circle"></i>'
                                  + ' <span class="tooltiptext tt_twolines">Rupture fournisseur'
                                  + '</span> </div>';
                    }

                    return display;
                }
            },
636
            {data:"product_uom.1", title: "Unité vente", className:"dt-body-center", orderable: false, width: "5%"},
637 638
            {
                data:"product_qty",
639
                title: qty_title_tooltip,
640
                className: (reception_status == "qty_valid") ? "dt-head-center dt-body-center product_qty_cell" : "dt-head-center dt-body-center",
641
                width: "5%",
642
                // visible: (reception_status == "False"),
643 644
                render: function (data, type, full) {
                    let disp = [
645 646
                        data,
                        (full.old_qty !== undefined) ? full.old_qty : data
647 648 649
                    ].join("/");

                    return disp;
650
                },
651 652 653 654 655 656
                orderable: false
            },
            {
                data:"price_unit",
                title:"Prix unit",
                className:"dt-body-center",
657
                visible: (reception_status == "qty_valid"),
Damien Moulard committed
658
                width: "5%"
659 660 661 662 663
            },
            {
                title:"Editer",
                defaultContent: "<a class='btn' id='processed_line_edit' href='#'><i class='far fa-edit'></i></a>",
                className:"dt-body-center",
664
                orderable: false,
Damien Moulard committed
665
                width: "5%"
666 667 668 669 670 671 672 673 674 675 676 677 678
            },
            {
                title:"Autres",
                className:"dt-body-center",
                orderable: false,
                visible: display_autres === "True",
                render: function (data, type, full) {
                    let disabled = (full.supplier_shortage) ? "disabled" : '';

                    return "<select class='select_product_action'>"
                          + "<option value=''></option>"
                          + "<option value='supplier_shortage' "+disabled+">Rupture fournisseur</option>"
                          + "</select>";
679
                }
680 681 682
            }
        ];

683 684 685 686 687 688 689 690 691 692

        table_to_process_ordering = [
            [
                0,
                "asc"
            ]
        ];

        // For grouped orders, order first by number of order, then by product id
        if (is_grouped_order()) {
Damien Moulard committed
693 694 695 696
            table_to_process_ordering.push([
                1,
                "asc"
            ]);
697 698
        }

699 700 701 702
        // Init table for to_process content
        table_to_process = $('#table_to_process').DataTable({
            data: list_to_process,
            columns: columns_to_process,
703
            rowId : "product_id.0",
704
            order: table_to_process_ordering,
705 706 707 708
            scrollY: "33vh",
            scrollCollapse: true,
            paging: false,
            dom: 'lrtip', // Remove the search input from that table
709 710 711 712 713 714 715 716 717 718 719 720 721
            language: {url : '/static/js/datatables/french.json'},
            createdRow: function(row) {
                // Add class to rows with product with qty at 0
                var row_data = $('#table_to_process').DataTable()
                    .row(row)
                    .data();

                if (row_data !== undefined && row_data.product_qty === 0) {
                    for (var i = 0; i < row.cells.length; i++) {
                        const cell_node = row.cells[i];

                        $(cell_node).addClass('row_product_no_qty');
                    }
722 723 724 725 726 727 728 729 730 731 732
                } else if (
                    row_data !== undefined
                    && row_data.product_qty !== 0
                    && 'old_qty' in row_data
                    && row_data.old_qty != row_data.product_qty
                ) {
                    for (var j = 0; j < row.cells.length; j++) {
                        const cell_node = row.cells[j];

                        $(cell_node).addClass('row_product_qty_changed');
                    }
733 734
                }
            }
735
        });
736

737 738 739
        // Init table for processed content
        table_processed = $('#table_processed').DataTable({
            data: list_processed,
740
            columns: columns_processed,
741 742 743 744 745 746 747 748 749 750 751
            rowId : "product_id.0",
            order: [
                [
                    0,
                    "desc"
                ]
            ],
            scrollY: "28vh",
            scrollCollapse: true,
            paging: false,
            dom: 'lrtip', // Remove the search input from that table
752 753 754 755 756 757 758 759 760 761 762 763
            language: {url : '/static/js/datatables/french.json'},
            createdRow: function(row) {
                var row_data = $('#table_processed').DataTable()
                    .row(row)
                    .data();

                if (row_data !== undefined && row_data.product_qty === 0) {
                    for (var i = 0; i < row.cells.length; i++) {
                        const cell_node = row.cells[i];

                        $(cell_node).addClass('row_product_no_qty');
                    }
764 765 766 767 768 769 770 771 772 773 774
                } else if (
                    row_data !== undefined
                    && row_data.product_qty !== 0
                    && 'old_qty' in row_data
                    && row_data.old_qty != row_data.product_qty
                ) {
                    for (var j = 0; j < row.cells.length; j++) {
                        const cell_node = row.cells[j];

                        $(cell_node).addClass('row_product_qty_changed');
                    }
775 776
                }
            }
777
        });
Administrator committed
778
    } catch (e) {
779 780 781
        err = {msg: e.name + ' : ' + e.message, ctx: 'initLists: init tables'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
782 783
    }

784 785
    /* Listeners */
    // Direct valid from to_process
786
    $('#table_to_process tbody').on('click', 'a.toProcess_line_valid', function () {
787 788
        if (is_time_to('reception_direct_valid_order_line', 500)) {
            try {
789 790
                let row = table_to_process.row($(this).parents('tr'));
                let data = row.data();
791 792 793 794

                add_to_processed(data);
                remove_from_toProcess(row, data);

795 796
                // Update product's order
                if (!orders[data.id_po]['valid_products']) {
797
                    orders[data.id_po]['valid_products'] = [];
798
                }
799
                orders[data.id_po]['valid_products'].push(data['id']);
Damien Moulard committed
800
                update_distant_order(data.id_po);
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816

                // Reset search
                document.getElementById('search_input').value = '';
                $('table.dataTable').DataTable()
                    .search('')
                    .draw();

                // Re set focus on input
                document.getElementById('search_input').focus();
            } catch (e) {
                err = {msg: e.name + ' : ' + e.message, ctx: 'initLists: listener validate line'};
                console.error(err);
                report_JS_error(err, 'reception');
            }
        }
    });
Administrator committed
817

818
    // Edit to_process line
819
    $('#table_to_process tbody').on('click', 'a.toProcess_line_edit', function () {
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
        try {
            // Prevent editing mutiple lines at a time
            if (editing_product == null) {
                var row = table_to_process.row($(this).parents('tr'));
                var data = row.data();

                // Product goes to editing
                editing_origin = "to_process";
                setLineEdition(data);
                remove_from_toProcess(row, data);

                document.getElementById('search_input').value = '';
                $('table.dataTable').DataTable()
                    .search('')
                    .draw();
            }
        } catch (e) {
            err = {msg: e.name + ' : ' + e.message, ctx: 'initLists : listener edit line from list to process'};
            console.error(err);
            report_JS_error(err, 'reception');
        }
    });
Administrator committed
842

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
    $('#table_to_process tbody').on('change', '.select_product_action', function () {
        try {
            if ($(this).val() == 'supplier_shortage') {
                var row = table_to_process.row($(this).parents('tr'));
                var data = row.data();

                var modal_shortage = $('#modal_set_supplier_shortage');

                modal_shortage.find(".supplier_shortage_product").text(' ' + data.product_id[1]);
                modal_shortage.find(".supplier_shortage_supplier").text(' ' + data.partner_id[1]);

                openModal(
                    modal_shortage.html(),
                    function() {
                        set_supplier_shortage(row, data);
                    },
                    'Valider',
                    true,
                    true,
                    function() {
                        $(".select_product_action").val('');
                    }
                );
            }
        } catch (e) {
            err = {msg: e.name + ' : ' + e.message, ctx: 'initLists : listener set supplier shortage'};
            console.error(err);
            report_JS_error(err, 'reception');
        }
    });


875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    // Edit processed line
    $('#table_processed tbody').on('click', 'a#processed_line_edit', function () {
        try {
            // Prevent editing mutiple lines at a time
            if (editing_product == null) {
                var row = table_processed.row($(this).parents('tr'));
                var data = row.data();

                //Go to editing
                editing_origin = "processed";
                setLineEdition(row.data());
                remove_from_processed(row, data);

                document.getElementById('search_input').value = '';
                $('table.dataTable').DataTable()
                    .search('')
                    .draw();
            }
        } catch (e) {
            err = {
                msg: e.name + ' : ' + e.message,
                ctx: 'initLists: listener edit line from processed list'
            };
            console.error(err);
            report_JS_error(err, 'reception');
        }
    });
Administrator committed
902

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
    $('#table_processed tbody').on('change', '.select_product_action', function () {
        try {
            if ($(this).val() == 'supplier_shortage') {
                var row = table_processed.row($(this).parents('tr'));
                var data = row.data();

                var modal_shortage = $('#modal_set_supplier_shortage');

                modal_shortage.find(".supplier_shortage_product").text(' ' + data.product_id[1]);
                modal_shortage.find(".supplier_shortage_supplier").text(' ' + data.partner_id[1]);

                openModal(
                    modal_shortage.html(),
                    function() {
                        set_supplier_shortage(row, data, true);
                    },
                    'Valider',
                    true,
                    true,
                    function() {
                        $(".select_product_action").val('');
                    }
                );
            }
        } catch (e) {
            err = {msg: e.name + ' : ' + e.message, ctx: 'initLists : listener set supplier shortage'};
            console.error(err);
            report_JS_error(err, 'reception');
        }
    });

934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    // Search input for both tables
    $('#search_input').on('keyup', function () {
        try {
            $('table.dataTable')
                .DataTable()
                .search(jQuery.fn.DataTable.ext.type.search.string(this.value)) // search without accents (see DataTable plugin)
                .draw();

        } catch (e) {
            err = {
                msg: e.name + ' : ' + e.message,
                ctx: 'initLists: listener search_input '
            };
            console.error(err);
            report_JS_error(err, 'reception');
        }
    });

    // Cancel line editing
    $('#edition_cancel').on('click', function () {
        if (editing_product != null) {
            if (editing_origin == "to_process") {
                add_to_toProcess(editing_product);
            } else if (editing_origin == "processed") {
                add_to_processed(editing_product, false);
            }
            clearLineEdition();
        }
    });
963 964

    $('#table_to_process tbody').on('click', '.product_qty_cell', function () {
965 966 967 968
        // Prevent editing mutiple lines at a time
        if (editing_product == null) {
            let pswd = prompt('Mot de passe requis pour éditer la quantité de ce produit');

969
            if (pswd == update_qty_pswd) {
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
                // Password ok, edit product qty
                let row = table_to_process.row($(this).parents('tr'));
                let data = row.data();

                // Product goes to editing
                editing_origin = "to_process";
                re_editing_qty = true;

                setLineEdition(data);
                remove_from_toProcess(row, data);

                document.getElementById('search_input').value = '';
                $('table.dataTable').DataTable()
                    .search('')
                    .draw();
985 986 987 988 989
            } else if (pswd == null) {
                return;
            } else {
                alert('Mauvais mot de passe !');
            }
990
        } else {
Damien Moulard committed
991
            alert("Il y a déjà un produit dans la zone d'édition. Terminez d'abord d'éditer ce produit.");
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
        }
    });

    $('#table_processed tbody').on('click', '.product_qty_cell', function () {
        // Prevent editing mutiple lines at a time
        if (editing_product == null) {
            let pswd = prompt('Mot de passe requis pour éditer la quantité de ce produit');

            if (pswd == update_qty_pswd) {
                // Password ok, edit product qty
                let row = table_processed.row($(this).parents('tr'));
                let data = row.data();

                // Product goes to editing
                editing_origin = "processed";
                re_editing_qty = true;

                setLineEdition(data);
                remove_from_processed(row, data);

                document.getElementById('search_input').value = '';
                $('table.dataTable').DataTable()
                    .search('')
                    .draw();
            } else if (pswd == null) {
                return;
            } else {
                alert('Mauvais mot de passe !');
            }
        } else {
Damien Moulard committed
1022
            alert("Il y a déjà un produit dans la zone d'édition. Terminez d'abord d'éditer ce produit.");
1023
        }
1024
    });
Administrator committed
1025 1026 1027
}

// Add a line to to_process
1028 1029
function add_to_toProcess(product) {
    try {
Administrator committed
1030
    // Add to list
1031 1032 1033 1034 1035
        list_to_process.push(product);

        // Add to table (no data binding...)
        var rowNode = table_to_process.row.add(product).draw(false)
            .node();
1036 1037

        // Handle blinking effect for newly added row
1038 1039 1040
        var onAnimationEnd = function() {
            rowNode.classList.remove('blink_me');
        };
1041 1042 1043 1044 1045 1046 1047 1048

        $(rowNode).addClass('blink_me');
        rowNode.addEventListener('animationend', onAnimationEnd);
        rowNode.addEventListener('webkitAnimationEnd', onAnimationEnd);
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'add_to_toProcess'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
1049 1050 1051 1052
    }
}

// Add a line to processed
1053 1054
function add_to_processed(product, withCounter = true) {
    try {
Administrator committed
1055
    // Add to list
1056
        list_processed.push(product);
Administrator committed
1057

1058 1059 1060 1061 1062
        // Add a counter to display first the last row added
        if (withCounter) {
            product.row_counter = processed_row_counter;
            processed_row_counter++;
        }
Administrator committed
1063

1064 1065 1066
        // Add to table (no data binding...)
        var rowNode = table_processed.row.add(product).draw(false)
            .node();
1067 1068

        // Handle blinking efect for newly added row
1069 1070 1071
        var onAnimationEnd = function() {
            rowNode.classList.remove('blink_me');
        };
Administrator committed
1072

1073 1074 1075 1076 1077 1078 1079
        $(rowNode).addClass('blink_me');
        rowNode.addEventListener('animationend', onAnimationEnd);
        rowNode.addEventListener('webkitAnimationEnd', onAnimationEnd);
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'add_to_processed'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
1080 1081 1082 1083
    }
}

// Remove a line from to_process
1084 1085
function remove_from_toProcess(row, product) {
    try {
Administrator committed
1086
    // Remove from list
1087 1088 1089 1090 1091
        var index = list_to_process.indexOf(product);

        if (index > -1) {
            list_to_process.splice(index, 1);
        }
Administrator committed
1092

1093 1094 1095 1096 1097 1098 1099
        //Remove from table
        row.remove().draw();
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'remove_from_processed'};
        console.error(err);
        report_JS_error(err, 'reception');
    }
Administrator committed
1100 1101 1102
}

// Remove a line from processed
1103 1104
function remove_from_processed(row, product) {
    try {
Administrator committed
1105
    // Remove from list
1106
        var index = list_processed.indexOf(product);
Administrator committed
1107

1108 1109 1110
        if (index > -1) {
            list_processed.splice(index, 1);
        }
Administrator committed
1111

1112 1113 1114 1115 1116 1117 1118 1119
        //Remove from table
        row.remove().draw();

    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'remove_from_processed'};
        console.error(err);
        report_JS_error(err, 'reception');
    }
Administrator committed
1120 1121
}

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
// Indicate the product is on supplier shortage.
// Direct validation from to_process & set qty to 0
function set_supplier_shortage(row, product, from_processed = false) {
    try {
        product.supplier_shortage = true;

        // Step 1: set qty to 0
        if (reception_status == 'False') {
            if (!from_processed) {
                product.old_qty = product.product_qty;
            }
            product.product_qty = 0;
1134
            product.package_qty = 0;
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
        // Step 2: for consistency purposes, updated products need these fields to be set
        } else {
            if (!from_processed) {
                product.old_price_unit = product.price_unit;
                product.new_shelf_price = null;
            }
        }

        // Create 'updated products' list in order if doesn't exists
        if (!orders[product.id_po]['updated_products'])
            orders[product.id_po]['updated_products'] = [];

        if (from_processed) {
            // Look for product in order's updated products list
            let already_updated = false;

            for (i in orders[product.id_po]['updated_products']) {
                if (orders[product.id_po]['updated_products'][i]['id']
                    == product['id']) {

                    orders[product.id_po]['updated_products'][i] = product;
                    already_updated = true;
                }
            }

            // If not updated before, add product to updated list...
            if (!already_updated) {
                orders[product.id_po]['updated_products'].push(product);

                // ... and remove product from 'direct validated' products if was there
                if ('valid_products' in orders[product.id_po]) {
                    for (i in orders[product.id_po]['valid_products']) {
                        if (orders[product.id_po]['valid_products'][i] == product['id']) {
                            orders[product.id_po]['valid_products'].splice(i, 1);
                        }
                    }
                }
            }

        } else {
            // Add the product to the updated products
            updatedProducts.push(product);
            orders[product.id_po]['updated_products'].push(product);
        }

        // Re-add product in table
        if (from_processed) {
            remove_from_processed(row, product);
        } else {
            remove_from_toProcess(row, product);
        }
        add_to_processed(product);

1188 1189
        // Update product's order
        update_distant_order(product.id_po);
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203

        // Reset search
        document.getElementById('search_input').value = '';
        $('table.dataTable').DataTable()
            .search('')
            .draw();
        document.getElementById('search_input').focus();
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'set_supplier_shortage'};
        console.error(err);
        report_JS_error(err, 'reception');
    }
}

Administrator committed
1204 1205 1206

/* EDITION */

1207
// Set edition area
Administrator committed
1208
function setLineEdition(product) {
1209 1210 1211 1212 1213
    editing_product = product;
    // name
    document.getElementById('product_name').innerHTML = editing_product.product_id[1];

    // intput
1214
    if (reception_status == 'False' || re_editing_qty === true)
1215
        document.getElementById('edition_input').value = editing_product.product_qty;
1216 1217
    else
        document.getElementById('edition_input').value = editing_product.price_unit;
1218 1219 1220 1221 1222

    document.getElementById("edition_input").focus();

    // uom
    if (editing_product.product_uom[0] == 1) { // Unit
1223
        if (reception_status == 'False' || re_editing_qty === true) {
1224
            document.getElementById('product_uom').innerHTML = ' unité(s)';
1225 1226 1227
            $('#edition_input').attr('type', 'number')
                .attr('step', 1)
                .attr('max', 9999);
1228 1229
        } else {
            document.getElementById('product_uom').innerHTML = ' / unité';
1230
            $('#edition_input').attr('type', 'number')
François C. committed
1231
                .attr('step', (allow_four_digits_in_reception_price == "True" ? 0.0001 : 0.01))
1232
                .attr('max', 9999);
1233 1234
        }
    } else if (editing_product.product_uom[0] == 21) { // kg
1235
        if (reception_status == 'False' || re_editing_qty === true) {
1236
            document.getElementById('product_uom').innerHTML = ' kg';
1237 1238 1239
            $('#edition_input').attr('type', 'number')
                .attr('step', 0.001)
                .attr('max', 9999);
1240 1241
        } else {
            document.getElementById('product_uom').innerHTML = ' / kg';
1242
            $('#edition_input').attr('type', 'number')
François C. committed
1243
                .attr('step', (allow_four_digits_in_reception_price == "True" ? 0.0001 : 0.01))
1244
                .attr('max', 9999);
1245
        }
Administrator committed
1246 1247
    }

1248 1249 1250 1251 1252 1253
    // If editing qty during prices edition
    if (re_editing_qty === true) {
        document.getElementById('edition_header').innerHTML = "Ré-éditer la quantité";
        document.getElementById('edition_input_label').innerHTML = "Qté";
    }

1254 1255
    // Make edition area blink when edition button clicked
    container_edition.classList.add('blink_me');
Administrator committed
1256 1257 1258 1259
}

// Clear edition
function clearLineEdition() {
1260
    editing_product = null;
Administrator committed
1261

1262 1263 1264 1265 1266
    // Reset DOM values
    document.getElementById('product_name').innerHTML = '';
    document.getElementById('edition_input').value = null;
    document.getElementById('search_input').focus();
    document.getElementById('product_uom').innerHTML = '';
1267 1268 1269 1270 1271 1272 1273

    if (re_editing_qty === true) {
        document.getElementById('edition_header').innerHTML = "Editer les prix";
        document.getElementById('edition_input_label').innerHTML = "Prix unit.";

        re_editing_qty = false;
    }
Administrator committed
1274 1275 1276 1277
}

/**
  * Update a product info : qty or unit price
Damien Moulard committed
1278
  * @param {Object} productToEdit
1279 1280
  * @param {Float} value if set, use it as new value
  * @param {Boolean} batch if true, don't update couchdb data here
Damien Moulard committed
1281
  * @returns
Administrator committed
1282
  */
1283
function editProductInfo (productToEdit, value = null, batch = false) {
1284
    try {
Administrator committed
1285
    // Check if the product is already in the 'updated' list
1286 1287
        var index = searchUpdatedProduct();
        var firstUpdate = false;
1288
        var isValid = false;  // "valid" == no change from initial value 
1289
        let newValue = value;
1290 1291
        var addition = false;

1292 1293
        // If 'value' parameter not set, get value from edition input
        if (value == null) {
1294
            newValue = parseFloat(document.getElementById('edition_input').value.replace(',', '.'));
1295
            newValue = isFinite(newValue) ? newValue : 0;
1296
        }
Administrator committed
1297

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
        // Particular process in case of qty reedition during prices update
        if (re_editing_qty === true) {
            // Look for product in product's order first step data
            let previous_step_index = -1;

            for (let i = 0; i < orders[productToEdit.id_po]["previous_steps_data"]["False"]["updated_products"].length; i++) {
                if (
                    orders[productToEdit.id_po]["previous_steps_data"]["False"]["updated_products"][i].id
                    ===
                    productToEdit.id
                ) {
                    previous_step_index = i;
                    break;
                }
            }

            if (previous_step_index === -1) {
                // Product qty hasn't been updated yet: add to first step data
                productToEdit.old_qty = productToEdit.product_qty;
Damien Moulard committed
1317

1318 1319 1320 1321
                productToEdit.product_qty = newValue;
                productToEdit.product_qty_package = 1;
                productToEdit.package_qty = productToEdit.product_qty;

Damien Moulard committed
1322
                orders[productToEdit.id_po]["previous_steps_data"]["False"]["updated_products"].push(productToEdit);
1323 1324 1325
            } else {
                productToEdit.product_qty = newValue;
                productToEdit.package_qty = productToEdit.product_qty;
Damien Moulard committed
1326

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
                // Product qty has been updated before, update first step data
                orders[productToEdit.id_po]["previous_steps_data"]["False"]["updated_products"][previous_step_index].product_qty = newValue;
                orders[productToEdit.id_po]["previous_steps_data"]["False"]["updated_products"][previous_step_index].package_qty = newValue;
            }

            /* Send request to server to update a single product */
            updateType = "qty_valid";
            send([productToEdit]);

            // Update temp couchdb order
            update_distant_order(productToEdit.id_po);

            // Put back product in its original list
            if (editing_origin === "to_process") {
                add_to_toProcess(productToEdit);
            } else if (editing_origin === "processed") {
                add_to_processed(productToEdit);
            }

            return true;
        }

1349
        // addition mode = weight is directly added from scanned product
1350
        $.each(list_processed, function(i, e) {
1351
            if (
Damien Moulard committed
1352 1353
                e.product_id[0] == productToEdit.product_id[0]
                && "weightAddition" in productToEdit
1354 1355
                && productToEdit.weightAddition === true
            ) {
1356 1357
                addition = true;
                productToEdit = e;
1358
                newValue = Number((newValue + productToEdit.product_qty).toFixed(3));
1359 1360
            }
        });
1361

1362
        // If qty edition & Check if qty changed
Alexis AOUN committed
1363 1364
        if (reception_status == "False") {
            firstUpdate = (index == -1); //first update
1365

Alexis AOUN committed
1366
            if (productToEdit.product_qty != newValue) {
1367 1368
                // If no old_qty in productToEdit, product qty wasn't edited before
                if (productToEdit.old_qty === undefined) {
Alexis AOUN committed
1369 1370
                    productToEdit.old_qty = productToEdit.product_qty;
                } else {
1371
                    //if it is not the first update AND newValue is equal to the validation qty then the product is valid (qty not changed)
Alexis AOUN committed
1372 1373
                    isValid = (newValue === productToEdit.old_qty);
                }
1374

Alexis AOUN committed
1375 1376
                // Edit product info
                productToEdit.product_qty = newValue;
1377

Alexis AOUN committed
1378
                /*
1379 1380 1381
                    If qty has changed, we choose to set detailed values as follow:
                    1 package (product_qty_package) of X products (package_qty)
                */
Alexis AOUN committed
1382 1383 1384 1385 1386 1387 1388
                productToEdit.product_qty_package = 1;
                productToEdit.package_qty = productToEdit.product_qty;

            } else if (firstUpdate) {
                // if the product is updated for the first time and productQty is equal to the newValue then the product is validated
                isValid = true;
            }
Administrator committed
1389 1390
        }

1391 1392 1393 1394
        // Check if price changed
        if (reception_status == "qty_valid" && productToEdit.price_unit != newValue) {
            if (index == -1) { // First update
                productToEdit.old_price_unit = productToEdit.price_unit;
1395 1396 1397
                productToEdit.new_shelf_price = parseFloat(newValue);
                try {
                    // Let's compute product final price, using coeffs.
1398
                    let computing_shelf_price_details = {base_value: productToEdit.new_shelf_price, intermediate_values: []};
1399

1400 1401
                    for (let k = 1; k <10; k++) {
                        if (typeof productToEdit['coeff' + k + '_id'] !== "undefined") {
1402 1403 1404 1405 1406 1407 1408 1409
                            product_coeffs.forEach((coeff) => {
                                if (coeff.id == productToEdit['coeff' + k + '_id']) {
                                    if (coeff.operation_type == "fixed") {
                                        productToEdit.new_shelf_price += coeff.value;
                                        computing_shelf_price_details.intermediate_values.push({msg: "Found fixed coeff " + coeff.value, new_value: productToEdit.new_shelf_price});
                                    } else if (coeff.operation_type == "multiplier") {
                                        productToEdit.new_shelf_price *= (1 + coeff.value);
                                        computing_shelf_price_details.intermediate_values.push({msg: "Found multiplier coeff " + coeff.value, new_value: productToEdit.new_shelf_price});
1410 1411
                                    }
                                }
1412
                            });
1413
                        }
1414
                    }
1415
                    productToEdit.new_shelf_price *= productToEdit.tax_coeff;
1416
                    computing_shelf_price_details.intermediate_values.push({msg: "Applying tax coeff " + productToEdit.tax_coeff, new_value: productToEdit.new_shelf_price});
1417
                    productToEdit.new_shelf_price = productToEdit.new_shelf_price.toFixed(2);
1418 1419
                    computing_shelf_price_details.final_value = productToEdit.new_shelf_price;
                    productToEdit.computing_shelf_price_details = computing_shelf_price_details;
1420 1421 1422 1423 1424
                } catch (e) {
                    productToEdit.new_shelf_price = null;
                    err = {msg: e.name + ' : ' + e.message, ctx: 'computing new_shelf_price'};
                    console.error(err);
                    report_JS_error(err, 'reception');
1425
                }
Administrator committed
1426

1427
                firstUpdate = true;
1428 1429
            } else if (productToEdit.old_price_unit == newValue) {
                productToEdit.new_shelf_price = null;
1430
            }
Administrator committed
1431

1432 1433
            productToEdit.price_unit = newValue;
        }
Administrator committed
1434

1435 1436
        // If the product info has been updated and for the first time
        if (firstUpdate) {
1437
            //if product is validated thru edition without change -> add to valid_products
Alexis AOUN committed
1438 1439 1440 1441 1442 1443 1444
            if (isValid) {
                // Create 'valid_products' list in order if not exists
                if (!orders[productToEdit.id_po]['valid_products']) {
                    orders[productToEdit.id_po]['valid_products'] = [];
                }
                orders[productToEdit.id_po]['valid_products'].push(productToEdit['id']);
            } else {
1445 1446
                updatedProducts.push(productToEdit);

Alexis AOUN committed
1447 1448 1449 1450
                // Create 'updated_products' list in order if not exists
                if (!orders[productToEdit.id_po]['updated_products']) {
                    orders[productToEdit.id_po]['updated_products'] = [];
                }
Administrator committed
1451

Alexis AOUN committed
1452 1453
                // Add product to order's updated products if first update
                orders[productToEdit.id_po]['updated_products'].push(productToEdit);
1454

Alexis AOUN committed
1455 1456 1457 1458 1459 1460
                // May have been directly validated then updated from processed list
                //  -> remove from 'valid_products' list
                for (i in orders[productToEdit.id_po]['valid_products']) {
                    if (orders[productToEdit.id_po]['valid_products'][i] == productToEdit['id']) {
                        orders[productToEdit.id_po]['valid_products'].splice(i, 1);
                    }
1461 1462 1463
                }
            }
        } else {
Alexis AOUN committed
1464 1465 1466 1467
            if (isValid) {
                //if product is valid -> remove from updated_products list and add to valid_products list
                //removing from updated_products
                for (i in orders[productToEdit.id_po]['updated_products']) {
1468 1469 1470 1471
                    if (
                        orders[productToEdit.id_po]['updated_products'][i]['product_id'][0]
                            == productToEdit['product_id'][0]
                    ) {
Alexis AOUN committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
                        orders[productToEdit.id_po]['updated_products'].splice(i, 1);
                    }
                }

                //add to valid_products
                // Create 'valid_products' list in order if not exists
                if (!orders[productToEdit.id_po]['valid_products']) {
                    orders[productToEdit.id_po]['valid_products'] = [];
                }
                orders[productToEdit.id_po]['valid_products'].push(productToEdit['id']);

            } else {
                // Look for product in order's updated products list
                for (i in orders[productToEdit.id_po]['updated_products']) {
                    if (orders[productToEdit.id_po]['updated_products'][i]['product_id'][0]
                == productToEdit['product_id'][0]) {
                        orders[productToEdit.id_po]['updated_products'][i] = productToEdit;
                    }
1490 1491
                }
            }
Administrator committed
1492
        }
1493

1494 1495 1496 1497
        if (batch === false) {
            // Update product order
            update_distant_order(productToEdit.id_po);
        }
Administrator committed
1498

1499 1500 1501 1502
        // Remove product from processed list if:
        //  - we're adding directly weight from scanned product
        //  - product comes from processed list
        if (addition === true || firstUpdate === false) {
1503
            let row = table_processed.row($('#'+productToEdit.product_id[0]));
Damien Moulard committed
1504

1505 1506 1507
            remove_from_processed(row, productToEdit);
        }

1508 1509 1510 1511 1512 1513
        add_to_processed(productToEdit);
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'edit product info'};
        console.error(err);
        report_JS_error(err, 'reception');
    }
Administrator committed
1514

1515
    return true;
Administrator committed
1516 1517 1518
}

// Validate product edition
1519
function validateEdition(form = null) {
1520 1521 1522 1523
    if (editing_product != null) {
        if (editProductInfo(editing_product)) {
            clearLineEdition();
        }
Administrator committed
1524 1525 1526 1527 1528
    }
}

// Set the quantity to 0 for all the products in to_process
function setAllQties() {
1529
    // Iterate over all rows in to_process
Damien Moulard committed
1530
    table_to_process.rows().every(function () {
1531 1532
        var data = this.data();

1533
        editProductInfo(data, 0, true);
Damien Moulard committed
1534 1535

        return true;
1536 1537 1538 1539
    });
    list_to_process = [];
    table_to_process.rows().remove()
        .draw();
Administrator committed
1540

1541
    // Batch update orders
Damien Moulard committed
1542
    update_distant_orders();
Administrator committed
1543 1544 1545 1546 1547
}

/* ACTIONS */

function print_product_labels() {
1548 1549 1550
    try {
        if (is_time_to('print_pdt_labels', 10000)) {
            $.ajax("../../orders/print_product_labels?oids=" + group_ids.join(','))
1551 1552
                .done(function(data) {
                    let success = false;
1553

1554 1555 1556 1557 1558 1559 1560 1561 1562
                    if (typeof data.res !== "undefined") {
                        if (typeof data.res.error === "undefined") {
                            success = true;
                        }
                    }
                    if (success == true) {
                        alert("l' impression des étiquettes à coller sur les articles vient d'être lancée.");
                        $('#barcodesToPrint').hide();
                    } else {
1563
                        alert("Une erreur est survenue.");
1564
                    }
1565 1566 1567 1568 1569 1570 1571 1572
                });
        } else {
            alert("Vous avez cliqué il y a moins de 10s... Patience, la demande est en cours de traitement.");
        }
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'print_product_labels'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
    }
}

/** DEPRECATED, printing is fired automaticaly now from server side. **/
// Send request to print a new shelf labels file for products with new price
// function print_etiquettes() {
//   try {
//     // Additionnal security to be sure request isn't sent during step 1
//     if (reception_status == 'qty_valid') {
//       // For all products with updated price
//       for (i in updatedProducts) {
//         // Send request
//         if (updatedProducts[i].new_shelf_price) {
//           $.ajax({
//             url: tools_server + "/products/label_print/"
//             + updatedProducts[i].product_tmpl_id + "/"
//             + updatedProducts[i].new_shelf_price
//           });
//         }
//
//       }
//
//       document.getElementById("etiquettesToPrint").innerHTML = "<br/><h5><b>Impression lancée !</b></h5>";
//     }
//   } catch (e) {
//     err = {msg: e.name + ' : ' + e.message, ctx: 'print_etiquettes'}
//     console.error(err)
//     report_JS_error(err, 'reception')
//   }
// }

// Verifications before sending BC update
function pre_send(type) {
1606 1607
    if (list_to_process.length > 0) {
        alert("Il reste des produits à traiter dans la commande.");
Administrator committed
1608
    } else {
1609
        let modal_next_step = '#templates #modal_prices_validation';
Administrator committed
1610

1611
        updateType = type;
1612

1613
        if (type == 'qty_valid') {
1614
            modal_next_step = '#templates #modal_qties_validation';
Administrator committed
1615
        }
1616
        openModal($(modal_next_step).html(), data_validation, 'Confirmer', false);
Administrator committed
1617 1618 1619
    }
}

1620
function data_validation() {
Administrator committed
1621 1622 1623
    openModal();

    $.ajax({
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
        type: "POST",
        url: "../data_validation",
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(group_ids),
        success: function(data) {
            if (data.unprocessable.length == 0) {
                // No product unprocessable, do process
                send();
Administrator committed
1634
            } else {
1635 1636 1637 1638 1639 1640 1641
                $("#modal_unprocessable_porducts #list_unprocessable_porducts").html('');
                for (p of data.unprocessable) {
                    $("#modal_unprocessable_porducts #list_unprocessable_porducts").append("<li>" + p[1] + "</li>");
                }
                openModal($("#modal_unprocessable_porducts").html(), function() {
                    return 0;
                }, 'Confirmer', true, false);
Administrator committed
1642
            }
1643 1644 1645 1646 1647 1648
        },
        error: function(data) {
            // if error during validation, report error & go on so we don't block the process
            err = {msg: "erreur serveur lors de la validation des données", ctx: 'data_validation'};
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
Administrator committed
1649
            }
1650 1651
            console.error(err);
            report_JS_error(err, 'reception');
Administrator committed
1652

1653 1654 1655 1656
            send();
        }
    });
}
Administrator committed
1657

1658 1659
/**
 * Send the request to update order(s) data
Damien Moulard committed
1660
 *
1661 1662 1663 1664 1665
 * @param {Array} given_products If set, only update these products.
 * If no given products, we're in the regular process, ie the end of a reception.
 * Else, we're in the middle of a reception, so we'll skip some parts.
 */
function send(given_products = []) {
1666
    try {
1667
        // Loading on
1668
        openModal();
Administrator committed
1669

1670
        /* Prepare data for orders update */
1671 1672 1673 1674 1675
        // Only send to server the updated lines
        var update_data = {
            update_type: updateType,
            orders: {}
        };
Administrator committed
1676

1677 1678 1679 1680
        // Set orders in update data with empty list of updated products
        for (order_id in orders) {
            update_data.orders[order_id] = {'po' : []};
        }
Administrator committed
1681

1682 1683 1684 1685
        has_given_products = given_products.length > 0;
        // If given products, update these only, else update global updatedProducts list
        products_to_update = has_given_products === true ? given_products : updatedProducts;

1686
        // for each updated product, add it to its order list
1687
        for (i in products_to_update) {
1688 1689

            /* ---> The following part concerns products found in different orders */
1690
            if ('other_orders_data' in products_to_update[i]) {
1691
                // for each other order of product
1692
                for (other_order_data of products_to_update[i].other_orders_data) {
1693
                    // Make a clone (deep copy) of the product object
1694
                    let product_copy = $.extend(true, {}, products_to_update[i]);
1695 1696 1697 1698 1699 1700 1701 1702

                    // Set correct order line id for this product
                    product_copy.id = other_order_data.id_product;

                    // If in step 1, dispatch quantity in other orders
                    if (reception_status == 'False') {
                        // Reset initial qties in respective orders
                        product_copy.old_qty = other_order_data.initial_qty;
1703 1704
                        for (j in orders[products_to_update[i].id_po]['updated_products']) {
                            if (orders[products_to_update[i].id_po]['updated_products'][j].product_id[0]
1705
                            == product_copy.product_id[0]) {
1706
                                orders[products_to_update[i].id_po]['updated_products'][j].old_qty -= other_order_data.initial_qty;
1707 1708 1709 1710
                                break;
                            }
                        }

1711
                        if (product_copy.product_uom[0] == 21 && products_to_update[i].product_qty > 0.1) { // kg
1712 1713 1714 1715 1716 1717
                            // Add minimum qty in other orders
                            product_copy.product_qty_package = 1;
                            product_copy.package_qty = 0.1;
                            product_copy.product_qty = 0.1;

                            // Remove this qty from first order
1718 1719 1720
                            products_to_update[i].package_qty -= 0.1;
                            products_to_update[i].product_qty -= 0.1;
                        } else if (product_copy.product_uom[0] == 1 && products_to_update[i].product_qty > 1) { // Unit
1721 1722 1723 1724
                            product_copy.product_qty_package = 1;
                            product_copy.package_qty = 1;
                            product_copy.product_qty = 1;

1725 1726
                            products_to_update[i].package_qty -= 1;
                            products_to_update[i].product_qty -= 1;
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
                        } else { // Not handled, all qty in one order
                            product_copy.product_qty_package = 0;
                            product_copy.package_qty = 0;
                            product_copy.product_qty = 0;
                        }
                    }

                    /* Add product to the other orders it belongs to */
                    // In update data
                    update_data.orders[other_order_data.id_po]['po'].push(product_copy);

                    // Add it to the 'updated products' of other orders (for error report)
                    if (!('updated_products' in orders[other_order_data.id_po])) {
                        orders[other_order_data.id_po]['updated_products'] = [];
                    }

                    orders[other_order_data.id_po]['updated_products'].push(product_copy);
Administrator committed
1744 1745
                }
            }
1746
            /* <--- */
Administrator committed
1747

1748
            // Add product to order's prod list
1749 1750
            prod_order_id = products_to_update[i].id_po;
            update_data.orders[prod_order_id]['po'].push(products_to_update[i]);
1751 1752
        }

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
        // Only send error report & no barcode list when no given products (ie normal process, end of reception)
        if (has_given_products === false) {
            /* Create the error report */
            // Send changes between items to process and processed items
            var error_report_data = {
                'group_amount_total' : 0,
                'update_type' : updateType,
                'updated_products' : products_to_update,
                'user_comments': user_comments,
                'orders' : []
            };
Damien Moulard committed
1764

1765 1766 1767
            for (let i in orders) {
                error_report_data.group_amount_total += orders[i].amount_total;
                error_report_data.orders.push(orders[i]);
1768
            }
Damien Moulard committed
1769

1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
            //Create list of articl with no barcode
            no_barcode_list = [];
            for (var i = 0; i < list_processed.length; i++) {
                if (list_processed[i].product_qty != 0 && (list_processed[i].barcode == false || list_processed[i].barcode == null || list_processed[i].barcode == "")) {
                    no_barcode_list.push([
                        list_processed[i]["product_id"][0],
                        list_processed[i]["product_id"][1]
                    ]);
                }
            }
Damien Moulard committed
1780

1781 1782 1783 1784
            data_send_no_barcode={
                "order" : orders[order_data['id_po']],
                "no_barcode_list" : no_barcode_list
            };
Damien Moulard committed
1785 1786


1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
            // Send of articl with no barcode to mail send
            if (no_barcode_list.length > 0) {
                $.ajax({
                    type: "POST",
                    url: "../send_mail_no_barcode",
                    dataType: "json",
                    traditional: true,
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(data_send_no_barcode),
                    success: function() {},
                    error: function() {
                        alert('Erreur dans l\'envoi des produite sont barre code.');
                    }
                });
            }
Damien Moulard committed
1802

1803
            // Send request for error report
1804 1805
            $.ajax({
                type: "POST",
1806
                url: "../save_error_report",
1807 1808 1809
                dataType: "json",
                traditional: true,
                contentType: "application/json; charset=utf-8",
1810
                data: JSON.stringify(error_report_data),
1811 1812
                success: function() {},
                error: function() {
1813 1814
                    closeModal();
                    alert('Erreur dans l\'envoi du rapport.');
1815 1816 1817
                }
            });
        }
1818

1819
        /* Update orders */
1820 1821 1822 1823 1824 1825 1826
        $.ajax({
            type: "PUT",
            url: "../update_orders",
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(update_data),
Damien Moulard committed
1827
            success: function() {
1828 1829
                closeModal();

1830 1831 1832 1833 1834 1835
                if (has_given_products === false) {
                    try {
                        // If step 1 (counting)
                        if (reception_status == "False") {
                            /* Open pop-up with procedure explanation */
                            var barcodes_to_print = false;
Damien Moulard committed
1836

1837 1838 1839 1840 1841 1842 1843
                            // Select products with local barcode and without barcode, when qty > 0
                            for (var i = 0; i < list_processed.length; i++) {
                                if (list_processed[i].product_qty != 0) {
                                    // set DOM data
                                    if (typeof(list_processed[i].barcode) == "string" && list_processed[i].barcode.startsWith(fixed_barcode_prefix) && !barcodes_to_print) {
                                        // Products with barcode to print (local barcode)
                                        document.getElementById("barcodesToPrint").hidden = false;
1844
                                        document.getElementById("nothingToDo").hidden = true;
Damien Moulard committed
1845

1846 1847 1848 1849 1850
                                        barcodes_to_print = true;
                                    } /* else if (list_processed[i].barcode == false || list_processed[i].barcode == null || list_processed[i].barcode == "") {
                                        // Products with no barcode
                                        var node = document.createElement('li');
                                        let textNode = document.createTextNode(list_processed[i]["product_id"][1]);
Damien Moulard committed
1851

1852 1853
                                        node.appendChild(textNode);
                                        document.getElementById('barcodesEmpty_list').appendChild(node);
Damien Moulard committed
1854

1855 1856 1857 1858 1859 1860
                                        if (document.getElementById("barcodesEmpty").hidden) {
                                            document.getElementById("barcodesEmpty").hidden = false;
                                            document.getElementById("nothingToDo").hidden = true;
                                        }
                                    }*/
                                }
1861
                            }
Damien Moulard committed
1862

1863 1864 1865
                            for (let i = 0; i < no_barcode_list.length; i++) {
                                var node = document.createElement('li');
                                let textNode = document.createTextNode(no_barcode_list[i]);
Damien Moulard committed
1866

1867 1868
                                node.appendChild(textNode);
                                document.getElementById('barcodesEmpty_list').appendChild(node);
Damien Moulard committed
1869

1870 1871 1872 1873
                                if (document.getElementById("barcodesEmpty").hidden) {
                                    document.getElementById("barcodesEmpty").hidden = false;
                                    document.getElementById("nothingToDo").hidden = true;
                                }
1874
                            }
Damien Moulard committed
1875

1876 1877 1878 1879 1880 1881
                            // Set order(s) name in popup DOM
                            if (is_grouped_order() === false) { // Single order
                                document.getElementById("order_ref").innerHTML = orders[Object.keys(orders)[0]].name;
                            } else { // group
                                document.getElementById("success_order_name_container").hidden = true;
                                document.getElementById("success_orders_name_container").hidden = false;
Damien Moulard committed
1882

1883 1884
                                for (order_id in orders) {
                                    var p_node = document.createElement('p');
Damien Moulard committed
1885

1886
                                    var span_node = document.createElement('span');
Damien Moulard committed
1887

1888 1889
                                    span_node.className = 'order_ref_reminder';
                                    let textNode = document.createTextNode(orders[order_id].name);
Damien Moulard committed
1890

1891
                                    span_node.appendChild(textNode);
Damien Moulard committed
1892

1893 1894 1895 1896
                                    textNode = document.createTextNode(orders[order_id].partner
                                                + ' du ' + orders[order_id].date_order + ' : ');
                                    p_node.appendChild(textNode);
                                    p_node.appendChild(span_node);
Damien Moulard committed
1897

1898
                                    document.getElementById("orders_ref").appendChild(p_node);
1899 1900
                                }
                            }
Damien Moulard committed
1901

1902 1903 1904 1905 1906 1907 1908
                            openModal(
                                $('#modal_qtiesValidated').html(),
                                back,
                                'Retour à la liste des commandes',
                                true,
                                false
                            );
Damien Moulard committed
1909

1910 1911 1912 1913 1914 1915 1916 1917 1918
                            /* Not last step: update distant data */
                            for (let order_id in orders) {
                                // Save current step updated data
                                orders[order_id].previous_steps_data = {};
                                orders[order_id].previous_steps_data[reception_status] = {
                                    updated_products: orders[order_id].updated_products || [],
                                    user_comments: user_comments
                                };
                                orders[order_id].reception_status = updateType;
Damien Moulard committed
1919

1920 1921 1922 1923 1924
                                // Unlock order
                                orders[order_id].last_update = {
                                    timestamp: null,
                                    fingerprint: null
                                };
Damien Moulard committed
1925

1926 1927 1928 1929
                                // Delete temp data
                                delete orders[order_id].valid_products;
                                delete orders[order_id].updated_products;
                            }
Damien Moulard committed
1930

1931
                            dbc.bulkDocs(Object.values(orders)).catch((err) => {
Damien Moulard committed
1932 1933
                                console.log(err);
                            });
1934 1935 1936 1937 1938
                        } else {
                            // Print etiquettes with new prices
                            if (updatedProducts.length > 0) {
                                document.getElementById("etiquettesToPrint").hidden = false;
                            }
Damien Moulard committed
1939

1940 1941 1942 1943 1944 1945 1946
                            openModal(
                                $('#templates #modal_pricesValidated').html(),
                                back,
                                'Retour à la liste des commandes',
                                true,
                                false
                            );
Damien Moulard committed
1947

1948 1949 1950 1951 1952
                            /* Last step: Clear distant data */
                            // Delete orders doc
                            for (let order_id in orders) {
                                orders[order_id]._deleted = true;
                            }
Damien Moulard committed
1953

1954 1955 1956
                            // Remove orders group
                            dbc.get("grouped_orders").then((doc) => {
                                let couchdb_update_data = Object.values(orders);
Damien Moulard committed
1957

1958 1959 1960
                                // We're in a group, remove it & update groups doc
                                if (is_grouped_order()) {
                                    let groups_doc = doc;
Damien Moulard committed
1961

1962
                                    let first_order_id = parseInt(Object.keys(orders)[0]);
Damien Moulard committed
1963

1964 1965 1966 1967 1968 1969
                                    for (let i in groups_doc.groups) {
                                        if (groups_doc.groups[i].includes(first_order_id)) {
                                            groups_doc.groups.splice(i, 1);
                                            break;
                                        }
                                    }
Damien Moulard committed
1970

1971 1972
                                    couchdb_update_data.push(groups_doc);
                                }
Damien Moulard committed
1973

1974 1975 1976 1977 1978 1979
                                return dbc.bulkDocs(couchdb_update_data);
                            })
                                .catch(function (err) {
                                    console.log(err);
                                });
                        }
Damien Moulard committed
1980

1981 1982 1983 1984 1985 1986 1987
                        // Back if modal closed
                        $('#modal_closebtn_top').on('click', back);
                        $('#modal_closebtn_bottom').on('click', back);
                    } catch (ee) {
                        err = {msg: ee.name + ' : ' + ee.message, ctx: 'callback update_orders'};
                        console.error(err);
                        report_JS_error(err, 'reception');
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
                    }
                }
            },
            error: function() {
                closeModal();
                alert('Erreur lors de la sauvegarde des données.');
            }
        });
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'send'};
        console.error(err);
        report_JS_error(err, 'reception');
        alert('Erreur : ' + err.msg);
Administrator committed
2001 2002 2003 2004 2005
    }
}

// Fired from verification modal for 'all prices' validation
function confirmPricesAllValid() {
2006 2007
    updateType = 'br_valid';
    send();
Administrator committed
2008 2009 2010 2011
}

// Fired from All left is good modal
function confirm_all_left_is_good() {
2012 2013
    // all products left are to be considered as well filled
    // Iterate over all rows in to_process
Damien Moulard committed
2014
    table_to_process.rows().every(function () {
2015 2016 2017 2018 2019 2020 2021 2022
        let data = this.data();
        var value = null;

        if (reception_status == "False") {
            value = data.product_qty;
        } else {
            value = data.price_unit;
        }
2023
        editProductInfo(data, value, true);
Damien Moulard committed
2024 2025

        return true;
2026 2027 2028 2029
    });
    list_to_process = [];
    table_to_process.rows().remove()
        .draw();
2030 2031

    // Batch update orders
Damien Moulard committed
2032
    update_distant_orders();
2033
    closeModal();
Administrator committed
2034
}
2035

2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
function saveErrorReport() {
    user_comments = document.getElementById("error_report").value;

    // Save comments in all orders
    for (order_id of Object.keys(orders)) {
        orders[order_id].user_comments = user_comments;
        update_distant_order(order_id);
    }

    document.getElementById("search_input").focus();
}

/**
2049 2050
 * Check if all qty inputs are set first.
 * Adding products leads to creating a new order (for each supplier) that will be grouped with the current one(s)
2051 2052 2053 2054 2055 2056 2057
 */
function add_products_action() {
    let qty_inputs = $("#modal .products_lines").find(".product_qty_input");
    let has_empty_qty_input = false;

    for (let qty_input of qty_inputs) {
        if ($(qty_input).val() === "") {
2058
            has_empty_qty_input = true;
Damien Moulard committed
2059 2060
            $(qty_input).closest(".product_qty")
                .find(".product_qty_input_alert")
2061
                .show();
2062
        } else {
Damien Moulard committed
2063 2064
            $(qty_input).closest(".product_qty")
                .find(".product_qty_input_alert")
2065
                .hide();
2066 2067 2068
        }
    }

2069
    if (products_to_add.length > 0 && qty_inputs.length > 0 && has_empty_qty_input === false) {
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
        create_orders();
    }
}

/**
 * Send request to create the new orders
 */
function create_orders() {
    let orders_data = {
        "suppliers_data": {}
    };

    // Mock order date_planned : today
    let date_object = new Date();
2084

2085
    formatted_date = date_object.toISOString().replace('T', ' ')
2086
        .split('.')[0]; // Get ISO format bare string
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098

    for (let supplier_id of get_suppliers_id()) {
        orders_data.suppliers_data[supplier_id] = {
            date_planned: formatted_date,
            lines: []
        };
    }

    // Prepare data: get products with their qty
    for (let p of products_to_add) {
        // Get product qty from input
        let product_qty = 0;
2099
        let product_uom = "";
2100 2101 2102

        let add_products_lines = $("#modal .add_product_line");

2103 2104
        for (let i = 0; i < add_products_lines.length; i++) {
            let line = add_products_lines[i];
2105

Damien Moulard committed
2106 2107 2108 2109
            if ($(line).find(".product_name")
                .text() === p.name) {
                product_uom = $(line).find(".product_uom")
                    .text();
2110 2111 2112 2113 2114 2115 2116 2117

                if (product_uom.includes("kg")) {
                    product_qty = parseFloat($(line).find(".product_qty_input")
                        .val());
                } else {
                    product_qty = parseInt($(line).find(".product_qty_input")
                        .val(), 10);
                }
2118 2119 2120 2121 2122 2123 2124
                break;
            }
        }

        let p_supplierinfo = p.suppliersinfo[0]; // product is ordered at its first supplier
        const supplier_id = p_supplierinfo.supplier_id;

2125 2126
        let item_qty_package = 0;

Damien Moulard committed
2127
        // If package qty is > than input value, package qty will be used while creating order
2128
        let package_qty = p_supplierinfo.package_qty;
Damien Moulard committed
2129

2130 2131 2132 2133
        if (product_qty < package_qty) {
            package_qty = product_qty;
        }

Damien Moulard committed
2134
        // Round differently for unit & kg products
Damien Moulard committed
2135
        if (product_uom.includes("kg")) {
2136 2137
            item_qty_package = Math.round((product_qty / package_qty) * 1e2) / 1e2;
        } else {
Damien Moulard committed
2138
            item_qty_package = Math.round(product_qty / package_qty);
2139 2140
        }

2141
        orders_data.suppliers_data[supplier_id].lines.push({
2142
            'package_qty': package_qty,
2143 2144
            'product_id': p.id,
            'name': p.name,
2145
            'product_qty_package': item_qty_package,
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
            'product_qty': product_qty,
            'product_uom': p.uom_id[0],
            'price_unit': p_supplierinfo.price,
            'supplier_taxes_id': p.supplier_taxes_id,
            'product_variant_ids': p.product_variant_ids,
            'product_code': p_supplierinfo.product_code
        });
    }

    // Remove supplier from order data if no lines
    for (const supplier_id in orders_data.suppliers_data) {
        if (orders_data.suppliers_data[supplier_id].lines.length === 0) {
            delete(orders_data.suppliers_data[supplier_id]);
        }
2160
    }
2161 2162

    openModal();
2163
    $("#modal em:contains('Chargement en cours...')").append("<br/>L'opération peut prendre un certain temps...");
2164 2165 2166 2167 2168 2169 2170 2171 2172

    $.ajax({
        type: "POST",
        url: "/orders/create_orders",
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(orders_data),
        success: (result) => {
2173
            po_ids = [];
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
            for (let po of result.res.created) {
                po_ids.push(po.id_po);
            }

            // Get orders data as needed by the module with order lines
            $.ajax({
                type: 'GET',
                url: "/reception/get_list_orders",
                dataType:"json",
                traditional: true,
                contentType: "application/json; charset=utf-8",
                data: {
                    poids: po_ids,
                    get_order_lines: true
                },
                success: function(result2) {
                    let current_orders_key = group_ids.length;

                    for (let new_order of result2.data) {
                        // Add key (position in orders list) to new orders data
                        current_orders_key += 1;
                        new_order.key = current_orders_key;
2196

2197 2198
                        // Consider new order lines as updated products
                        new_order.updated_products = new_order.po;
2199
                        delete(new_order.po);
2200 2201 2202 2203 2204

                        // Add necessary data to order updated products
                        for (let noup of new_order.updated_products) {
                            noup.order_key = current_orders_key;
                            noup.id_po = String(new_order.id);
2205
                            noup.old_qty = 0; // products weren't originally ordered
2206
                        }
2207

2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
                        // Create couchdb doc for the new order
                        create_order_doc(new_order);
                    }

                    dbc.get("grouped_orders").then((doc) => {
                        // Not a group (yet)
                        if (group_ids.length === 1) {
                            group_ids = group_ids.concat(po_ids);
                            doc.groups.push(group_ids);
                        } else {
                            for (let i in doc.groups) {
                                // If group found in saved distatnt groups
                                if (group_ids.findIndex(e => e == doc.groups[i][0]) !== -1) {
                                    doc.groups[i] = doc.groups[i].concat(po_ids);
                                    doc.groups[i].sort();
                                    group_ids = doc.groups[i];
                                }
                            }
                        }
2227

2228
                        dbc.put(doc, () => {
2229 2230 2231
                            // Update screen
                            // The easy way: reload page now all data is correctly set.
                            window.location.reload();
2232
                        });
2233
                    });
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
                },
                error: function(data) {
                    err = {msg: "erreur serveur lors de la récupération des commandes", ctx: 'get_list_orders'};
                    if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                        err.msg += ' : ' + data.responseJSON.error;
                    }
                    report_JS_error(err, 'orders');

                    closeModal();
                    alert('Erreur lors de la récupération des commandes, rechargez la page plus tard.');
                }
            });
        },
        error: function(data) {
            let msg = "erreur serveur lors de la création des product orders";

            err = {msg: msg, ctx: 'create_orders', data: orders_data};
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }
            report_JS_error(err, 'reception');

            closeModal();
            alert('Erreur lors de la création des commandes. Veuillez ré-essayer plus tard.');
        }
    });
}

/**
 * Create a couchdb document for an order
 *
 * @param {Object} order_data
 */
2267
function create_order_doc(order_data) {
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
    const order_doc_id = 'order_' + order_data.id;

    order_data._id = order_doc_id;
    order_data.last_update = {
        timestamp: Date.now(),
        fingerprint: fingerprint
    };

    dbc.put(order_data).then(() => {})
        .catch((err) => {
            error = {
                msg: 'Erreur dans la creation de la commande dans couchdb',
                ctx: 'create_order_doc',
                details: err
            };
            report_JS_error(error, 'reception');
            console.log(error);
        });
2286 2287 2288 2289
}

/* DOM */

2290 2291
function openFAQ() {
    openModal($("div#modal_FAQ_content").html(), function() {}, 'Compris !', true, false);
Administrator committed
2292 2293
}

2294 2295 2296
function openErrorReport() {
    openModal($('#templates #modal_error_report').html(), saveErrorReport, 'Confirmer');

2297 2298 2299 2300
    // listener for error report textarea
    // this is necessary because default behavior is overwritten by the listener defined in jquery.pos.js;
    $("#error_report").keypress(function(e) {
        var key = e.keyCode;
2301

2302 2303 2304 2305 2306
        if (key === 13) {
            this.value += "\n";
        }
    });

2307
    var textarea = document.getElementById("error_report");
Administrator committed
2308

2309
    textarea.value = (user_comments != undefined) ? user_comments : "";
2310 2311
    textarea.focus();
    textarea.setSelectionRange(textarea.value.length, textarea.value.length);
Administrator committed
2312 2313
}

2314 2315 2316 2317 2318
/**
 * Set the autocomplete on add products modal, search product input.
 * If extists, destroys instance and recreate it.
 * Filter autocomplete data by removing products already selected.
 */
Damien Moulard committed
2319
function set_products_autocomplete() {
2320
    // Filter autocomplete products on products already selected
2321
    let autocomplete_products = suppliers_products.filter(p => products_to_add.findIndex(pta => pta.name === p.name) === -1);
Damien Moulard committed
2322

2323 2324 2325 2326
    try {
        $("#modal .search_product_input").autocomplete("destroy");
    } catch (error) {
        // autocomplete not set yet, do nothing
2327 2328
    }

2329 2330 2331 2332 2333
    $("#modal .search_product_input").autocomplete({
        source: autocomplete_products.map(p => p.name),
        classes: {
            "ui-autocomplete": "autocomplete_dropdown"
        },
2334 2335 2336 2337 2338
        delay: 0,
        select: function(event, ui) {
            // Action called when an item is selected
            event.preventDefault();
            let product_name = ui.item.label;
Administrator committed
2339

2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
            // extra secutiry but shouldn't happen
            if (products_to_add.findIndex(p => p.name === product_name) === -1) {
                let product = suppliers_products.find(p => p.name === product_name);

                products_to_add.push(product);

                // Display
                let add_product_template = $("#add_product_line_template");

                add_product_template.find(".product_name").text(product_name);
2350
                add_product_template.find(".product_uom").text(product.uom_id[1]);
2351 2352 2353 2354 2355 2356 2357 2358
                $("#modal .products_lines").append(add_product_template.html());

                if (products_to_add.length === 1) {
                    $("#modal .products_lines").show();
                }

                $(".remove_line_icon").off("click");
                $(".remove_line_icon").on("click", remove_product_line);
2359

2360 2361 2362 2363
                // Reset search elements
                $("#modal .search_product_input").val('');
                set_products_autocomplete();
            }
2364 2365 2366 2367 2368 2369
        }
    });
}

/**
 * Remove product from list of products to add & remove line from DOM
2370
 * @param {Event} e
2371 2372 2373 2374 2375
 */
function remove_product_line(e) {
    let product_line = $(e.target).closest(".add_product_line");
    let product_name = product_line.find(".product_name").text();
    let product_to_add_index = products_to_add.findIndex(p => p.name === product_name);
2376

2377 2378 2379 2380
    products_to_add.splice(product_to_add_index, 1);
    product_line.remove();
    set_products_autocomplete();
}
Administrator committed
2381

2382
/**
2383 2384
 * Set & display the modal to search products.
 * If no products to add, display the according modal.
2385 2386
 */
function set_add_products_modal() {
2387 2388
    if (suppliers_products.length === 0) {
        let modal_no_product_to_add = $("#modal_no_product_to_add");
2389

2390 2391 2392 2393 2394 2395 2396
        openModal(
            modal_no_product_to_add.html(),
            () => {},
            'OK'
        );
    } else {
        let add_products_modal = $("#modal_add_products");
Damien Moulard committed
2397

2398 2399 2400 2401 2402 2403
        openModal(
            add_products_modal.html(),
            add_products_action,
            'Ajouter les produits',
            false
        );
Damien Moulard committed
2404

2405
        products_to_add = []; // Reset on modal opening
2406 2407
        set_products_autocomplete();
    }
2408
}
Damien Moulard committed
2409

2410

2411 2412
/**
 * Init the page according to order(s) data (texts, colors, events...)
Damien Moulard committed
2413 2414
 *
 * @param {Array} partners_display_data
2415 2416
 */
function init_dom(partners_display_data) {
2417 2418 2419 2420 2421 2422
    // Back button
    $('#back_button').on('click', function () {
        // Liberate current orders
        for (let order_id in orders) {
            orders[order_id].last_update = {
                timestamp: null,
Damien Moulard committed
2423
                fingerprint: null
2424
            };
2425
        }
2426

2427
        dbc.bulkDocs(Object.values(orders)).then(() => {
2428 2429
            back();
        })
Damien Moulard committed
2430 2431 2432
            .catch((err) => {
                console.log(err);
            });
2433
    });
Administrator committed
2434

2435
    // Grouped orders
2436
    if (is_grouped_order()) {
2437
        $('#partner_name').html(Object.keys(orders).length + " commandes");
Administrator committed
2438

2439 2440
        // Display order data for each order
        var msg = "";
Administrator committed
2441

2442 2443 2444
        for (display_partner_data of partners_display_data) {
            if (msg != "") {
                msg += ", ";
2445
            }
2446
            msg += display_partner_data;
Administrator committed
2447
        }
2448 2449 2450 2451
        $('#container_multiple_partners').append('<h6> ' + msg + '</h6>');
    } else {
        $('#partner_name').html(orders[Object.keys(orders)[0]].partner);
    }
Administrator committed
2452

2453 2454 2455 2456 2457
    /* Set DOM according to reception status */
    if (reception_status == "qty_valid") { // Step 2
        // Header
        document.getElementById('header_step_two').classList.add('step_two_active');
        var check_icon = document.createElement('i');
2458

2459 2460
        check_icon.className = 'far fa-check-circle';
        document.getElementById('header_step_one_content').appendChild(check_icon);
2461

2462 2463 2464 2465 2466
        // Products lists containers
        document.getElementById('container_left').style.border = "3px solid #0275D8"; // container qty_checked
        document.getElementById('container_right').style.border = "3px solid #5CB85C"; // container processed items
        document.getElementById('header_container_left').innerHTML = "Prix à mettre à jour";
        document.getElementById('header_container_right').innerHTML = "Prix mis à jour";
2467

2468 2469 2470
        // Edition
        document.getElementById('edition_header').innerHTML = "Editer les prix";
        document.getElementById('edition_input_label').innerHTML = "Prix unit.";
2471

2472 2473 2474
        // Validation buttons
        document.getElementById("valid_all").innerHTML = "<button class='btn--danger full_width_button' id='valid_all_uprices' onclick=\"openModal($('#templates #modal_no_prices').html(), confirmPricesAllValid, 'Confirmer', false);\" disabled>Pas de prix sur le bon de livraison</button>";
        document.getElementById("validation_button").innerHTML = "<button class='btn--success full_width_button' id='valid_uprice' onclick=\"pre_send('br_valid')\" disabled>Valider la mise à jour des prix</button>";
2475

2476 2477 2478 2479
        // Modal content after validation
        $("#modal_pricesValidated").load("/reception/reception_pricesValidated");
    } else if (reception_status == "False") { // Step 1
        document.getElementById('header_step_one').classList.add('step_one_active');
2480

2481 2482 2483 2484
        document.getElementById('container_left').style.border = "3px solid #212529"; // container products to process
        document.getElementById('container_right').style.border = "3px solid #0275D8"; // container qty_checked
        document.getElementById('header_container_left').innerHTML = "Produits à compter";
        document.getElementById('header_container_right').innerHTML = "Produits déjà comptés";
2485

2486 2487
        document.getElementById('edition_header').innerHTML = "Editer les quantités";
        document.getElementById('edition_input_label').innerHTML = "Qté";
2488

2489 2490 2491
        // Add products button
        document.getElementById('add_products_button').style.display = "block";

2492 2493
        document.getElementById("valid_all").innerHTML = "<button class='btn--danger full_width_button' id='valid_all_qties' onclick=\"openModal($('#templates #modal_no_qties').html(), setAllQties, 'Confirmer');\" disabled>Il n'y a plus de produits à compter</button>";
        document.getElementById("validation_button").innerHTML = "<button class='btn--primary full_width_button' id='valid_qty' onclick=\"pre_send('qty_valid')\" disabled>Valider le comptage des produits</button>";
2494

2495 2496
        $("#modal_qtiesValidated").load("/reception/reception_qtiesValidated");
    } else {
2497
        // Extra security, shouldn't get in here: reception status not valid
2498
        back();
Administrator committed
2499 2500
    }

2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
    // Load modals content
    $("#modal_FAQ_content").load("/reception/reception_FAQ");
    $("#modal_qtiesValidated").load("/reception/reception_qtiesValidated");
    $("#modal_pricesValidated").load("/reception/reception_pricesValidated");

    // Handling blinking effect
    var container_edition = document.querySelector('#container_edition');

    container_edition.addEventListener('animationend', onAnimationEnd);
    container_edition.addEventListener('webkitAnimationEnd', onAnimationEnd);

Damien Moulard committed
2512
    function onAnimationEnd() {
2513
        container_edition.classList.remove('blink_me');
Administrator committed
2514
    }
2515 2516

    // Disable mousewheel on an input number field when in focus
Damien Moulard committed
2517
    $('#edition_input').on('focus', function () {
2518 2519 2520
        $(this).on('wheel.disableScroll', function (e) {
            e.preventDefault();
        });
Administrator committed
2521
    })
Damien Moulard committed
2522
        .on('blur', function () {
2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
            $(this).off('wheel.disableScroll');
        });

    // client-side validation of numeric inputs, optionally replacing separator sign(s).
    $("input.number").on("keydown", function (e) {
        // allow function keys and decimal separators
        if (
        // backspace, delete, tab, escape, enter, comma and .
            $.inArray(e.keyCode, [
                46,
                8,
                9,
                27,
                13,
                110,
                188,
                190
            ]) !== -1 ||
Administrator committed
2541
          // Ctrl/cmd+A, Ctrl/cmd+C, Ctrl/cmd+X
2542 2543 2544 2545 2546
          ($.inArray(e.keyCode, [
              65,
              67,
              88
          ]) !== -1 && (e.ctrlKey === true || e.metaKey === true)) ||
Administrator committed
2547 2548 2549
          // home, end, left, right
          (e.keyCode >= 35 && e.keyCode <= 39)) {

2550
            /*
Administrator committed
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
          // optional: replace commas with dots in real-time (for en-US locals)
          if (e.keyCode === 188) {
              e.preventDefault();
              $(this).val($(this).val() + ".");
          }

          // optional: replace decimal points (num pad) and dots with commas in real-time (for EU locals)
          if (e.keyCode === 110 || e.keyCode === 190) {
              e.preventDefault();
              $(this).val($(this).val() + ",");
          }
          */

2564 2565 2566 2567 2568 2569
            return;
        }
        // block any non-number
        if (
        //Figures entered with Shift + key (59 ==> .)
            (e.shiftKey && ((e.keyCode < 48 || e.keyCode > 57) && e.keyCode !== 59)) ||
Administrator committed
2570 2571
          //Numeric keyboard
          (!e.shiftKey && (e.keyCode < 96 || e.keyCode > 105))
2572 2573 2574 2575 2576
        ) {
            e.preventDefault();
        }
    });

2577 2578 2579 2580 2581 2582 2583
    $("#edition_input").keypress(function(event) {
        // Force validation when enter pressed in edition
        if (event.keyCode == 13 || event.which == 13) {
            validateEdition();
        }
    });

2584
    $("#add_products_button").on('click', () => {
2585 2586
        if (reception_status == "False") {
            let pswd = prompt('Merci de demander à un.e salarié.e le mot de passe pour ajouter des produits à la commande');
2587

2588 2589 2590 2591 2592 2593 2594 2595
            // Minimum security level
            if (pswd == add_products_pswd) {
                fetch_suppliers_products();
            } else if (pswd == null) {
                return;
            } else {
                alert('Mauvais mot de passe !');
            }
2596 2597 2598
        }
    });

2599 2600
    // Barcode reader
    $(document).pos();
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
    $(document).on('keydown','#edition_input',function(event) {
        const keypressTime = event.timeStamp;
        const timeDifference = keypressTime - lastKeypressTime;
        lastKeypressTime = keypressTime;

        // Assuming a scanner would input faster than 50ms between keystrokes
        if (timeDifference < 50) {
            // Looks like scanner input, ignore or handle differently
            event.preventDefault();
            // You can display a message or handle the input differently
            alert("Vous ne pouvez pas scanner pour saisir une quantité.");
        }
    });
2614 2615 2616 2617 2618 2619 2620 2621 2622
    $(document).on('scan.pos.barcode', function(event) {
        //access `event.code` - barcode data
        var barcode = event.code;

        if (barcode.length >=13) {
            barcode = barcode.substring(barcode.length-13);
        } else if (barcode.length == 12 && barcode.indexOf('0') !== 0) {
        // User may use a scanner which remove leading 0
            barcode = '0' + barcode;
2623 2624 2625
        } else if (barcode.length >= 8) {
            // For EAN8
            barcode = barcode.substring(barcode.length-8);
2626 2627 2628 2629 2630
        } else {
        //manually submitted after correction
            var barcode_input = $('#search_input');

            barcode = barcode_input.val();
2631
        }
2632 2633 2634 2635 2636 2637

        document.getElementById('search_input').value = '';
        $('table.dataTable').DataTable()
            .search('')
            .draw();
        select_product_from_bc(barcode);
2638
    });
2639 2640 2641 2642 2643
}


$(document).ready(function() {
    $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
Damien Moulard committed
2644

2645
    fingerprint = new Fingerprint({canvas: true}).get();
2646 2647 2648 2649 2650 2651 2652 2653

    // Load barcodes
    get_barcodes();

    // Get Route parameter
    let pathArray = window.location.pathname.split('/');
    let id = pathArray[pathArray.length-1];

Damien Moulard committed
2654
    // Init couchdb
2655 2656 2657 2658 2659 2660 2661
    dbc = new PouchDB(couchdb_dbname),
    sync = PouchDB.sync(couchdb_dbname, couchdb_server, {
        live: true,
        retry: true,
        auto_compaction: false
    });

Damien Moulard committed
2662
    sync.on('change', function (info) {
2663 2664 2665 2666 2667 2668 2669 2670 2671
        if (info.direction === "pull") {
            for (const doc of info.change.docs) {
                // Redirect if one of the current order is being modified somewhere else
                if (String(doc.id) in orders && orders[doc.id]._rev !== doc._rev) {
                    alert("Un autre navigateur est en train de modifier cette commande ! Vous allez être redirigé.e.");
                    back();
                }
            }
        }
Damien Moulard committed
2672
    }).on('error', function (err) {
2673 2674 2675
        if (err.status === 409) {
            alert("Une erreur de synchronisation s'est produite, la commande a sûrement été modifiée sur un autre navigateur. Vous allez être redirigé.e.");
            back();
Damien Moulard committed
2676
        }
2677
        console.log('erreur sync', err);
Damien Moulard committed
2678 2679
    });

2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
    // Disable alert errors from datatables
    $.fn.dataTable.ext.errMode = 'none';

    // Listen for errors in tables with custom behavior
    $('#table_to_process').on('error.dt', function (e, settings, techNote, message) {
        var err_msg = message;

        try {
            var split = message.split(" ");
            var row_number = null;

            for (var i = 0; i < split.length; i++) {
                if (split[i] == "row")
                    row_number = split[i+1];
            }

            row_number = row_number.replace(',', '');
            var row_data = $('#table_to_process').DataTable()
                .row(row_number)
                .data();

            err_msg += " - Order id: " + row_data.id_po;
            err_msg += " - Product: " + row_data.product_id[1];
        } catch (e) {
            console.log(e);
        }

        err = {msg: err_msg, ctx: 'datatable: table to_process'};
        console.error(err);
        report_JS_error(err, 'reception');
    });

    $('#table_processed').on('error.dt', function (e, settings, techNote, message) {
        var err_msg = message;

        try {
            var split = message.split(" ");
            var row_number = null;

            for (var i = 0; i < split.length; i++) {
                if (split[i] == "row")
                    row_number = split[i+1];
            }

            row_number = row_number.replace(',', '');
            var row_data = $('#table_processed').DataTable()
                .row(row_number)
                .data();

            err_msg += " - Order id: " + row_data.id_po;
            err_msg += " - Product: " + row_data.product_id[1];
        } catch (e) {
            console.log(e);
        }

        err = {msg: err_msg, ctx: 'datatable: table processed'};
        console.error(err);
        report_JS_error(err, 'reception');
    });

    /* Get order info from couchdb */
    // Get order groups
Damien Moulard committed
2742 2743
    let order_groups = [];

2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
    dbc.get("grouped_orders").then((doc) => {
        order_groups = doc.groups;

        for (let group of order_groups) {
            for (group_order_id of group) {
                if (group_order_id == id) {
                    // We're in a group!
                    group_ids = group;
                }
            }
        }

2756
        // if not in group, add current order to group (1 order = group of 1)
2757
        if (group_ids.length == 0) {
2758
            group_ids.push(parseInt(id));
2759 2760 2761 2762 2763 2764 2765 2766
        }

        let partners_display_data = [];

        dbc.allDocs({
            include_docs: true
        }).then(function (result) {
            // for each order in the group
2767
            for (let i in group_ids) {
Damien Moulard committed
2768
                // find order
2769
                let order_id = group_ids[i];
2770
                let order = result.rows.find(el => el.id == 'order_' + order_id);
Damien Moulard committed
2771

2772
                order = order.doc;
2773
                order.key = parseInt(i) + 1;
2774 2775
                orders[order_id] = order;

2776
                // Add each order's already updated and validated products to common list
2777 2778 2779 2780 2781 2782 2783 2784 2785
                if (order["updated_products"]) {
                    updatedProducts = updatedProducts.concat(order["updated_products"]);
                }

                if (order["valid_products"]) {
                    validProducts = validProducts.concat(order["valid_products"]);
                }

                // Prepare data to display in 'partner name' area
2786
                partners_display_data.push(`<span class="title_partner_key">${order.key}.</span> ${order.partner} du ${order.date_order}`);
2787 2788 2789 2790 2791 2792 2793 2794
            }

            // Set current reception status: take first order's
            reception_status = orders[Object.keys(orders)[0]].reception_status;

            // Load saved user comments, get it from first order
            user_comments = orders[Object.keys(orders)[0]].user_comments || "";

2795
            // Indicate that these orders are used in this navigator
Damien Moulard committed
2796
            update_distant_orders();
2797

2798 2799 2800 2801 2802
            // Fetch orders data
            fetch_data();

            init_dom(partners_display_data);
        })
Damien Moulard committed
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
            .catch(function (e) {
                let msg = ('message' in e && 'name' in e) ? e.name + ' : ' + e.message : '';

                err = {msg, ctx: 'page init - get orders from couchdb', details: e};
                console.error(err);
                report_JS_error(err, 'reception');

                // Should be there, redirect
                alert("Erreur au chargement de cette commande. Vous allez être redirigé.");
                back();
            });
    })
2815 2816
        .catch(function (e) {
            let msg = ('message' in e && 'name' in e) ? e.name + ' : ' + e.message : '';
Damien Moulard committed
2817 2818

            err = {msg, ctx: 'page init - get grouped orders', details: e};
2819 2820 2821 2822 2823 2824 2825
            console.error(err);
            report_JS_error(err, 'reception');

            // Should be there, redirect
            alert("Erreur au chargement de cette commande. Vous allez être redirigé.");
            back();
        });
Administrator committed
2826
});