admin.js 7.37 KB
$(document).ready(function() {
    var sorting_direction = -1;

    // button handlers (runs once)
    function button_handlers() {
        function show_chevron(col, dir) {
            var chevron;
            if (dir > 0)
                chevron = '<i class="fa fa-chevron-up" aria-hidden="true"></i>';
            else
                chevron = '<i class="fa fa-chevron-down" aria-hidden="true"></i>';

            $("#col-numero-dir").html(col == "col-numero" ? chevron : "");
            $("#col-nome-dir").html(col == "col-nome" ? chevron : "");
            $("#col-estado-dir").html(col == "col-estado" ? chevron : "");
            $("#col-nota-dir").html(col == "col-nota" ? chevron : "");
        }

        $("#col-numero, #col-nome, #col-estado, #col-nota").click(
            function() {
                sorting_direction = -sorting_direction;
                show_chevron(this.id, sorting_direction);
            }    
        );

        $("#allow_all").click(
            function() {
                $(":checkbox").prop("checked", true).trigger('change');
            }
        );
        $("#deny_all").click(
            function() {
                $(":checkbox").prop("checked", false).trigger('change');
            }
        );
        $("#reset_password").click(
            function () {
                $.ajax({
                    type: "POST",
                    url: "/admin",
                    data: {
                        "cmd": "reset_password",
                        "value": $("#reset_number").val()
                    }
                });
            }
        );
        $("#inserir_novo_aluno").click(
            function () {
                $.ajax({
                    type: "POST",
                    url: "/admin",
                    data: {
                        "cmd": "insert_student",
                        "value": JSON.stringify({
                            "number": $("#novo_numero").val(),
                            "name": $("#novo_nome").val()
                        })
                    }
                });
            }
        );
    }

    // ----------------------------------------------------------------------
    // checkbox handler to allow/deny students individually
    function autorizeStudent(e) {
        if (this.checked) {
            $(this).parent().parent().addClass("active");
            $.ajax({
                type: "POST",
                url: "/admin",
                data: {"cmd": "allow", "value": this.name}
            });
        }
        else {
            $(this).parent().parent().removeClass("active");
            $.ajax({
                type: "POST",
                url: "/admin",
                data: {"cmd": "deny", "value": this.name}
            });
        }
    }

    // ----------------------------------------------------------------------
    function populateOnlineTable(students) {
        var rows = "";
        // make list of online students
        var active = [];
        $.each(students, function(i, r) {
            if (r['start_time'] != '') {
                active.push([r['uid'], r['name'], r['start_time'], r['ip_address'], r['user_agent'], r['focus']]);
            }
        });
        // sort by start time
        active.sort(function(a,b){return a[2] < b[2] ? -1 : (a[2] == b[2] ? 0 : 1);});
        n = active.length;
        for(var i = 0; i < n; i++) {
            rows += '<tr' + (active[i][5]? '' : ' class="bg-danger"') + '>\
            <td>' + active[i][0] + '</td>\
            <td>' + active[i][1] + '</td>\
            <td>' + active[i][2].slice(11,19) + '</td>\
            <td>' + (active[i][5]? '' : '<span class="label bg-danger">unfocus</span>') + '</td>\
            </tr>';
        }
        $("#online_students").html(rows);
        $("#online-header").html(n);

    }

    // ----------------------------------------------------------------------
    function generate_grade_bar(grade) {
        var barcolor;
        if (grade < 10)
            barcolor = 'bg-danger';
        else if (grade < 15)
            barcolor = 'bg-warning';
        else
            barcolor = 'bg-success';

        return '<div class="progress"><div class="progress-bar ' + barcolor 
            + '" role="progressbar" aria-valuenow="' + grade 
            + '" aria-valuemin="0" aria-valuemax="20" style="min-width: 2em; width: ' 
            + (5*grade) + '%;">' + grade + '</div></div>';
    }

    // ----------------------------------------------------------------------
    function populateStudentsTable(students) {
        var rows = "";

        $.each(students, function(i, d) {
            var uid = d['uid'];
            var checked = d['allowed'] ? 'checked' : '';
            var password_defined = d['password_defined'] ? ' <span class="badge badge-secondary"><i class="fa fa-key" aria-hidden="true"></i></span>' : '';
            var hora_inicio = d['start_time'] ? ' <span class="badge badge-success">' + d['start_time'].slice(11,19) + '</span>': '';
            var estado = password_defined + hora_inicio;

            if (d['start_time'] != '')  // test
                rows += '<tr id="' + uid + '" + class="table-success">';
            else if (d['online'])       // online
                rows += '<tr id="' + uid + '" + class="table-warning">';
            else if (d['allowed'])      // allowed
                rows += '<tr id="' + uid + '" + class="table-active">';
            else                        // offline
                rows += '<tr id="' + uid + '" + class="">';

            rows += '<td><input type="checkbox" name="' + uid + '" value="true"' 
                + checked + '> ' + uid + '</td>\
                <td>' + d['name'] + '</td>\
                <td>' + estado + '</td>\
                <td>';
            var g = d['grades'];
            var glength = g.length;
            for (var i=0; i < glength; i++) {
                rows += '<div data-toggle="tooltip" data-placement="top" title="' + g[i][1].slice(0,19) + '"><a href="review?test_id=' + g[i][2] + '">' + generate_grade_bar(g[i][0]) + '</a></div>';
            }
            rows += '</td></tr>';
        });

        $("#students").html(rows);
        // $('[data-toggle="tooltip"]').tooltip();  FIXME
        $("#students-header").html(students.length);
    }

    // ----------------------------------------------------------------------
    function populate() {
        $.ajax({
            type: "POST",
            url: "/admin",
            data: {"cmd": "get_students", "value": ""},
            dataType: "json",
            success: function(data) {
                // fill jumbotron data
                $("#title").html(data['test']['title']);
                $("#ref").html(data['test']['ref']);
                $("#filename").html(data['test']['filename']);
                $("#database").html(data['test']['database']);
                $("#answers_dir").html(data['test']['answers_dir']);

                // fill online and student tables
                // populateOnlineTable(data["students"]);
                populateStudentsTable(data["students"])

                // add event handlers
                $('input[type="checkbox"]').change(autorizeStudent);
            },
            error: function() {alert("Servidor não responde.");}
        });
    }

    populate();                    // run once when the page is loaded
    button_handlers();             // assign handlers to buttons
    setInterval(populate, 5000);   // poll server on 5s interval
});