shop_drafts.js 13.4 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var orders_table = null,
    orders = [],
    main_content = $('#main-content'),
    checkbox = '<input type = "checkbox" />',
    print_icon = '<i class="fas fa-print"></i>',
    eye = '<i class="fas fa-eye"></i>',
    delete_icon = '<i class="fas fa-trash"></i>',
    cart_details = $('#templates .cart-details'),
    cart_destroy_msg = $('#templates .destroy-cart-msg'),
    multiple_carts_destroy_msg = $('#templates .destroy-multiple-carts-msg'),
    multiple_carts_item_destroy = $('#templates .destroy-multiple-carts-item'),
    remove_closing_date_msg = $('#templates .remove-closing-date-msg'),
    internal_get_msg = $('#templates .get-cart-ref'),
    main_msg_area = $('#main-msg-area'),
    waiting_for_display = {'new': [], 'update': [], 'delete': []},
    cart_id = null,
    cart_revisions = {},
    shop_settings = null,
19 20 21
    loading_img = $('#rotating_loader').clone()
        .removeAttr('id')
        .addClass('rotating_loader');
Administrator committed
22 23 24

/** pouchdb listner **/
sync.on('change', function (info) {
25
    // handle change
Administrator committed
26 27
    //console.log(info)
    try {
28
        if (info.direction == "pull") {
Administrator committed
29
        //new order or updated order from another brow
30
            $.each(info.change.docs, function(i, e) {
Administrator committed
31

32 33 34
                updateWaitingForDisplayWithNewArrival(e);
            });
        }
Administrator committed
35
    } catch (err) {
36
        console.log(err);
Administrator committed
37 38 39 40 41 42 43 44
    }
}).on('paused', function (err) {
    // replication paused (e.g. replication up to date, user went offline)
    if (err) {
        online = false;
    }


45 46 47 48
})
    .on('active', function () {
    // replicate resumed (e.g. new changes replicating, user went back online)
        online = true;
Administrator committed
49

50 51 52 53 54 55 56
    })
    .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)
Administrator committed
57

58 59 60 61 62 63
    })
    .on('error', function (err) {
    // handle error
        console.log('erreur sync');
        console.log(err);
    });
Administrator committed
64 65

var putLoadingImgOn = function(target) {
66 67
    target.append(loading_img);
};
Administrator committed
68
var removeLoadingImg = function() {
69 70
    $('.rotating_loader').remove();
};
Administrator committed
71 72

var updateWaitingForDisplayWithNewArrival = function(doc) {
73 74
    var type = 'new';

Administrator committed
75
    if (typeof doc._deleted == "undefined") {
76 77 78 79
        var date = new Date(parseInt(doc.submitted_time*1000, 10));

        doc.total = parseFloat(doc.total).toFixed(2);
        doc.h_submitted_date = format_date_to_sortable_string(date);
Administrator committed
80 81
        // check if it's a new order or an updated one
        if (orders_table) {
82 83 84 85 86 87
            var found = false;

            $.each(orders_table.rows().ids(), function(idx, id) {
                if (id == doc._id) found = true;
            });
            if (found == true) type = 'update';
Administrator committed
88 89
        }
    } else {
90
        type = 'delete';
Administrator committed
91 92 93
    }


94 95
    waiting_for_display[type].push(doc);
    updateArrivalsMsg();
Administrator committed
96

97
};
Administrator committed
98 99
var updateArrivalsMsg = function () {
    for (type in waiting_for_display) {
100 101 102 103
        var target = main_msg_area.find('.' + type + ' span');
        var nb = waiting_for_display[type].length;
        var w = "nouvelle";

Administrator committed
104
        if (type == 'update') {
105
            w = "modifiée";
Administrator committed
106
        } else if (type == "delete") {
107
            w = "supprimée";
Administrator committed
108
        }
109 110 111 112
        if (nb > 1) w += 's';
        var msg = ('00' + nb).slice(-3) + ' ' + w;

        target.text(msg);
Administrator committed
113
    }
114
    main_msg_area.show();
Administrator committed
115

116
};
Administrator committed
117 118

var downloadArrivals = function () {
119
    window.location.reload();
Administrator committed
120

121
};
Administrator committed
122 123 124



125 126 127
function coop_init_datatable(params, data, domsel, cols, action_btn) {
    var buttons = [];
    var columns = [];
Administrator committed
128 129 130


    columns.push({
131 132 133 134 135 136 137 138 139 140
        data: null,
        defaultContent: checkbox,
        orderDataType: "dom-checkbox",
        title: "Sél.",
        className: 'order_selector',
        width: '3%',
        targets:   0
    });
    $.each(cols, function(i, e) {
        columns.push(e);
Administrator committed
141 142 143
    });

    columns.push({
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        data: null,
        defaultContent: eye,
        orderable: false,
        width: "30px",
        className: 'action',
        targets:   0
    });
    columns.push({
        data: null,
        defaultContent: print_icon,
        orderable: false,
        width: "30px",
        className: 'action',
        targets:   0
    });
Administrator committed
159 160

    columns.push({
161 162 163 164 165 166 167
        data: null,
        defaultContent: delete_icon,
        orderable: false,
        width: "30px",
        className: 'action',
        targets:   0
    });
Administrator committed
168 169

    var settings = {
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
        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'}
    };

Administrator committed
197 198
    if (params) {
        if (params.page) {
199
            settings.displayStart = params.page.start;
Administrator committed
200 201
        }
        if (params.ordering) {
202
            settings.order = params.ordering;
Administrator committed
203 204 205
        }
    }

206
    return main_content.find('table'+domsel).DataTable(settings);
Administrator committed
207
}
208
function init_and_fill_order_list() {
Administrator committed
209 210

    dbc.allDocs({include_docs: true, descending: true}, function(err, resp) {
211 212 213 214 215 216
        if (err) {
            return console.log(err);
        }
        var data = [];

        $.each(resp.rows, function(i, e) {
Administrator committed
217
            if (e.doc.state == 'init') {
218 219 220 221 222
                var date = new Date(parseInt(e.doc.init_time*1000, 10));

                e.doc.total = parseFloat(e.doc.total).toFixed(2);
                e.doc.h_init_date = format_date_to_sortable_string(date);
                data.push(e.doc);
Administrator committed
223 224 225
            }
        });
        if (orders_table)
226 227 228 229 230 231 232
            orders_table.destroy();
        var cols = [
            {data: 'h_init_date', title: "Date init"},
            {data: 'partner.display_name', title: "Nom"},
            {data: 'best_date', title: "Livraison"}

        ];
Administrator committed
233 234 235 236 237 238 239 240 241

        orders_table = coop_init_datatable(null, data, '.orders', cols);
    });


}

// Get the selected rows in the table
var getSelectedRows = function() {
242 243 244 245 246 247
    if (orders_table) {
        return orders_table.rows('.selected');
    } else {
        return null;
    }
};
Administrator committed
248 249 250

// Set a row as selected : a row is selected if selection checkbox is checked
var selectRow = function() {
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    var clicked = $(this);
    var cb = clicked.find('input[type="checkbox"]');

    if (cb.is(":checked")) {
        clicked.parent().addClass('selected');
    } else {
        clicked.parent().removeClass('selected');
    }

    // Display batch action selector & button if more than 1 row selected
    var selected = getSelectedRows();

    if (selected[0].length > 1) {
        $('#multiple_actions_container').slideDown('fast');
    } else {
        $('#multiple_actions_container').slideUp('fast');
    }
};
Administrator committed
269 270 271

// Deselect rows from the table
var unselectRows = function(selected_rows) {
272 273 274 275 276 277 278 279
    for (row_id in selected_rows[0]) {
        var row = orders_table.row(row_id);

        $(row.node()).find('input[type="checkbox"]')
            .prop('checked', false);
        row.deselect();
    }
};
Administrator committed
280 281

var removeRows = function(selected_rows) {
282 283
    selected_rows.remove().draw();
};
Administrator committed
284 285

var updateCouchDB = function(data, callback) {
286 287 288 289
    var clicked = data.clicked;

    delete data.clicked;
    data.state_change_ts = format_date_to_sortable_string(new Date());
Administrator committed
290 291 292 293

    dbc.put(data, function(err, result) {
        if (!err) {
            if (result.ok === true) {
294 295 296 297 298 299
                var r = clicked.parents('tr');

                data._rev = result.rev;
                orders_table.row(r).data(data)
                    .draw();
                rowUpdate(r, data);
Administrator committed
300
            }
301
            callback(result);
Administrator committed
302
        } else {
303
            callback(null);
Administrator committed
304 305 306
            console.log(err);
        }
    });
307
};
Administrator committed
308 309 310


var rowGetData = function(clicked) {
311 312 313 314 315
    var row = orders_table.row(clicked.parents('tr'));


    return row.data();
};
Administrator committed
316 317 318 319 320



var printCart = function(cart_id, callback) {
    // Send request & diret download pdf
321 322
    var filename = "Commande_" + cart_id + ".pdf";

Administrator committed
323 324
    $.ajax({
        url: "admin/print_cart",
325
        data: {id : cart_id}
Administrator committed
326 327 328

        //TODO : find a way to test if answer is really a PDF (test with sucess: function(rData){...} -> download.bind doesn't work inside)
    })
329 330 331 332 333 334
        .done(download.bind(true, "pdf", filename))
        .always(function(rData) {
            callback(rData.split("\n").shift()
                .indexOf('%PDF-') == 0); // true returned data is a PDF doc
        });
};
Administrator committed
335 336 337
var showCart = function() {
    var row = orders_table.row($(this).parents('tr'));
    var data = row.data();
338

Administrator committed
339
    if (typeof data === "undefined") {
340
        data = arguments[0];
Administrator committed
341
    }
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    var cart = cart_details.clone();

    cart.find('.member').text(data.partner.display_name);
    var tbody = cart.find('tbody');

    $.each(data.products, function(i, e) {
        var tr = $('<tr>');

        tr.append($('<td>').text(e.name));
        tr.append($('<td>').text(e.qty));
        tr.append($('<td>').text(e.price));
        tbody.append(tr);
    });
    cart.append('<br>');
    cart.append('Info récupération : ' + data.best_date);

    openModal(
        cart.html(),
        function() {
            printCart(data._id, function(res) {
                if (res == false) {
                    //data retrieved was not a PDF
                }
            });
        },
        'Imprimer'
    );
};
Administrator committed
370
var addMemberAndDateToMsg = function (msg, data) {
371 372 373 374 375
    var date = data.h_init_date;

    msg.find('.member').text(data.partner.display_name);
    msg.find('.date').text(date);
};
Administrator committed
376 377

var deleteCart = function() {
378 379 380 381 382
    var clicked = $(this);
    var data = rowGetData(clicked);
    var msg = cart_destroy_msg.clone();

    addMemberAndDateToMsg(msg, data);
Administrator committed
383 384

    if (data.best_date.length > 0)
385
        msg.find('.bdate').text(' , Info livraison : ' + data.best_date);
Administrator committed
386 387

    openModal(
388 389
        msg.html(),
        function() {
Administrator committed
390
        // Confirm button callback
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
            openModal();

            post_form(
                '/shop/admin/delete_cart',
                {cart_id: data._id},
                function(err, result) {
                    if (!err) {
                        if (typeof result.res !== "undefined" && typeof result.res.del_action !== "undefined") {
                            clicked.parents('tr').remove();
                            alert("Commande définitivement détruite");
                        } else {
                            console.log(result);
                        }

                    } else {
                        console.log(err);
                    }
Administrator committed
408

409 410 411 412 413 414 415
                    closeModal();
                }
            );
        },
        'Détruire',
        false
    );
Administrator committed
416

417
};
Administrator committed
418 419 420

// Delete multiple orders
var batch_delete = function() {
421
    var selected_rows = getSelectedRows();
Administrator committed
422

423 424
    if (selected_rows[0].length > 0) {
        var msg = multiple_carts_destroy_msg.clone();
Administrator committed
425

426 427
        var rows_data = selected_rows.data();
        var carts_id = [];
Administrator committed
428

429 430
        for (var i = 0; i < rows_data.length; i++) {
            carts_id.push(rows_data[i]._id);
Administrator committed
431

432
            var msg_item = multiple_carts_item_destroy.clone();
Administrator committed
433

434 435 436
            addMemberAndDateToMsg(msg_item, rows_data[i]);
            if (rows_data[i].best_date.length > 0)
                msg_item.find('.bdate').text(' , Info livraison : ' + rows_data[i].best_date);
Administrator committed
437

438
            msg.find('.items').append(msg_item);
Administrator committed
439 440
        }

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
        openModal(
            msg.html(),
            function() {
                // Confirm button callback
                if (is_time_to('delete_orders', 5000)) { // prevent double click or browser hic up bug
                    openModal();

                    post_form(
                        '/shop/admin/batch_delete_carts',
                        {carts_id: carts_id},
                        function(err, result) {
                            if (!err) {
                                if (typeof result.res !== "undefined" && result.res.length > 0) {
                                    removeRows(selected_rows);
                                    $('#multiple_actions_container').slideUp('fast');
                                    alert("Commandes définitivement détruites");
                                } else {
                                    console.log(result);
                                }

                            } else {
                                console.log(err);
                            }

                            closeModal();
                        }
                    );
                }
            },
            'Détruire',
            false
        );
    }
};
Administrator committed
475 476 477



478 479 480 481
$(function() {
    if (coop_is_connected()) {
        init_and_fill_order_list();
        /* Make search accent insensitive */
Administrator committed
482

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
        $(document).on('keyup', '#main_content input[type="search"]', function() {
            orders_table
                .search(jQuery.fn.DataTable.ext.type.search.string(this.value))
                .draw();
        });
        $(document).on('click', '.orders .fa-trash', deleteCart);
        $(document).on('click', '#download-arrivals', downloadArrivals);
        $(document).on('click', '#batch_action', function() {
            var action = $(this).parent()
                .find('#batch_action_select option:selected')
                .val();

            if (action == "delete") {
                batch_delete();
            }
        });
Administrator committed
499

500
    }
Administrator committed
501
});