manage_makeups.js 19.8 KB
Newer Older
1
var makeups_members_table = null,
2
    makeups_members = null,
3
    members_search_results = [],
Damien Moulard committed
4
    selected_rows = []; // Contain members id
5 6


7 8 9
/**
 * Load partners who have makeups to do
 */
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
function load_makeups_members() {
    $.ajax({
        type: 'GET',
        url: "/members/get_makeups_members",
        dataType:"json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            makeups_members = data.res;
            display_makeups_members();
        },
        error: function(data) {
            err = {msg: "erreur serveur lors de la récupération des membres avec rattrapage", ctx: 'load_makeups_members'};
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }
            report_JS_error(err, 'orders');

            closeModal();
            alert('Erreur serveur lors de la récupération des membres avec rattrapage. Ré-essayez plus tard.');
        }
    });
}

34 35 36
/**
 * (Re)Display table of makeup members
 */
37 38 39 40 41 42 43
function display_makeups_members() {
    if (makeups_members_table) {
        $('#makeups_members_table').off();
        makeups_members_table.clear().destroy();
        $('#makeups_members_table').empty();
    }

44
    // Remove members with 0 makeups to do and 0 makeups to come
Damien Moulard committed
45
    ids_to_remove = [];
46
    for (let member_item of makeups_members) {
47
        if (member_item.makeups_to_do === 0 && member_item.makeups_to_come === 0) {
Damien Moulard committed
48
            ids_to_remove.push(member_item.id);
49 50
        }
    }
Damien Moulard committed
51
    makeups_members = makeups_members.filter(m => !ids_to_remove.includes(m.id));
52 53 54 55 56 57 58

    // TODO : select multiple and grouped action
    makeups_members_table = $('#makeups_members_table').DataTable({
        data: makeups_members,
        columns: [
            {
                data: "id",
59
                title: "",
60 61
                className: "dt-body-center",
                orderable: false,
62 63 64 65 66 67
                render: function (data, type, full) {
                    var html = ``;
                    if(full.shift_type == 'standard') { //prevent checking of ftop members so that they can't be target of makeup removal
                        html = `<input type="checkbox" class="select_member_cb" id="select_member_${data}" value="${data}">`;
                    }
                    return html;
68 69 70 71 72
                },
                width: "3%"
            },
            {
                data: "name",
Damien Moulard committed
73
                title: "Nom"
74
            },
Félicie committed
75
            {
76 77 78 79 80 81 82 83 84 85 86
                data: "id",
                title: "",
                className: "dt-body-center",
                orderable: false,
                width: "10%",
                render: function (data, type, row) {
                    return `<button class="btn--primary extend_delay_button" data-member-id="${row.id}">Augmenter le délai</button>`;
                }
            },
            {
                data: "date_delay_stop",
87
                title: "<div class='title_center'>Limite du délai</div>",
Félicie committed
88 89
                className: "dt-body-center",
                width: "10%",
90 91 92 93
                render: function (data) {
                    return (data === false) ? "Pas de délai en cours" : new Date(data).toLocaleDateString();
                }
            },
94 95 96 97 98 99 100 101 102 103 104 105 106
            {
                data: "shift_type",
                title: "<div class='title_center'>Type de créneau</div>",
                className: "dt-body-center",
                width: "5%",
                render: function (data) {
                    if (data == 'ftop') {
                        return (has_committe_shift === "True") ? "Comités" : "Volant";
                    } else {
                        return 'ABCD';
                    }
                }
            },
Félicie committed
107
            {
108
                data: "makeups_to_come",
Yvon committed
109
                title: "<div class='title_center' title=\"Services de rattrapage à venir déjà choisis depuis l'espace membre.\">Rattrapages à venir déjà choisis</div>",
Félicie committed
110
                className: "dt-body-center",
111 112 113
                width: "8%",
                render: function (data, type, full) {
                    return `<b>${data}</b>`;
Félicie committed
114 115
                }
            },
116 117
            {
                data: "makeups_to_do",
Yvon committed
118
                title: "<div class='title_center' title=\"Rattrapages en attente de sélection sur l'espace membre.\">Rattrapages pas encore choisis</div>",
119 120 121
                className: "dt-body-center",
                width: "10%",
                render: function (data, type, full) {
122
                    var html = `<b>${data}</b>`
123
                    if(full.shift_type == 'standard') {
124 125 126 127 128 129
                        if(data > 0) {
                            html += `
                            <button class="decrement_makeup btn--primary" id="decrement_member_${full.id}">
                                <i class="fas fa-minus"></i>
                            </button>`;
                        }
130
                        html += `
131 132
                        <button class="increment_makeup btn--primary" id="increment_member_${full.id}">
                            <i class="fas fa-plus"></i>
133
                        </button>`;
134 135
                    }
                    return html;
Damien Moulard committed
136
                }
137 138
            },
            {
139
                data: "shift_type",
Yvon committed
140
                title: "<div class='title_center' title=\"Information d'interprétation délicate réservée aux utilisateurs avancés.\">Points (avancé)</div>",
141 142 143 144 145 146 147 148 149 150 151
                className: "dt-body-center",
                width: "5%",
                render: function (data, type, row) {
                    if (data == 'ftop') {
                        return row.display_ftop_points;
                    } else if (data == 'standard') {
                        return row.display_std_points;
                    }

                    return null;
                }
152 153 154 155 156 157 158 159 160 161 162 163 164 165
            }
        ],
        aLengthMenu: [
            [
                25,
                50,
                -1
            ],
            [
                25,
                50,
                "Tout"
            ]
        ],
166
        iDisplayLength: 25,
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        oLanguage: {
            "sProcessing":     "Traitement en cours...",
            "sSearch":         "Rechercher dans le tableau",
            "sLengthMenu":     "Afficher _MENU_ &eacute;l&eacute;ments",
            "sInfo":           "Affichage de l'&eacute;l&eacute;ment _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments",
            "sInfoEmpty":      "Affichage de l'&eacute;l&eacute;ment 0 &agrave; 0 sur 0 &eacute;l&eacute;ment",
            "sInfoFiltered":   "(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)",
            "sInfoPostFix":    "",
            "sLoadingRecords": "Chargement en cours...",
            "sZeroRecords":    "Aucun &eacute;l&eacute;ment &agrave; afficher",
            "sEmptyTable":     "Aucune donn&eacute;e disponible dans le tableau",
            "oPaginate": {
                "sFirst":      "Premier",
                "sPrevious":   "Pr&eacute;c&eacute;dent",
                "sNext":       "Suivant",
                "sLast":       "Dernier"
            },
            "oAria": {
                "sSortAscending":  ": activer pour trier la colonne par ordre croissant",
                "sSortDescending": ": activer pour trier la colonne par ordre d&eacute;croissant"
            },
            "select": {
Damien Moulard committed
189 190 191 192 193
                "rows": {
                    "_": "%d lignes séléctionnées",
                    "0": "Aucune ligne séléctionnée",
                    "1": "1 ligne séléctionnée"
                }
194 195
            }
        }
196 197 198
    });

    $('#makeups_members_table').on('click', 'tbody td .decrement_makeup', function () {
Damien Moulard committed
199 200
        const button_id = $(this).prop('id')
            .split('_');
201 202 203 204
        const member_id = button_id[button_id.length - 1];

        const member = makeups_members.find(m => m.id == member_id);

205 206 207 208
        let modal_template = $("#modal_decr_makeup_counter");

        modal_template.find(".member_name").text(member.name);

209
        openModal(
210
            modal_template.html(),
211
            () => {
212 213 214
                update_members_makeups(
                    [member_id],
                    "decrement",
215
                    ($("#decr-signature")[0].value || "auteur inconnu") + ' : ' + ($("#decr-explanation")[0].value || "pas d'explication")
216
                );
217 218 219
            },
            "Confirmer",
            false
Damien Moulard committed
220
        );
221
    });
222

223 224 225 226 227 228 229
    $('#makeups_members_table').on('click', 'tbody td .increment_makeup', function () {
        const button_id = $(this).prop('id')
            .split('_');
        const member_id = button_id[button_id.length - 1];

        const member = makeups_members.find(m => m.id == member_id);

230 231 232 233
        let modal_template = $("#modal_incr_makeup_counter");

        modal_template.find(".member_name").text(member.name);

234
        openModal(
235
            modal_template.html(),
236
            () => {
237 238 239
                update_members_makeups(
                    [member_id],
                    "increment",
240
                    ($("#incr-signature")[0].value || "auteur inconnu") + ' : ' + ($("#incr-explanation")[0].value || "pas d'explication")
241
                );
242 243 244 245 246 247
            },
            "Confirmer",
            false
        );
    });

248 249 250 251 252 253 254 255 256 257 258 259
    $('#makeups_members_table').on('click', 'tbody td .select_member_cb', function () {
        $(this).closest('tr')
            .toggleClass('selected');

        // Save / unsave selected row
        const m_id = makeups_members_table.row($(this).closest('tr')).data().id;
        const first_select = selected_rows.length === 0;

        if (this.checked) {
            selected_rows.push(m_id);
        } else {
            const i = selected_rows.findIndex(id => id == m_id);
Damien Moulard committed
260

261 262 263 264 265 266 267 268
            selected_rows.splice(i, 1);
        }

        if (selected_rows.length > 0) {
            $("#decrement_selected_members_makeups").show();
            if (first_select) {
                $("#decrement_selected_members_makeups").on("click", () => {
                    openModal(
269
                        $("#modal_decr_selected_makeup_counter").html(),
270
                        () => {
271 272 273
                            update_members_makeups(
                                selected_rows,
                                "decrement",
274
                                ($("#decr-signature-selected")[0].value || "auteur inconnu") + ' : ' + ($("#decr-explanation-selected")[0].value || "pas d'explication")
275
                            );
276 277 278
                        },
                        "Confirmer",
                        false
Damien Moulard committed
279
                    );
280 281 282
                });
            }
        } else {
Damien Moulard committed
283 284
            $("#decrement_selected_members_makeups").off()
                .hide();
285 286
        }
    });
287 288 289 290 291 292

    $('#makeups_members_table').on('click', 'tbody td .extend_delay_button', function () {
        const member_id = this.dataset.memberId;
        const member = makeups_members.find(m => m.id == member_id);

        let modal = $("#modal_extend_delay_template");
293

294 295 296 297 298 299 300 301 302 303 304
        modal.find(".member_name").text(member.name);

        openModal(
            modal.html(),
            () => {
                extend_member_delay(member);
            },
            "Confirmer",
            false
        );
    });
305 306
}

307 308
/**
 * Send request to update members nb of makeups to do
François committed
309
 *
Damien Moulard committed
310
 * @param {Array} member_ids
311
 * @param {String} action increment | decrement
312
 * @param description
313
 */
314
function update_members_makeups(member_ids, action, description) {
315 316
    openModal();

Damien Moulard committed
317
    data = [];
318 319
    for (mid of member_ids) {
        member_index = makeups_members.findIndex(m => m.id == mid);
320 321 322
        /* Becareful : makeups_members will be modified while nobody knows wether ajax process will succeed or not !
        TODO : make the changes only when it is sure that odoo records have been changed
        */
323 324 325 326
        if (action === "increment") {
            makeups_members[member_index].makeups_to_do += 1;
        } else {
            makeups_members[member_index].makeups_to_do -= 1;
327
        }
Damien Moulard committed
328

329 330
        data.push({
            member_id: mid,
331
            target_makeups_nb: makeups_members[member_index].makeups_to_do,
332 333
            member_shift_type: makeups_members[member_index].shift_type,
            display_ftop_points: makeups_members[member_index].display_ftop_points,
334 335
            display_std_points: makeups_members[member_index].display_std_points,
            description: description,
336 337 338 339 340 341 342 343 344 345
        });
    }

    $.ajax({
        type: 'POST',
        url: "/members/update_members_makeups",
        data: JSON.stringify(data),
        dataType:"json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
346
        success: function(res) {
347
            selected_rows = [];
348 349 350 351 352 353 354 355 356
            for (element of res['res']) {
                member_index = makeups_members.findIndex(m => m.id == element['mid']);
                if (makeups_members[member_index].shift_type === 'standard') {
                    makeups_members[member_index].display_std_points = element['standard_points']
                }
                //there is no point change when shift_type is not standard
                //and I think operation on rattrapages should definitely be forbidden for ftop because it
                //has no sense !!
            }
357 358 359 360
            display_makeups_members();
            closeModal();
        },
        error: function(data) {
361
            err = {msg: "erreur serveur pour incrémenter ou décrémenter les rattrapages", ctx: 'update_members_makeups'};
362 363 364
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }
365 366 367
            report_JS_error(err, 'members_admin-manage_makeups');

            closeModal();
368
            alert('Erreur serveur pour incrémenter ou décrémenter les rattrapages. Veuillez contacter le service informatique.');
369 370 371 372 373 374
        }
    });
}

/**
 * Send request to extend the member's delay, or create one if none open.
375
 * @param {Object} member
376 377 378 379
 */
function extend_member_delay(member) {
    openModal();

380
    let today = new Date();
381 382
    let today_plus_extension_duration = new Date();
    today_plus_extension_duration.setMonth(today_plus_extension_duration.getMonth()+ extension_duration);
383
    const diff_time = Math.abs(today_plus_extension_duration - today);
384 385
    const diff_days = Math.ceil(diff_time / (1000 * 60 * 60 * 24));

386
    let data = {
387 388
        member_id: member.id,
        duration: diff_days
389 390 391 392 393 394 395 396 397
    };

    $.ajax({
        type: 'POST',
        url: "/members/admin/regenerate_member_delay",
        data: JSON.stringify(data),
        dataType:"json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
398 399 400 401 402
        success: function(result) {
            let i = makeups_members.findIndex(m => m.id == result.member_data.id);

            makeups_members[i].date_delay_stop = result.member_data.date_delay_stop;

403 404 405 406 407 408 409 410 411
            display_makeups_members();
            closeModal();
        },
        error: function(data) {
            err = {msg: "erreur serveur pour créer un délai", ctx: 'extend_member_delay'};
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }
            report_JS_error(err, 'members_admin-manage_makeups');
412 413

            closeModal();
414
            alert('Erreur serveur pour créer un délai. Veuillez contacter le service informatique.');
415 416 417 418
        }
    });
}

419 420 421 422 423 424
/**
 * Display the members from the search result
 */
function display_possible_members() {
    $('.search_member_results_area').show();
    $('.search_member_results').empty();
425
    $('.btn_possible_member').off();
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

    let no_result = true;

    if (members_search_results.length > 0) {
        for (member of members_search_results) {
            // Don't display members already in the table
            if (makeups_members.find(m => m.id == member.id) != null) {
                continue;
            }

            $(".search_results_text").show();
            no_result = false;

            // Display results (possible members) as buttons
            var member_button = '<button class="btn--success btn_possible_member" member_id="'
                + member.id + '">'
                + member.barcode_base + ' - ' + member.name
                + '</button>';

            $('.search_member_results').append(member_button);

447 448 449 450 451 452 453 454
        }

        // Set action on member button click
        $('.btn_possible_member').on('click', function() {
            for (member of members_search_results) {
                if (member.id == $(this).attr('member_id')) {
                    if (makeups_members === null) {
                        makeups_members = [];
455
                    }
456 457 458 459 460

                    makeups_members.unshift({
                        id: member.id,
                        name: member.name,
                        makeups_to_do: 0,
461 462
                        shift_type: member.shift_type,
                        display_std_points: member.display_std_points,
463 464
                        display_ftop_points: member.display_ftop_points,
                        makeups_to_come: member.makeups_to_come
465 466
                    });

467 468 469 470
                    let modal_template = $("#modal_incr_makeup_counter");

                    modal_template.find(".member_name").text(member.name);

471
                    openModal(
472
                        modal_template.html(),
473
                        () => {
474 475 476
                            update_members_makeups(
                                [member.id],
                                "increment",
477
                                ($("#incr-signature")[0].value || "auteur inconnu") + ' : ' + ($("#incr-explanation")[0].value || "pas d'explication")
478
                            );
479 480 481 482 483 484 485 486 487 488
                            members_search_results = [];
                            $('#search_member_input').val('');
                            $('.search_member_results_area').hide();
                            $('.search_member_results').empty();
                        },
                        "Confirmer",
                        false
                    );

                    break;
489
                }
490 491
            }
        });
492
    }
Damien Moulard committed
493

494 495 496
    if (no_result === true) {
        $(".search_results_text").hide();
        $('.search_member_results').html(`<p>
Damien Moulard committed
497
            <i>Aucun résultat ! Vérifiez votre recherche, ou si le.la membre n'est pas déjà dans le tableau...</i>
498 499 500 501
        </p>`);
    }
}

502
$(document).ready(function() {
503
    if (coop_is_connected()) {
Damien Moulard committed
504 505
        $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });

506 507 508 509 510
        $(".page_content").show();
        load_makeups_members();
    } else {
        $(".page_content").hide();
    }
511

512 513
    $('#back_to_admin_index').on('click', function() {
        let base_location = window.location.href.split("manage_makeups")[0].slice(0, -1);
Damien Moulard committed
514

515 516 517
        window.location.assign(base_location);
    });

518 519 520 521 522
    // Set action to search for the member
    $('#search_member_form').submit(function() {
        let search_str = $('#search_member_input').val();

        $.ajax({
523
            url: '/members/search/' + search_str +'?search_type=makeups_data',
524 525 526
            dataType : 'json',
            success: function(data) {
                members_search_results = [];
527
                members_search_results = data.res;
528 529 530

                display_possible_members();
            },
Damien Moulard committed
531
            error: function() {
532 533
                err = {
                    msg: "erreur serveur lors de la recherche de membres",
534
                    ctx: 'members.admin.manage_makeups.search_members'
535 536 537 538 539 540 541 542 543 544
                };
                report_JS_error(err, 'stock');

                $.notify("Erreur lors de la recherche de membre, il faut ré-essayer plus tard...", {
                    globalPosition:"top right",
                    className: "error"
                });
            }
        });
    });
545
});