members.js 20.5 KB
Newer Older
Administrator committed
1 2
//The magic code to add show/hide custom event triggers
(function ($) {
3 4 5 6 7
    $.each([
        'show',
        'hide',
        'css'
    ], function (i, ev) {
Administrator committed
8
        var el = $.fn[ev];
9

Administrator committed
10
        $.fn[ev] = function () {
11 12 13
            this.trigger(ev);

            return el.apply(this, arguments);
Administrator committed
14
        };
15
    });
Administrator committed
16 17 18 19 20 21 22
})(jQuery);

var current_displayed_member = null,
    results = null,
    loaded_services = null,
    selected_service = null,
    last_search_time = null,
23 24
    rattrapage_ou_volant = null,
    timeout_counter = null;
Administrator committed
25 26 27 28 29 30 31 32 33 34 35 36
var search_button = $('.btn--primary.search');
var loading2 = $('.loading2');
var search_field = $('input[name="search_string"]');
var shift_title = $('#current_shift_title');
var shift_members = $('#current_shift_members');
var service_validation = $('#service_validation');
var validation_last_call = 0;
var rattrapage_wanted = $('[data-next="rattrapage_1"]');
var rattrapage_validation = $('#rattrapage_validation');
var webcam_is_attached = false;
var photo_advice = $('#photo_advice');
var photo_studio = $('#photo_studio');
37
var coop_info = $('.coop-info');
Administrator committed
38

39
let no_pict_msg = $('#no-picture-msg');
Administrator committed
40 41 42 43 44 45 46 47

var pages = {
    'first_page' : $('#first_page'),
    'shopping_entry' : $('#shopping_entry'),
    'service_entry' : $('#service_entry'),
    'service_entry_validation': $('#service_entry_validation'),
    'service_entry_success': $('#service_entry_success'),
    'rattrapage_1' : $('#rattrapage_1'),
48
    'rattrapage_2' : $('#rattrapage_2')
Administrator committed
49

50
};
Administrator committed
51 52 53 54 55 56 57 58 59 60 61

var html_elts = {
    member_slide : $('#member_slide'),
    barcode_base : $('#barcode_base'),
    barcode : $('#barcode'),
    name : $('#name'),
    image_medium : $('#image_medium'),
    real_capture : $('#real_capture'),
    multi_results : $('#multi_results_preview'),
    cooperative_state : $('#cooperative_state'),
    next_shifts : $('#next_shifts')
62
};
Administrator committed
63

64
var chars = []; //input chars buffer
Administrator committed
65 66

function fill_member_slide(member) {
67
    no_pict_msg.hide();
Administrator committed
68 69
    current_displayed_member = member;
    html_elts.next_shifts.html('');
70 71
    coop_info.removeClass('b_red');
    coop_info.removeClass('b_orange');
Administrator committed
72 73
    if (member.barcode) {
        html_elts.barcode.JsBarcode()
74 75 76
            .options({font: "OCR-B"}) // Will affect all barcodes
            .EAN13(member.barcode, {fontSize: 14, textMargin: 0})
            .render();
Administrator committed
77 78 79
    }
    html_elts.barcode_base.html(member.barcode_base);
    html_elts.name.html(member.name);
80 81
    var img_src = '';

82
    if (member.image_medium) {
Administrator committed
83 84
        img_src = 'data:image/'+member.image_extension+';base64,'+member.image_medium;
    } else {
85
        img_src = "/static/img/pas-de-photo.png";
86
        no_pict_msg.show();
Administrator committed
87 88
    }
    html_elts.image_medium.html('<img src="'+img_src+'" width="128" />');
89 90 91
    html_elts.cooperative_state.html(member.cooperative_state);
    if (member.cooperative_state == 'Désinscrit(e)') coop_info.addClass('b_red');
    else if (member.cooperative_state == 'En alerte' || member.cooperative_state == 'Délai accordé') coop_info.addClass('b_orange');
Administrator committed
92 93 94 95

    if (member.shifts.length > 0) {
        html_elts.next_shifts.append('Prochains services : ');
        var slist = $('<ul>');
96

Administrator committed
97 98
        for (i in member.shifts) {
            var s = $('<li>').text(member.shifts[i].start);
99 100

            slist.append(s);
Administrator committed
101 102 103 104
        }
        html_elts.next_shifts.append(slist);
    }
    html_elts.member_slide.show();
105 106 107 108 109 110
    setTimeout(
        function() {
            html_elts.member_slide.hide();
        },
        180000
    );
Administrator committed
111 112
}

113
function search_box_clear_html_elts() {
Administrator committed
114 115 116

    for (elt in html_elts)
        if (elt != 'member_slide')
117
            html_elts[elt].html('');
Administrator committed
118 119 120 121 122 123 124
    html_elts.barcode.removeAttr('src');
}

function preview_member_search_select() {
    var clicked = $(this);
    var context = clicked.closest('section[id]').attr('id');
    var selected_member = results[clicked.data('i')];
125

Administrator committed
126 127 128 129 130 131 132 133 134 135
    if (context == "shopping_entry") {
        fill_member_slide(selected_member);
    } else if (context == "rattrapage_1") {
        current_displayed_member = selected_member;
        fill_rattrapage_2();
        goto_page(pages.rattrapage_2);

    }
}

136
function preview_results() {
Administrator committed
137

138
    for (i in results) {
Administrator committed
139

140 141 142
        if (results[i].is_member != false || results[i].is_associated_people != false) {
            var m = $('<button>').attr('data-i', i)
                .text(results[i].name);
Administrator committed
143

144 145
            html_elts.multi_results.append(m);
        }
Administrator committed
146

147 148

    }
Administrator committed
149 150 151 152 153

}

function canSearch() {
    var answer = true;
154

Administrator committed
155 156 157 158
    if (last_search_time != null) {
        if (new Date().getTime() - last_search_time < 5000)
            answer = false;
    }
159

Administrator committed
160 161 162
    return answer;
}

163
function search_member(force_search = false) {
164
    chars = []; // to prevent false "as barcode-reader" input
165
    if (canSearch() || force_search) {
Administrator committed
166 167 168 169 170

        html_elts.member_slide.hide();
        search_box_clear_html_elts();
        current_displayed_member = null;

171
        var search_seed = search_field.val() || '';
Administrator committed
172 173 174 175 176 177 178 179 180

        if (search_seed.length > 0) {
            last_search_time = new Date().getTime();
            search_button.hide();
            loading2.show();
            $.ajax({
                url: '/members/search/' + search_seed,
                dataType : 'json'
            })
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
                .done(function(rData) {
                    var nb = rData.res.length || 0;

                    if (nb > 0) {
                        if (nb == 1) {
                            var context = search_field.closest('section[id]')
                                .attr('id');

                            if (context == 'rattrapage_1') {
                                current_displayed_member = rData.res[0];
                                fill_rattrapage_2();
                                goto_page(pages.rattrapage_2);
                            } else {
                                fill_member_slide(rData.res[0]);
                            }

Administrator committed
197 198
                        } else {

199 200 201
                            results = rData.res;
                            preview_results();
                        }
Administrator committed
202
                    } else {
203
                        alert('Aucun résultat');
Administrator committed
204
                    }
205 206 207
                    loading2.hide();
                    search_button.show();
                });
Administrator committed
208 209 210 211 212 213 214 215 216
        }

    }


}

function get_simple_service_name(s) {
    var simple_name = s.name;
217
    var reg = new RegExp('([a-z]+). - [0-9:]+ ?-? ?([a-z]*)', 'i');
218

Administrator committed
219 220 221
    if (reg.exec(s.name)) {
        var wd = RegExp.$1;
        var p = RegExp.$2;
222

Administrator committed
223
        if (p == 'Balar') {
224
            p = 'BDM';
Administrator committed
225
        } else if (p == 'Cleme') {
226
            p = 'Magasin';
Administrator committed
227
        } else {
228
            p = 'Magasin';
Administrator committed
229 230 231
        }
        var start = new Date(Date.parse(s.date_begin_tz));
        var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
232 233
        var end_time = new Date(Date.parse(s.date_end_tz)).toTimeString()
            .replace(/^(\d{2}:\d{2}).*/, "$1");
Administrator committed
234
        var start_time = start.toTimeString().replace(/^(\d{2}:\d{2}).*/, "$1");
235

Administrator committed
236 237
        simple_name = 'Service au ' + p;
        simple_name += ' le '+ start.toLocaleDateString('fr-FR', options);
238
        simple_name += ' de ' + start_time + ' à ' + end_time;
Administrator committed
239 240
        simple_name += ' (' + wd[0] + ') ';
    } else {
241
        simple_name = '???';
Administrator committed
242
    }
243

Administrator committed
244 245 246 247
    return simple_name;
}

function move_service_validation_to(page) {
248
    service_validation.find('.btn').data('stid', '0');
Administrator committed
249
    page.find('.validation_wrapper')
250
        .append(service_validation.detach());
Administrator committed
251 252 253 254 255
}

function fill_service_entry(s) {
    selected_service = s;
    shift_title.text(get_simple_service_name(s));
256
    shift_title.show();
Administrator committed
257
    var m_list = 'Personne n\'est inscrit à ce service.';
258 259 260 261

    if (s.members) {
        m_list = '<ul class="members_list">';
        $.each(s.members, function(i, e) {
Administrator committed
262 263
            var li_class = "btn";
            var li_data = "";
264

Administrator committed
265
            if (e.state == "done") {
266
                li_class += "--inverse";
Administrator committed
267 268 269 270 271 272
            } else {
                li_data = ' data-rid="'+e.id+'" data-mid="'+e.partner_id[0]+'"';
            }
            m_list += '<li class="'+li_class+'" '+li_data+'>';
            m_list += e.partner_id[1];
            m_list += '</li>';
273 274
        });
        m_list += '</ul>';
Administrator committed
275 276 277 278 279 280 281 282 283 284 285 286 287

    }
    rattrapage_ou_volant = null;
    shift_members.html(m_list);
    rattrapage_wanted.show();
}

function clean_service_entry() {
    rattrapage_wanted.hide();
    shift_title.text('');
    shift_members.html('');
}

288
function fill_service_validation(rid, coop_num_name, coop_id) {
Administrator committed
289
    var coop_name_elts = coop_num_name.split(' - ');
290

Administrator committed
291 292 293
    pages.service_entry_validation.find('span.member_name').text(coop_name_elts[1]);
    move_service_validation_to(pages.service_entry_validation);
    service_validation.find('.btn')
294 295 296
        .data('rid', rid)
        .data('sid', selected_service.id)
        .data('mid', coop_id);
Administrator committed
297 298 299

}

300 301 302 303
function select_possible_service() {
    var clicked = $(this);
    var id = clicked.data('id');

Administrator committed
304 305
    if (loaded_services && !isNaN(id)) {
        var selected = null;
306 307

        $.each(loaded_services, function(i, e) {
Administrator committed
308 309 310 311 312 313 314 315 316 317 318 319 320
            if (e.id == id) {
                selected = e;
            }
        });
        if (selected) {

            fill_service_entry(selected);
            pages.service_entry.find('.info').empty();
            pages.service_entry.find('h1').text('Qui es-tu ? (ou personne remplacée)');
        }
    }

}
321
function get_service_entry_data() {
Administrator committed
322
    var info_place = pages.service_entry.find('.info');
323

Administrator committed
324
    info_place.text('Chargement du service actuel...');
325
    shift_title.hide();
Administrator committed
326 327 328 329

    var now = new Date();
    var time_param = now.toISOString();
    var offset = now.getTimezoneOffset();
330

331
    if (/([^/]+)$/.exec(window.location)) {
332
        time_param = RegExp.$1.replace('%20', 'T') + 'Z';
Administrator committed
333 334 335 336
        offset = 0;
    }
    //time_param = '2018-10-29T09:45:18.37'
    $.ajax({
337
        url: '/members/services_at_time/'+time_param
Administrator committed
338
                    +'/'+ offset,
339
        dataType : 'json'
Administrator committed
340
    })
341
        .done(function(rData) {
Administrator committed
342
        //console.log(rData);
343 344
            info_place.text('');
            var page_title = pages.service_entry.find('h1');
Administrator committed
345

346 347 348 349 350
            page_title.text('Qui es-tu ?');
            try {
                if (rData.res.length == 0) {
                    info_place.text('La période pendant laquelle il est possible de s\'enregistrer est close.');
                    page_title.text('');
Administrator committed
351 352

                } else {
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
                    if (rData.res.length > 1) {
                        loaded_services = rData.res;
                        var message = rData.res.length + ' possibilités : <br />';

                        for (i in rData.res) {
                            var s_name = get_simple_service_name(rData.res[i]);

                            message += '<a data-id="' + rData.res[i].id + '" class="btn">';
                            message += s_name + ' </a><br/>';
                        }
                        info_place.html(message);
                        page_title.text('Quel est ton service ?');

                    } else {
                        fill_service_entry(rData.res[0]);
                    }
Administrator committed
369
                }
370 371
            } catch (e) {
                console.log(e);
Administrator committed
372
            }
373
        });
Administrator committed
374 375 376 377 378 379
}

function fill_service_entry_sucess(member) {
    pages.service_entry_success.find('span.member_name').text(member.name);

    var points = member.display_std_points;
380

Administrator committed
381 382 383 384 385
    if (member.in_ftop_team == true) {
        points = member.display_ftop_points;
    }
    pages.service_entry_success.find('span.points').text(points);
    var compteur_div = pages.service_entry_success.find('.compteur');
386

Administrator committed
387 388 389 390 391 392
    if (points < 0 || rattrapage_ou_volant) {
        compteur_div.show();
    } else {
        compteur_div.hide();
    }

393
    var next_shift = '???';
Administrator committed
394
    var service_verb = 'est prévu';
395

Administrator committed
396 397
    if (member.next_shift) {
        if (member.in_ftop_team == true
398
            && member.next_shift.shift_type == "ftop") {
Administrator committed
399
            var start_elts = member.next_shift.start.split(' à ');
400

Administrator committed
401 402 403 404 405 406 407 408 409 410 411 412 413
            next_shift = start_elts[0];
            service_verb = 'est à faire avant';
        } else {
            next_shift = member.next_shift.start;
        }
    }
    pages.service_entry_success.find('span.next_shift').text(next_shift);
    pages.service_entry_success.find('span.service_verb').text(service_verb);


}

function record_service_presence() {
414 415 416
    var d = new Date();
    var elapsed_since_last_call = d.getTime() - validation_last_call;

Administrator committed
417 418
    if (elapsed_since_last_call > 10000) {
        loading2.show();
419 420
        validation_last_call = d.getTime();
        var clicked = service_validation.find('.btn');
Administrator committed
421 422 423 424
        var rid = clicked.data('rid');
        var mid = clicked.data('mid');
        var sid = clicked.data('sid');
        var stid = clicked.data('stid');
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

        post_form(
            '/members/service_presence/',
            {'mid': mid, 'rid': rid, 'sid': sid, 'stid' : stid},
            function(err, rData) {
                if (!err) {
                    var res = rData.res;
                    var next = (res.update == 'ok')
                                  ||(res.rattrapage && !isNaN(res.rattrapage));

                    if (next) {
                        fill_service_entry_sucess(rData.res.member);
                        goto_page(pages.service_entry_success);
                    } else if (rData.res.error) {
                        alert(rData.res.error);
                    }
                }
                loading2.hide();
            }
Administrator committed
444 445 446 447
        );
    }
}

448 449
function fill_rattrapage_2() {
    pages.rattrapage_2.find('span.member_name').text(current_displayed_member.name);
Administrator committed
450 451
    var msg = "Bienvenue pour ton rattrapage !";
    var shift_ticket_id = selected_service.shift_ticket_ids[0];
452

Administrator committed
453 454 455 456 457 458 459 460 461 462 463 464
    if (current_displayed_member.in_ftop_team == true) {
        msg ="Bienvenue dans ce service !";
        if (selected_service.shift_ticket_ids[1])
            shift_ticket_id = selected_service.shift_ticket_ids[1];
    }
    if (current_displayed_member.state == 'unsubscribed') {
        msg = "Tu es en désincrit.e ... La situation doit être réglée avez le Bureau des Membres";
    } else {
        move_service_validation_to(pages.rattrapage_2);


        service_validation.find('.btn')
465 466 467 468
            .data('rid', 0)
            .data('sid', selected_service.id)
            .data('stid', shift_ticket_id)
            .data('mid', current_displayed_member.id);
Administrator committed
469 470 471 472 473 474
    }
    pages.rattrapage_2.find('h2').text(msg);


}

475
function init_webcam() {
Administrator committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
    try {

        /*
        Webcam.set({
            width: $('#img_width').val(),
            height: $('#img_height').val(),
            dest_width: $('#img_dest_width').val(),
            dest_height: $('#img_dest_height').val(),
            crop_width: $('#img_crop_width').val(),
            crop_height: $('#img_crop_height').val(),
            image_format: 'jpeg',
            jpeg_quality: 90

        });
        */
        Webcam.set({
            width: 320,
            height: 240,
            dest_width: 640,
            dest_height: 480,
            crop_width: $('#crop_width').val(),
            crop_height: 480,
            image_format: 'jpeg',
            jpeg_quality: 90

        });
502
        Webcam.attach('#webcam');
Administrator committed
503 504


505
    } catch (e) {
Administrator committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        //console.log(e)
    }

}


function preview_snapshot() {

    // freeze camera so user can preview current frame
    Webcam.freeze();

    // swap button sets
    document.getElementById('pre_take_buttons').style.display = 'none';
    document.getElementById('post_take_buttons').style.display = '';
}

function cancel_preview() {
    // cancel preview freeze and return to live camera view
    Webcam.unfreeze();

    // swap buttons back to first set
    document.getElementById('pre_take_buttons').style.display = '';
    document.getElementById('post_take_buttons').style.display = 'none';
}

function save_photo() {
    // actually snap photo (from preview freeze) and store it
533
    Webcam.snap(function(data_uri) {
Administrator committed
534

535
        if (/data:image\/jpeg;base64,(.+)/.exec(data_uri)) {
Administrator committed
536 537
            image_code = RegExp.$1;
            if (current_displayed_member != null) {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
                cancel_preview();
                photo_studio.hide();
                html_elts.image_medium.html('<img src="/static/img/Pedro_luis_romani_ruiz.gif" />');
                $.post(
                    '/members/save_photo/'+current_displayed_member.id,
                    {'photo':image_code,
                        'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
                    }
                )
                    .done(function(rData) {
                        if (rData.res == true) {
                            $.get('/members/image/'+ current_displayed_member.id)
                                .done(function(img_b64) {
                                    var img_src = 'data:image/jpeg;base64,'+img_b64;

                                    html_elts.image_medium.html('<img src="'+img_src+'" />');
Administrator committed
554

555 556
                                });
                        }
Administrator committed
557 558 559 560 561 562 563 564 565 566
                    });
            } else {
                html_elts.real_capture.html('<img src="'+data_uri+'" />');
            }



        }


567
    });
Administrator committed
568 569
}

570
function search_input_listing(e) {
Administrator committed
571 572 573 574 575 576 577 578
    e = e || window.event;
    if (e.keyCode == '13') {
        // enter
        e.preventDefault();
        search_member();
    }
}

579
function move_search_box(from, to) {
Administrator committed
580 581 582
    search_box_clear_html_elts();
    search_field.val('');
    var search_box = from.find('.search_box_wrapper section').detach();
583

Administrator committed
584 585 586 587 588
    if (search_box.length > 0)
        search_box.appendTo(to.find('.search_box_wrapper'));
}

function goto_page(jquery_page_selected) {
589 590
    $.each(pages, function(i, e) {
        e.hide();
Administrator committed
591
    });
592
    jquery_page_selected.css('display', 'grid');
Administrator committed
593 594
}

595 596 597 598 599 600 601
function timeout_to_homepage() {
    if (timeout_counter) clearTimeout(timeout_counter);
    timeout_counter = setTimeout(function() {
        goto_page(pages.first_page);
    }, 40000);
}

Administrator committed
602
$('button.search').click(search_member);
603
search_field.keyup(search_input_listing);
Administrator committed
604

605 606
$('.btn[data-next]').click(function() {
    var clicked = $(this);
Administrator committed
607 608 609 610
    var next_page = $('#' + clicked.data('next'));

    if (clicked.data('type')) {
        var type = clicked.data('type');
611

Administrator committed
612 613 614 615 616
        if (type == "rattrapage" || type == "volant") {
            rattrapage_ou_volant = type;
        }
    }

617 618
    if (next_page.length > 0) {
        goto_page(next_page);
Administrator committed
619 620 621 622
    }

});

623 624 625 626 627 628
service_validation.on("click", ".btn", record_service_presence);

shift_members.on("click", '.btn[data-rid]', function() {
    var clicked = $(this);
    var rid = clicked.data('rid');
    var mid = clicked.data('mid');
Administrator committed
629 630 631 632 633 634

    goto_page(pages.service_entry_validation);
    fill_service_validation(rid, clicked.text(), mid);

});

635
pages.shopping_entry.on('css', function(e) {
Administrator committed
636 637 638 639 640 641 642
    photo_advice.hide();
    photo_studio.hide();
    search_box_clear_html_elts();
    html_elts.member_slide.hide();
    move_search_box(pages.rattrapage_1, pages.shopping_entry);
});

643
pages.service_entry.on('css', function(e) {
Administrator committed
644 645 646 647 648 649
    photo_advice.hide();
    photo_studio.hide();
    clean_service_entry();
    get_service_entry_data();
});

650
pages.rattrapage_1.on('css', function(e) {
Administrator committed
651 652
    search_box_clear_html_elts();
    var msg = "Vous venez pour un rattrapage.";
653

Administrator committed
654 655 656 657 658 659 660
    if (rattrapage_ou_volant == "volant") {
        msg = "Vous venez en tant que volant.";
    }
    pages.rattrapage_1.find('h1').text(msg);
    move_search_box(pages.shopping_entry, pages.rattrapage_1);

});
661 662
pages.service_entry.on("click", '.info a[data-id]', select_possible_service);
$("#multi_results_preview").on("click", 'button', preview_member_search_select);
Administrator committed
663 664 665 666 667
html_elts.image_medium.on('click', function() {
    if (webcam_is_attached == true) {
        // photo_advice.show();
        photo_studio.show();
    }
668
});
Administrator committed
669 670

$(document).ready(function() {
671 672 673 674 675 676 677 678 679 680 681
    var shopping_entry_btn = $('a[data-next="shopping_entry"]');

    shopping_entry_btn.on('click', function() {
        // Always focus on search field
        search_field.focus();

        // Return to homepage after 40 seconds
        timeout_to_homepage();
    });

    // Force barcode-reader to search member
Administrator committed
682 683 684 685 686
    $(window).keypress(function(e) {
        if (e.which >= 48 && e.which <= 57) {
            chars.push(String.fromCharCode(e.which));
        }

687
        timeout_to_homepage();
688

689 690 691
        setTimeout(function() {
            if (chars.length >= 13) {
                var barcode = chars.join("");
Administrator committed
692

693 694 695 696 697 698
                if (!isNaN(barcode)) {
                    chars = [];
                    goto_page(pages.shopping_entry);
                    search_field.val(barcode);
                    last_search_time = null;
                    search_member(true);
Administrator committed
699
                }
700
            }
Administrator committed
701

702
        }, 300);
Administrator committed
703
    });
704

705 706 707 708 709
    init_webcam();
    $('#crop_width').change(function() {
        Webcam.reset();
        init_webcam();
    });
Administrator committed
710 711 712

});

713 714
Webcam.on('live', function() {
    webcam_is_attached = true;
Administrator committed
715
});