products_index.js 8.88 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9 10
/*
 * Récupération d'un produit par scan et affichage des informations du produits.
 * Les informations actuellements récupérées sont :
 *  - Numéro de Rayon
 *  - Stock théorique
 *
 * Les informations actuellement modifiables sont :
 *  - Stock théorique
 */

11 12 13
var products = [],
    products_table = null,
    search_chars = [];
Administrator committed
14 15

function reset_focus() {
16 17
    $('#barcode_selector').val('');
    $('#barcode_selector').focus();
Administrator committed
18 19 20
}

function add_product(product) {
21
    try {
Administrator committed
22
    // Add to list
23 24 25 26 27 28 29 30 31 32 33 34 35 36
        products.push(product);

        if (products_table == null) {
            // create table, show panel
            products_table = $('#products_table').DataTable({
                data: products,
                columns:[
                    {data:"id", title: "id", visible: false},
                    {
                        data:"name",
                        title:"Produit",
                        width: "50%",
                        render: function (data, type, full, meta) {
                            // Add tooltip with barcode over product name
37 38
                            let display_barcode = "Aucun";

39
                            if ('barcode' in full) {
40
                                display_barcode = full.barcode;
41 42 43
                            }

                            return '<div class="tooltip">' + data
Administrator committed
44 45
                + ' <span class="tooltiptext tt_twolines">Code barre : '
                + display_barcode + '</span> </div>';
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
                        }
                    },
                    {data:"shelf_sortorder", title: "Rayon"},
                    {
                        data:"uom_id.1",
                        title: "Unité de vente",
                        className:"dt-body-center",
                        orderable: false
                    },
                    {
                        data:"qty_available",
                        title: "Stock théorique",
                        className:"dt-body-center",
                        render: function (data, type, full, meta) {
                            return '<input type="number" class="stock_edit_input" value="' + data + '">'
              + ' <button type="button" class="stock_edit_button btn--primary"><i class="fas fa-lg fa-check"></i></button>';
                        }
                    }
                ],
                order: [
                    [
                        0,
                        "asc"
                    ]
                ],
                paging: false,
                dom: 'lrtip', // Remove the search input from that table
                language: {url : '/static/js/datatables/french.json'}
            });
Administrator committed
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
            // Listener on 'Update product stock' button
            $('#products_table tbody').on('click', 'button.stock_edit_button', function () {
                var row = products_table.row($(this).parents('tr'));
                var row_data = row.data();

                // Data validation
                qty = $(this).parents('tr')
                    .find('input')
                    .val();
                if (row_data.uom_id[0] == 1) {
                    if (qty/parseInt(qty) != 1) {
                        $.notify(
                            "Ce produit est vendu à l'unité : la valeur doit être un nombre entier !",
                            {
                                globalPosition:"top left",
                                className: "error"
                            }
                        );

                        return 0;
                    }

                    qty = parseInt(qty); // product by unit
                } else {
                    qty = parseFloat(qty);
                }

                // Value is valid
                if (!isNaN(qty)) {
                    row_data.qty = $(this).parents('tr')
                        .find('input')
                        .val();

                    if (row_data.qty != row_data.qty_available) {
                        update_product_stock(row_data);
                    } else {
                        $.notify(
                            "Valeur inchangée.",
                            {
                                globalPosition:"top left",
                                className: "info"
                            }
                        );
                    }
                } else {
                    $.notify(
                        "Valeur invalide.",
                        {
                            globalPosition:"top left",
                            className: "error"
                        }
                    );
                }
            });
Administrator committed
130 131

        } else {
132 133 134
            // Add row to table
            var rowNode = products_table.row.add(product).draw(false)
                .node();
135 136 137
            let onAnimationEnd = function() {
                rowNode.classList.remove('blink_me');
            };
138 139 140 141 142

            // Handle blinking effect for newly added row
            $(rowNode).addClass('blink_me');
            rowNode.addEventListener('animationend', onAnimationEnd);
            rowNode.addEventListener('webkitAnimationEnd', onAnimationEnd);
Administrator committed
143
        }
144 145 146 147
    } catch (e) {
        err = {msg: e.name + ' : ' + e.message, ctx: 'add_product'};
        console.error(err);
        report_JS_error(err, 'produits');
Administrator committed
148 149 150 151
    }
}

function update_product_stock(p_data) {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    openModal();
    $.ajax({
        type: "POST",
        url: "/products/update_product_stock",
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(p_data),
        success: function(data) {
            p_data.qty_available = p_data.qty;
            delete p_data.qty;

            closeModal();
            $.notify(
                "Stock mis à jour !",
                {
                    globalPosition:"top left",
                    className: "success"
                }
            );

            reset_focus();
        },
        error: function(data) {
            // server error
            err = {msg: "erreur serveur lors de la maj du stock", ctx: 'update_product_stock'};
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }

            console.error(err);
            report_JS_error(err, 'produits');

            closeModal();
            reset_focus();
Administrator committed
187
        }
188
    });
Administrator committed
189 190 191 192
}

// Fetch a product when barcode is read
function fetch_product_from_bc(barcode) {
193 194
    if (barcode == '') {
        reset_focus();
Administrator committed
195

196
        return 0;
Administrator committed
197
    }
198 199 200 201 202 203 204 205 206 207 208 209 210 211

    for (p of products) {
        if (p.barcode == barcode) {
            $.notify(
                "Produit déjà récupéré !",
                {
                    globalPosition:"top left",
                    className: "info"
                }
            );

            reset_focus();

            return 0;
Administrator committed
212 213
        }
    }
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

    $.ajax({
        url: "/products/get_product_data?barcode=" + barcode,
        success: function(data) {
            reset_focus();

            if (data.product.active == false) {
                alert('Ce produit est archivé !');

                return 0;
            }

            add_product(data.product);
        },
        error: function(data) {
            if (data.status == 404) {
                // Product not found (shouldn't rise)
                $.notify(
                    "Aucun produit trouvé avec ce code barre !",
                    {
                        globalPosition:"top left",
                        className: "error"
                    }
                );
                reset_focus();
            } else {
                // server error
                err = {msg: "erreur serveur lors de la récupération du produit", ctx: 'fetch_product_from_bc'};
                if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                    err.msg += ' : ' + data.responseJSON.error;
                }
                console.error(err);
                report_JS_error(err, 'produits');
                reset_focus();
            }
        }
    });
Administrator committed
251 252 253
}

$(document).ready(function() {
254
    $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
Administrator committed
255

256
    reset_focus();
Administrator committed
257

258 259 260 261
    $('#button_barcode_selector').on('click', function () {
        bc = $('#barcode_selector').val();
        fetch_product_from_bc(bc);
    });
Administrator committed
262

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    // Barcode reader: listen for 13 digits read in a very short time
    $('#search_input').keypress(function(e) {
        if (e.which >= 48 && e.which <= 57) {
            search_chars.push(String.fromCharCode(e.which));
        }
        if (search_chars.length >= 13) {
            var barcode = search_chars.join("");

            if (!isNaN(barcode)) {
                search_chars = [];
                setTimeout(function() {
                    fetch_product_from_bc(barcode);
                }, 300);
            }
        }
    });
Administrator committed
279
});