inventory.js 28.7 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9 10 11 12
var admin_list_menu = $('#list_inventories');
var title = $('.header h1');
var main_content = $('#main_content');
var create_tpl = $('#admin_create_template');
var list_tpl = $('#admin_list_template');
var inventory_tpl = $('#inventory_filling');
var create_pdt_list_table = null;
var inventories_table = null;
var inventory_table = null;
var active_table = null;
var current_inventory = {_id: null, _rev: null};
var inventory_update_retries = 0;
13
var conflicts = [];
Administrator committed
14
var online = true;
15
var first_db_display = null;
Administrator committed
16 17 18
var focus_cell_value = null;

sync.on('change', function (info) {
19
    // handle change
Administrator committed
20

21 22 23 24 25
    var refresh_products_inventory_list = false;
    var datatable_state = {};
    var incoming_products = [];

    $.each(info.change.docs, function(i, e) {
Administrator committed
26
        if (e._id == current_inventory._id) {
27
            refresh_products_inventory_list = true;
Administrator committed
28
            if (info.direction == "pull") {
29
                $.each(e.products, function(i, e) {
Administrator committed
30
                    if (typeof(e.shelf_qty) != "undefined")
31 32
                        incoming_products.push(e);
                });
Administrator committed
33 34 35 36
            }
        }
    });
    if (active_table) {
37 38
        var order = active_table.order();

Administrator committed
39
        if (typeof (order[0][0]) != "undefined") {
40 41 42 43 44
            datatable_state.page = active_table.page.info();
            datatable_state.ordering = [
                order[0][0],
                order[0][1]
            ];
Administrator committed
45 46
        }
    }
47 48 49 50
    if (info.direction == "push") {
        if (refresh_products_inventory_list === true)
            display_inventory_product_list(current_inventory._id, datatable_state);
    } else if (info.direction == "pull") {
Administrator committed
51 52 53
        try {
            if (refresh_products_inventory_list === true) {

54 55
                msg = 'Changements externes ';
                msg += ' <button type="button" name="global_to_local_sync" class="btn--success">Recevoir</button>';
Administrator committed
56
                // Looking for conflicts
57 58 59
                conflicts = [];
                $.each(get_current_product_table_local_modif(), function(i, e) {
                    $.each(incoming_products, function(j, p) {
Administrator committed
60
                        if (e._id == p._id)
61 62
                            conflicts.push(p);

Administrator committed
63 64 65 66
                    });
                });
                if (conflicts.length > 0) {
                    // Les valeurs de l'import et des saisies locales sont sommées
67 68 69 70 71
                    var local_modifications = getLocalModifications();
                    var current_inv_modif = local_modifications[current_inventory._id];

                    $.each(conflicts, function(i, e) {
                        $.each(current_inv_modif, function(j, p) {
Administrator committed
72
                            if (p.id == e.id) {
73 74 75
                                var local_shelf_qty = local_stock_qty = imported_shelf_qty = imported_stock_qty = 0;
                                var empty_shelf = empty_stock = true;

Administrator committed
76
                                if (current_inv_modif[j]['shelf_qty'].length > 0) {
77 78
                                    local_shelf_qty = parseFloat(current_inv_modif[j]['shelf_qty']);
                                    empty_shelf = false;
Administrator committed
79 80
                                }

81 82 83 84

                                if (current_inv_modif[j]['stock_qty'].length > 0) {
                                    local_stock_qty = parseFloat(current_inv_modif[j]['stock_qty']);
                                    empty_stock = false;
Administrator committed
85 86
                                }

87 88 89 90

                                if (e.shelf_qty.length > 0) {
                                    imported_shelf_qty = parseFloat(e.shelf_qty);
                                    empty_shelf = false;
Administrator committed
91 92
                                }

93 94 95 96

                                if (e.stock_qty.length > 0) {
                                    imported_stock_qty = parseFloat(e.stock_qty);
                                    empty_stock = false;
Administrator committed
97 98
                                }

99 100 101 102 103

                                current_inv_modif[j]['shelf_qty'] = local_shelf_qty + imported_shelf_qty;
                                current_inv_modif[j]['stock_qty'] = local_stock_qty + imported_stock_qty;
                                current_inv_modif[j]['delta'] =
                                current_inv_modif[j]['qty'] - (current_inv_modif[j]['shelf_qty'] + current_inv_modif[j]['stock_qty']);
Administrator committed
104 105

                                if (empty_shelf == false) {
106
                                    current_inv_modif[j]['shelf_qty'] = current_inv_modif[j]['shelf_qty'].toFixed(2);
Administrator committed
107
                                } else {
108
                                    current_inv_modif[j]['shelf_qty'] = '';
Administrator committed
109 110
                                }
                                if (empty_stock == false) {
111
                                    current_inv_modif[j]['stock_qty'] = current_inv_modif[j]['stock_qty'].toFixed(2);
Administrator committed
112
                                } else {
113
                                    current_inv_modif[j]['stock_qty'] = '';
Administrator committed
114 115
                                }

116
                                current_inv_modif[j]['delta'] = current_inv_modif[j]['delta'].toFixed(2);
Administrator committed
117 118 119

                            }
                        });
120 121 122 123 124 125

                    });

                    local_modifications[current_inventory._id] = current_inv_modif;
                    localStorage.setItem("inventories_modifications", JSON.stringify(local_modifications));

Administrator committed
126
                }
127
                set_data_info_msg(msg, 'global');
Administrator committed
128 129 130 131 132
            } else {
                // Something else than inventory product list shown or first loading on this browser

            }
        } catch (e) {
133
            console.log(e);
Administrator committed
134 135 136 137 138 139 140 141 142 143 144 145
        }

    }


}).on('paused', function (err) {
    // replication paused (e.g. replication up to date, user went offline)
    if (err) {
        online = false;
    }


146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
})
    .on('active', function () {
    // replicate resumed (e.g. new changes replicating, user went back online)
        online = true;

    })
    .on('denied', function (err) {
    // a document failed to replicate (e.g. due to permissions)
    })
    .on('complete', function (info) {
    // handle complete
    //never triggered with live = true (only if replication is cancelled)

    })
    .on('error', function (err) {
    // handle error
        console.log('erreur sync');
        console.log(err);
    });
Administrator committed
165 166 167 168



function getLocalModifications() {
169 170 171
    local_modifications = localStorage.getItem("inventories_modifications") || '{}';

    return JSON.parse(local_modifications);
Administrator committed
172 173 174
}

function get_jstree_json(data) {
175 176 177 178 179
    var json = [];

    $.each(data, function(i, e) {
        var node = {id: 'cat_'+e.id, text: e.name};

Administrator committed
180
        if (typeof (e.children) != "undefined")
181
            node.children = get_jstree_json(e.children);
Administrator committed
182 183
        json.push(node);
    });
184 185

    return json;
Administrator committed
186 187 188 189
}

async function init_and_fill_jstree(data) {
    jstree_div = main_content.find('.jstree');
190 191
    var list = await get_jstree_json(data);

Administrator committed
192
    jstree_div.jstree({
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        "plugins" : [
            "wholerow",
            "checkbox"
        ],
        "core" : {
            "data" : [
                {
                    'id': 'cat_0',
                    'text': 'Ensemble',
                    'state' : {"opened" : true},
                    'children': list
                }
            ]
        }
    });

Administrator committed
209 210 211
}

function print_shelf_labels() {
212 213
    products = [];
    create_pdt_list_table.rows().every(function (rowIdx, tableLoop, rowLoop) {
Administrator committed
214
        var data = this.data();
215 216 217 218 219

        products.push({product_tmpl_id:data.product_tmpl_id});
    });
    products_shelf_label_print(products, function() {
        console.log('Appel terminé');
Administrator committed
220 221 222
    });
}

223 224 225
function coop_init_datatable(params, data, domsel, cols, action_btn) {
    var buttons = [];
    var columns = [];
Administrator committed
226
    var select = {
227 228 229 230 231
        style:    'os',
        selector: 'td:first-child'

    };

Administrator committed
232 233
    if (action_btn) {
        buttons = [
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
            {
                extend: 'selected',
                text: 'Supprimer les sélectionnés',
                action: function (e, dt, button, config) {
                    dt.rows({selected: true}).remove()
                        .draw();

                }
            },
            {
                extend: 'selected',
                text: 'Ne garder que les sélectionnés',
                action: function (e, dt, button, config) {
                    dt.rows({selected: false}).remove()
                        .draw();

                }
            }
        ];

        buttons.push(action_btn);
Administrator committed
255
        buttons.push({
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
            text: 'Imprimer Etiquettes Rayons',
            action : function(e, dt) {
                if (dt.rows().indexes().length > 0)
                    openModal("Lancer l'impression ?", print_shelf_labels, 'Imprimer');
                else
                    alert("Impossible, il n'y a aucun produit !");

            }
        });
        columns = [
            {
                data: null,
                defaultContent: '',
                orderable: false,
                className: 'select-checkbox',
                targets:   0
            }
        ];
        select.style = 'multi';

Administrator committed
276 277
    }
    if (coop_is_connected()) {
278
        buttons.push('csvHtml5');
Administrator committed
279
    }
280 281 282

    $.each(cols, function(i, e) {
        columns.push(e);
Administrator committed
283 284
    });
    var settings = {
285 286 287 288 289 290 291 292 293 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 320
        dom: '<lf<t>ip><"clear"><B>',
        lengthMenu : [
            [
                10,
                25,
                50,
                100,
                -1
            ],
            [
                10,
                25,
                50,
                100,
                'Tout'
            ]
        ],
        buttons: buttons,

        columns: columns,
        select: select,
        rowId : "id",
        data : data,
        language: {url : '/static/js/datatables/french.json'},
        createdRow: function(row, rdata, index) {
            if (coop_is_weighted_product(rdata) === true) {
                $(row).addClass("to_weight");
            }
        },
        initComplete: function() {
            if (! coop_is_connected())
                $('#main_content input[type="search"]').attr('disabled', 'disabled');

        }
    };

Administrator committed
321 322
    if (params) {
        if (params.page) {
323
            settings.displayStart = params.page.start;
Administrator committed
324 325
        }
        if (params.ordering) {
326
            settings.order = params.ordering;
Administrator committed
327 328 329 330
        }
    }
    active_table = main_content.find('table'+domsel).DataTable(settings);

331
    return active_table;
Administrator committed
332 333 334 335 336 337 338 339 340 341
}

function update_products_qties_for_global(doc) {
    dbc.put(doc, function(err, result) {
        if (err) {
            console.log(err);
            //get new rev and submit again
            if (inventory_update_retries < 5) {
                dbc.get(current_inventory._id, function(err, rdoc) {
                    if (err) {
342
                        console.log(err);
Administrator committed
343 344
                        // What can be done here ?
                    } else {
345
                        doc._rev = rdoc._rev;
Administrator committed
346
                        inventory_update_retries++;
347 348 349
                        setTimeout(function() {
                            update_products_qties_for_global(doc);
                        }, coop_get_random(10, 700));
Administrator committed
350 351 352
                    }
                });
            } else {
353
                alert('Problème avec CouchDB !');
Administrator committed
354 355 356
            }
        } else {
            inventory_update_retries = 0;
357 358 359
            reset_current_product_table_local_modif();
            set_data_info_msg('Mise à jour effectuée', 'local');
            main_content.find('td').removeClass('highlight');
Administrator committed
360
        }
361
    });
Administrator committed
362 363 364 365 366 367
}

function make_local_to_global_sync() {
    // Get current_inventory._id
    dbc.get(current_inventory._id, function(err, doc) {
        if (err) {
368
            console.log(err);
Administrator committed
369 370

        } else {
371 372 373 374 375
            var modified_products = get_current_product_table_local_modif();
            var retrieved_products = doc.products;
            var i = 0;

            $.each(retrieved_products, function(i, e) {
Administrator committed
376
                if (typeof (modified_products[e.id]) !== "undefined") {
377 378
                    doc.products[i].shelf_qty = modified_products[e.id].shelf_qty;
                    doc.products[i].stock_qty = modified_products[e.id].stock_qty;
Administrator committed
379 380
                }
                i++;
381 382
            });
            update_products_qties_for_global(doc);
Administrator committed
383 384 385 386 387
        }
    });
}

function make_global_to_local_sync() {
388 389
    var datatable_state = {};

Administrator committed
390
    if (active_table) {
391 392
        var order = active_table.order();

Administrator committed
393
        if (typeof (order[0][0]) != "undefined") {
394 395 396 397 398
            datatable_state.page = active_table.page.info();
            datatable_state.ordering = [
                order[0][0],
                order[0][1]
            ];
Administrator committed
399
        }
400

Administrator committed
401
    }
402 403

    display_inventory_product_list(current_inventory._id, datatable_state);
Administrator committed
404 405
}

406 407
function init_and_fill_inventories_list() {

Administrator committed
408
    dbc.allDocs({include_docs: true, descending: true}, function(err, resp) {
409 410 411 412 413 414 415
        if (err) {
            return console.log(err);
        }
        var data = [];
        var is_one_opened = false;

        $.each(resp.rows, function(i, e) {
Administrator committed
416 417 418 419
            if (e.doc.state == 'opened') {
                is_one_opened = true;
            }
        });
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        $.each(resp.rows, function(i, e) {
            var available_actions = '';

            if (e.doc.state == 'draft') {
                if (is_one_opened === false)
                    available_actions = '<button type="button" class="btn--success start">Commencer</button>';
            } else if (e.doc.state == 'opened') {
                available_actions+= '<button type="button" class="btn--primary fill">Remplir</button>';
                available_actions+= '<button type="button" class="btn--success end">Clore</button>';
            } else if (e.doc.state == 'closed') {

                available_actions+= '<button type="button" class="btn--success push">M.A.J stocks Odoo</button>';
            } else if (e.doc.state == 'completed') {
                available_actions = '<button type="button" class="btn--info report">Rapport</button>';
            }
            data.push({id: e.id, name: e.doc.name, pdts_num:e.doc.products.length, state: e.doc.state, action: available_actions});
Administrator committed
436
        });
437 438 439 440 441 442 443 444 445 446 447 448

        if (inventories_table)
            inventories_table.destroy();

        var cols = [
            {data: 'name', title: "Nom"},
            {data: 'pdts_num', title: "Nb articles"},
            {data: 'state', title: "Etat"},
            {data: 'action', title: "Action"}
        ];

        inventories_table = coop_init_datatable(null, data, '.inventories', cols);
Administrator committed
449 450 451 452 453 454 455 456 457 458 459 460 461
    });


}

function update_inventory(obj) {
    dbc.put(obj, function(err, result) {
        if (err) {
            console.log(err);
        } else {
            console.log('Update fait');
            admin_list_menu.click();
        }
462
    });
Administrator committed
463 464 465 466
}
function update_inventory_state(id, newstate) {
    dbc.get(id, function(err, doc) {
        if (err) {
467
            console.log(err);
Administrator committed
468
        } else {
469 470
            doc.state = newstate;
            update_inventory(doc);
Administrator committed
471 472 473 474
        }

    });

475
}
Administrator committed
476

477
function record_inventory() {
Administrator committed
478
    var selected_products= [];
479 480

    create_pdt_list_table.rows().every(function (rowIdx, tableLoop, rowLoop) {
Administrator committed
481
        var data = this.data();
482

Administrator committed
483 484 485 486
        selected_products.push(data);
    });
    var name = $('input[name="inventory_name"]').val();
    var now = new Date();
487

Administrator committed
488
    if (name == '') {
489

Administrator committed
490 491 492 493

        name = getCookie("uid") + '_' + now.toISOString();
    }
    var inventory = {
494 495 496 497 498 499
        _id: now.getTime().toString(),
        name: name,
        products: selected_products,
        state: 'draft'
    };

Administrator committed
500 501
    dbc.put(inventory, function callback(err, result) {
        if (!err) {
502 503 504
            //alert('Enregistrement réussi !');
            admin_list_menu.click();

Administrator committed
505 506 507 508 509 510 511 512 513
        } else {
            alert('Enregistrement impossible !');
            console.log(err);
        }
    });

}

function create_inventory(cats) {
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    post_form(
        'create_inventory',
        {
            'cats': JSON.stringify(cats)
        },
        function(err, result) {
            //console.log(result);
            if (typeof (result.products) != "undefined") {
                main_content.find('.loading').hide();
                main_content.find('.dataTables_wrapper').show();
                data = [];
                var products = result.products;

                for (k in products) {
                    //console.log(products[k])
                    data.push({
                        id: products[k]['id'],
                        name: products[k]['name'],
                        qty:products[k]['qty'],
                        barcode: products[k]['barcode'],
                        product_variant_count: products[k]['product_variant_count'],
                        product_tmpl_id: products[k]['product_tmpl_id'],
                        uom_id: products[k]['uom_id']
                    });
Administrator committed
538
                }
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

                //console.log(data);
                if (create_pdt_list_table)
                    create_pdt_list_table.destroy();

                var action_btn = {
                    text: 'Ouvrir une opération avec ces produits',
                    action : function(e, dt) {
                        if (dt.rows().indexes().length > 0)
                            openModal($('#new_inventory_form_template').html(), record_inventory, 'Enregistrer');
                        else
                            alert("Impossible, il n'y a aucun produit !");

                    }
                };
                var cols = [
                    {data: 'barcode', title: "Code-barre"},
                    {data: 'name', title: "Nom"},
                    {data: 'qty', title: "Qté"},
                    {data: 'product_variant_count', visible: false},
                    {data: 'product_tmpl_id', visible: false},
                    {data: 'uom_id', visible: false}
                ];

                create_pdt_list_table = coop_init_datatable(null, data, '.pdt_liste_for_creation', cols, action_btn);

            }


        }
    );
}
Administrator committed
571 572

function get_current_product_table_local_modif() {
573 574
    current_table_lm = {};
    local_modifications = getLocalModifications();
Administrator committed
575
    if (typeof (local_modifications[current_inventory._id]) !== "undefined") {
576
        current_table_lm = local_modifications[current_inventory._id];
Administrator committed
577
    }
578 579

    return current_table_lm;
Administrator committed
580 581 582
}

function reset_current_product_table_local_modif() {
583 584
    local_modifications = localStorage.getItem("inventories_modifications") || '{}';
    local_modifications = JSON.parse(local_modifications);
Administrator committed
585
    if (typeof (local_modifications[current_inventory._id]) !== "undefined") {
586 587
        delete local_modifications[current_inventory._id];
        localStorage.setItem("inventories_modifications", JSON.stringify(local_modifications));
Administrator committed
588 589 590
    }
}
function set_data_info_msg(msg, type) {
591 592
    $('#main_content .'+ type +'-data-info').html(msg)
        .show();
Administrator committed
593 594 595
}

function highlight_non_sync_qty(pids) {
596 597 598
    main_content.find('td').removeClass('highlight');
    for (i in pids) {
        main_content.find('tr#'+pids[i]).addClass('highlight');
Administrator committed
599 600 601
    }
}
function update_local_data_info_msg() {
602 603 604 605 606
    if (current_inventory._id) {
        local_modifications = get_current_product_table_local_modif();
        var product_ids = Object.keys(local_modifications);
        var not_sync_changes = product_ids.length;

Administrator committed
607
        if (not_sync_changes > 0) {
608 609
            var msg = not_sync_changes + ' produit';

Administrator committed
610
            if (not_sync_changes > 1)
611
                msg += 's';
Administrator committed
612

613 614 615 616
            msg += ' à synchroniser';
            msg += ' <button type="button" name="local_to_global_sync" class="btn--success">Envoyer</button>';
            set_data_info_msg(msg, 'local');
            highlight_non_sync_qty(product_ids);
Administrator committed
617
        }
618

Administrator committed
619 620 621 622 623 624
    }
}

function update_product_inventory_quantities(updatedCell, updatedRow, oldValue) {
    if (updatedCell.data().length > 0) {
        // Update inventory products
625
        local_modifications = getLocalModifications();
Administrator committed
626

627
        var row = updatedRow.data();
Administrator committed
628

629 630
        row.shelf_qty = row.shelf_qty.toString().replace(/,/, '.');
        row.stock_qty = row.stock_qty.toString().replace(/,/, '.');
Administrator committed
631
        if (typeof (local_modifications[current_inventory._id]) == "undefined") {
632 633 634 635 636 637 638 639 640
            local_modifications[current_inventory._id] = {};

        }
        local_modifications[current_inventory._id][row.id] = row;

        localStorage.setItem("inventories_modifications", JSON.stringify(local_modifications));
        q_elts = compute_product_qties_and_delta(row);
        main_content.find('tr#'+row.id+' .delta').text(q_elts[2]);
        update_local_data_info_msg();
Administrator committed
641 642 643 644
    }
}

function compute_product_qties_and_delta(local_p) {
645 646 647 648 649
    delta = '';
    found = 0;
    sh_qty = parseFloat(local_p.shelf_qty);
    st_qty = parseFloat(local_p.stock_qty);

Administrator committed
650
    if (isNaN(sh_qty)) {
651
        sh_qty = '';
Administrator committed
652
    } else {
653
        found = sh_qty;
Administrator committed
654 655
    }
    if (isNaN(st_qty)) {
656
        st_qty = '';
Administrator committed
657
    } else {
658
        found += st_qty;
Administrator committed
659 660
    }

661 662 663 664 665 666 667
    delta = found - parseFloat(local_p.qty);

    return [
        sh_qty,
        st_qty,
        delta.toFixed(2)
    ];
Administrator committed
668 669 670 671
}

function update_odoo_stock(doc_id) {
    openModal(
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
        "Avant de procéder à la mise à jour des stocks,<br/> assurez-vous que tous les postes utilisés pour l'inventaire <b>ont bien synchronisé les données</b> saisies.<br /><img src=\"/static/img/loading-gear-8.gif\" style=\"display:none;\"/>",
        function() {
            modal.find('img').show();
            btn_nok.off('click');
            btn_ok.off('click');
            post_form(
                'update_odoo_stock',
                {
                    doc_id: doc_id
                },
                function(err, result) {
                    if (result.action.missed.length == 0) {
                        update_inventory_state(doc_id, 'completed');
                        init_and_fill_inventories_list();
                    }
                    closeModal();
                }
Administrator committed
689
            );
690 691 692 693
        },
        'Mettre à jour',
        false
    );
Administrator committed
694 695 696 697
}

function display_inventory_product_list(id, params) {
    title.text('Saisie inventaire');
698
    main_content.html(inventory_tpl.html());
Administrator committed
699 700 701

    dbc.get(id, function(err, doc) {
        if (err) {
702
            console.log(err);
Administrator committed
703 704

        } else {
705 706 707 708 709 710 711 712 713 714 715 716 717
            current_inventory._rev = doc._rev;
            current_inventory._id = doc._id;
            var data = [];

            local_modifications = get_current_product_table_local_modif();

            $.each(doc.products, function(i, e) {
                var sh_qty = '';
                var st_qty = '';
                var delta = '';
                var ref_prod = null;
                var recount = '';

Administrator committed
718
                if (typeof (local_modifications[e.id]) !== "undefined") {
719
                    ref_prod = local_modifications[e.id];
Administrator committed
720
                } else if (typeof (e.shelf_qty) !== "undefined") {
721
                    ref_prod = e;
Administrator committed
722 723 724
                }

                if (ref_prod) {
725 726 727 728 729
                    var q_elts = compute_product_qties_and_delta(ref_prod);

                    sh_qty = q_elts[0];
                    st_qty = q_elts[1];
                    delta = q_elts[2];
Administrator committed
730 731
                }

732 733 734
                data.push({id: e.id, barcode: e.barcode, name: e.name, qty: e.qty, shelf_qty: sh_qty, stock_qty: st_qty, delta:delta, recount:recount});
            });

Administrator committed
735 736
            if (inventory_table) {
                inventory_table.MakeCellsEditable("destroy");
737
                inventory_table.destroy();
Administrator committed
738 739
            }

740 741 742 743 744 745 746 747 748 749 750 751
            var cols = [
                {data: 'barcode', title: "Code-barre", className: 'barcode'},
                {data: 'name', title: "Nom", className: 'name'},
                {data: 'qty', title: "Qté"},
                {data: 'shelf_qty', title: "Rayon", className: 'shelf_qty'},
                {data: 'stock_qty', title: "Stock", className: 'stock_qty'},
                {data: 'delta', title: "Delta", className: 'delta'}
            ];
            var editable_cols = [
                3,
                4
            ];
Administrator committed
752 753

            if (coop_is_connected()) {
754
                cols.push({data: 'recount', title: 'Recompter'});
Administrator committed
755
                //editable_cols.push(6)
756 757 758
            }

            inventory_table = coop_init_datatable(params, data, '.inventory', cols);
Administrator committed
759 760 761 762 763 764 765

            inventory_table.MakeCellsEditable({
                inputCss: 'editable-cell',
                columns: editable_cols,
                onUpdate: update_product_inventory_quantities,
                confirmationButton: {listenToKeys: true, confirmCss: 'hidden', cancelCss: 'hidden'}
            });
766 767 768

            update_local_data_info_msg();

Administrator committed
769 770 771
        }

    });
772

Administrator committed
773 774 775 776 777
}



function show_opened_inventory() {
778 779

    dbc.allDocs({include_docs: true, descending: true}, function(err, resp) {
Administrator committed
780
        if (first_db_display == null)
781 782 783 784 785 786 787
            first_db_display = new Date().getTime();
        if (err) {
            return console.log(err);
        }
        var id = null;

        $.each(resp.rows, function(i, e) {
Administrator committed
788
            if (e.doc.state == 'opened') {
789
                id = e.id;
Administrator committed
790 791 792
            }
        });
        if (id) {
793
            display_inventory_product_list(id);
Administrator committed
794 795 796 797
        } else {
            set_data_info_msg('Aucun inventaire en cours', 'local');
        }
    });
798

Administrator committed
799 800 801 802 803 804 805 806 807
}






/* Make search accent insensitive */

808 809 810 811
$(document).on('keyup', '#main_content input[type="search"]', function() {
    active_table
        .search(jQuery.fn.DataTable.ext.type.search.string(this.value))
        .draw();
Administrator committed
812 813 814 815 816 817
});


$('#create_inventory').click(function() {
    $('.header h1').text('Créer (ouvrir) un inventaire');
    main_content.html(create_tpl.html());
818
    $.ajax('get_product_categories').done(function(rData) {
Administrator committed
819
        init_and_fill_jstree(rData);
820 821


Administrator committed
822 823 824 825 826
    });
});

$('#raz_archived').click(function() {
    openModal(
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
        "Le stock des produits archivés sera mis à 0.<br/><img src=\"/static/img/loading-gear-8.gif\" style=\"display:none;\"/>",
        function() {
            modal.find('img').show();
            btn_nok.off('click');
            btn_ok.off('click');
            post_form(
                'raz_archived_stock',
                {},
                function(err, result) {
                    console.log(result);
                    closeModal();
                }
            );
        },
        'Mettre à jour',
        false
Administrator committed
843 844 845 846
    );
});
$('#raz_not_saleable').click(function() {
    openModal(
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
        "Le stock des produits non vendables sera mis à 0.<br/><img src=\"/static/img/loading-gear-8.gif\" style=\"display:none;\"/>",
        function() {
            modal.find('img').show();
            btn_nok.off('click');
            btn_ok.off('click');
            post_form(
                'raz_not_saleable',
                {},
                function(err, result) {
                    console.log(result);
                    closeModal();
                }
            );
        },
        'Mettre à jour',
        false
Administrator committed
863 864 865 866
    );
});


867
$(document).on('click', '#main_content .create_from_cat_selection', function() {
Administrator committed
868
    var selected = main_content.find('.jstree').jstree('get_selected');
869

Administrator committed
870 871 872 873 874 875 876
    if (selected.length > 0) {
        main_content.find('.loading').show();
        main_content.find('.dataTables_wrapper').hide();
        create_inventory(selected);
    }
});

877
$(document).on('click', '#main_content .inventories button', function() {
Administrator committed
878
    var clicked = $(this);
879 880
    var doc_id = clicked.closest('tr').attr('id');

Administrator committed
881
    if (clicked.hasClass('start')) {
882
        update_inventory_state(doc_id, 'opened');
Administrator committed
883 884
    } else if (clicked.hasClass('report')) {
        //
885
        alert('Rapport: fonctionnalité en construction');
Administrator committed
886
    } else if (clicked.hasClass('fill')) {
887
        display_inventory_product_list(doc_id);
Administrator committed
888
    } else if (clicked.hasClass('end')) {
889
        update_inventory_state(doc_id, 'closed');
Administrator committed
890
    } else if (clicked.hasClass('push')) {
891
        update_odoo_stock(doc_id);
Administrator committed
892 893 894
    }
});

895 896
$(document).on('click', '#main_content button[name="local_to_global_sync"]', make_local_to_global_sync);
$(document).on('click', '#main_content button[name="global_to_local_sync"]', make_global_to_local_sync);
Administrator committed
897

898
admin_list_menu.click(function() {
Administrator committed
899 900 901 902 903 904 905
    title.text('Listes des inventaires');
    main_content.html(list_tpl.html());
    init_and_fill_inventories_list();

});

$(document).pos();
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
$(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)


        var focused = $(':focus');

        if (focused.hasClass('editable-cell')) {
            focus_cell_value = focused.val();
            focused.val(focus_cell_value.replace(barcode, ''));
            focused.updateEditableCell(focused.get(0));
        }
        active_table.search(barcode).draw();
        var t_info = active_table.page.info();

        if (t_info.recordsDisplay == 0) {
            // Poids / prix variables ? -> test again with less figures
            barcode = barcode.substring(0, 8);
            active_table.search(barcode).draw();
Administrator committed
929
        }
930 931 932 933 934
    } else {
        console.log(new Date().getTime() + ' -> '+barcode);
    }

});
Administrator committed
935 936 937 938

if (!coop_is_connected()) {
    show_opened_inventory();
}