shop_admin.js 31.8 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 73

var updateWaitingForDisplayWithNewArrival = function(doc) {
    if (doc.state != 'init') {
74 75
        var type = 'new';

Administrator committed
76
        if (typeof doc._deleted == "undefined" && doc.state != "deleted") {
77 78 79 80
            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
81 82
            // check if it's a new order or an updated one
            if (orders_table) {
83 84 85 86 87 88
                var found = false;

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


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

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

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

117
};
Administrator committed
118 119

var downloadArrivals = function () {
120
    window.location.reload();
Administrator committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    /*
    if (is_time_to('download_arrivals', 2000)) { // prevent double click or browser hic up bug
        try {
            displayMsg("Mise à jour en cours...")
            for (type in waiting_for_display) {
                var i = 0 // tp prevent infinite loop
                var elt = waiting_for_display[type].pop()
                while (elt  && i < 500) {
                    if (type == "new"){
                        orders_table.row.add(elt).draw()
                    } else {
                        var impacted_row = null
                        $.each(orders_table.rows(), function(i,r) {
                            var data = orders_table.row(r).data()
                            if (data._id == elt._id) impacted_row = r
                        })
                        if (impacted_row != null) {
                            if (type == "update") {
                                orders_table.row(impacted_row).data(elt).draw()
                            } else {
                                orders_table.row(impacted_row).remove().draw()
                                //impacted_row.remove()
                            }
                        }

                    }
                    elt = waiting_for_display[type].pop()
                    i += 1
                }

            }
            var all_empty = true
            for (type in waiting_for_display) {
                if (waiting_for_display[type].length > 0) all_empty = false
            }
            if (all_empty == true)
                main_msg_area.hide()
            else {
                console.log(waiting_for_display)
                updateArrivalsMsg()
            }
            closeModal()
        } catch(e) {
            closeModal()
            console.log(e)
        }
    }
    */
169
};
Administrator committed
170 171 172 173

var rowUpdate = function (row, rdata) {
    //console.log(row, rdata)
    if (rdata.state === 'in_process' || rdata.state === 'ready' || rdata.state === 'paid') {
174 175
        $(row).find('td.take_it input')
            .prop('checked', true);
Administrator committed
176
        if (rdata.state === 'ready' || rdata.state === 'paid') {
177 178 179 180 181 182
            var internal_ref = rdata.internal_ref || 'rien';

            $(row).find('td.ready input')
                .prop('checked', true);
            $(row).find('td.internal-ref')
                .text(internal_ref);
Administrator committed
183 184
        }
        if (rdata.state === 'paid') {
185 186
            $(row).find('td.paid input')
                .prop('checked', true);
Administrator committed
187 188
        }
    }
189
};
Administrator committed
190

191 192 193
function coop_init_datatable(params, data, domsel, cols, action_btn) {
    var buttons = [];
    var columns = [];
Administrator committed
194 195 196


    columns.push({
197 198 199 200 201 202 203 204 205 206 207
        data: null,
        defaultContent: checkbox,
        orderable: false,
        orderDataType: "dom-checkbox",
        title: "Sélection",
        className: 'order_selector',
        width: '3%',
        targets:   0
    });
    $.each(cols, function(i, e) {
        columns.push(e);
Administrator committed
208 209
    });
    columns.push({
210 211 212 213 214 215 216 217
        data: null,
        defaultContent: checkbox,
        orderable: true,
        orderDataType: "dom-checkbox",
        title: "Pris en charge",
        className: 'take_it',
        targets:   0
    });
Administrator committed
218
    columns.push({
219 220 221 222 223 224 225 226
        data: null,
        defaultContent: checkbox,
        orderable: true,
        orderDataType: "dom-checkbox",
        title: "Prêt",
        className: 'ready',
        targets:   0
    });
Administrator committed
227
    columns.push({
228 229 230 231 232 233 234
        data: null,
        defaultContent: '',
        orderable: false,
        title: "Numéro",
        className: 'internal-ref',
        targets:   0
    });
Administrator committed
235
    columns.push({
236 237 238 239 240 241 242 243
        data: null,
        defaultContent: checkbox,
        orderable: true,
        orderDataType: "dom-checkbox",
        title: "Réglé",
        className: 'paid',
        targets:   0
    });
Administrator committed
244
    columns.push({
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        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
260 261

    columns.push({
262 263 264 265 266 267 268
        data: null,
        defaultContent: delete_icon,
        orderable: false,
        width: "30px",
        className: 'action',
        targets:   0
    });
Administrator committed
269 270

    var settings = {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        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'},
        createdRow: function(row, rdata, index) {
            rowUpdate(row, rdata);

        },
        initComplete: function() {
            /*
Administrator committed
302 303 304
                                if (! coop_is_connected())
                                    $('#main_content input[type="search"]').attr('disabled','disabled')
                                */
305 306 307 308 309 310 311 312 313
        },
        order: [
            [
                3,
                'desc'
            ]
        ]
    };

Administrator committed
314 315
    if (params) {
        if (params.page) {
316
            settings.displayStart = params.page.start;
Administrator committed
317 318
        }
        if (params.ordering) {
319
            settings.order = params.ordering;
Administrator committed
320 321 322
        }
    }

323
    return main_content.find('table'+domsel).DataTable(settings);
Administrator committed
324
}
325
function init_and_fill_order_list() {
Administrator committed
326 327

    dbc.allDocs({include_docs: true, descending: true}, function(err, resp) {
328 329 330 331 332 333
        if (err) {
            return console.log(err);
        }
        var data = [];

        $.each(resp.rows, function(i, e) {
Administrator committed
334 335
            if (e.doc.state != 'init' && e.doc.state != 'deleted') {
                try {
336 337
                    var timestamp = e.doc.submitted_time || e.doc.init_time || Date.now()/1000;

Administrator committed
338
                    if (timestamp) {
339 340 341 342 343
                        var date = new Date(parseInt(timestamp*1000, 10));

                        e.doc.total = parseFloat(e.doc.total).toFixed(2);
                        e.doc.h_submitted_date = format_date_to_sortable_string(date);
                        data.push(e.doc);
Administrator committed
344
                    } else {
345
                        console.log(e);
Administrator committed
346
                    }
347 348 349
                } catch (error) {
                    console.log(error);
                    console.log(e);
Administrator committed
350 351 352 353
                }
            }
        });
        if (orders_table)
354 355 356
            orders_table.destroy();
        var cols = [
            {data: 'h_submitted_date', title: "Date commande"},
357 358 359 360 361 362 363 364 365 366 367 368
            {
                data: 'type',
                title: "Type",
                width: "5%",
                render: function (data) {
                    if (data == 'delivery') {
                        return 'Livraison';
                    } else {
                        return 'Commande';
                    }
                }
            },
369 370 371 372 373
            {data: 'partner.display_name', title: "Nom"},
            {data: 'best_date', title: "Livraison"},
            {data: 'total', title: "Montant"}
        ];

Administrator committed
374 375 376 377 378 379 380 381
        orders_table = coop_init_datatable(null, data, '.orders', cols);
    });


}

// Get the selected rows in the table
var getSelectedRows = function() {
382 383 384 385 386 387
    if (orders_table) {
        return orders_table.rows('.selected');
    } else {
        return null;
    }
};
Administrator committed
388 389 390

// Set a row as selected : a row is selected if selection checkbox is checked
var selectRow = function() {
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    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
409 410 411

// Deselect rows from the table
var unselectRows = function(selected_rows) {
412 413 414 415 416 417 418 419
    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
420 421

var removeRows = function(selected_rows) {
422 423
    selected_rows.remove().draw();
};
Administrator committed
424 425

var updateCouchDB = function(data, callback) {
426 427 428 429
    var clicked = data.clicked;

    delete data.clicked;
    data.state_change_ts = format_date_to_sortable_string(new Date());
Administrator committed
430 431 432 433

    dbc.put(data, function(err, result) {
        if (!err) {
            if (result.ok === true) {
434 435 436 437 438 439
                var r = clicked.parents('tr');

                data._rev = result.rev;
                orders_table.row(r).data(data)
                    .draw();
                rowUpdate(r, data);
Administrator committed
440
            }
441
            callback(result);
Administrator committed
442
        } else {
443
            callback(null);
Administrator committed
444 445 446
            console.log(err);
        }
    });
447
};
Administrator committed
448 449

var changeCartStateAndUpdateCDB = function(clicked, data, prev_state, state) {
450
    data.state = state;
Administrator committed
451
    if (clicked.find('input:checked').length == 0) {
452
        data.state = prev_state;
Administrator committed
453
    }
454
    data.clicked = clicked;
Administrator committed
455 456 457
    updateCouchDB(data, function (res) {
        if (res) {
            if (res.ok === true) {
458
                cart_revisions[data._id] = res.rev;
Administrator committed
459 460 461 462 463 464 465
                //data._rev = res.rev
                //orders_table.row(clicked.parents('tr')).data(data).draw(false)

            } else {
                //?? What to do
            }
        } else {
466
            console.log('erreur rencontré pendant maj couchdb');
Administrator committed
467 468
        }

469 470
    });
};
Administrator committed
471
var rowGetData = function(clicked) {
472 473 474 475 476
    var row = orders_table.row(clicked.parents('tr'));


    return row.data();
};
Administrator committed
477
var takeCartInCharge = function() {
478 479
    var clicked = $(this);

Administrator committed
480
    if (clicked.closest('th').length == 0) {
481
        var data = rowGetData(clicked);
Administrator committed
482

483 484 485
        data.clicked = clicked;

        if (typeof data.printed === "undefined") {
Administrator committed
486
            //Open modal message with print option
487 488 489 490 491 492 493 494 495
            showCart(data);
        }
        data.state = 'in_process';
        if (clicked.closest('tr').find('td.take_it input')
            .prop('checked') == false) {
            data.state = 'waiting';
        }

        updateCouchDB(data, function (res) {
Administrator committed
496
            //What can be done if succes or error
497
        });
Administrator committed
498 499 500


    }
501
};
Administrator committed
502
var addMemberAndDateToMsg = function (msg, data) {
503 504 505 506 507
    var date = data.h_submitted_date;

    msg.find('.member').text(data.partner.display_name);
    msg.find('.date').text(date);
};
Administrator committed
508
var putCartInReadyState = function() {
509 510
    var clicked = $(this);

Administrator committed
511
    if (clicked.closest('th').length == 0) {
512 513
        var parent_tr = clicked.closest('tr');

Administrator committed
514
        if (parent_tr.find('td.take_it input:checked').length > 0) {
515 516 517
            var data = rowGetData(clicked);
            var td_ready = parent_tr.find('td.ready input');

Administrator committed
518
            if (td_ready.prop('checked') == false) { // was checked before click
519 520 521 522 523 524 525 526 527
                td_ready.prop('checked', true); // if user doesn't validate action
                openModal(
                    'Etes-vous sûr de vouloir déselectionner cette case ?',
                    function() {
                        td_ready.prop('checked', false);
                        changeCartStateAndUpdateCDB(clicked, data, 'in_process', 'in_process');
                    },
                    'Oui'
                );
Administrator committed
528
            } else {
529
                var msg = internal_get_msg.clone();
Administrator committed
530

531
                addMemberAndDateToMsg(msg, data);
Administrator committed
532
                openModal(
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
                    msg.html(),
                    function() {
                        // Confirm button callback
                        var internal_ref = $('.mconfirm input[name="internal-ref"]');

                        if (internal_ref.val().length > 0) {
                            data.internal_ref = internal_ref.val();
                            parent_tr.find('td.internal-ref').text(data.internal_ref);
                            changeCartStateAndUpdateCDB(clicked, data, 'in_process', 'ready');
                        } else {
                            setTimeout(function() {
                                modal.css("width", "100%"); //modal div is closed after callback has been triggered
                                internal_ref.css({'border':'1px solid red', 'background-color':'#fcbbf4'}).focus();
                            }, 500);
                        }
                    }
                );
Administrator committed
550 551
            }
        } else {
552 553
            clicked.find('input').prop('checked', false);
            alert("La commande doit avoir été prise en charge avant de la déclarée prête !");
Administrator committed
554 555 556
        }
    }

557
};
Administrator committed
558 559

var putCartInPaidState = function() {
560 561
    var clicked = $(this);

Administrator committed
562 563
    if (clicked.closest('th').length == 0) {
        if (clicked.parents('tr').find('td.ready input:checked').length > 0) {
564 565 566
            var data = rowGetData(clicked);

            changeCartStateAndUpdateCDB(clicked, data, 'ready', 'paid');
Administrator committed
567
        } else {
568 569
            clicked.find('input').prop('checked', false);
            alert("La commande doit avoir été déclarée prête avant de la déclarer payée !");
Administrator committed
570 571
        }
    }
572
};
Administrator committed
573 574 575

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

Administrator committed
578 579
    $.ajax({
        url: "admin/print_cart",
580
        data: {id : cart_id}
Administrator committed
581 582 583

        //TODO : find a way to test if answer is really a PDF (test with sucess: function(rData){...} -> download.bind doesn't work inside)
    })
584 585 586 587 588 589
        .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
590 591 592
var showCart = function() {
    var row = orders_table.row($(this).parents('tr'));
    var data = row.data();
593

Administrator committed
594
    if (typeof data === "undefined") {
595
        data = arguments[0];
Administrator committed
596
    }
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
    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
625 626

var deleteCart = function() {
627 628 629 630 631
    var clicked = $(this);
    var data = rowGetData(clicked);
    var msg = cart_destroy_msg.clone();

    addMemberAndDateToMsg(msg, data);
Administrator committed
632 633

    if (data.best_date.length > 0)
634
        msg.find('.bdate').text(' , Info livraison : ' + data.best_date);
Administrator committed
635 636

    openModal(
637 638
        msg.html(),
        function() {
Administrator committed
639
        // Confirm button callback
640 641 642 643 644 645 646 647 648 649 650 651 652
            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étruite");
                        } else {
                            console.log(result);
                        }
Administrator committed
653

654 655 656
                    } else {
                        console.log(err);
                    }
Administrator committed
657

658 659 660 661 662 663 664
                    closeModal();
                }
            );
        },
        'Détruire',
        false
    );
Administrator committed
665

666
};
Administrator committed
667 668 669

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

672 673
    if (selected_rows[0].length > 0) {
        var msg = multiple_carts_destroy_msg.clone();
Administrator committed
674

675 676
        var rows_data = selected_rows.data();
        var carts_id = [];
Administrator committed
677

678 679
        for (var i = 0; i < rows_data.length; i++) {
            carts_id.push(rows_data[i]._id);
Administrator committed
680

681
            var msg_item = multiple_carts_item_destroy.clone();
Administrator committed
682

683 684 685
            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
686

687 688
            msg.find('.items').append(msg_item);
        }
Administrator committed
689

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
        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étruites");
                                } else {
                                    console.log(result);
                                }
Administrator committed
709

710 711 712
                            } else {
                                console.log(err);
                            }
Administrator committed
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
                            closeModal();
                        }
                    );
                }
            },
            'Détruire',
            false
        );
    }
};

var setShopSettingsDom = function(shop_settings) {
    if (shop_settings != null) {
        if (typeof shop_settings.closing_dates !== "undefined") {
            if (shop_settings.closing_dates.length > 0) {
                $(document).find('#settings_shop_closed .no_dates')
                    .hide();

                $("#settings_shop_closed ul").html('');
                for (scd of shop_settings.closing_dates) {
                    $("#settings_shop_closed ul")
                        .append('<li class="closing_date_item"><span class="closing_date_value">'+scd+'</span> '+delete_icon+'</li>');
                }
                $(document).find('#settings_shop_closed .dates')
                    .show();
            } else {
                $(document).find('#settings_shop_closed .dates')
                    .hide();
                $(document).find('#settings_shop_closed .no_dates')
                    .show();
Administrator committed
744 745
            }
        }
746 747 748
        if (typeof shop_settings.capital_message !== "undefined") {
            $('[name="capital_message"]').val(shop_settings.capital_message);
        }
Administrator committed
749 750

    }
751
};
Administrator committed
752 753

var getShopSettings = function() {
754
    shop_settings_content = $(document).find('#shop_settings_content');
Administrator committed
755

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    shop_settings_content.hide();
    putLoadingImgOn($(document).find('#tab_settings_content'));

    post_form(
        '/shop/admin/get_shop_settings',
        {},
        function(err, result) {
            if (!err) {
                if (typeof result.res.shop_settings !== "undefined") {
                    shop_settings = result.res.shop_settings;
                    setShopSettingsDom(shop_settings);
                } else {
                    alert('Les réglages n\'ont pas pu être récupérés, merci de réessayer plus tard.');
                    console.log(result);
                }
            } else {
                alert('Les réglages n\'ont pas pu être récupérés, merci de réessayer plus tard.');
                console.log(err);
            }

            shop_settings_content.show();
            removeLoadingImg();
        }
    );
};
Administrator committed
781 782

var switchActiveTab = function() {
783
    var clicked = $(this);
Administrator committed
784

785 786 787 788
    // Set tabs
    $(document).find('.tab')
        .removeClass('active');
    $(this).addClass('active');
Administrator committed
789

790 791 792
    // Tabs content
    $(document).find('.tab_content')
        .hide();
Administrator committed
793

794
    var tab = $(this).attr('id');
Administrator committed
795

796 797 798 799 800 801 802 803 804
    if (tab == 'tab_settings') {
        $(document).find('#tab_settings_content')
            .show();

        // If shop_settings not set, fetch data
        if (shop_settings == null) {
            getShopSettings();
        }
    } else {
Administrator committed
805
    // Default
806 807 808 809
        $(document).find('#tab_orders_content')
            .show();
    }
};
Administrator committed
810 811

var addClosingDate = function() {
812 813
    var closing_date = $(document).find('#settings_shop_closed #closing_date_picker')
        .val();
Administrator committed
814

815 816 817 818
    if (shop_settings != null && 'closing_dates' in shop_settings && shop_settings['closing_dates'].includes(closing_date)) {
        alert('Cette date est déjà présente dans les dates de fermeture.');
        $(document).find('#settings_shop_closed #closing_date_picker')
            .val('');
Administrator committed
819

820 821
        return null;
    }
Administrator committed
822

823 824
    if (closing_date != "") {
        openModal();
Administrator committed
825

826 827 828 829 830 831 832 833
        post_form(
            '/shop/admin/add_shop_closing_date',
            {closing_date: closing_date},
            function(err, result) {
                if (!err) {
                    if (typeof result.res.shop_settings !== "undefined") {
                        shop_settings = result.res.shop_settings;
                        setShopSettingsDom(shop_settings);
Administrator committed
834

835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
                        $(document).find('#settings_shop_closed #closing_date_picker')
                            .val('');
                    } else {
                        console.log(result);
                    }
                } else {
                    alert('Les réglages n\'ont pas pu être récupérés, merci de réessayer plus tard.');
                    console.log(err);
                }

                closeModal();
            }
        );
    }
};
Administrator committed
850 851

var saveMaxOrdersPerSlot = function() {
852 853 854 855
    var val_input = $('[name="new_max_orders_per_slot"]');
    var newVal = val_input.val();

    openModal();
Administrator committed
856
    post_form(
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
        '/shop/admin/save_max_orders_ps',
        {nb: newVal},
        function(err, result) {
            if (!err) {
                if (typeof result.res.shop_settings !== "undefined") {
                    shop_settings = result.res.shop_settings;
                    $('.max-carts-per-slot .nb').text(shop_settings['max_timeslot_carts']);
                    val_input.val('');
                } else {
                    console.log(result);
                }
            } else {
                alert('La valeur n\'a pas pu être enregistrée, merci de réessayer plus tard.');
                console.log(err);
            }
Administrator committed
872

873 874 875 876
            closeModal();
        }
    );
};
Administrator committed
877 878

var saveCapitalMessage = function() {
879 880 881
    var text = $('[name="capital_message"]').val();

    openModal();
Administrator committed
882
    post_form(
883 884 885 886 887 888 889 890 891 892 893 894 895
        '/shop/admin/save_capital_message',
        {text: text},
        function(err, result) {
            if (!err) {
                if (typeof result.res.shop_settings !== "undefined") {
                    console.log(result);
                } else {
                    console.log(result);
                }
            } else {
                alert('La valeur n\'a pas pu être enregistrée, merci de réessayer plus tard.');
                console.log(err);
            }
Administrator committed
896

897 898 899 900
            closeModal();
        }
    );
};
Administrator committed
901 902

var removeClosingDate = function() {
903 904 905
    var clicked = $(this);
    var closing_date = clicked.parent().find('.closing_date_value')
        .text();
Administrator committed
906

907
    var msg = remove_closing_date_msg.clone();
Administrator committed
908

909
    msg.find('.confirm_closing_date').text(closing_date);
Administrator committed
910

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
    openModal(
        msg.html(),
        function() {
            // Confirm button callback
            if (is_time_to('remove_shop_closing_date', 5000)) { // prevent double click or browser hic up bug
                openModal();

                post_form(
                    '/shop/admin/remove_shop_closing_date',
                    {closing_date: closing_date},
                    function(err, result) {
                        if (!err) {
                            if (typeof result.res.shop_settings !== "undefined") {
                                shop_settings = result.res.shop_settings;
                                setShopSettingsDom(shop_settings);
                            } else {
                                console.log(result);
                            }
                        } else {
                            alert('Cette date n\'a pas pu être supprimée');
                            console.log(err);
                        }
Administrator committed
933

934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
                        closeModal();
                    }
                );
            }
        },
        'Supprimer',
        false
    );
};

$(function() {
    if (coop_is_connected()) {
        init_and_fill_order_list();
        /* Make search accent insensitive */

        $(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', '.order_selector', selectRow);
        $(document).on('click', '.take_it', takeCartInCharge);
        $(document).on('click', '.ready', putCartInReadyState);
        $(document).on('click', '.paid', putCartInPaidState);
        $(document).on('click', '.fa-eye', showCart);
        $(document).on('click', '.orders .fa-trash', deleteCart);
        $(document).on('click', '.fa-print', function() {
            var clicked = $(this);
            var data = rowGetData(clicked);

            displayMsg('Génération du PDF.....');
            printCart(data._id, function(res) {
                if (res == true) {

                    openModal(
                        'Voulez-vous marquer la commande comme "Imprimée" (Prise en charge) ?',
                        function() {
                            data.printed = true;
                            data.state = 'in_process';
                            data.clicked = clicked;
                            updateCouchDB(data, function (res) {
                                //What can be done if succes or error
                            });
                        },
                        'Oui'
                    );
                }
Administrator committed
981

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 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 1057 1058 1059 1060 1061 1062 1063 1064
            });
        });
        $(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();
            }
        });
        $(document).on('click', '.tabs .tab', switchActiveTab);
        $(document).on('click', '#add_closing_date', addClosingDate);
        $(document).on('click', '#settings_shop_closed .dates .fa-trash', removeClosingDate);
        $(document).on('click', '#save_max_orders_ps', saveMaxOrdersPerSlot);
        $(document).on('click', '#save_capital_message', saveCapitalMessage);

        // Set datepicker
        $.datepicker.regional['fr'] = {
            monthNames: [
                'Janvier',
                'Fevrier',
                'Mars',
                'Avril',
                'Mai',
                'Juin',
                'Juillet',
                'Aout',
                'Septembre',
                'Octobre',
                'Novembre',
                'Decembre'
            ],
            monthNamesShort: [
                'Jan',
                'Fev',
                'Mar',
                'Avr',
                'Mai',
                'Jun',
                'Jul',
                'Aou',
                'Sep',
                'Oct',
                'Nov',
                'Dec'
            ],
            dayNames: [
                'Dimanche',
                'Lundi',
                'Mardi',
                'Mercredi',
                'Jeudi',
                'Vendredi',
                'Samedi'
            ],
            dayNamesShort: [
                'Dim',
                'Lun',
                'Mar',
                'Mer',
                'Jeu',
                'Ven',
                'Sam'
            ],
            dayNamesMin: [
                'Di',
                'Lu',
                'Ma',
                'Me',
                'Je',
                'Ve',
                'Sa'
            ],
            dateFormat: 'yy-mm-dd',
            firstDay: 1,
            minDate: 1,
            maxDate: '+12M +0D'
        };
        $.datepicker.setDefaults($.datepicker.regional['fr']);
        $("#closing_date_picker").datepicker();
    }
Administrator committed
1065
});