members-space.js 8.96 KB
Newer Older
1 2 3 4 5 6
/**
 * Common logic between pages
 */

var base_location = null,
    current_location = null,
7 8
    incoming_shifts = null,
    partner_history = null;
9 10

var date_options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
11
var time_options = {hour: '2-digit', minute:'2-digit'};
12

Damien Moulard committed
13 14 15 16 17
const possible_cooperative_state = {
    suspended: "Rattrapage",
    exempted: "Exempté.e",
    alert: "En alerte",
    up_to_date: "À jour",
18
    unsubscribed: "Désinscrit.e des créneaux",
Thibault Grandjean committed
19 20
    delay: "En délai",
    gone: "Parti.e"
Damien Moulard committed
21 22
};

23 24 25 26
/* - Data */

/**
 * Load the shifts the member is registered to
27
 * @param {int} partner_id either the members id, or its parent's if s.he's attached
28 29
 */
function load_partner_shifts(partner_id) {
30
    return new Promise((resolve) => {
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        $.ajax({
            type: 'GET',
            url: "/shifts/get_list_shift_partner/" + partner_id,
            dataType:"json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                incoming_shifts = data;
                resolve();
            },
            error: function(data) {
                err = {msg: "erreur serveur lors de la récupération des services", ctx: 'load_partner_shifts'};
                if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                    err.msg += ' : ' + data.responseJSON.error;
                }
46
                report_JS_error(err, 'members_space.index');
47 48 49 50 51 52 53 54 55 56 57 58

                closeModal();
                // TODO Notify
                alert('Erreur lors de la récupération de vos services.');
            }
        });
    });
}

/* - Navigation */

/**
Etienne Freiss committed
59
 * @param {String} page home | mes-infos | mes-services | echange-de-services | faq
60
 */
François committed
61
function goto(page) {
62 63 64 65 66 67 68 69 70 71
    if (window.location.pathname === base_location) {
        history.pushState({}, '', page);
    } else {
        history.replaceState({}, '', page);
    }
    update_dom();
}

/**
 * Define which html content to load from server depending on the window location
Damien Moulard committed
72 73
 *
 * WARNING: For the routing system to work,
74 75
 *          public urls (those the users will see & navigate to) must be different than the server urls used to fetch resources
 * (ex: public url: /members_space/mes-info ; server url: /members_space/my_info)
76 77 78 79 80 81
 */
function update_dom() {
    $(".nav_item").removeClass('active');

    if (window.location.pathname === base_location || window.location.pathname === base_location + "home") {
        current_location = "home";
François committed
82
        $("#main_content").load("/members_space/homepage", update_content);
83 84 85
        $("#nav_home").addClass("active");
    } else if (window.location.pathname === base_location + "mes-infos") {
        current_location = "my_info";
François committed
86
        $("#main_content").load("/members_space/my_info", update_content);
87 88 89
        $("#nav_my_info").addClass("active");
    } else if (window.location.pathname === base_location + "mes-services") {
        current_location = "my_shifts";
François committed
90
        $("#main_content").load("/members_space/my_shifts", update_content);
91
        $("#nav_my_shifts").addClass("active");
Etienne Freiss committed
92
    } else if (window.location.pathname === base_location + "faq") {
Damien Moulard committed
93
        current_location = "faq";
Etienne Freiss committed
94
        $("#main_content").load("/members_space/faqBDM", update_content);
Damien Moulard committed
95
        $("#nav_faq").addClass("active");
96 97
    } else if (window.location.pathname === base_location + "echange-de-services") {
        current_location = "shifts_exchange";
François committed
98
        $("#main_content").load("/members_space/shifts_exchange", update_content);
99 100
        $("#nav_shifts_exchange").addClass("active");
    } else {
François committed
101
        $("#main_content").load("/members_space/no_content");
102 103 104 105
    }
}

/**
Damien Moulard committed
106
 * Update the data displayed depending on the current location
107
 * (ex: insert personal data in the DOM when on the 'My Info' page)
108
 */
François committed
109
function update_content() {
110
    switch (current_location) {
François committed
111 112 113 114 115 116 117 118 119
    case 'home':
        init_home();
        break;
    case 'my_info':
        init_my_info();
        break;
    case 'my_shifts':
        init_my_shifts();
        break;
120 121 122
    case 'faq':
        init_faq();
        break;
François committed
123 124 125 126 127 128
    case 'shifts_exchange':
        init_shifts_exchange();
        break;
    default:
        console.log(`Bad input`);
    }
129
}
130

131 132 133 134 135
/* - Shifts */

/**
 * Prepare a shift line to insert into the DOM.
 * Is used in: Home - My Shifts tile ; My Shifts - Incoming shifts section
François committed
136
 *
137 138 139 140 141
 * @param {String} date_begin beginning datetime of the shift
 * @returns JQuery node object of the formatted template
 */
function prepare_shift_line_template(date_begin) {
    let shift_line_template = $("#shift_line_template");
Félicie committed
142
    let datetime_shift_start = new Date(date_begin.replace(/\s/, 'T'));
143 144

    let f_date_shift_start = datetime_shift_start.toLocaleDateString("fr-fr", date_options);
François committed
145

146
    f_date_shift_start = f_date_shift_start.charAt(0).toUpperCase() + f_date_shift_start.slice(1);
François committed
147

148
    shift_line_template.find(".shift_line_date").text(f_date_shift_start);
149
    shift_line_template.find(".shift_line_time").text(datetime_shift_start.toLocaleTimeString("fr-fr", time_options));
Damien Moulard committed
150

151 152 153
    return shift_line_template;
}

Damien Moulard committed
154 155 156 157 158 159 160
/* - Member info */

/**
 * Init common personal data between screens
 */
function init_my_info_data() {
    $(".choose_makeups").off();
161
    $(".choose_makeups").hide();
162
    $(".remove_future_registration").off();
163
    $(".remove_future_registration").hide();
Damien Moulard committed
164
    $(".unsuscribed_form_link").off();
165
    $(".unsuscribed_form_link").hide();
Damien Moulard committed
166 167 168

    $(".member_shift_name").text(partner_data.regular_shift_name);

169 170
    let pns = partner_data.name.split(" - ");
    let name = pns.length > 1 ? pns[1] : pns[0];
Damien Moulard committed
171

172
    $(".member_name").text(name);
Damien Moulard committed
173 174 175 176 177 178

    // Status related
    $(".member_status")
        .text(possible_cooperative_state[partner_data.cooperative_state])
        .addClass("member_status_" + partner_data.cooperative_state);

179
    if (partner_data.cooperative_state === 'unsubscribed' || partner_data.cooperative_state === 'gone') {
Damien Moulard committed
180 181 182 183 184 185 186 187 188 189
        $(".member_shift_name").text('X');

        $(".unsuscribed_form_link")
            .show()
            .attr('href', unsuscribe_form_link)
            .on('click', function() {
                setTimeout(500, () => {
                    $(this).removeClass('active');
                });
            });
190
    } else if (partner_data.cooperative_state === 'exempted') {
François committed
191
        const d = new Date(Date.parse(partner_data.leave_stop_date));
192
        const f_date_leave_stop = d.getDate()+'/'+("0" + (d.getMonth() + 1)).slice(-2)+'/'+d.getFullYear();
193

194 195
        $(".leave_date_stop").text(f_date_leave_stop);
        $(".leave_date_stop_container").show();
Damien Moulard committed
196
    }
Damien Moulard committed
197

198 199 200 201
    if (
        partner_data.makeups_to_do > 0
        && partner_data.cooperative_state !== 'unsubscribed'
    ) {
Damien Moulard committed
202
        $(".choose_makeups").show();
203
        $(".choose_makeups").on('click', () => {
Damien Moulard committed
204
                goto('echange-de-services');
205
        });
Damien Moulard committed
206 207
    }

208 209 210 211 212 213 214
    if (partner_data.extra_shift_done > 0) {
        $(".remove_future_registration").show();
        $(".remove_future_registration").on('click', () => {
            goto('echange-de-services');
        });
    }

Damien Moulard committed
215 216 217
    $(".member_coop_number").text(partner_data.barcode_base);
}

218 219
$(document).ready(function() {
    $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
220

221 222 223 224 225 226
    // If partner is associated (attached), display the pair's main partner shift data
    partner_data.concerned_partner_id =
        (partner_data.is_associated_people === "True")
            ? partner_data.parent_id
            : partner_data.partner_id;

Damien Moulard committed
227
    partner_data.is_in_association =
228 229 230 231
        partner_data.is_associated_people === "True" || partner_data.associated_partner_id !== "False";

    // For associated people, their parent name is attached in their display name
    let partner_name_split = partner_data.name.split(', ');
Damien Moulard committed
232

233 234
    partner_data.name = partner_name_split[partner_name_split.length - 1];

235
    base_location = (app_env === 'dev') ? '/members_space/' : '/';
236
    update_dom();
Damien Moulard committed
237 238 239 240

    window.onpopstate = function() {
        update_dom();
    };
241
});
242

François committed
243
(function($, sr) {
244 245 246
    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
Damien Moulard committed
247
        var timeout = null;
François committed
248

249 250
        return function debounced () {
            var obj = this, args = arguments;
François committed
251

252 253 254 255
            function delayed () {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
François committed
256 257
            }

258 259 260 261
            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);
François committed
262

263 264
            timeout = setTimeout(delayed, threshold || 100);
        };
François committed
265 266 267 268 269 270 271
    };
    // smartresize

    jQuery.fn[sr] = function(fn) {
        return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr);
    };

Félicie committed
272
})(jQuery, 'smartresize');
Félicie committed
273 274 275 276 277 278 279

function display_messages_for_service_exchange_24h_before() {
    if (block_service_exchange_24h_before === "False") {
        $(".free_service_exchange").show(); 
    } else {
        $(".block_service_exchange").show();
    }
Félicie committed
280
}