reception_produits.js 67.2 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
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
16
* -> check for Object.keys(orders).length to know if we're in a group case
Administrator committed
17
*/
18 19 20
var orders = {},
    group_ids = [];

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 33
    updateType = "", // step 1: qty_valid; step2: br_valid
    barcodes = null; // Barcodes stored locally
Administrator committed
34

35
var dbc = null,
36 37
    sync = null,
    fingerprint = null;
Administrator committed
38 39 40 41

/* UTILS */

function back() {
42
    document.location.href = "/reception";
Administrator committed
43 44 45 46 47 48
}

/** Search if the product being edited is already in the updated products.
  * Returns its index or -1.
  */
function searchUpdatedProduct() {
49 50 51 52 53 54 55
    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
56
        }
57 58 59 60
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'searchUpdatedProduct'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
61 62
    }

63
    return -1;
Administrator committed
64 65 66 67
}

// Directly send a line to edition when barcode is read
function select_product_from_bc(barcode) {
68 69
    try {
        if (editing_product == null) {
70 71 72 73 74 75 76 77
            let p = barcodes.get_corresponding_odoo_product(barcode);

            if (p == null) {
                alert("Le code-barre " + barcode + " ne correspond à aucun article connu.");

                return -1;
            }

78
            var found = {data: null, place: null};
Administrator committed
79

80
            $.each(list_to_process, function(i, e) {
81
                if (e.product_id[0] == p.data[barcodes['keys']['id']]) {
82 83 84 85
                    found.data = e;
                    found.place = 'to_process';
                }
            });
Administrator committed
86

87 88 89 90 91 92 93 94
            if (found.data != null) {
                $.each(list_processed, function(i, e) {
                    if (e.product_id[0] == p.data[barcodes['keys']['id']]) {
                        found.data = e;
                        found.place = 'processed';
                    }
                });
            }
95 96 97 98

            if (found.data !== null) {
                setLineEdition(found.data);
                if (found.place === 'to_process') {
99
                    let row = table_to_process.row($('#'+found.data.product_id[0]));
100 101 102

                    remove_from_toProcess(row, found.data);
                } else {
103
                    let row = table_processed.row($('#'+found.data.product_id[0]));
104 105 106 107

                    remove_from_processed(row, found.data);
                }
            }
Administrator committed
108
        }
109 110 111 112
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'select_product_from_bc'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
113
    }
Damien Moulard committed
114 115

    return 0;
Administrator committed
116 117
}

118 119
/**
 * Update couchdb order
Damien Moulard committed
120
 * @param {int} order_id
121 122
 */
function update_distant_order(order_id) {
123 124
    orders[order_id].last_update = {
        timestamp: Date.now(),
Damien Moulard committed
125
        fingerprint: fingerprint
126
    };
127

Damien Moulard committed
128
    dbc.put(orders[order_id], (err, result) => {
129 130 131 132 133 134 135 136 137
        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);
        }
    });
}

138 139 140 141
/**
 * Update distant orders with local data
 * @param {int} order_id
 */
Damien Moulard committed
142
function update_distant_orders() {
143 144 145
    for (let order_id in orders) {
        orders[order_id].last_update = {
            timestamp: Date.now(),
Damien Moulard committed
146
            fingerprint: fingerprint
147 148 149 150 151 152 153
        };
    }

    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
154 155

            orders[order_id]._rev = doc.rev;
156 157
        }
    })
Damien Moulard committed
158 159 160
        .catch((err) => {
            console.log(err);
        });
161 162
}

Administrator committed
163 164 165 166
/* INIT */

// Get order(s) data from server
function fetch_data() {
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    try {
        $.ajax({
            type: 'POST',
            url: '../get_orders_lines',
            dataType:"json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({'po_ids' : group_ids}),
            success: function(data) {
                // for each order
                for (order_data of data.orders) {
                    // for each product in order
                    for (i in order_data.po) {
                        // 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 {
                            // 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
219

220 221 222 223
                initLists();
            },
            error: function() {
                alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.');
Administrator committed
224
            }
225 226 227 228 229 230
        });
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'fetch_data'};
        console.error(err);
        report_JS_error(err, 'reception');
    }
Administrator committed
231 232 233 234 235 236
}


/* LISTS HANDLING */

// Init Data & listeners
237 238
function initLists() {
    try {
Administrator committed
239
    // Un-disable validation buttons now the data's here
240 241 242 243 244 245 246
        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
247

248
        // Set processed and to_process lists based on saved data
249
        for (var i = 0; i < updatedProducts.length; i++) {
250
            let product = updatedProducts[i];
Administrator committed
251

252 253
            product['row_counter'] = -1;
            list_processed.push(product);
254
            let toProcess_index = list_to_process.findIndex(x => x.id == updatedProducts[i]['id']);
Administrator committed
255

256 257
            if (toProcess_index > -1) {
                list_to_process.splice(toProcess_index, 1);
Administrator committed
258 259 260
            }
        }

261 262
        for (var j = 0; j < validProducts.length; j++) {
            let toProcess_index = list_to_process.findIndex(x => x.id == validProducts[j]);
263 264

            if (toProcess_index > -1) {
265
                let product = list_to_process[toProcess_index];
266 267 268 269

                product['row_counter'] = -1;
                list_processed.push(product);
                list_to_process.splice(toProcess_index, 1);
Administrator committed
270
            }
271
        }
Administrator committed
272

273 274 275 276 277 278 279 280 281
        // Init table for to_process content
        table_to_process = $('#table_to_process').DataTable({
            data: list_to_process,
            columns:[
                {data:"product_id.0", title: "id", visible: false},
                {data:"shelf_sortorder", title: "Rayon", className: "dt-body-center"},
                {
                    data:"product_id.1",
                    title:"Produit",
282
                    width: "45%",
Damien Moulard committed
283
                    render: function (data, type, full) {
284
                        // Add tooltip with barcode over product name
285
                        let display_barcode = "Aucun";
286

287
                        if ('barcode' in full) {
288
                            display_barcode = full.barcode;
289 290 291
                        }

                        return '<div class="tooltip">' + data
Administrator committed
292 293
              + ' <span class="tooltiptext tt_twolines">Code barre : '
              + display_barcode + '</span> </div>';
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
                    }
                },
                {data:"product_uom.1", title: "Unité vente", className:"dt-body-center", orderable: false},
                {
                    data:"product_qty",
                    title: "Qté",
                    className:"dt-body-center",
                    visible: (reception_status == "False")
                },
                {
                    data:"price_unit",
                    title:"Prix unit.",
                    className:"dt-body-center",
                    visible: (reception_status == "qty_valid")
                },
                {
                    title:"Editer",
                    defaultContent: "<a class='btn' id='toProcess_line_edit' href='#'><i class='far fa-edit'></i></a>",
                    className:"dt-body-center",
                    orderable: false
                },
                {
                    title:"Valider",
                    defaultContent: "<a class='btn' id='toProcess_line_valid' href='#'><i class='far fa-check-square'></i></a>",
                    className:"dt-body-center",
                    orderable: false
320 321 322 323 324
                },
                {
                    title:"Autres",
                    defaultContent: "<select class='select_product_action'><option value=''></option><option value='supplier_shortage'>Rupture fournisseur</option></select>",
                    className:"dt-body-center",
325
                    orderable: false,
326
                    visible: display_autres === "True"
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
                }
            ],
            rowId : "product_id.0",
            order: [
                [
                    0,
                    "asc"
                ]
            ],
            scrollY: "33vh",
            scrollCollapse: true,
            paging: false,
            dom: 'lrtip', // Remove the search input from that table
            language: {url : '/static/js/datatables/french.json'}
        });
        // Init table for processed content
        table_processed = $('#table_processed').DataTable({
            data: list_processed,
            columns:[
                {data:"row_counter", title:"row_counter", visible: false}, // Hidden counter to display last row first
                {data:"shelf_sortorder", title: "Rayon", className:"dt-body-center"},
                {
                    data:"product_id.1",
                    title:"Produit",
351
                    width: "55%",
Damien Moulard committed
352
                    render: function (data, type, full) {
353
                        // Add tooltip with barcode over product name
354
                        let display_barcode = "Aucun";
355

356
                        if ('barcode' in full) {
357
                            display_barcode = full.barcode;
358 359
                        }

360 361 362 363 364 365 366 367 368 369 370
                        let display = '<div class="tooltip">' + data
                                      + ' <span class="tooltiptext tt_twolines">Code barre : '
                                      + display_barcode + '</span> </div>';

                        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;
371 372 373 374 375 376
                    }
                },
                {data:"product_uom.1", title: "Unité vente", className:"dt-body-center", orderable: false},
                {
                    data:"product_qty",
                    title:"Qté",
377 378 379
                    className:"dt-head-center dt-body-center",
                    visible: (reception_status == "False"),
                    render: function (data, type, full) {
380 381 382 383 384 385 386
                        let disp = [
                            full.product_qty,
                            (full.old_qty !== undefined)?full.old_qty:full.product_qty
                        ].join("/");


                        return disp;
387 388
                    },
                    orderable: false
389 390 391 392 393 394 395 396 397 398 399 400
                },
                {
                    data:"price_unit",
                    title:"Prix unit",
                    className:"dt-body-center",
                    visible: (reception_status == "qty_valid")
                },
                {
                    title:"Editer",
                    defaultContent: "<a class='btn' id='processed_line_edit' href='#'><i class='far fa-edit'></i></a>",
                    className:"dt-body-center",
                    orderable: false
401 402 403 404 405
                },
                {
                    title:"Autres",
                    className:"dt-body-center",
                    orderable: false,
406
                    visible: display_autres === "True",
Damien Moulard committed
407
                    render: function (data, type, full) {
408 409 410 411 412 413 414
                        let disabled = (full.supplier_shortage) ? "disabled" : '';

                        return "<select class='select_product_action'>"
                              + "<option value=''></option>"
                              + "<option value='supplier_shortage' "+disabled+">Rupture fournisseur</option>"
                              + "</select>";
                    }
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
                }
            ],
            rowId : "product_id.0",
            order: [
                [
                    0,
                    "desc"
                ]
            ],
            scrollY: "28vh",
            scrollCollapse: true,
            paging: false,
            dom: 'lrtip', // Remove the search input from that table
            language: {url : '/static/js/datatables/french.json'}
        });
Administrator committed
430
    } catch (e) {
431 432 433
        err = {msg: e.name + ' : ' + e.message, ctx: 'initLists: init tables'};
        console.error(err);
        report_JS_error(err, 'reception');
Administrator committed
434 435
    }

436 437 438 439 440
    /* Listeners */
    // Direct valid from to_process
    $('#table_to_process tbody').on('click', 'a#toProcess_line_valid', function () {
        if (is_time_to('reception_direct_valid_order_line', 500)) {
            try {
441 442
                let row = table_to_process.row($(this).parents('tr'));
                let data = row.data();
443 444 445 446

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

447 448
                // Update product's order
                if (!orders[data.id_po]['valid_products']) {
449
                    orders[data.id_po]['valid_products'] = [];
450
                }
451
                orders[data.id_po]['valid_products'].push(data['id']);
Damien Moulard committed
452
                update_distant_order(data.id_po);
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

                // 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
469

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    // Edit to_process line
    $('#table_to_process tbody').on('click', 'a#toProcess_line_edit', function () {
        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
494

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    $('#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');
        }
    });


527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    // 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
554

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    $('#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');
        }
    });

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    // 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();
        }
    });
Administrator committed
615 616 617
}

// Add a line to to_process
618 619
function add_to_toProcess(product) {
    try {
Administrator committed
620
    // Add to list
621 622 623 624 625
        list_to_process.push(product);

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

        // Handle blinking effect for newly added row
628 629 630
        var onAnimationEnd = function() {
            rowNode.classList.remove('blink_me');
        };
631 632 633 634 635 636 637 638

        $(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
639 640 641 642
    }
}

// Add a line to processed
643 644
function add_to_processed(product, withCounter = true) {
    try {
Administrator committed
645
    // Add to list
646
        list_processed.push(product);
Administrator committed
647

648 649 650 651 652
        // Add a counter to display first the last row added
        if (withCounter) {
            product.row_counter = processed_row_counter;
            processed_row_counter++;
        }
Administrator committed
653

654 655 656
        // Add to table (no data binding...)
        var rowNode = table_processed.row.add(product).draw(false)
            .node();
657 658

        // Handle blinking efect for newly added row
659 660 661
        var onAnimationEnd = function() {
            rowNode.classList.remove('blink_me');
        };
Administrator committed
662

663 664 665 666 667 668 669
        $(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
670 671 672 673
    }
}

// Remove a line from to_process
674 675
function remove_from_toProcess(row, product) {
    try {
Administrator committed
676
    // Remove from list
677 678 679 680 681
        var index = list_to_process.indexOf(product);

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

683 684 685 686 687 688 689
        //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
690 691 692
}

// Remove a line from processed
693 694
function remove_from_processed(row, product) {
    try {
Administrator committed
695
    // Remove from list
696
        var index = list_processed.indexOf(product);
Administrator committed
697

698 699 700
        if (index > -1) {
            list_processed.splice(index, 1);
        }
Administrator committed
701

702 703 704 705 706 707 708 709
        //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
710 711
}

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
// 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;
        // 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);

777 778
        // Update product's order
        update_distant_order(product.id_po);
779 780 781 782 783 784 785 786 787 788 789 790 791 792

        // 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
793 794 795 796 797

/* EDITION */

// Set edition
function setLineEdition(product) {
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    editing_product = product;
    // name
    document.getElementById('product_name').innerHTML = editing_product.product_id[1];

    // intput
    if (reception_status == "qty_valid")
        document.getElementById('edition_input').value = editing_product.price_unit;
    else
        document.getElementById('edition_input').value = editing_product.product_qty;

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

    // uom
    if (editing_product.product_uom[0] == 1) { // Unit
        if (reception_status == 'False') {
            document.getElementById('product_uom').innerHTML = ' unité(s)';
814 815 816
            $('#edition_input').attr('type', 'number')
                .attr('step', 1)
                .attr('max', 9999);
817 818
        } else {
            document.getElementById('product_uom').innerHTML = ' / unité';
819 820 821
            $('#edition_input').attr('type', 'number')
                .attr('step', 0.01)
                .attr('max', 9999);
822 823 824 825
        }
    } else if (editing_product.product_uom[0] == 21) { // kg
        if (reception_status == 'False') {
            document.getElementById('product_uom').innerHTML = ' kg';
826 827 828
            $('#edition_input').attr('type', 'number')
                .attr('step', 0.001)
                .attr('max', 9999);
829 830
        } else {
            document.getElementById('product_uom').innerHTML = ' / kg';
831 832 833
            $('#edition_input').attr('type', 'number')
                .attr('step', 0.01)
                .attr('max', 9999);
834
        }
Administrator committed
835 836
    }

837 838
    // Make edition area blink when edition button clicked
    container_edition.classList.add('blink_me');
Administrator committed
839 840 841 842
}

// Clear edition
function clearLineEdition() {
843
    editing_product = null;
Administrator committed
844

845 846 847 848 849
    // Reset DOM values
    document.getElementById('product_name').innerHTML = '';
    document.getElementById('edition_input').value = null;
    document.getElementById('search_input').focus();
    document.getElementById('product_uom').innerHTML = '';
Administrator committed
850 851 852 853
}

/**
  * Update a product info : qty or unit price
Damien Moulard committed
854
  * @param {Object} productToEdit
855 856
  * @param {Float} value if set, use it as new value
  * @param {Boolean} batch if true, don't update couchdb data here
Damien Moulard committed
857
  * @returns
Administrator committed
858
  */
859
function editProductInfo (productToEdit, value = null, batch = false) {
860
    try {
Administrator committed
861
    // Check if the product is already in the 'updated' list
862 863
        var index = searchUpdatedProduct();
        var firstUpdate = false;
864
        let newValue = value;
Administrator committed
865

866 867
        // If 'value' parameter not set, get value from edition input
        if (value == null) {
868
            newValue = parseFloat(document.getElementById('edition_input').value.replace(',', '.'));
869
        }
Administrator committed
870

871 872 873 874 875 876
        // If qty edition & Check if qty changed
        if (reception_status == "False" && productToEdit.product_qty != newValue) {
            if (index == -1) { // First update
                productToEdit.old_qty = productToEdit.product_qty;
                firstUpdate = true;
            }
Administrator committed
877

878 879 880
            // Edit product info
            productToEdit.product_qty = newValue;
            /*
881 882 883
            If qty has changed, we choose to set detailed values as follow:
            1 package (product_qty_package) of X products (package_qty)
            */
884 885
            productToEdit.product_qty_package = 1;
            productToEdit.package_qty = productToEdit.product_qty;
Administrator committed
886 887
        }

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        // 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;
                productToEdit.new_shelf_price = null;

                if (! isNaN(productToEdit.p_coeff)) {
                    try {
                        new_shelf_price = parseFloat(newValue * productToEdit.p_coeff);
                        old_shelf_price = parseFloat(productToEdit.p_price * productToEdit.p_coeff);
                        if (Math.abs(new_shelf_price - old_shelf_price) > 0.001)
                            productToEdit.new_shelf_price = new_shelf_price.toFixed(2);
                    } catch (e) {
                        err = {msg: e.name + ' : ' + e.message, ctx: 'computing new_shelf_price'};
                        console.error(err);
                        report_JS_error(err, 'reception');
                    }
                }
Administrator committed
906

907 908
                firstUpdate = true;
            }
Administrator committed
909

910 911
            productToEdit.price_unit = newValue;
        }
Administrator committed
912

913 914 915
        // If the product info has been updated and for the first time
        if (firstUpdate) {
            updatedProducts.push(productToEdit);
Administrator committed
916

917
            // Create 'updated_products' list in order if not exists
918
            if (!orders[productToEdit.id_po]['updated_products']) {
919
                orders[productToEdit.id_po]['updated_products'] = [];
920
            }
Administrator committed
921

922 923 924 925
            // Add product to order's updated products if first update
            orders[productToEdit.id_po]['updated_products'].push(productToEdit);

            // May have been directly validated then updated from processed list
926
            //  -> remove from 'valid_products' list
927 928 929 930 931 932 933 934 935
            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);
                }
            }
        } 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]
Administrator committed
936
            == productToEdit['product_id'][0]) {
937 938 939
                    orders[productToEdit.id_po]['updated_products'][i] = productToEdit;
                }
            }
Administrator committed
940 941
        }

942 943 944 945
        if (batch === false) {
            // Update product order
            update_distant_order(productToEdit.id_po);
        }
Administrator committed
946

947 948 949 950 951 952
        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
953

954
    return true;
Administrator committed
955 956 957
}

// Validate product edition
958
function validateEdition(form = null) {
959 960 961 962
    if (editing_product != null) {
        if (editProductInfo(editing_product)) {
            clearLineEdition();
        }
Administrator committed
963 964 965 966 967
    }
}

// Set the quantity to 0 for all the products in to_process
function setAllQties() {
968
    // Iterate over all rows in to_process
Damien Moulard committed
969
    table_to_process.rows().every(function () {
970 971
        var data = this.data();

972
        editProductInfo(data, 0, true);
Damien Moulard committed
973 974

        return true;
975 976 977 978
    });
    list_to_process = [];
    table_to_process.rows().remove()
        .draw();
Administrator committed
979

980
    // Batch update orders
Damien Moulard committed
981
    update_distant_orders();
Administrator committed
982 983 984 985 986 987
}

/* ACTIONS */

// Get labels to print for current orders from server
function get_pdf_labels() {
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    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');
Administrator committed
1007 1008 1009 1010
    }
}

function print_product_labels() {
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    try {
        if (is_time_to('print_pdt_labels', 10000)) {
            $.ajax("../../orders/print_product_labels?oids=" + group_ids.join(','))
                .done(function() {
                    alert('Impression des étiquettes à coller sur les articles lancée.');
                });
        } 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
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    }
}

/** 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) {
1057 1058
    if (list_to_process.length > 0) {
        alert("Il reste des produits à traiter dans la commande.");
Administrator committed
1059
    } else {
1060
        let modal_next_step = '#templates #modal_prices_validation';
Administrator committed
1061

1062
        updateType = type;
1063

1064
        if (type == 'qty_valid') {
1065
            modal_next_step = '#templates #modal_qties_validation';
Administrator committed
1066
        }
1067
        openModal($(modal_next_step).html(), data_validation, 'Confirmer', false);
Administrator committed
1068 1069 1070
    }
}

1071
function data_validation() {
Administrator committed
1072 1073 1074
    openModal();

    $.ajax({
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        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
1085
            } else {
1086 1087 1088 1089 1090 1091 1092
                $("#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
1093
            }
1094 1095 1096 1097 1098 1099
        },
        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
1100
            }
1101 1102
            console.error(err);
            report_JS_error(err, 'reception');
Administrator committed
1103

1104 1105 1106 1107
            send();
        }
    });
}
Administrator committed
1108

1109 1110 1111
// Send the request to the server
function send() {
    try {
1112
        // Loading on
1113
        openModal();
Administrator committed
1114

1115
        /* Prepare data for orders update */
1116 1117 1118 1119 1120
        // Only send to server the updated lines
        var update_data = {
            update_type: updateType,
            orders: {}
        };
Administrator committed
1121

1122 1123 1124 1125
        // Set orders in update data with empty list of updated products
        for (order_id in orders) {
            update_data.orders[order_id] = {'po' : []};
        }
Administrator committed
1126

1127 1128
        // for each updated product, add it to its order list
        for (i in updatedProducts) {
1129 1130

            /* ---> The following part concerns products found in different orders */
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
            if ('other_orders_data' in updatedProducts[i]) {
                // for each other order of product
                for (other_order_data of updatedProducts[i].other_orders_data) {
                    // Make a clone (deep copy) of the product object
                    let product_copy = $.extend(true, {}, updatedProducts[i]);

                    // 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;
                        for (j in orders[updatedProducts[i].id_po]['updated_products']) {
                            if (orders[updatedProducts[i].id_po]['updated_products'][j].product_id[0]
1146
                            == product_copy.product_id[0]) {
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
                                orders[updatedProducts[i].id_po]['updated_products'][j].old_qty -= other_order_data.initial_qty;
                                break;
                            }
                        }

                        if (product_copy.product_uom[0] == 21 && updatedProducts[i].product_qty > 0.1) { // kg
                            // 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
                            updatedProducts[i].package_qty -= 0.1;
                            updatedProducts[i].product_qty -= 0.1;
                        } else if (product_copy.product_uom[0] == 1 && updatedProducts[i].product_qty > 1) { // Unit
                            product_copy.product_qty_package = 1;
                            product_copy.package_qty = 1;
                            product_copy.product_qty = 1;

                            updatedProducts[i].package_qty -= 1;
                            updatedProducts[i].product_qty -= 1;
                        } 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
1185 1186
                }
            }
1187
            /* <--- */
Administrator committed
1188

1189 1190 1191 1192 1193
            // Add product to order's prod list
            prod_order_id = updatedProducts[i].id_po;
            update_data.orders[prod_order_id]['po'].push(updatedProducts[i]);
        }

1194
        /* Create the error report */
1195
        // Send changes between items to process and processed items
1196
        var error_report_data = {
1197 1198 1199 1200 1201 1202 1203
            'group_amount_total' : 0,
            'update_type' : updateType,
            'updated_products' : updatedProducts,
            'user_comments': user_comments,
            'orders' : []
        };

1204 1205 1206
        for (let i in orders) {
            error_report_data.group_amount_total += orders[i].amount_total;
            error_report_data.orders.push(orders[i]);
1207 1208
        }

1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
        // Send request for error report
        $.ajax({
            type: "POST",
            url: "../save_error_report",
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(error_report_data),
            success: function() {},
            error: function() {
                closeModal();
                alert('Erreur dans l\'envoi du rapport.');
            }
        });
1223 1224

        /* Update orders */
1225 1226 1227 1228 1229 1230 1231
        $.ajax({
            type: "PUT",
            url: "../update_orders",
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(update_data),
Damien Moulard committed
1232
            success: function() {
1233 1234
                closeModal();

1235
                try {
Damien Moulard committed
1236
                    // If step 1 (counting)
1237
                    if (reception_status == "False") {
1238
                        /* Open pop-up with procedure explanation */
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
                        var barcodes_to_print = false;

                        // 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;
                                    document.getElementById("nothingToDo").hidden = true;

                                    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');
1254
                                    let textNode = document.createTextNode(list_processed[i]["product_id"][1]);
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267

                                    node.appendChild(textNode);
                                    document.getElementById('barcodesEmpty_list').appendChild(node);

                                    if (document.getElementById("barcodesEmpty").hidden) {
                                        document.getElementById("barcodesEmpty").hidden = false;
                                        document.getElementById("nothingToDo").hidden = true;
                                    }
                                }
                            }
                        }

                        // Set order(s) name in popup DOM
Damien Moulard committed
1268
                        if (Object.keys(orders).length === 1) { // Single order
1269
                            document.getElementById("order_ref").innerHTML = orders[Object.keys(orders)[0]].name;
Damien Moulard committed
1270
                        } else { // group
1271 1272 1273 1274 1275 1276 1277 1278 1279
                            document.getElementById("success_order_name_container").hidden = true;
                            document.getElementById("success_orders_name_container").hidden = false;

                            for (order_id in orders) {
                                var p_node = document.createElement('p');

                                var span_node = document.createElement('span');

                                span_node.className = 'order_ref_reminder';
1280
                                let textNode = document.createTextNode(orders[order_id].name);
1281 1282 1283 1284

                                span_node.appendChild(textNode);

                                textNode = document.createTextNode(orders[order_id].partner
1285
                                            + ' du ' + orders[order_id].date_order + ' : ');
1286 1287 1288 1289 1290 1291 1292 1293 1294
                                p_node.appendChild(textNode);
                                p_node.appendChild(span_node);

                                document.getElementById("orders_ref").appendChild(p_node);
                            }
                        }

                        openModal(
                            $('#modal_qtiesValidated').html(),
1295
                            back,
1296 1297 1298 1299
                            'Retour à la liste des commandes',
                            true,
                            false
                        );
1300 1301 1302 1303

                        /* Not last step: update distant data */
                        for (let order_id in orders) {
                            // Save current step updated data
Damien Moulard committed
1304
                            orders[order_id].previous_steps_data = {};
1305
                            orders[order_id].previous_steps_data[reception_status] = {
1306
                                updated_products: orders[order_id].updated_products || []
Damien Moulard committed
1307
                            };
1308
                            orders[order_id].reception_status = updateType;
1309 1310 1311 1312

                            // Unlock order
                            orders[order_id].last_update = {
                                timestamp: null,
Damien Moulard committed
1313 1314 1315
                                fingerprint: null
                            };

1316 1317 1318 1319 1320 1321 1322
                            // Delete temp data
                            delete orders[order_id].valid_products;
                            delete orders[order_id].updated_products;
                        }

                        dbc.bulkDocs(Object.values(orders)).catch((err) => {
                            console.log(err);
Damien Moulard committed
1323
                        });
1324 1325 1326 1327 1328 1329 1330 1331
                    } else {
                        // Print etiquettes with new prices
                        if (updatedProducts.length > 0) {
                            document.getElementById("etiquettesToPrint").hidden = false;
                        }

                        openModal(
                            $('#templates #modal_pricesValidated').html(),
1332
                            back,
1333 1334 1335 1336 1337
                            'Retour à la liste des commandes',
                            true,
                            false
                        );

1338 1339 1340 1341 1342
                        /* Last step: Clear distant data */
                        // Delete orders doc
                        for (let order_id in orders) {
                            orders[order_id]._deleted = true;
                        }
1343

1344 1345 1346
                        // Remove orders group
                        dbc.get("grouped_orders").then((doc) => {
                            let couchdb_update_data = Object.values(orders);
1347

1348 1349 1350
                            // We're in a group, remove it & update groups doc
                            if (Object.keys(orders).length > 1) {
                                let groups_doc = doc;
1351

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

1354 1355 1356 1357
                                for (let i in groups_doc.groups) {
                                    if (groups_doc.groups[i].includes(first_order_id)) {
                                        groups_doc.groups.splice(i, 1);
                                        break;
1358 1359
                                    }
                                }
1360 1361

                                couchdb_update_data.push(groups_doc);
1362 1363
                            }

1364 1365
                            return dbc.bulkDocs(couchdb_update_data);
                        })
Damien Moulard committed
1366 1367 1368
                            .catch(function (err) {
                                console.log(err);
                            });
1369 1370
                    }

1371
                    // Back if modal closed
1372 1373
                    $('#modal_closebtn_top').on('click', back);
                    $('#modal_closebtn_bottom').on('click', back);
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
                } catch (ee) {
                    err = {msg: ee.name + ' : ' + ee.message, ctx: 'callback update_orders'};
                    console.error(err);
                    report_JS_error(err, 'reception');
                }
            },
            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
1390 1391 1392 1393 1394
    }
}

// Fired from verification modal for 'all prices' validation
function confirmPricesAllValid() {
1395 1396
    updateType = 'br_valid';
    send();
Administrator committed
1397 1398 1399 1400
}

// Fired from All left is good modal
function confirm_all_left_is_good() {
1401 1402
    // all products left are to be considered as well filled
    // Iterate over all rows in to_process
Damien Moulard committed
1403
    table_to_process.rows().every(function () {
1404 1405 1406 1407 1408 1409 1410 1411
        let data = this.data();
        var value = null;

        if (reception_status == "False") {
            value = data.product_qty;
        } else {
            value = data.price_unit;
        }
1412
        editProductInfo(data, value, true);
Damien Moulard committed
1413 1414

        return true;
1415 1416 1417 1418
    });
    list_to_process = [];
    table_to_process.rows().remove()
        .draw();
1419 1420

    // Batch update orders
Damien Moulard committed
1421
    update_distant_orders();
1422
    closeModal();
Administrator committed
1423
}
1424

1425 1426
function openFAQ() {
    openModal($("div#modal_FAQ_content").html(), function() {}, 'Compris !', true, false);
Administrator committed
1427 1428
}

1429 1430 1431
function openErrorReport() {
    openModal($('#templates #modal_error_report').html(), saveErrorReport, 'Confirmer');

1432 1433 1434 1435
    // 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;
1436

1437 1438 1439 1440 1441
        if (key === 13) {
            this.value += "\n";
        }
    });

1442
    var textarea = document.getElementById("error_report");
Administrator committed
1443

1444
    textarea.value = (user_comments != undefined) ? user_comments : "";
1445 1446
    textarea.focus();
    textarea.setSelectionRange(textarea.value.length, textarea.value.length);
Administrator committed
1447 1448 1449
}

function saveErrorReport() {
1450
    user_comments = document.getElementById("error_report").value;
1451

1452
    // Save comments in all orders
1453 1454
    for (order_id of Object.keys(orders)) {
        orders[order_id].user_comments = user_comments;
Damien Moulard committed
1455
        update_distant_order(order_id);
1456 1457
    }

1458
    document.getElementById("search_input").focus();
Administrator committed
1459 1460
}

1461 1462 1463 1464 1465
// Load barcodes at page loading, then barcodes are stored locally
var get_barcodes = async function() {
    if (barcodes == null) barcodes = await init_barcodes();
};

Administrator committed
1466

1467

1468 1469
/**
 * Init the page according to order(s) data (texts, colors, events...)
Damien Moulard committed
1470 1471
 *
 * @param {Array} partners_display_data
1472 1473
 */
function init_dom(partners_display_data) {
1474 1475 1476 1477 1478 1479
    // 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
1480
                fingerprint: null
1481
            };
1482
        }
Administrator committed
1483

1484 1485 1486
        dbc.bulkDocs(Object.values(orders)).then((response) => {
            back();
        })
Damien Moulard committed
1487 1488 1489
            .catch((err) => {
                console.log(err);
            });
1490
    });
Administrator committed
1491

1492 1493 1494
    // Grouped orders
    if (Object.keys(orders).length > 1) {
        $('#partner_name').html(Object.keys(orders).length + " commandes");
1495

1496 1497
        // Display order data for each order
        var msg = "";
1498

1499 1500 1501
        for (display_partner_data of partners_display_data) {
            if (msg != "") {
                msg += ", ";
1502
            }
1503
            msg += display_partner_data;
Administrator committed
1504
        }
1505 1506 1507 1508
        $('#container_multiple_partners').append('<h6> ' + msg + '</h6>');
    } else {
        $('#partner_name').html(orders[Object.keys(orders)[0]].partner);
    }
1509

1510 1511 1512 1513 1514
    /* 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');
1515

1516 1517
        check_icon.className = 'far fa-check-circle';
        document.getElementById('header_step_one_content').appendChild(check_icon);
1518

1519 1520 1521 1522 1523
        // 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";
1524

1525 1526 1527
        // Edition
        document.getElementById('edition_header').innerHTML = "Editer les prix";
        document.getElementById('edition_input_label').innerHTML = "Prix unit.";
1528

1529 1530 1531
        // 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>";
1532

1533 1534 1535 1536
        // 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');
1537

1538 1539 1540 1541
        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";
1542

1543 1544
        document.getElementById('edition_header').innerHTML = "Editer les quantités";
        document.getElementById('edition_input_label').innerHTML = "Qté";
1545

1546 1547
        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>";
1548

1549 1550
        $("#modal_qtiesValidated").load("/reception/reception_qtiesValidated");
    } else {
1551
        // Extra security, shouldn't get in here: reception status not valid
1552
        back();
Administrator committed
1553 1554
    }

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    // 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
1566
    function onAnimationEnd() {
1567
        container_edition.classList.remove('blink_me');
Administrator committed
1568
    }
1569 1570

    // Disable mousewheel on an input number field when in focus
Damien Moulard committed
1571
    $('#edition_input').on('focus', function () {
1572 1573 1574
        $(this).on('wheel.disableScroll', function (e) {
            e.preventDefault();
        });
Administrator committed
1575
    })
Damien Moulard committed
1576
        .on('blur', function () {
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
            $(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
1595
          // Ctrl/cmd+A, Ctrl/cmd+C, Ctrl/cmd+X
1596 1597 1598 1599 1600
          ($.inArray(e.keyCode, [
              65,
              67,
              88
          ]) !== -1 && (e.ctrlKey === true || e.metaKey === true)) ||
Administrator committed
1601 1602 1603
          // home, end, left, right
          (e.keyCode >= 35 && e.keyCode <= 39)) {

1604
            /*
Administrator committed
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
          // 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() + ",");
          }
          */

1618 1619 1620 1621 1622 1623
            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
1624 1625
          //Numeric keyboard
          (!e.shiftKey && (e.keyCode < 96 || e.keyCode > 105))
1626 1627 1628 1629 1630
        ) {
            e.preventDefault();
        }
    });

1631 1632 1633 1634 1635 1636 1637
    $("#edition_input").keypress(function(event) {
        // Force validation when enter pressed in edition
        if (event.keyCode == 13 || event.which == 13) {
            validateEdition();
        }
    });

1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
    // Barcode reader
    $(document).pos();
    $(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;
        } else {
        //manually submitted after correction
            var barcode_input = $('#search_input');

            barcode = barcode_input.val();
1654
        }
1655 1656 1657 1658 1659 1660

        document.getElementById('search_input').value = '';
        $('table.dataTable').DataTable()
            .search('')
            .draw();
        select_product_from_bc(barcode);
1661
    });
1662 1663 1664 1665 1666
}


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

1668
    fingerprint = new Fingerprint({canvas: true}).get();
1669 1670 1671 1672 1673 1674 1675 1676

    // Load barcodes
    get_barcodes();

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

Damien Moulard committed
1677
    // Init couchdb
1678 1679 1680 1681 1682 1683 1684
    dbc = new PouchDB(couchdb_dbname),
    sync = PouchDB.sync(couchdb_dbname, couchdb_server, {
        live: true,
        retry: true,
        auto_compaction: false
    });

Damien Moulard committed
1685
    sync.on('change', function (info) {
1686 1687 1688 1689 1690 1691 1692 1693 1694
        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
1695
    }).on('error', function (err) {
1696 1697 1698
        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
1699
        }
1700
        console.log('erreur sync');
Damien Moulard committed
1701 1702 1703
        console.log(err);
    });

1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
    // 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
1766 1767
    let order_groups = [];

1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
    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;
                }
            }
        }

        // if not in group, add current order to group
        if (group_ids.length == 0) {
            group_ids.push(id);
        }

        let partners_display_data = [];

        dbc.allDocs({
            include_docs: true
        }).then(function (result) {
            // for each order in the group
            for (let order_id of group_ids) {
Damien Moulard committed
1792
                // find order
1793
                let order = result.rows.find(el => el.id == 'order_' + order_id);
Damien Moulard committed
1794

1795 1796 1797 1798
                order = order.doc;

                orders[order_id] = order;

1799
                // Add each order's already updated and validated products to common list
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
                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
                partners_display_data.push(order['partner'] + ' du ' + order['date_order']);
            }

            // 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 || "";

1818
            // Indicate that these orders are used in this navigator
Damien Moulard committed
1819
            update_distant_orders();
1820

1821 1822 1823 1824 1825
            // Fetch orders data
            fetch_data();

            init_dom(partners_display_data);
        })
Damien Moulard committed
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
            .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();
            });
    })
1838 1839
        .catch(function (e) {
            let msg = ('message' in e && 'name' in e) ? e.name + ' : ' + e.message : '';
Damien Moulard committed
1840 1841

            err = {msg, ctx: 'page init - get grouped orders', details: e};
1842 1843 1844 1845 1846 1847 1848
            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
1849
});