members.js 30.4 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
})(jQuery);

var current_displayed_member = null,
19
    operator = null,
Administrator committed
20 21 22 23
    results = null,
    loaded_services = null,
    selected_service = null,
    last_search_time = null,
24 25
    rattrapage_ou_volant = null,
    timeout_counter = null;
Administrator committed
26
var search_button = $('.btn--primary.search');
27 28
var sm_search_member_button = $('#sm_search_member_button'),
    sm_search_member_input = $('#sm_search_member_input');
Administrator committed
29 30 31 32 33
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');
Etienne Freiss committed
34
var associated_service_validation = $('#associated_service_validation');
Administrator committed
35 36 37 38 39
var validation_last_call = 0;
var rattrapage_wanted = $('[data-next="rattrapage_1"]');
var webcam_is_attached = false;
var photo_advice = $('#photo_advice');
var photo_studio = $('#photo_studio');
40
var coop_info = $('.coop-info');
Etienne Freiss committed
41
var service_data = null;
Administrator committed
42

43
const missed_begin_msg = $('#missed_begin_msg').html();
44
const current_shift_process_data_actions = $('#current_shift_process_data_actions');
45

46
let no_pict_msg = $('#no-picture-msg');
Administrator committed
47 48 49 50 51 52 53 54

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'),
55
    'rattrapage_2' : $('#rattrapage_2')
Administrator committed
56

57
};
Administrator committed
58 59 60 61 62 63 64 65 66 67

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'),
68
    status_explanation: $('#status_explanation'),
Administrator committed
69
    next_shifts : $('#next_shifts')
70
};
Administrator committed
71

72
var chars = []; //input chars buffer
Administrator committed
73

74 75 76 77
var reset_shift_process_actions_zone = function() {
    current_shift_process_data_actions.off('click', 'a');
    current_shift_process_data_actions.hide();
    current_shift_process_data_actions.empty();
Damien Moulard committed
78
};
79

Administrator committed
80
function fill_member_slide(member) {
81
    no_pict_msg.hide();
Administrator committed
82 83
    current_displayed_member = member;
    html_elts.next_shifts.html('');
84 85
    coop_info.removeClass('b_red');
    coop_info.removeClass('b_orange');
Administrator committed
86 87
    if (member.barcode) {
        html_elts.barcode.JsBarcode()
88 89 90
            .options({font: "OCR-B"}) // Will affect all barcodes
            .EAN13(member.barcode, {fontSize: 14, textMargin: 0})
            .render();
Administrator committed
91 92 93
    }
    html_elts.barcode_base.html(member.barcode_base);
    html_elts.name.html(member.name);
94 95
    var img_src = '';

96
    if (member.image_medium) {
Administrator committed
97 98
        img_src = 'data:image/'+member.image_extension+';base64,'+member.image_medium;
    } else {
99
        img_src = "/static/img/pas-de-photo.png";
100
        no_pict_msg.show();
Administrator committed
101 102
    }
    html_elts.image_medium.html('<img src="'+img_src+'" width="128" />');
103
    html_elts.cooperative_state.html(member.cooperative_state);
104
    if (member.cooperative_state == 'Suspendu(e)') {
Damien Moulard committed
105 106 107
        var explanation = "Tu as dû manquer un service! Pour pouvoir faire tes courses aujourd'hui, tu dois d'abord sélectionner un rattrapage sur ton espace membre.";

        html_elts.status_explanation.html(explanation);
Thibault Grandjean committed
108
    }
109 110

    if (member.cooperative_state == 'Désinscrit(e)' || member.cooperative_state == 'Parti(e)' || member.cooperative_state == 'Rattrapage' || member.cooperative_state == 'Suspendu(e)') {
111 112 113 114
        coop_info.addClass('b_red');
    }
    else if (member.cooperative_state == 'En alerte' || member.cooperative_state == 'Délai accordé') {
        coop_info.addClass('b_yellow')
115
    } 
Administrator committed
116 117 118 119 120 121

    if (member.shifts.length > 0) {
        html_elts.next_shifts.append('Prochains services : ');
        var slist = $('<ul>');
        for (i in member.shifts) {
            var s = $('<li>').text(member.shifts[i].start);
122 123

            slist.append(s);
Administrator committed
124 125 126 127
        }
        html_elts.next_shifts.append(slist);
    }
    html_elts.member_slide.show();
128 129 130 131 132 133
    setTimeout(
        function() {
            html_elts.member_slide.hide();
        },
        180000
    );
Administrator committed
134 135
}

136
function search_box_clear_html_elts() {
Administrator committed
137 138 139

    for (elt in html_elts)
        if (elt != 'member_slide')
140
            html_elts[elt].html('');
Administrator committed
141 142 143 144 145 146 147
    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')];
148

Administrator committed
149 150 151 152 153 154 155 156 157 158
    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);

    }
}

159
function preview_results() {
Administrator committed
160

161
    for (i in results) {
Administrator committed
162

Félicie committed
163
        if (results[i].is_member != false) {
Félicie committed
164 165
            var m = $('<button class="button_is_member">').attr('data-i', i)
                .text(results[i].barcode_base + ' - ' + results[i].name);
Félicie committed
166 167 168 169

            html_elts.multi_results.append(m);
        }
        if (results[i].is_associated_people != false) {
Félicie committed
170 171 172 173
            m = $('<button class="button_is_associated_people"></button_is_member>').attr('data-i', i)
                .text('B ' + results[i].barcode_base + ' - ' + results[i].name);


Administrator committed
174

175 176
            html_elts.multi_results.append(m);
        }
Administrator committed
177

178 179

    }
Administrator committed
180 181 182 183 184

}

function canSearch() {
    var answer = true;
185

Administrator committed
186 187 188 189
    if (last_search_time != null) {
        if (new Date().getTime() - last_search_time < 5000)
            answer = false;
    }
190

Administrator committed
191 192 193
    return answer;
}

194
function search_member(force_search = false) {
195
    chars = []; // to prevent false "as barcode-reader" input
196
    operator = null;
197
    if (canSearch() || force_search) {
Administrator committed
198 199 200 201 202

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

203
        var search_seed = search_field.val() || '';
Administrator committed
204 205 206 207 208 209 210 211 212

        if (search_seed.length > 0) {
            last_search_time = new Date().getTime();
            search_button.hide();
            loading2.show();
            $.ajax({
                url: '/members/search/' + search_seed,
                dataType : 'json'
            })
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                .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
229 230
                        } else {

231 232 233
                            results = rData.res;
                            preview_results();
                        }
Administrator committed
234
                    } else {
235
                        alert('Aucun résultat');
Administrator committed
236
                    }
237 238 239
                    loading2.hide();
                    search_button.show();
                });
Administrator committed
240 241 242 243 244 245 246 247 248
        }

    }


}

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

Administrator committed
251 252 253
    if (reg.exec(s.name)) {
        var wd = RegExp.$1;
        var p = RegExp.$2;
254

Administrator committed
255
        if (p == 'Balar') {
256
            p = 'BDM';
Administrator committed
257
        } else if (p == 'Cleme') {
258
            p = 'Magasin';
Administrator committed
259
        } else {
260
            p = 'Magasin';
Administrator committed
261 262 263
        }
        var start = new Date(Date.parse(s.date_begin_tz));
        var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
264 265
        var end_time = new Date(Date.parse(s.date_end_tz)).toTimeString()
            .replace(/^(\d{2}:\d{2}).*/, "$1");
Administrator committed
266
        var start_time = start.toTimeString().replace(/^(\d{2}:\d{2}).*/, "$1");
267

Administrator committed
268 269
        simple_name = 'Service au ' + p;
        simple_name += ' le '+ start.toLocaleDateString('fr-FR', options);
270
        simple_name += ' de ' + start_time + ' à ' + end_time;
Administrator committed
271 272
        simple_name += ' (' + wd[0] + ') ';
    } else {
273
        simple_name = '???';
Administrator committed
274
    }
275

Administrator committed
276 277 278 279
    return simple_name;
}

function move_service_validation_to(page) {
Etienne Freiss committed
280
    service_data.stid=0;
Administrator committed
281
    page.find('.validation_wrapper')
282
        .append(service_validation.detach());
Administrator committed
283 284 285 286 287
}

function fill_service_entry(s) {
    selected_service = s;
    shift_title.text(get_simple_service_name(s));
288
    shift_title.show();
Administrator committed
289
    var m_list = 'Personne n\'est inscrit à ce service.';
290 291 292

    if (s.members) {
        m_list = '<ul class="members_list">';
293 294 295
        // if (typeof s.late != "undefined" && s.late == true) {
        //     m_list = '<ul class="members_list late">';
        // }
296 297 298
        if (s.state == 'done') {
            m_list = '<ul class="members_list done">';
        }
299
        $.each(s.members, function(i, e) {
Administrator committed
300 301
            var li_class = "btn";
            var li_data = "";
302

Etienne Freiss committed
303
            if (e.state == "done" && coop_is_connected()) {
Etienne Freiss committed
304
                li_data = ' data-rid="'+e.id+'" data-mid="'+e.partner_id[0]+'"';
305
                li_class += "--inverse";
306 307 308
                if (e.is_late == true) {
                    li_class += " late";
                }
Etienne Freiss committed
309 310 311
                if (e.associate_registered=='both') {
                    li_class += " both";
                }
Etienne Freiss committed
312 313 314 315 316 317
            } else if (e.state == "done" && !coop_is_connected()) {
                li_data = ' data-rid="'+e.id+'" data-mid="'+e.partner_id[0]+'"';
                li_class += "--inverse not_connected";
                if (e.is_late == true) {
                    li_class += " late";
                }
Administrator committed
318 319 320
            } else {
                li_data = ' data-rid="'+e.id+'" data-mid="'+e.partner_id[0]+'"';
            }
321 322 323
            if (s.state == 'done') {
                li_data += ' disabled ';
            }
Administrator committed
324 325 326
            m_list += '<li class="'+li_class+'" '+li_data+'>';
            m_list += e.partner_id[1];
            m_list += '</li>';
327 328
        });
        m_list += '</ul>';
Administrator committed
329 330

    }
331 332 333 334 335
    if (coop_is_connected()) {
        // Add shift process data
        reset_shift_process_actions_zone();
        if (s.state == 'draft' || s.state == 'confirm') {
            let btn = $('<a>').addClass('btn btn--primary txtcenter')
Damien Moulard committed
336 337 338
                .text('Enregistrer les absences / présences')
                .attr('id', 'record_shift_absences');

339
            current_shift_process_data_actions.append(btn);
Damien Moulard committed
340
            current_shift_process_data_actions.on('click', '#record_shift_absences', function() {
341 342
                msg = "<p>Lancer le traitement des présences et absences de ce service</p>";
                openModal(msg, function() {
Damien Moulard committed
343
                    btn.attr('disabled', 'true');
344 345 346 347 348
                    try {
                        $.ajax({
                            url: '/members/record_shift_absences/' + s.id,
                            dataType : 'json'
                        })
Damien Moulard committed
349 350 351 352 353 354 355 356 357 358
                            .done(function(rData) {
                                if (typeof rData.res.update !== "undefined" && rData.res.update == true) {
                                    enqueue_message_for_next_loading("Données de présences traitées.");
                                    location.reload();
                                } else {
                                    closeModal();
                                    btn.removeAttr('disabled');
                                    alert(JSON.stringify(rData.res));
                                }
                            });
359 360 361 362
                    } catch (e) {
                        console.log(e);
                    }
                }, 'Confirmer');
Damien Moulard committed
363

364 365 366 367
            });
        } else {
            current_shift_process_data_actions.append("<em>Traitement des présences : " + s.state + "</em>");
        }
Damien Moulard committed
368

369 370
        current_shift_process_data_actions.show();
    }
Administrator committed
371 372 373 374 375
    rattrapage_ou_volant = null;
    shift_members.html(m_list);
    rattrapage_wanted.show();
}

376
function clean_search_for_easy_validate_zone() {
377 378
    $('.search_member_results_area').hide();
    $('.search_member_results').empty();
379 380 381 382 383 384
    sm_search_member_input.val('');
    operator = null;
}

function clean_service_entry() {
    clean_search_for_easy_validate_zone();
Administrator committed
385 386 387 388 389
    rattrapage_wanted.hide();
    shift_title.text('');
    shift_members.html('');
}

390
function fill_service_validation(rid, coop_num_name, coop_id) {
Administrator committed
391
    var coop_name_elts = coop_num_name.split(' - ');
392

Etienne Freiss committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
    for (member of loaded_services[0].members) {
        if (member.id ==rid) {
            if (member.associate_name) {
                pages.service_entry_validation.find('#service_validation').hide();
                pages.service_entry_validation.find('#associated_service_validation').show();
                pages.service_entry_validation.find('#associated_btn').text(member.associate_name);
                pages.service_entry_validation.find('#partner_btn').text(member.partner_name);

            } else {
                pages.service_entry_validation.find('#associated_service_validation').hide();
                pages.service_entry_validation.find('#service_validation').show();

            }
        }
    }
    service_data={
        rid: rid,
        sid: selected_service.id,
        mid: coop_id};


Administrator committed
414 415 416 417
    pages.service_entry_validation.find('span.member_name').text(coop_name_elts[1]);
    move_service_validation_to(pages.service_entry_validation);
}

418 419 420 421
function select_possible_service() {
    var clicked = $(this);
    var id = clicked.data('id');

Administrator committed
422 423
    if (loaded_services && !isNaN(id)) {
        var selected = null;
424 425

        $.each(loaded_services, function(i, e) {
Administrator committed
426 427 428 429 430 431 432 433 434 435 436 437 438
            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)');
        }
    }

}
439
function get_service_entry_data() {
Administrator committed
440
    var info_place = pages.service_entry.find('.info');
441

Administrator committed
442
    info_place.text('Chargement du service actuel...');
443
    shift_title.hide();
Administrator committed
444 445 446 447

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

449
    if (/([^/]+)$/.exec(window.location)) {
450
        time_param = RegExp.$1.replace('%20', 'T') + 'Z';
Administrator committed
451 452 453 454
        offset = 0;
    }
    //time_param = '2018-10-29T09:45:18.37'
    $.ajax({
455
        url: '/members/services_at_time/'+time_param
Administrator committed
456
                    +'/'+ offset,
457
        dataType : 'json'
Administrator committed
458
    })
459 460
        .done(function(rData) {
            info_place.text('');
461 462
            reset_shift_process_actions_zone();

463
            var page_title = pages.service_entry.find('h1');
Administrator committed
464

465 466 467
            page_title.text('Qui es-tu ?');
            try {
                if (rData.res.length == 0) {
468 469
                    info_place.html(missed_begin_msg);
                    page_title.html('');
Administrator committed
470 471

                } else {
472 473 474 475 476 477 478 479 480 481 482 483 484 485
                    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 {
Etienne Freiss committed
486
                        loaded_services = rData.res;
487 488
                        fill_service_entry(rData.res[0]);
                    }
Administrator committed
489
                }
490 491
            } catch (e) {
                console.log(e);
Administrator committed
492
            }
493
        });
Administrator committed
494 495 496 497 498 499
}

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

    var points = member.display_std_points;
500

501
    if (member.shift_type == 'ftop') {
Administrator committed
502 503 504 505
        points = member.display_ftop_points;
    }
    pages.service_entry_success.find('span.points').text(points);
    var compteur_div = pages.service_entry_success.find('.compteur');
506

Administrator committed
507 508 509 510 511 512
    if (points < 0 || rattrapage_ou_volant) {
        compteur_div.show();
    } else {
        compteur_div.hide();
    }

513
    var next_shift = '???';
Administrator committed
514
    var service_verb = 'est prévu';
515

Administrator committed
516
    if (member.next_shift) {
517
        if (member.shift_type == 'ftop'
518
            && member.next_shift.shift_type == "ftop") {
Administrator committed
519
            var start_elts = member.next_shift.start.split(' à ');
520

Administrator committed
521 522 523 524 525 526 527 528 529 530 531 532
            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);


}

Etienne Freiss committed
533
function record_service_presence(e) {
534 535 536
    var d = new Date();
    var elapsed_since_last_call = d.getTime() - validation_last_call;

Etienne Freiss committed
537
    if (elapsed_since_last_call > 1000) {
Administrator committed
538
        loading2.show();
539
        validation_last_call = d.getTime();
Etienne Freiss committed
540 541 542 543
        var rid = service_data.rid;
        var mid = service_data.mid;
        var sid = service_data.sid;
        var stid = service_data.stid;
544 545 546

        post_form(
            '/members/service_presence/',
Etienne Freiss committed
547
            {'mid': mid, 'rid': rid, 'sid': sid, 'stid' : stid, 'cancel': false, 'type': e.data.type},
548 549 550 551 552
            function(err, rData) {
                if (!err) {
                    var res = rData.res;
                    var next = (res.update == 'ok')
                                  ||(res.rattrapage && !isNaN(res.rattrapage));
François committed
553

554 555 556 557 558
                    if (next) {
                        fill_service_entry_sucess(rData.res.member);
                        goto_page(pages.service_entry_success);
                    } else if (rData.res.error) {
                        alert(rData.res.error);
559
                    } else {
François committed
560
                        alert("Un problème est survenu. S'il persiste merci de le signaler à un responsable du magasin.");
561
                    }
François committed
562
                }
563 564
                loading2.hide();
            }
Administrator committed
565 566 567 568
        );
    }
}

Etienne Freiss committed
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
function cancel_service_presence(mid, rid) {
    var d = new Date();
    var elapsed_since_last_call = d.getTime() - validation_last_call;

    if (elapsed_since_last_call > 1000) {
        loading2.show();
        validation_last_call = d.getTime();
        var sid = selected_service.id;

        post_form(
            '/members/service_presence/',
            {'mid': mid, 'rid': rid, 'sid': sid, 'stid' : 0, 'cancel': true},
            function(err) {
                if (!err) {
                    get_service_entry_data();
                }
                loading2.hide();
            }
        );
    }
}

591 592
function fill_rattrapage_2() {
    pages.rattrapage_2.find('span.member_name').text(current_displayed_member.name);
Administrator committed
593 594
    var msg = "Bienvenue pour ton rattrapage !";
    var shift_ticket_id = selected_service.shift_ticket_ids[0];
595

596
    if (current_displayed_member.shift_type == 'ftop') {
Administrator committed
597 598 599 600 601 602 603 604
        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);
Etienne Freiss committed
605 606 607 608 609
        service_data = {
            rid : 0,
            sid : selected_service.id,
            stid : shift_ticket_id,
            mid : current_displayed_member.id};
Administrator committed
610 611 612 613 614 615
    }
    pages.rattrapage_2.find('h2').text(msg);


}

616
function init_webcam() {
Administrator committed
617 618 619 620 621 622 623 624 625 626 627 628
    try {
        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

        });
629
        Webcam.attach('#webcam');
Administrator committed
630 631


632
    } catch (e) {
Administrator committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
        //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
660
    Webcam.snap(function(data_uri) {
Administrator committed
661

662
        if (/data:image\/jpeg;base64,(.+)/.exec(data_uri)) {
Administrator committed
663 664
            image_code = RegExp.$1;
            if (current_displayed_member != null) {
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
                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
681

682 683
                                });
                        }
Administrator committed
684 685 686 687 688 689 690 691 692 693
                    });
            } else {
                html_elts.real_capture.html('<img src="'+data_uri+'" />');
            }



        }


694
    });
Administrator committed
695 696
}

697
function search_input_listing(e) {
Administrator committed
698 699 700 701 702 703 704 705
    e = e || window.event;
    if (e.keyCode == '13') {
        // enter
        e.preventDefault();
        search_member();
    }
}

706
function move_search_box(from, to) {
Administrator committed
707 708 709
    search_box_clear_html_elts();
    search_field.val('');
    var search_box = from.find('.search_box_wrapper section').detach();
710

Administrator committed
711 712 713 714 715
    if (search_box.length > 0)
        search_box.appendTo(to.find('.search_box_wrapper'));
}

function goto_page(jquery_page_selected) {
716 717
    $.each(pages, function(i, e) {
        e.hide();
Administrator committed
718
    });
719
    jquery_page_selected.css('display', 'grid');
Administrator committed
720 721
}

722 723 724 725 726 727 728
function timeout_to_homepage() {
    if (timeout_counter) clearTimeout(timeout_counter);
    timeout_counter = setTimeout(function() {
        goto_page(pages.first_page);
    }, 40000);
}

Administrator committed
729
$('button.search').click(search_member);
730
search_field.keyup(search_input_listing);
Administrator committed
731

732 733
$('.btn[data-next]').click(function() {
    var clicked = $(this);
Administrator committed
734 735 736 737
    var next_page = $('#' + clicked.data('next'));

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

Administrator committed
739 740 741 742 743
        if (type == "rattrapage" || type == "volant") {
            rattrapage_ou_volant = type;
        }
    }

744 745
    if (next_page.length > 0) {
        goto_page(next_page);
Administrator committed
746 747 748 749
    }

});

Etienne Freiss committed
750 751 752 753
service_validation.on("click", ".btn", {type:'normal'}, record_service_presence);
associated_service_validation.on("click", "#associated_btn", {type:'associate'}, record_service_presence);
associated_service_validation.on("click", "#partner_btn", {type:'partner'}, record_service_presence);
associated_service_validation.on("click", "#both_btn", {type:'both'}, record_service_presence);
754 755 756 757 758

shift_members.on("click", '.btn[data-rid]', function() {
    var clicked = $(this);
    var rid = clicked.data('rid');
    var mid = clicked.data('mid');
Administrator committed
759 760 761 762 763 764

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

});

Etienne Freiss committed
765
shift_members.on("click", '.btn--inverse', function() {
Etienne Freiss committed
766 767 768 769
    if (coop_is_connected()) {
        var clicked = $(this);
        var rid = clicked.data('rid');
        var mid = clicked.data('mid');
Etienne Freiss committed
770

Etienne Freiss committed
771 772
        cancel_service_presence(mid, rid);
    }
Etienne Freiss committed
773 774
});

Damien Moulard committed
775
pages.shopping_entry.on('css', function() {
Administrator committed
776 777 778 779 780 781 782
    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);
});

Damien Moulard committed
783
pages.service_entry.on('css', function() {
Administrator committed
784 785 786 787 788 789
    photo_advice.hide();
    photo_studio.hide();
    clean_service_entry();
    get_service_entry_data();
});

Damien Moulard committed
790
pages.rattrapage_1.on('css', function() {
Administrator committed
791 792
    search_box_clear_html_elts();
    var msg = "Vous venez pour un rattrapage.";
793

Administrator committed
794 795 796 797 798 799 800
    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);

});
801 802
pages.service_entry.on("click", '.info a[data-id]', select_possible_service);
$("#multi_results_preview").on("click", 'button', preview_member_search_select);
Administrator committed
803 804 805 806 807
html_elts.image_medium.on('click', function() {
    if (webcam_is_attached == true) {
        // photo_advice.show();
        photo_studio.show();
    }
808
});
Administrator committed
809

810 811 812 813
function ask_for_easy_shift_validation() {
    //alert("operator = " + JSON.stringify(operator))
    msg = "<p>Je suis bien " + operator.name + "<br/> et <br/>je valide mon service 'Comité' </p>";
    openModal(msg, function() {
814 815 816 817 818 819
        try {
            post_form(
                '/members/easy_validate_shift_presence',
                {
                    coop_id: operator.id
                },
Damien Moulard committed
820
                function(err) {
821 822 823 824 825 826 827 828 829 830 831
                    if (!err) {
                        alert("1 point volant vient d'être ajouté.");
                        clean_search_for_easy_validate_zone();
                        closeModal();
                    } else {
                        if (typeof (err.responseJSON) != "undefined"
                                        && typeof (err.responseJSON.error) != "undefined") {
                            alert(err.responseJSON.error);
                        } else {
                            console.log(err);
                        }
832
                    }
833 834 835 836 837
                }
            );
        } catch (e) {
            console.log(e);
        }
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
    }, 'Confirmer');
}
// Display the members from the search result (copied from stock_movements)
function display_possible_members() {
    $('.search_member_results_area').show();
    $('.search_member_results').empty();

    if (members_search_results.length > 0) {
        for (member of members_search_results) {
            let btn_classes = "btn";

            if (operator != null && operator.id == member.id) {
                btn_classes = "btn--success";
            }

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

            $('.search_member_results').append(member_button);
            // Set action on click on a member button
            $('.btn_member').on('click', function() {
                for (member of members_search_results) {
                    if (member.id == $(this).attr('member_id')) {
                        operator = member;
                        // Enable validation button when operator is selected
                        ask_for_easy_shift_validation();
                        break;
                    }
                }
                display_possible_members();
            });
        }
    } else {
        $('.search_member_results').html('<p><i>Aucun résultat ! Faites-vous partie d\'un comité ? <br/> Si oui, vérifiez la recherche..</i></p>');
    }
}
Administrator committed
877
$(document).ready(function() {
878 879 880 881 882 883 884 885 886 887 888
    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
889 890 891 892 893
    $(window).keypress(function(e) {
        if (e.which >= 48 && e.which <= 57) {
            chars.push(String.fromCharCode(e.which));
        }

894
        timeout_to_homepage();
895

896 897 898
        setTimeout(function() {
            if (chars.length >= 13) {
                var barcode = chars.join("");
Administrator committed
899

900 901 902 903 904 905
                if (!isNaN(barcode)) {
                    chars = [];
                    goto_page(pages.shopping_entry);
                    search_field.val(barcode);
                    last_search_time = null;
                    search_member(true);
Administrator committed
906
                }
907
            }
Administrator committed
908

909
        }, 300);
Administrator committed
910
    });
911

912 913 914 915 916
    init_webcam();
    $('#crop_width').change(function() {
        Webcam.reset();
        init_webcam();
    });
Administrator committed
917

918
    $('#sm_search_member_form').submit(function() {
919 920 921 922 923
        if (is_time_to('search_member', 1000)) {
            sm_search_member_button.empty().append(`<i class="fas fa-spinner fa-spin"></i>`);
            let search_str = sm_search_member_input.val();

            $.ajax({
924
                url: '/members/search/' + search_str + '/' + window.committees_shift_id,
925 926 927 928 929 930 931
                dataType : 'json',
                success: function(data) {
                    members_search_results = [];
                    for (member of data.res) {
                        if (member.shift_type == 'ftop') {
                            members_search_results.push(member);
                        }
932
                    }
933 934 935

                    display_possible_members();
                },
Damien Moulard committed
936
                error: function() {
937 938 939 940 941 942 943 944 945 946 947 948 949
                    err = {
                        msg: "erreur serveur lors de la recherche de membres",
                        ctx: 'easy_validate.search_members'
                    };
                    report_JS_error(err, 'members');

                    $.notify("Erreur lors de la recherche de membre, il faut ré-essayer plus tard...", {
                        globalPosition:"top right",
                        className: "error"
                    });
                },
                complete: function() {
                    sm_search_member_button.empty().append(`Recherche`);
950
                }
951 952 953
            });
        }
    });
954

Administrator committed
955 956
});

957 958
Webcam.on('live', function() {
    webcam_is_attached = true;
Administrator committed
959
});