members-space-shifts-exchange.js 34.2 KB
Newer Older
1
var calendar = null,
2
    selected_shift = null,
3 4
    vw = null,
    adding_mode = false;
5

6 7
/* - Logic */

8 9 10 11
/**
 * A partner can exchange shifts if:
 *  - s.he doesn't have to choose a makeup shift
 *  - s.he's not an associated partner
12
 *  - s.he's is an associated partner who is not blocked in his actions
13 14 15
 * @returns boolean
 */
function can_exchange_shifts() {
16
    return partner_data.makeups_to_do == 0 && (partner_data.is_associated_people === "False" || (partner_data.is_associated_people === "True" && block_actions_for_attached_people === "False"));
17 18 19
}

/**
20
 * A partner should select a shift if:
21 22 23 24
 *  - s.he has makeups to do
 *  - s.he's not an associated partner
 * @returns boolean
 */
25
function should_select_makeup() {
Etienne Freiss committed
26
    return partner_data.makeups_to_do > 0 || (partner_data.makeups_to_do > 0 && partner_data.is_associated_people === "True" && block_actions_for_attached_people === "False");
27 28
}

29 30
/* - Server requests */

31 32
/**
 * Proceed to shift exchange or registration
33
 * @param {int} new_shift_id
34 35 36
 */
function add_or_change_shift(new_shift_id) {
    if (is_time_to('change_shift')) {
37
        setTimeout(openModal, 100); // loading on
38

39 40 41 42 43
        if (partner_data.is_associated_people === "False") {
            tData = 'idNewShift=' + new_shift_id
                +'&idPartner=' + partner_data.partner_id
                + '&shift_type=' + partner_data.shift_type
                + '&verif_token=' + partner_data.verif_token;
Etienne Freiss committed
44
        } else if (partner_data.is_associated_people === "True" && block_actions_for_attached_people === "False") {
45 46 47 48 49 50 51
            tData = 'idNewShift=' + new_shift_id
                +'&idPartner=' + partner_data.parent_id
                + '&shift_type=' + partner_data.shift_type
                + '&verif_token=' + partner_data.parent_verif_token;
        } else {
            return false;
        }
52 53 54

        if (selected_shift === null) {
            tUrl = '/shifts/add_shift';
55 56 57
            if (partner_data.makeups_to_do > 0) {
                tData += '&is_makeup=1';
            }
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        } else {
            tUrl = '/shifts/change_shift';
            tData = tData + '&idOldShift='+ selected_shift.shift_id[0] +'&idRegister=' + selected_shift.id;
        }

        $.ajax({
            type: 'POST',
            url: tUrl,
            dataType:"json",
            data: tData,
            timeout: 3000,
            success: function(data) {
                if (data.result) {
                    // Decrement makeups to do if needed
                    if (partner_data.makeups_to_do > 0) {
                        partner_data.makeups_to_do = parseInt(partner_data.makeups_to_do, 10) - 1;

                        if (partner_data.makeups_to_do === 0) {
                            $("#need_to_select_makeups_message").hide();
                        } else {
                            $(".makeups_nb").text(partner_data.makeups_to_do);
                        }
                    }

                    let msg = "Parfait! ";
83 84 85 86

                    msg += (selected_shift === null)
                        ? "Le service choisi a été ajouté."
                        : "Le service a été échangé.";
87 88 89 90 91 92 93 94 95 96

                    selected_shift = null;

                    // Refetch partner shifts list & update DOM
                    load_partner_shifts(partner_data.concerned_partner_id)
                        .then(() => {
                            init_shifts_list();
                            closeModal();

                            setTimeout(() => {
97

98 99 100 101 102 103 104

                                alert(msg);
                            }, 100);
                        });

                    // Redraw calendar
                    calendar.refetchEvents();
105 106 107 108 109 110 111
                } else {
                    closeModal();
                    selected_shift = null;
                    alert(`Une erreur est survenue. ` +
                        `Il est néanmoins possible que la requête ait abouti, ` +
                        `veuillez patienter quelques secondes puis vérifier vos services enregistrés.`);

Etienne Freiss committed
112
                    // Refectch shifts anyway, if registration/exchange was still succesful
113 114
                    setTimeout(() => {
                        load_partner_shifts(partner_data.concerned_partner_id)
Etienne Freiss committed
115
                            .then(init_shifts_list);
116
                    }, 300);
117 118 119 120
                }
            },
            error: function(error) {
                closeModal();
121
                selected_shift = null;
122
                if (error.status === 400 && 'msg' in error.responseJSON && error.responseJSON.msg === "Old service in less than 24hours.") {
Thibault Grandjean committed
123
                    alert(`Désolé ! Le service que tu souhaites échanger démarre dans moins de 24h. ` +
124 125 126
                        `Afin de faciliter la logistique des services, il n'est plus possible de l'échanger. ` +
                        `Si tu ne peux vraiment pas venir, tu seras noté.e absent.e à ton service. ` +
                        `Tu devras alors sélectionner un service de rattrapage sur ton espace membre.`);
127 128 129 130 131
                } else if (error.status === 400 && 'msg' in error.responseJSON && error.responseJSON.msg === "Not allowed to change shift") {
                    alert(`Désolé ! Le service que tu souhaites échanger démarre dans trop peu de temps. ` +
                        `Afin de faciliter la logistique des services, il n'est plus possible de l'échanger. ` +
                        `Si tu ne peux vraiment pas venir, tu seras noté.e absent.e à ton service. ` +
                        `Tu devras alors sélectionner un service de rattrapage sur ton espace membre.`);
132
                } else if (error.status === 500 && 'msg' in error.responseJSON && error.responseJSON.msg === "Fail to create shift") {
133
                    // TODO differentiate error cases!
134 135 136
                    alert(`Une erreur est survenue. ` +
                        `Il est néanmoins possible que la requête ait abouti, ` +
                        `veuillez patienter quelques secondes puis vérifier vos services enregistrés.`);
137
                } else if (error.status === 400 && 'msg' in error.responseJSON && error.responseJSON.msg === "Bad arguments") {
138 139 140
                    alert(`Une erreur est survenue. ` +
                        `Il est néanmoins possible que la requête ait abouti, ` +
                        `veuillez patienter quelques secondes puis vérifier vos services enregistrés.`);
141
                } else {
Damien Moulard committed
142 143
                    alert(`Une erreur est survenue. ` +
                        `Il est néanmoins possible que la requête ait abouti, ` +
144 145 146 147 148 149 150 151 152 153
                        `veuillez patienter quelques secondes puis vérifier vos services enregistrés.`);
                }

                // Refectch shifts anyway, if registration/exchange was still succesful
                setTimeout(() => {
                    load_partner_shifts(partner_data.concerned_partner_id)
                        .then(init_shifts_list);
                }, 300);
            }
        });
154 155
        adding_mode = false;
        $('#start_adding_shift').prop('disabled', false);
156
    }
Damien Moulard committed
157 158

    return null;
159 160
}

161 162 163 164 165 166 167
/**
 * Send request to delete (cancel) a shift registration.
 * @param {Int} shift_registration_id shift registration to cancel
 */
function delete_shift_registration(shift_registration_id) {
    if (is_time_to('delete_shift_registration')) {
        openModal();
Damien Moulard committed
168

169 170 171
        tData = 'idPartner=' + partner_data.concerned_partner_id
                + '&idRegister=' + shift_registration_id
                + '&extra_shift_done=' + partner_data.extra_shift_done;
Damien Moulard committed
172

173 174
        if (partner_data.is_associated_people === "False") {
            tData += '&verif_token=' + partner_data.verif_token;
Damien Moulard committed
175
        } else if (partner_data.is_associated_people === "True" && block_actions_for_attached_people === "False") {
176 177 178 179
            tData += '&verif_token=' + partner_data.parent_verif_token;
        } else {
            return false;
        }
Damien Moulard committed
180

181 182 183 184 185 186 187 188
        $.ajax({
            type: 'POST',
            url: "/shifts/cancel_shift",
            dataType:"json",
            data: tData,
            timeout: 3000,
            success: function() {
                partner_data.extra_shift_done -= 1;
Damien Moulard committed
189

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
                // Refetch partner shifts list & update DOM
                load_partner_shifts(partner_data.concerned_partner_id)
                    .then(() => {
                        init_shifts_list();

                        if (partner_data.extra_shift_done > 0) {
                            $(".extra_shift_done").text(partner_data.extra_shift_done);
                            init_delete_registration_buttons();
                        } else {
                            $("#can_delete_future_registrations_area").hide();
                            $(".delete_registration_button").off();
                            $(".delete_registration_button").hide();
                        }

                        closeModal();
Damien Moulard committed
205

206 207 208 209
                        setTimeout(() => {
                            alert("La présence a bien été annulée !");
                        }, 100);
                    });
Damien Moulard committed
210

211 212 213 214 215 216 217 218 219
                // Redraw calendar
                calendar.refetchEvents();
            },
            error: function() {
                closeModal();
                alert("Une erreur est survenue.");
            }
        });
    }
Damien Moulard committed
220 221

    return null;
222 223 224 225 226 227 228
}

/**
 * Proceed affecting a shift registration to a/both member(s) of a pair
 * @param {string} partner
 * @param {string} shift_id
 */
Damien Moulard committed
229
function affect_shift(partner, shift_id) {
Etienne Freiss committed
230
    if (is_time_to('affect_shift', 1000)) {
231 232 233 234
        tData = 'idShiftRegistration=' + shift_id
            +'&idPartner=' + partner_data.partner_id
            + '&affected_partner=' + partner
            + '&verif_token=' + partner_data.verif_token;
Damien Moulard committed
235

236
        tUrl = '/shifts/affect_shift';
Damien Moulard committed
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        $.ajax({
            type: 'POST',
            url: tUrl,
            dataType:"json",
            data: tData,
            timeout: 3000,
            success: function() {
                load_partner_shifts(partner_data.concerned_partner_id)
                    .then(() => {
                        init_shifts_list();
                        modal.find(".btn-modal-ok").show();
                        closeModal();
                    });
            },
            error: function() {
                init_shifts_list();
                modal.find(".btn-modal-ok").show();
                closeModal();
Damien Moulard committed
256

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                alert(`Une erreur est survenue. ` +
                    `Il est néanmoins possible que la requête ait abouti, ` +
                    `veuillez patienter quelques secondes puis vérifier vos services enregistrés.`);
            }
        });
    }
}

/**
 * Reset a member extra_shift_done to 0
 */
function offer_extra_shift() {
    if (is_time_to('offer_extra_shift')) {
        openModal();

        $.ajax({
            type: 'POST',
            url: "/members_space/offer_extra_shift",
            dataType:"json",
            data: {
                partner_id: partner_data.concerned_partner_id
            },
            timeout: 3000,
            success: function() {
281
                partner_data.extra_shift_done -= 1;
Damien Moulard committed
282

283
                $("#can_delete_future_registrations_area").hide();
284 285 286
                $(".delete_registration_button").off();
                $(".delete_registration_button").hide();

287 288 289 290 291 292 293 294 295 296 297 298 299
                closeModal();
                alert("Don de service effectué");
            },
            error: function() {
                closeModal();
                alert("Une erreur est survenue");
            }
        });
    }
}

/* - DOM */

300 301 302 303 304 305 306 307 308
function init_shifts_list() {
    $(".loading-incoming-shifts").hide();
    $("#shifts_list").show();

    if (incoming_shifts.length === 0) {
        $("#shifts_list").text("Aucun service à venir...");
    } else {
        $("#shifts_list").empty();

309
        for (let shift of incoming_shifts) {
310
            let shift_line_template = $("#selectable_shift_line_template");
Félicie committed
311
            let datetime_shift_start = new Date(shift.date_begin.replace(/\s/, 'T'));
312 313 314 315 316 317

            let f_date_shift_start = datetime_shift_start.toLocaleDateString("fr-fr", date_options);

            f_date_shift_start = f_date_shift_start.charAt(0).toUpperCase() + f_date_shift_start.slice(1);

            shift_line_template.find(".shift_line_date").text(f_date_shift_start);
318 319
            shift_line_template.find(".shift_line_time").text(datetime_shift_start.toLocaleTimeString("fr-fr", time_options));

320
            // Disable or not
Etienne Freiss committed
321 322 323
            shift_line_template.find(".selectable_shift_line").removeClass("btn--primary");
            shift_line_template.find(".selectable_shift_line").removeClass("btn");
            shift_line_template.find(".selectable_shift_line").removeClass("btn--warning");
Damien Moulard committed
324

325
            if (!can_exchange_shifts()) {
326 327
                shift_line_template.find(".selectable_shift_line").addClass("btn");
                shift_line_template.find(".checkbox").prop("disabled", "disabled");
328
                $('#start_adding_shift').prop('disabled', true);
329
            } else {
Etienne Freiss committed
330 331 332 333 334 335 336 337 338
                if (shift.is_makeup==true) {
                    shift_line_template.find(".selectable_shift_line").addClass("btn--warning");
                    shift_line_template.find(".checkbox").prop("disabled", false);
                    shift_line_template.find(".checkbox").prop("value", shift.id);
                } else {
                    shift_line_template.find(".selectable_shift_line").addClass("btn--primary");
                    shift_line_template.find(".checkbox").prop("disabled", false);
                    shift_line_template.find(".checkbox").prop("value", shift.id);
                }
339
            }
340
            // Set assign shift button
Etienne Freiss committed
341
            if (partner_data.associated_partner_id === "False" && partner_data.parent_id === "False") {
342
                shift_line_template.find('.affect_associate_registered').hide();
Etienne Freiss committed
343
            } else {
344 345 346 347 348 349
                if (!can_exchange_shifts()) {
                    shift_line_template.find('.affect_associate_registered').hide();
                } else {
                    shift_line_template.find('.affect_associate_registered').show();
                }

Damien Moulard committed
350 351
                shift_line_template.find('.affect_associate_registered').closest(".shift_line_container")
                    .attr('id', 'shift_id_'+shift.id);
Etienne Freiss committed
352 353
                if (shift.associate_registered==="both") {
                    shift_line_template.find('.affect_associate_registered').text("Les deux");
Etienne Freiss committed
354
                    shift_line_template.find('.affect_associate_registered').addClass('btn--success');
Etienne Freiss committed
355
                } else if (shift.associate_registered==="partner") {
Etienne Freiss committed
356
                    shift_line_template.find('.affect_associate_registered').addClass('btn--success');
Etienne Freiss committed
357 358 359 360
                    if (partner_data.associated_partner_id !== "False") {
                        shift_line_template.find('.affect_associate_registered').text(partner_data.name);
                    } else {
                        shift_line_template.find('.affect_associate_registered').text(partner_data.parent_name);
Etienne Freiss committed
361
                    }
Etienne Freiss committed
362 363

                } else if (shift.associate_registered==="associate") {
Etienne Freiss committed
364
                    shift_line_template.find('.affect_associate_registered').addClass('btn--success');
Etienne Freiss committed
365 366 367 368
                    if (partner_data.associated_partner_id !== "False") {
                        shift_line_template.find('.affect_associate_registered').text(partner_data.associated_partner_name);
                    } else {
                        shift_line_template.find('.affect_associate_registered').text(partner_data.name);
Etienne Freiss committed
369
                    }
Etienne Freiss committed
370 371
                } else {
                    shift_line_template.find('.affect_associate_registered').text("A déterminer");
Etienne Freiss committed
372
                    shift_line_template.find('.affect_associate_registered').addClass('btn--danger');
Etienne Freiss committed
373
                }
Etienne Freiss committed
374
            }
Etienne Freiss committed
375

376 377 378 379
            // Set delete registration button if shift isn't a makeup
            if (partner_data.extra_shift_done > 0 && shift.is_makeup === false) {
                if (shift_line_template.find(".delete_registration_button").length === 0) {
                    let delete_reg_button_template = $("#delete_registration_button_template");
Damien Moulard committed
380

381
                    shift_line_template.find(".shift_line_extra_actions").append(delete_reg_button_template.html());
Etienne Freiss committed
382
                }
383 384
            } else {
                shift_line_template.find(".delete_registration_button").remove();
Etienne Freiss committed
385
            }
Etienne Freiss committed
386

387
            $("#shifts_list").append(shift_line_template.html());
Etienne Freiss committed
388 389
            shift_line_template.find('.affect_associate_registered').removeClass('btn--danger');
            shift_line_template.find('.affect_associate_registered').removeClass('btn--success');
390
        }
391 392 393 394

        $(".selectable_shift_line").on("click", function(e) {
            if (can_exchange_shifts()) {
                let cb = $(this).find(".checkbox");
395

396 397 398 399
                // Select checkbox on click on button
                if (!$(e.target).hasClass("checkbox")) {
                    cb.prop("checked", !cb.prop("checked"));
                }
400

401 402 403 404 405
                if (cb.prop("checked")) {
                    selected_shift = incoming_shifts.find(s => s.id == cb.prop("value"));
                } else {
                    selected_shift = null;
                }
406

407
                // Unselect other checkboxes
408 409
                if ($(this).find(".checkbox")
                    .prop("checked")) {
410 411 412 413 414 415 416 417
                    for (let cb_item of $("#shifts_list").find(".checkbox")) {
                        if (cb.prop("value") !== $(cb_item).prop("value")) {
                            $(cb_item).prop("checked", false);
                        }
                    }
                }
            }
        });
Etienne Freiss committed
418

Etienne Freiss committed
419
        $(".affect_associate_registered").on("click", function() {
Etienne Freiss committed
420
            // Display modal
Damien Moulard committed
421 422
            let id = $(this).closest(".shift_line_container")
                .attr('id')
Etienne Freiss committed
423
                .split('_')[2];
Etienne Freiss committed
424
            let modal_template = $("#modal_affect_shift");
Etienne Freiss committed
425 426

            if (partner_data.associated_partner_id != "False") {
Etienne Freiss committed
427 428
                modal_template.find("#shift_partner").text(partner_data.name);
                modal_template.find("#shift_associate").text(partner_data.associated_partner_name);
Etienne Freiss committed
429

Etienne Freiss committed
430
            } else {
Etienne Freiss committed
431 432
                modal_template.find("#shift_partner").text(partner_data.parent_name);
                modal_template.find("#shift_associate").text(partner_data.name);
Etienne Freiss committed
433
            }
Etienne Freiss committed
434

Etienne Freiss committed
435 436 437
            openModal(
                modal_template.html(),
                () => {
438
                    modal.find(".btn-modal-ok").show();
Etienne Freiss committed
439
                },
440
                "Valider", true, true,
Etienne Freiss committed
441
                () => {
442 443
                    modal.find(".btn-modal-ok").show();
                }
Etienne Freiss committed
444
            );
Etienne Freiss committed
445 446 447

            modal.find('#shift_partner').on("click", function() {
                affect_shift("partner", id);
Etienne Freiss committed
448
            });
Etienne Freiss committed
449 450
            modal.find('#shift_associate').on("click", function() {
                affect_shift("associate", id);
Etienne Freiss committed
451
            });
Etienne Freiss committed
452 453
            modal.find('#shift_both').on("click", function() {
                affect_shift("both", id);
Etienne Freiss committed
454 455
            });

Etienne Freiss committed
456
            modal.find(".btn-modal-ok").hide();
Etienne Freiss committed
457
        });
458 459 460
    }
}

461 462 463 464
/**
 * Inits the page when the calendar is displayed
 */
function init_calendar_page() {
Damien Moulard committed
465
    let template_explanations = $("#calendar_explaination_template");
466
    let event_src = '/shifts/get_list_shift_calendar/' + partner_data.concerned_partner_id;
467
    if (vw <= 992) {
468
        $(".loading-calendar").show();
Damien Moulard committed
469 470 471 472 473 474 475

        $("#calendar_explaination_area").hide();
        $("#calendar_explaination_button").on("click", () => {
            openModal(
                template_explanations.html(),
                closeModal,
                "J'ai compris"
Damien Moulard committed
476
            );
Etienne Freiss committed
477 478
        })
            .show();
Damien Moulard committed
479 480
    } else {
        $("#calendar_explaination_button").hide();
Etienne Freiss committed
481 482
        $("#calendar_explaination_area").html(template_explanations.html())
            .show();
483 484
    }

485 486 487 488 489 490 491
    if (incoming_shifts !== null) {
        init_shifts_list();
    } else {
        load_partner_shifts(partner_data.concerned_partner_id)
            .then(init_shifts_list);
    }

492
    if (should_select_makeup()) {
493 494 495 496
        $(".makeups_nb").text(partner_data.makeups_to_do);
        $("#need_to_select_makeups_message").show();
    }

497 498
    if (partner_data.extra_shift_done > 0) {
        $(".extra_shift_done").text(partner_data.extra_shift_done);
499
        $("#can_delete_future_registrations_area").css('display', 'flex');
500 501 502

        $("#offer_extra_shift").on("click", () => {
            openModal(
503
                "<p>Je ne souhaite pas supprimer un service futur.</p>",
504 505 506
                offer_extra_shift,
                "Confirmer",
                false
507 508 509 510
            );
        });

        $("#delete_future_registration").on("click", init_delete_registration_buttons);
511
    }
512 513 514 515

    let default_initial_view = "";
    let header_toolbar = {};

516 517 518 519 520 521 522 523
    if (vw <= 768) {
        default_initial_view = 'listWeek';
        header_toolbar = {
            left: 'title',
            center: 'listWeek,timeGridDay',
            right: 'prev,next today'
        };
    } else if (vw <=992) {
524 525 526
        default_initial_view = 'listWeek';
        header_toolbar = {
            left: 'title',
527
            center: 'dayGridMonth,listWeek,timeGridDay',
528
            right: 'prev,next today'
529
        };
530 531 532 533 534 535
    } else {
        default_initial_view = 'dayGridMonth';
        header_toolbar = {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,listWeek,timeGridDay'
536
        };
537
    }
538

539
    const hidden_days = days_to_hide.length > 0 ? $.map(days_to_hide.split(", "), Number) : [];
540 541

    const calendarEl = document.getElementById('calendar');
542

543
    calendar = new FullCalendar.Calendar(calendarEl, {
544 545
        locale: 'fr',
        initialView: default_initial_view,
546 547 548
        headerToolbar: header_toolbar,
        buttonText: {
            list: "Semaine"
549 550 551 552 553 554 555 556 557
        },
        eventTimeFormat: {
            hour: '2-digit',
            minute: '2-digit'
        },
        allDaySlot: false,
        contentHeight: "auto",
        eventDisplay: "block",
        hiddenDays: hidden_days,
558
        events: event_src,
559
        eventClick: function(info) {
Etienne Freiss committed
560
            if (!$(info.el).hasClass("shift_booked") && !$(info.el).hasClass("shift_booked_makeup")) {
561 562 563 564 565
                const new_shift_id = info.event.id;

                // Set new shift
                const datetime_new_shift = info.event.start;
                let new_shift_date = datetime_new_shift.toLocaleDateString("fr-fr", date_options);
566 567
                let new_shift_time = datetime_new_shift.toLocaleTimeString("fr-fr", time_options);

568 569 570 571 572 573 574 575 576 577 578
                function showInfoAboutSelectedShift(modal_template, new_shift_date, new_shift_time) {
                    var new_shift_week_day = new_shift_date.replace(/ .*/,'');
                    if (on_picking_shift_template_msg.startsWith(new_shift_week_day + " " + new_shift_time + " ")) {
                        modal_template.find(".on_picking_shift_template_msg").text(
                            on_picking_shift_template_msg.replace(new_shift_week_day + " " + new_shift_time + " ","")
                        );
                    } else {
                        modal_template.find(".on_picking_shift_template_msg").text("");
                    }
                }

579 580 581 582 583
                if (selected_shift !== null && can_exchange_shifts()) {
                    /* shift exchange */
                    // Set old shift
                    let datetime_old_shift = new Date(selected_shift.date_begin);
                    let old_shift_date = datetime_old_shift.toLocaleDateString("fr-fr", date_options);
584
                    let old_shift_time = datetime_old_shift.toLocaleTimeString("fr-fr", time_options);
585 586 587

                    // Display modal
                    let modal_template = $("#modal_shift_exchange_template");
588

589 590 591 592
                    modal_template.find(".date_old_shift").text(old_shift_date);
                    modal_template.find(".time_old_shift").text(old_shift_time);
                    modal_template.find(".date_new_shift").text(new_shift_date);
                    modal_template.find(".time_new_shift").text(new_shift_time);
593

594 595
                    showInfoAboutSelectedShift(modal_template, new_shift_date, new_shift_time);

596 597 598 599 600 601 602 603
                    openModal(
                        modal_template.html(),
                        () => {
                            add_or_change_shift(new_shift_id);
                        },
                        "Valider"
                    );
                } else if (selected_shift === null && can_exchange_shifts()) {
604 605 606 607 608 609 610 611 612 613
                    if (adding_mode === false) {
                        /* could exchange shift but no old shift selected */
                        openModal(
                            "Je dois sélectionner un service à échanger.",
                            closeModal,
                            "J'ai compris"
                        );
                    } else {
                        // Display modal
                        let modal_template = $("#modal_add_shift_template");
Damien Moulard committed
614

615 616
                        modal_template.find(".date_new_shift").text(new_shift_date);
                        modal_template.find(".time_new_shift").text(new_shift_time);
617 618 619

                        showInfoAboutSelectedShift(modal_template, new_shift_date, new_shift_time);

620 621 622 623 624 625 626 627
                        openModal(
                            modal_template.html(),
                            () => {
                                add_or_change_shift(new_shift_id);
                            },
                            "Valider"
                        );
                    }
Damien Moulard committed
628

629
                } else if (should_select_makeup()) {
630
                    /* choose a makeup service */
631
                    // Check if selected new shift is in less than extension end
Damien Moulard committed
632 633
                    if (partner_data.date_delay_stop !== 'False') {
                        date_partner_delay_stop = new Date(partner_data.date_delay_stop);
Damien Moulard committed
634
                        if (datetime_new_shift > date_partner_delay_stop) {
Damien Moulard committed
635
                            let msg = `Vous avez jusqu'au ${date_partner_delay_stop.toLocaleDateString("fr-fr", date_options)} ` +
636
                                        `pour sélectionner un rattrapage (soit une période de ${extension_duration} mois depuis votre absence).`;
Damien Moulard committed
637

Damien Moulard committed
638
                            alert(msg);
Damien Moulard committed
639

Damien Moulard committed
640 641 642
                            return;
                        }
                    }
643
                    let modal_template = $("#modal_add_shift_template");
644

645 646 647
                    modal_template.find(".date_new_shift").text(new_shift_date);
                    modal_template.find(".time_new_shift").text(new_shift_time);

648 649
                    showInfoAboutSelectedShift(modal_template, new_shift_date, new_shift_time);

650 651 652 653 654 655 656 657 658 659 660
                    openModal(
                        modal_template.html(),
                        () => {
                            add_or_change_shift(new_shift_id);
                        },
                        "Valider"
                    );
                }
            }
        },
        eventDidMount: function() {
661 662 663
            // Calendar is hidden at first on mobile to hide header change when data is loaded
            $(".loading-calendar").hide();
            $("#calendar").show();
664

665 666 667 668
            if (vw <= 992) {
                $(".fc .fc-header-toolbar").addClass("resp-header-toolbar");
            } else {
                $(".fc .fc-header-toolbar").removeClass("resp-header-toolbar");
669
            }
670 671
        }
    });
672

673
    calendar.render();
674 675
}

676
async function init_read_only_calendar_page() {
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    let template_explanations = $("#calendar_explaination_template");

    if (vw <= 992) {
        $(".loading-calendar").show();

        $("#calendar_explaination_area").hide();
        $("#calendar_explaination_button").on("click", () => {
            openModal(
                template_explanations.html(),
                closeModal,
                "J'ai compris"
            );
        })
            .show();
    } else {
        $("#calendar_explaination_button").hide();
        $("#calendar_explaination_area").html(template_explanations.html())
            .show();
    }

    if (incoming_shifts !== null) {
        init_shifts_list();
    } else {
700 701
        await load_partner_shifts(partner_data.concerned_partner_id)
        init_shifts_list();
702 703 704 705 706 707 708 709 710 711 712 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
    }

    if (should_select_makeup()) {
        $(".makeups_nb").text(partner_data.makeups_to_do);
        $("#need_to_select_makeups_message").show();
    }

    let default_initial_view = "";
    let header_toolbar = {};

    if (vw <= 768) {
        default_initial_view = 'listWeek';
        header_toolbar = {
            left: 'title',
            center: 'listWeek,timeGridDay',
            right: 'prev,next today'
        };
    } else if (vw <=992) {
        default_initial_view = 'listWeek';
        header_toolbar = {
            left: 'title',
            center: 'dayGridMonth,listWeek,timeGridDay',
            right: 'prev,next today'
        };
    } else {
        default_initial_view = 'dayGridMonth';
        header_toolbar = {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,listWeek,timeGridDay'
        };
    }

    const hidden_days = days_to_hide.length > 0 ? $.map(days_to_hide.split(", "), Number) : [];

    const calendarEl = document.getElementById('read_only_calendar');
738 739 740 741 742 743 744 745 746 747
    let event_src = '/shifts/get_list_shift_calendar/' + partner_data.concerned_partner_id;
    if (partner_data.comite === "True") {
        let next_evts = []
        if (incoming_shifts.length > 0) {
            incoming_shifts.forEach((s) => {
                next_evts.push({id: s.id, title: 'Prélèvement 1 point', allDay: true, start: s.date_begin})
            });
        }
        event_src = next_evts
    }
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    calendar = new FullCalendar.Calendar(calendarEl, {
        locale: 'fr',
        initialView: default_initial_view,
        headerToolbar: header_toolbar,
        buttonText: {
            list: "Semaine"
        },
        eventTimeFormat: {
            hour: '2-digit',
            minute: '2-digit'
        },
        allDaySlot: false,
        contentHeight: "auto",
        eventDisplay: "block",
        hiddenDays: hidden_days,
763
        events: event_src,
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        eventDidMount: function() {
            // Calendar is hidden at first on mobile to hide header change when data is loaded
            $(".loading-calendar").hide();
            $("#calendar").show();

            if (vw <= 992) {
                $(".fc .fc-header-toolbar").addClass("resp-header-toolbar");
            } else {
                $(".fc .fc-header-toolbar").removeClass("resp-header-toolbar");
            }
        }
    });

    calendar.render();
}

Damien Moulard committed
780
function init_delete_registration_buttons() {
781
    $(".delete_registration_button").off();
782
    $(".delete_registration_button").hide();
783

784 785 786
    if (partner_data.extra_shift_done > 0) {
        $(".delete_registration_button").on("click", function() {
            let shift_name = $(this).closest("div")
Damien Moulard committed
787 788
                .parent()
                .parent()
789 790 791 792 793 794
                .find(".shift_line_date")
                .text()
                .trim();
            let shift_id = $(this).closest(".shift_line_container")
                .attr('id')
                .split('_')[2];
Damien Moulard committed
795

796 797 798 799 800 801 802 803 804
            openModal(
                `<p>Je m'apprête à supprimer ma présence au service du <b>${shift_name}</b></p>`,
                () => {
                    delete_shift_registration(shift_id);
                },
                "Confirmer",
                false
            );
        });
Damien Moulard committed
805

806 807
        $(".delete_registration_button").css('display', 'flex');
    }
808 809
}

810 811
function init_shifts_exchange() {
    $(".shifts_exchange_page_content").hide();
812
    vw = window.innerWidth;
813

814
    if (partner_data.cooperative_state === 'unsubscribed' || partner_data.cooperative_state === 'gone') {
815 816 817 818 819 820 821 822 823 824
        $("#unsuscribed_content").show();

        $(".unsuscribed_form_link")
            .show()
            .attr('href', unsuscribe_form_link)
            .on('click', function() {
                setTimeout(500, () => {
                    $(this).removeClass('active');
                });
            });
825 826
    } else if (
        partner_data.cooperative_state === 'suspended'
Damien Moulard committed
827
        && partner_data.can_have_delay === 'False') {
828
        let msg_template = $("#cant_have_delay_msg_template");
Damien Moulard committed
829 830 831

        $(".suspended_cant_have_delay_msg").html(msg_template.html());
        $("#suspended_cant_have_delay_content").show();
832 833 834 835 836 837 838 839 840

        $(".cant_have_delay_form_link")
            .show()
            .attr('href', member_cant_have_delay_form_link)
            .on('click', function() {
                setTimeout(500, () => {
                    $(this).removeClass('active');
                });
            });
841
    } else if (partner_data.comite === "True") {
842
        let msg_template = $("#comite_template");
Etienne Freiss committed
843

844 845
        $(".comite_content_msg").html(msg_template.html());
        $("#comite_content").show();
846
        init_read_only_calendar_page();
Etienne Freiss committed
847
    } else if (partner_data.cooperative_state === 'suspended'
848
                && partner_data.date_delay_stop === 'False') {
849
        $("#suspended_content .makeups_nb").text(partner_data.makeups_to_do);
Damien Moulard committed
850

851 852 853 854 855 856 857 858 859 860
        $("#suspended_content").show();

        $(".select_makeups").on('click', () => {
            openModal();
            // Create 6 month delay
            request_delay()
                .then(() => {
                    $("#suspended_content").hide();
                    $("#shifts_exchange_content").show();
                    closeModal();
861
                    init_calendar_page();
862 863 864 865 866 867
                });
        });
    } else {
        $("#shifts_exchange_content").show();
        init_calendar_page();
    }
868

869
    $('#start_adding_shift').click((c) => {
Damien Moulard committed
870 871 872 873 874 875 876 877 878 879 880
        openModal(
            "<p>Je souhaite sélectionner un service supplémentaire.</p>",
            () => {
                $(c.target).prop('disabled', true);
                adding_mode = true;
                closeModal();
            },
            "Confirmer",
            false
        );
    });
881

Etienne Freiss committed
882
    $(window).smartresize(function() {
Damien Moulard committed
883
        // only apply if a width threshold is passed
884
        if (
Etienne Freiss committed
885 886 887
            vw > 992 && window.innerWidth <= 992 ||
            vw <= 992 && window.innerWidth > 992 ||
            vw > 768 && window.innerWidth <= 768 ||
888 889 890 891 892 893 894
            vw <= 768 && window.innerWidth > 768
        ) {
            vw = window.innerWidth;
            init_calendar_page();
        } else {
            vw = window.innerWidth;
        }
895
    });
Thibault Grandjean committed
896
}