shelfs_admin.js 20.6 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9
var main_content = $('#main-content'),
    main_table_wrap = $('#main-table-wrap').html(),
    shelfs_table = null,
    create_form = $('#create_form'),
    shelf_id_input = create_form.find('input[name="shelf_id"]'),
    shelf_sort_order = create_form.find('input[name="sort_order"]'),
    shelf_name = create_form.find('input[name="name"]'),
    description = create_form.find('textarea[name="description"]'),
    eye = '<i class="fas fa-eye"></i>',
10 11
    delete_icon = '<i class="fas fa-trash p_action_icon"></i>',
    print_icon = '<i class="fas fa-print p_action_icon"></i>',
Administrator committed
12 13 14 15
    add_icon = '<i class="fas fa-plus-circle"></i>',
    edit_icon = '<i class="fas fa-edit"></i>',
    download_icon = '<i class="fas fa-download"></i>',
    destroy_shelf_msg = $('#destroy-shelf-msg'),
16 17
    adding_pdts_tpl = $('#adding-products').clone()
        .removeAttr('id'),
Administrator committed
18
    active_phase = 'main',
19
    add_to_shelf_product_ids = [],
20
    barcodes = null;
Administrator committed
21 22 23


var deleteShelf = function() {
24
    var clicked = $(this);
Administrator committed
25 26

    if (is_time_to('delete_shelf', 15000)) { // prevent double click or browser hic up bug
27 28 29 30
        var data = rowGetData(clicked);
        var msg = destroy_shelf_msg.clone();

        msg.find('span.shelf').text(data.name);
Administrator committed
31
        openModal(
32 33
            msg.html(),
            function() {
Administrator committed
34 35
                // Confirm button callback
                post_form(
36 37 38 39 40 41 42 43 44
                    '/shelfs/admin/delete',
                    {id: data.id},
                    function(err, result) {
                        if (!err) {
                            if (typeof result.res !== "undefined" && result.res == true) {
                                shelfs_table.row(clicked.parents('tr')).remove()
                                    .draw();

                                alert("Enregistrement détruit");
Administrator committed
45
                            } else {
46
                                console.log(result);
Administrator committed
47
                            }
48 49 50 51 52 53 54 55 56

                        } else {
                            console.log(err);
                        }
                    }
                );
            },
            'Détruire'
        );
Administrator committed
57
    }
58
};
Administrator committed
59 60 61 62 63

var create = function() {
    if (is_time_to('create_shelf', 5000)) { // prevent double click or browser hic up bug
        var shelf_name = modal.find('input[name="name"]'),
            sort_order = modal.find('input[name="sort_order"]'),
64 65
            description = modal.find('textarea[name="description"]');

Administrator committed
66
        if (shelf_name.val().length == 0 && sort_order.val().length > 0)
67
            shelf_name.val(sort_order.val());
Administrator committed
68
        if (shelf_name.val().length > 0 && sort_order.val().length > 0) {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
            $('.mconfirm .btns').hide();
            box_load.show();
            post_form(
                '/shelfs/admin/create',
                {name: shelf_name.val(), description: description.val(), sort_order: sort_order.val()},
                function(err, rData) {
                    if (typeof(rData.res.id) !== "undefined") {
                        rData.res.p_nb = 0;
                        if (shelfs_table)
                            shelfs_table.row.add(rData.res).draw();
                        else init_and_fill_selfs_list(); // first shelf
                        closeModal();
                    } else {
                        msg = rData.res.error;
                        if (msg.indexOf("Num must be unique !") > -1) {
                            msg = "Ce numéro de rayon est déjà utilisé !";
Administrator committed
85
                        }
86 87 88 89 90
                        alert(msg);
                    }
                    $('.mconfirm .btns').show();
                    box_load.hide();
                }
Administrator committed
91

92
            );
Administrator committed
93
        } else {
94
            alert("Champs obligatoires non remplis");
Administrator committed
95 96
        }
    }
97
};
Administrator committed
98 99

var open_create_form = function() {
100 101 102 103
    shelf_sort_order.attr('value', '');
    shelf_name.attr('value', '');
    description.text('');
    box_load.hide();
Administrator committed
104

105 106
    openModal(create_form.html(), create, 'Confirmer', false);
};
Administrator committed
107 108 109


var update_shelf = function() {
110 111 112 113 114
    if (is_time_to('update_shelf', 5000)) { // prevent double click or browser hic up bug
        var shelf_id = modal.find('input[name="shelf_id"]'),
            shelf_name = modal.find('input[name="name"]'),
            sort_order = modal.find('input[name="sort_order"]'),
            description = modal.find('textarea[name="description"]');
Administrator committed
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        if (shelf_name.val().length == 0 && sort_order.val().length > 0)
            shelf_name.val(sort_order.val());
        if (shelf_name.val().length > 0 && sort_order.val().length > 0) {
            $('.mconfirm .btns').hide();
            box_load.show();

            post_form(
                '/shelfs/admin/update',
                {
                    id: shelf_id.val(),
                    name: shelf_name.val(),
                    description: description.val(),
                    sort_order: sort_order.val()
                },
                function(err, rData) {
                    if (typeof(rData.res.id) !== "undefined") {
                        shelfs_table.rows().every(function () {
                            var data = this.data();

                            if (data.id == rData.res.id) {
                                rData.res.p_nb = data.p_nb;
                                this.data(rData.res).draw();
                            }
139 140

                            return 1;
141 142 143 144 145 146 147 148 149 150 151 152 153
                        });
                        closeModal();
                    } else alert(rData.res.error);

                    $('.mconfirm .btns').show();
                    box_load.hide();
                }
            );
        } else {
            alert("Champs obligatoires non remplis");
        }
    }
};
Administrator committed
154 155 156

// Set update form in modal
var open_update_form = function() {
157
    var clicked = $(this);
Administrator committed
158

159
    var shelf_data = rowGetData(clicked);
Administrator committed
160

161 162 163 164 165
    shelf_id_input.attr('value', shelf_data.id);
    shelf_sort_order.attr('value', shelf_data.sort_order);
    shelf_name.attr('value', shelf_data.name);
    description.text(shelf_data.description);
    box_load.hide();
Administrator committed
166

167 168
    openModal(create_form.html(), update_shelf, 'Mettre à jour', false);
};
Administrator committed
169 170

var downloadInventoryReport = function() {
171 172
    if (is_time_to('download_inv_report', 3000)) { // prevent double click or browser hic up bug
        var clicked = $(this);
Administrator committed
173

174
        var shelf_data = rowGetData(clicked);
Administrator committed
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
        if (shelf_data['last_inventory_id'] != 0) {
            $.ajax({
                type: "GET",
                url: "/shelfs/"+ shelf_data['id'] +"/last_inventory_report",
                xhrFields: {
                    responseType: 'blob'
                },
                success: function (data, textStatus, request) {
                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(data);

                    a.href = url;
                    // Assuming headers are correctly set :
                    // -> Content-Disposition : attachment; filename="xxx"
                    a.download = request.getResponseHeader('Content-Disposition').split("\"")[1];
                    document.body.append(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                },
                error: function(data) {
                    if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                        console.log(data.responseJSON.error);
                    }
                    alert('Le fichier n\'a pas pu être récupéré, réessayez plus tard ou bien allez le chercher dans l\'inventaire Odoo.');
                }
            });
Administrator committed
203 204
        }
    }
205
};
Administrator committed
206 207 208

// TODO put datatable common methods such as following in a file useable for all modules
var rowGetData = function(clicked) {
209
    var row = shelfs_table.row(clicked.parents('tr'));
Administrator committed
210 211


212 213 214
    return row.data();
};

215
function coop_init_datatable(params, data, domsel, cols) {
216 217 218 219 220 221
    var buttons = [];
    var columns = [];


    $.each(cols, function(i, e) {
        columns.push(e);
Administrator committed
222 223 224
    });

    columns.push({
225 226 227 228 229 230 231
        data: null,
        defaultContent: add_icon,
        title: "Ajout produits",
        className: 'products',
        orderable: false,
        targets:   0
    });
Administrator committed
232 233

    columns.push({
234 235 236 237 238 239 240
        data: null,
        defaultContent: edit_icon,
        title: "Modifier le rayon",
        className: 'action',
        orderable: false,
        targets:   0
    });
Administrator committed
241 242

    columns.push({
243 244 245 246 247 248
        data: null,
        defaultContent: delete_icon,
        orderable: false,
        className: 'action',
        targets:   0
    });
Administrator committed
249 250

    var settings = {
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        dom: '<lf<t>ip><"clear"><B>',
        lengthMenu : [
            [
                50,
                100,
                150,
                200,
                -1
            ],
            [
                50,
                100,
                150,
                200,
                'Tout'
            ]
        ],
        pageLength : 50,
        buttons: buttons,

        columns: columns,
        //select: select ,
        rowId : "id",
        data : data,
        language: {url : '/static/js/datatables/french.json'},
        initComplete: function() {
            /*
Administrator committed
278 279 280
                                if (! coop_is_connected())
                                    $('#main_content input[type="search"]').attr('disabled','disabled')
                                */
281 282 283
        }
    };

Administrator committed
284 285
    if (params) {
        if (params.page) {
286
            settings.displayStart = params.page.start;
Administrator committed
287 288
        }
        if (params.ordering) {
289
            settings.order = params.ordering;
Administrator committed
290 291 292
        }
    }

293
    return main_content.find('table'+domsel).DataTable(settings);
Administrator committed
294 295 296
}
var init_and_fill_selfs_list = function() {
    try {
297 298 299 300 301
        $.ajax({
            url :'/shelfs/all',
            dataType: 'json'
        })
            .done(function(rData) {
Administrator committed
302
                if (rData.res && rData.res.length > 0) {
303 304 305 306 307 308 309 310 311
                    var cols = [
                        {data: 'sort_order', title: "Numéro"},
                        {data: 'name', title: "Nom"},
                        {data: 'description', title: "Description"},
                        {data: 'p_nb', title: "Nb pdts", className: "p_nb"},
                        {
                            data:"last_inventory_id",
                            title:"Rapport dernier inventaire",
                            className: "action",
312
                            render: function (data) {
313 314 315 316 317 318 319 320 321 322
                                if (typeof data != "undefined" && data != 0) {
                                    return download_icon;
                                } else {
                                    return "";
                                }
                            }
                        }

                    ];

Administrator committed
323
                    if (shelfs_table)
324
                        shelfs_table.destroy();
Administrator committed
325 326 327 328
                    shelfs_table = coop_init_datatable(null, rData.res, '.shelfs', cols);
                }
                //console.log(rData.res)

329 330 331
            });
    } catch (e) {
        console.log(e);
Administrator committed
332
    }
333
};
Administrator committed
334
var deleteBarcodeFromList = function () {
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    let clicked = $(this);
    let new_pids_list = [];
    let tr_to_remove = clicked.closest('tr');
    let pid_to_remove = tr_to_remove.data('id');

    $.each(add_to_shelf_product_ids, function(idx, pid) {
        if (pid != pid_to_remove) new_pids_list.push(pid);
    });
    add_to_shelf_product_ids = new_pids_list;
    tr_to_remove.remove();
};
var is_product_in_shelf_adding_queue_list = function(testing_pid) {
    let found = false;

    $.each(add_to_shelf_product_ids, function(idx, pid) {
        if (pid == testing_pid) found = true;
    });
352

353
    return found;
354
};
355

Thibault Grandjean committed
356
var printProduct = function () {
357 358 359 360 361 362
    let clicked = $(this);
    let tr_to_print = clicked.closest('tr');
    let barcode = tr_to_print.data('bc');

    openModal();
    try {
Thibault Grandjean committed
363
        $.ajax({
364 365
            url: '/products/get_product_data',
            data: {'barcode': barcode}
Thibault Grandjean committed
366
        })
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
            .done(function(res) {
                var product = res.product;
                var product_tmpl_id = product.product_tmpl_id[0];

                $.ajax({
                    url: '/products/label_print/' + product_tmpl_id
                })
                    .done(function(res_print) {
                        closeModal();
                        if ("error" in res_print.res) {
                            console.log(res_print.res);
                            alert('Une erreur est survenue...');
                        } else {
                            alert('Impression lancée');
                        }
                    });
            });
    } catch (e) {
        closeModal();
        alert('Une erreur est survenue...');
    }
Thibault Grandjean committed
388 389 390

};

Administrator committed
391
var addProductToList = async function(barcode) {
392
    if (barcodes == null) barcodes = await init_barcodes(); // May appens (after inactivity?)
Administrator committed
393 394 395 396
    //Get Odoo corresponding barcode
    //(May be different due to weight encoded barcode)
    //It could also be a wrong reading one

397
    odoo_product = barcodes.get_corresponding_odoo_product(barcode);
Félicie committed
398 399 400
    if (odoo_product === null) {
        alert(barcode + " : ce code-barre est inconnu, merci d'apporter le produit à un salarié.");
    } else {
401 402
        if (is_product_in_shelf_adding_queue_list(odoo_product.data[barcodes.keys.id])) {
            alert("Produit déjà présent dans la liste.");
403
        } else {
404
            add_to_shelf_product_ids.push(odoo_product.data[4]);
Félicie committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
            var pdt_line = $('<tr>').attr('data-id', odoo_product.data[barcodes.keys.id])
                .attr('data-bc', odoo_product.barcode)
                .addClass('obc');

            $('<td>').text(barcode)
                .appendTo(pdt_line);
            $('<td>').text(odoo_product.barcode)
                .appendTo(pdt_line);
            $('<td>').text(odoo_product.data[barcodes.keys.name])
                .appendTo(pdt_line);
            $('<td>').html(odoo_product.data[barcodes.keys.list_price] + " €")
                .appendTo(pdt_line);
            $('<td>').html(delete_icon + " " + print_icon)
                .appendTo(pdt_line);
            adding_pdts_tpl.find('#added_products tbody').append(pdt_line);
420
            main_content.find('.add-products').css('display', 'block');
421
        }
Administrator committed
422
    }
423
};
Administrator committed
424 425

var addProducts = async function() {
426 427
    var clicked = $(this);
    var data = rowGetData(clicked);
Administrator committed
428

429
    if (barcodes == null) barcodes = await init_barcodes();
430
    add_to_shelf_product_ids = [];
431 432 433
    adding_pdts_tpl.find('.shelf').text(data.name + ' (num = ' + data.sort_order+')')
        .attr('data-shelfid', data.id);
    adding_pdts_tpl.find('#added_products tbody').empty();
Administrator committed
434

435 436
    main_content.html(adding_pdts_tpl);
    active_phase = "adding_products";
Félicie committed
437
    main_content.find('.add-products').css('display', 'none');
438 439 440
    if (admin_ids.find(id => id == getCookie("uid"))) $('.add-search').show();

};
Administrator committed
441 442

var recordProductsAddedShelf = function() {
443 444
    var to_add = adding_pdts_tpl.find('tr.obc');

Administrator committed
445
    if (to_add.length > 0) {
446 447 448 449 450 451
        var barcodes = [];
        var id = main_content.find('.shelf').data('shelfid');

        to_add.each(function(i, e) {
            barcodes.push($(e).data('bc'));
        });
452

Administrator committed
453
        if (is_time_to('add_pdts_to_shelf', 5000)) { // prevent double click or browser hic up bug
454 455
            openModal(); // loading on

456 457 458 459
            post_form(
                '/shelfs/admin/add_products',
                {bc: JSON.stringify(barcodes), shelf_id: id},
                function(err, rData) {
460 461
                    let msg = 'Echec';

462
                    if (typeof rData.res.added != "undefined") {
463
                        msg = "Ajout des produits réussi.";
464 465 466 467 468 469 470

                        if (typeof rData.res.missing != "undefined") {
                            msg += "\nSauf pour :";
                            rData.res.missing.forEach(function(bc) {
                                msg += "\n" + bc;
                            });
                        }
471 472
                        closeModal();

473 474 475 476 477 478 479 480
                        alert(msg);
                        backToMain();
                    } else {
                        if (typeof rData.res.error != "undefined")
                            msg = rData.res.error;
                        else if (typeof rData.res.msg != "undefined")
                            msg = rData.res.msg;
                        alert(msg);
481 482
                        main_content.find('.add-products').show();
                        closeModal();
483
                    }
Administrator committed
484

485 486
                }
            );
Administrator committed
487 488 489

        }
    }
490
};
Administrator committed
491 492

var showProductsList = function() {
493 494 495
    var clicked = $(this);
    var data = rowGetData(clicked);

Administrator committed
496 497 498
    if (is_time_to('add_pdts_to_shelf', 5000)) { // prevent double click or browser hic up bug

        try {
499 500 501 502 503
            $.ajax({
                url :'/shelfs/' + data.id + '/products',
                dataType: 'json'
            })
                .done(function(rData) {
Administrator committed
504
                    if (typeof rData.res.data != "undefined" && rData.res.data.length > 0) {
505 506 507 508 509 510 511 512 513 514 515 516 517 518
                        var table = $('<table>').attr('border', '1');

                        $.each(rData.res.data, function(i, pdt) {
                            var tr = $('<tr>');
                            var td1 = $('<td>').css('width', '100px')
                                .text(pdt.barcode);
                            var td2 = $('<td>').css({'text-align':'left', 'padding-left':'10px'})
                                .text(pdt.name);

                            tr.append(td1);
                            tr.append(td2);
                            table.append(tr);
                        });
                        displayMsg(table.html());
Administrator committed
519 520
                    }

521 522 523
                });
        } catch (e) {
            console.log(e);
Administrator committed
524 525 526
        }

    }
527
};
Administrator committed
528 529

var addSearchDisplay = function(action) {
530 531 532 533
    var isw = $('.input-search-wrapper');
    var open = $('.add-search .fa-eye');
    var close = $('.add-search .fa-eye-slash');

Administrator committed
534
    if (action == 'show') {
535 536 537
        isw.show();
        open.hide();
        close.show();
Administrator committed
538
    } else {
539 540 541
        isw.hide();
        open.show();
        close.hide();
Administrator committed
542
    }
543
};
Administrator committed
544 545
var processAddSearchInput = function() {
    //Basic process for now : append text as barcode to list
546 547
    addProductToList($('.input-search-wrapper input[name="kw"]').val());
};
Administrator committed
548 549

var backToMain = function () {
550 551 552 553 554
    active_phase = 'main';
    main_content.html(main_table_wrap);
    init_and_fill_selfs_list();
};

Administrator committed
555
$(document).ready(function() {
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
    if (coop_is_connected()) {
        $('#content_wrapper').show();
        $('#need_connect').hide();
        main_content.html(main_table_wrap);
        init_and_fill_selfs_list();
        /* Make search accent insensitive */

        $(document).on('keyup', '#main_content input[type="search"]', function() {
            shelfs_table
                .search(jQuery.fn.DataTable.ext.type.search.string(this.value))
                .draw();
        });

        $(document).on('click', 'button.create', open_create_form);
        $(document).on('click', '.shelfs .fa-edit', open_update_form);
        $(document).on('click', '.shelfs .fa-trash', deleteShelf);
        $(document).on('click', '.shelfs .fa-download', downloadInventoryReport);
573
        $(document).on('click', '.obc .fa-trash', deleteBarcodeFromList);
Thibault Grandjean committed
574
        $(document).on('click', '.obc .fa-print', printProduct);
575
        $(document).on('click', 'td.products .fa-plus-circle', addProducts);
Félicie committed
576
        $(document).on('click', '#main-content .add-products', recordProductsAddedShelf);
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
        $(document).on('click', 'td.p_nb', showProductsList);
        try {
            if (admin_ids.find(id => id == getCookie("uid"))) {
                $(document).on('click', '.add-search .fa-eye', function() {
                    addSearchDisplay('show');
                });
                $(document).on('click', '.add-search .fa-eye-slash', function() {
                    addSearchDisplay('hide');
                });
                $(document).on('click', '.input-search-wrapper button', processAddSearchInput);
            }
        } catch (e) {
            console.log(e);
        }

        $(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);
                //console.log(new Date().getTime() + ' ' + barcode)
            } else if (barcode.length == 12 && barcode.indexOf('0') !== 0) {
Administrator committed
601
            // User may use a scanner which remove leading 0
602
                barcode = '0' + barcode;
603 604 605
            } else if (barcode.length >= 8) {
                // For EAN8
                barcode = barcode.substring(barcode.length-8);
606
            }
Administrator committed
607 608


609 610 611
            if (active_phase == "adding_products") {
                addProductToList(barcode);
            }
Administrator committed
612

613
        });
Administrator committed
614

615 616
    }
});