manage_attached.js 15.3 KB
Newer Older
Thibault Grandjean committed
1 2 3
var parentId = null;
var childId = null;

4 5 6
var parentName = null;
var childName = null;

Félicie committed
7 8 9
var parentEmail = null;
var childEmail = null;

Félicie committed
10
const possible_cooperative_state = {
Thibault Grandjean committed
11 12 13 14 15 16
    suspended: "Rattrapage",
    exempted: "Exempté.e",
    alert: "En alerte",
    up_to_date: "À jour",
    unsubscribed: "Désinscrit.e des créneaux",
    delay: "En délai",
17 18
    gone: "Parti.e",
    associated: "En binôme"
Félicie committed
19 20
};

Félicie committed
21 22 23
/**
 * Load member infos
 */
Thibault Grandjean committed
24
function load_member_infos(divId, memberId) {
Félicie committed
25 26
    $.ajax({
        type: 'GET',
Thibault Grandjean committed
27
        url: "/members/get_member_info/" + memberId,
Félicie committed
28 29 30 31
        dataType:"json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function(data) {
Thibault Grandjean committed
32 33
            if (divId === 'parentInfo') {
                parentId = data.member.id;
34
                parentName = data.member.barcode_base + ' ' + data.member.name;
Thibault Grandjean committed
35 36
            } else if (divId === 'childInfo') {
                childId = data.member.id;
37
                childName = data.member.barcode_base + ' ' + data.member.name;
Thibault Grandjean committed
38 39
            }
            display_member_infos(divId, data.member);
Félicie committed
40 41 42 43 44 45 46
        },
        error: function(data) {
            err = {msg: "erreur serveur lors de la récupération des infos du membre", ctx: 'load_member_infos'};
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }
            report_JS_error(err, 'members.admin');
Félicie committed
47

Félicie committed
48 49 50 51 52
            closeModal();
            alert('Erreur lors de la récupération des infos du membre.');
        }
    });
}
Félicie committed
53

Félicie committed
54
/**
Thibault Grandjean committed
55
 * Display member info
Félicie committed
56
 */
Thibault Grandjean committed
57
function display_member_infos(divId, memberData) {
Thibault Grandjean committed
58 59 60
    $("#" + divId).show();
    $("#" + divId).find(".member_name")
        .text(memberData.name);
Félicie committed
61 62
    $("#" + divId).find(".member_email")
        .text(memberData.email);
Thibault Grandjean committed
63 64 65 66 67
    $("#" + divId).find(".member_status")
        .text(possible_cooperative_state[memberData.cooperative_state]);
    $("#" + divId).find(".member_makeups_to_do")
        .text(memberData.makeups_to_do);

68
    let member_shift_name = memberData.current_template_name === false ? 'X' : memberData.current_template_name;
69

70 71 72
    $("#" + divId).find(".member_shift_name")
        .text(member_shift_name);

Thibault Grandjean committed
73 74 75 76 77 78 79
    if (memberData.is_associated_people === false) {
        $("#" + divId).find(".member_associated_partner_area")
            .hide();
    }

    if (parentId != null && childId != null) {
        $("#createPair").prop("disabled", false);
80
        $("#createPair").addClass("btn--primary");
Thibault Grandjean committed
81
    }
82
}
Félicie committed
83

Félicie committed
84 85 86
/**
 * Load attached members
 */
Thibault Grandjean committed
87
function load_attached_members() {
88
    openModal();
Thibault Grandjean committed
89 90 91 92 93 94 95 96 97
    $.ajax({
        type: 'GET',
        url: "/members/get_attached_members",
        dataType:"json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            attached_members = data.res;
            display_attached_members();
98
            closeModal();
Thibault Grandjean committed
99 100
        },
        error: function(data) {
101
            err = {msg: "erreur serveur lors de la récupération des membres en binôme", ctx: 'load_makeups_members'};
Thibault Grandjean committed
102 103 104
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                err.msg += ' : ' + data.responseJSON.error;
            }
105
            report_JS_error(err, 'members');
Félicie committed
106

Thibault Grandjean committed
107
            closeModal();
108
            alert('Erreur serveur lors de la récupération des membres en binôme. Ré-essayez plus tard.');
Thibault Grandjean committed
109 110
        }
    });
Félicie committed
111 112 113 114 115
}

/**
 * Display table of attached members
 */
Thibault Grandjean committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
function display_attached_members() {

    // if (attached_members_table) {
    //   $('#attached_members_table').off();
    //   attached_members_table.clear().destroy();
    //   $('#attached_members_table').empty();
    // }

    attached_members_table = $('#attached_members_table').DataTable({
        data: attached_members,
        columns: [
            {
                data: "id",
                title: '',
                className: "dt-body-center",
                orderable: false,
                render: function (data) {
                    return `<input type="checkbox" class="select_member_cb" id="select_member_${data}" value="${data}">`;
                },
                width: "3%"
Félicie committed
136
            },
Thibault Grandjean committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150
            {
                data: "parent_name",
                title: "Nom du titulaire"
            },
            {
                data: "name",
                title: "en binôme avec"
            },
            {
                data: "action",
                title: "Action",
                width: "10%",
                render: function (data, type, full) {
                    return `
Thibault Grandjean committed
151 152 153
              <button class="delete_pair btn--danger" id="delete_pair_${full.id}">
                Désolidariser
              </button>`;
Thibault Grandjean committed
154
                }
Thibault Grandjean committed
155
            }
Félicie committed
156
        ],
Thibault Grandjean committed
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 187 188 189 190 191 192 193 194 195 196
        aLengthMenu: [
            [
                25,
                50,
                -1
            ],
            [
                25,
                50,
                "Tout"
            ]
        ],
        iDisplayLength: 25,
        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": {
                "rows": {
                    "_": "%d lignes séléctionnées",
                    "0": "Aucune ligne séléctionnée",
                    "1": "1 ligne séléctionnée"
                }
Félicie committed
197 198
            }
        }
Thibault Grandjean committed
199

Thibault Grandjean committed
200
    });
Thibault Grandjean committed
201

Félicie committed
202
}
Félicie committed
203 204


205 206
function delete_pair(childId, gone_checked) {
    var payload = {"child": {"id": childId}, "gone": []};
Damien Moulard committed
207

208
    if (gone_checked.length > 0) {
Damien Moulard committed
209 210 211 212 213
        $.each(gone_checked, function(i, e) {
            const elts = $(e).attr('name')
                .split("_");

            payload['gone'].push(elts[0]);
214 215
        });
    }
Thibault Grandjean committed
216

Thibault Grandjean committed
217 218 219 220 221 222 223
    $.ajax({
        type: "POST",
        url: '/members/admin/manage_attached/delete_pair',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(payload),
        success: function() {
224
            enqueue_message_for_next_loading("Binôme désolidarisé.");
Thibault Grandjean committed
225 226 227
            location.reload();
        },
        error: function(data) {
228
            err = {msg: "Erreur serveur lors de la désolidarisation du binôme.", ctx: 'load_makeups_members'};
Thibault Grandjean committed
229 230 231 232 233 234 235 236 237
            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 désolidarisation du binôme. Ré-essayez plus tard.');
        }
    });
Thibault Grandjean committed
238 239
}

240 241

function confirmDeletion(childId) {
242 243 244 245
    var modalContent = $('#confirmModal');

    modalContent.find("#parentName").text(parentName);
    modalContent.find("#childName").text(childName);
246 247

    if (parentEmail != false) {
248
        modalContent.find("#parentEmail").text(parentEmail);
249 250
    }
    if (childEmail != false) {
251
        modalContent.find("#childEmail").text(childEmail);
252 253
    }

254 255 256
    modalContent = modalContent.html();
    openModal(modalContent, () => {
        if (is_time_to('delete_pair')) {
Damien Moulard committed
257
            const gone_checked = $('input.after_unattached_state:checked');
Damien Moulard committed
258

259 260
            closeModal();
            openModal();
Damien Moulard committed
261
            delete_pair(childId, gone_checked);
262 263
        }
    }, 'Valider', false);
264 265
}

266 267

function create_pair(payload) {
268 269 270 271 272 273 274 275 276 277 278 279
    $.ajax({
        type: 'POST',
        url: "/members/admin/manage_attached/create_pair",
        dataType:"json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(payload),
        success: function() {
            enqueue_message_for_next_loading("Binôme créé.");
            location.reload();
        },
        error: function(data) {
            err = {msg: "erreur serveur", ctx: 'create pair'};
Damien Moulard committed
280 281
            var message = 'Erreur lors de création du binôme.';

282 283
            if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.errors != 'undefined') {
                err.msg += ' : ' + data.responseJSON.errors;
Damien Moulard committed
284 285 286

                data.responseJSON.errors.map(function(error) {
                    message += ('\n' + error);
Damien Moulard committed
287

Damien Moulard committed
288 289
                    return null;
                });
290 291
            }

Damien Moulard committed
292
            report_JS_error(err, 'members.admin');
293 294 295 296
            closeModal();
            alert(message);
        }
    });
297 298 299
}


Félicie committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
$(document).ready(function() {
    if (coop_is_connected()) {
        $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });

        $(".page_content").show();
    } else {
        $(".page_content").hide();
    }

    $('#back_to_admin_index').on('click', function() {
        let base_location = window.location.href.split("manage_attached")[0].slice(0, -1);

        window.location.assign(base_location);
    });

Félicie committed
315

Thibault Grandjean committed
316
    $("#search_member_input").autocomplete({source: function(request, response) {
Félicie committed
317
        $.ajax({
Thibault Grandjean committed
318
            url: '/members/search/' + request.term,
Félicie committed
319 320 321 322 323 324 325 326
            dataType : 'json',
            success: function(data) {
                members_search_results = [];
                for (member of data.res) {
                    if (member.is_member || member.is_associated_people) {
                        members_search_results.push(member);
                    }
                }
Thibault Grandjean committed
327
                response($.map(data.res, function(item) {
Thibault Grandjean committed
328 329 330 331 332
                    return {
                        label: item.barcode_base + ' ' + item.name,
                        value: item.id
                    };
                }));
Félicie committed
333 334 335 336 337 338 339 340 341 342 343 344 345
            },
            error: function() {
                err = {
                    msg: "erreur serveur lors de la recherche de membres",
                    ctx: 'search_member_form.search_members'
                };
                report_JS_error(err, 'members.admin');

                $.notify("Erreur lors de la recherche de membre, il faut ré-essayer plus tard...", {
                    globalPosition:"top right",
                    className: "error"
                });
            }
Thibault Grandjean committed
346 347 348
        });
    },
    minLength: 1,
349
    search: function() {
Thibault Grandjean committed
350 351
        $('#spinner1').show();
    },
352
    response: function() {
Thibault Grandjean committed
353 354 355 356 357 358 359 360 361
        $('#spinner1').hide();
    },
    select: function(event, ui) {
        event.preventDefault();
        if (ui.item) {
            load_member_infos("parentInfo", ui.item.value);
            $('#search_member_input').val(ui.item.label);

            return false;
Thibault Grandjean committed
362
        }
363 364

        return null;
Thibault Grandjean committed
365 366 367 368 369 370 371 372 373 374 375 376
    }
    });

    $("#search_child_input").autocomplete({source: function(request, response) {
        $.ajax({
            url: '/members/search/' + request.term,
            dataType : 'json',
            success: function(data) {
                members_search_results = [];
                for (member of data.res) {
                    if (member.is_member || member.is_associated_people) {
                        members_search_results.push(member);
Thibault Grandjean committed
377
                    }
Thibault Grandjean committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
                }
                response($.map(data.res, function(item) {
                    return {
                        label: item.barcode_base + ' ' + item.name,
                        value: item.id
                    };
                }));
            },
            error: function() {
                err = {
                    msg: "erreur serveur lors de la recherche de membres",
                    ctx: 'search_member_form.search_members'
                };
                report_JS_error(err, 'members.admin');

                $.notify("Erreur lors de la recherche de membre, il faut ré-essayer plus tard...", {
                    globalPosition:"top right",
                    className: "error"
                });
Thibault Grandjean committed
397
            }
Thibault Grandjean committed
398 399 400
        });
    },
    minLength: 1,
401
    search: function() {
Thibault Grandjean committed
402 403
        $('#spinner2').show();
    },
404
    response: function() {
Thibault Grandjean committed
405 406 407 408 409 410
        $('#spinner2').hide();
    },
    select: function(event, ui) {
        if (ui.item) {
            load_member_infos("childInfo", ui.item.value);
            $('#search_child_input').val(ui.item.label);
Thibault Grandjean committed
411

Thibault Grandjean committed
412 413
            return false;
        }
414 415

        return null;
Thibault Grandjean committed
416 417 418 419
    }
    });

    $("#createPair").on('click', function() {
420 421
        if (parentId && childId) { // Note : after reload, button "Créer le binôme" is clickable...It shouldn't
            var payload = {
422 423
                "parent": {"id": parentId},
                "child": {"id": childId}
424 425
            };

426 427 428 429
            var modalContent = $('#confirmModal');

            modalContent.find("#parentName").text(parentName);
            modalContent.find("#childName").text(childName);
430 431
            modalContent = modalContent.html();
            openModal(modalContent, () => {
432 433 434 435 436
                if (is_time_to('create_pair')) {
                    closeModal();
                    openModal(); // Show gears
                    create_pair(payload);
                }
437 438
            }, 'Valider', false);
        }
439

Thibault Grandjean committed
440 441 442 443 444 445 446 447
    });

    if ($("#attached_members_table") != "undefined") {
        load_attached_members();
    }

    $(document).on('click', '.delete_pair', function (event) {
        var childId = event.target.id.split('_').slice(-1)[0];
448

449 450 451 452 453 454 455
        $.ajax({
            type: 'GET',
            url: "/members/get_member_info/" + childId,
            dataType:"json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function(data) {
456 457 458 459 460
                if (data.member.parent_barcode_base !== undefined) {
                    parentName = data.member.parent_barcode_base + ' - ' + data.member.parent_name;
                } else {
                    parentName = data.member.parent_name;
                }
Félicie committed
461 462 463
                parentEmail = data.member.parent_email;
                childName = data.member.barcode_base + ' - ' + data.member.name;
                childEmail = data.member.email;
464 465 466 467 468 469 470 471
                confirmDeletion(childId);
            },
            error: function(data) {
                err = {msg: "erreur serveur lors de la récupération des infos du membre", ctx: 'load_member_infos'};
                if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                    err.msg += ' : ' + data.responseJSON.error;
                }
                report_JS_error(err, 'members.admin');
Thibault Grandjean committed
472

473 474 475 476
                closeModal();
                alert('Erreur lors de la récupération des infos du membre.');
            }
        });
Thibault Grandjean committed
477 478
    });
});