From 3d90733d4f25106eea5c4b2ac96b9956438994ff Mon Sep 17 00:00:00 2001
From: PavelBegunkov <asml.silence@gmail.com>
Date: Thu, 14 Jul 2016 13:52:09 +0300
Subject: [PATCH] Refactor exam.js (add es6 + eliminate dead code)

---
 media/js/discipline/rating/exam.js            | 273 +++++++-----------
 media/js/discipline/rating/rate.js            |   2 +-
 .../classes/Controller/Handler/Rating.php     |   2 +
 3 files changed, 108 insertions(+), 169 deletions(-)

diff --git a/media/js/discipline/rating/exam.js b/media/js/discipline/rating/exam.js
index 5b03dac95..c21e1e04b 100644
--- a/media/js/discipline/rating/exam.js
+++ b/media/js/discipline/rating/exam.js
@@ -161,7 +161,7 @@ $(function () {
 
             var id = $(this).attr('id');
             var col = +id.substr(4, 1);
-            var neighborAbsenceCheck = $($('#absence_' + col + '_' + row).children()[0]);
+            var neighborAbsenceCheck = $($(`#absence_${col}_${row}`).children()[0]);
 
             dependentCells[index][0] = $(this);
             dependentCells[index][1] = neighborAbsenceCheck.parent();
@@ -220,50 +220,6 @@ $(function () {
             needAccess = examAccess[index]; //&& (val == 0);
             setCellAccess(absenceCell.children()[0], needAccess);
         }
-        // чекбоксы влияют на соседей
-        /*
-        var followingExamsDisabled = false;
-        var firstInARow = true;
-        jAbsenceCheckBoxes.each(function () {
-            var id = $(this).parent().attr('id');
-            var col = parseInt(id.substr(8));
-            var neighborExamInput = $('#col_' + col + '_row_' + row).children();
-            var failedStudy =  (semesterRate < 38);
-            var stillFailedStudy = (semesterRate + extraRate < 38);
-
-            $(this).removeAttr('disabled');
-            if (autopass || // автомат
-                (firstInARow && failedStudy) || // задолженник
-                stillFailedStudy) // задолженник до сих пор
-            {
-                $(this).attr('disabled', true);
-            }
-
-            // TODO: условия этого и предыдущего if вынести в отдельную функцию, проверяющую допустимость
-            if (($(this)[0].checked) || autopass || followingExamsDisabled || stillFailedStudy) { // автомат, неявка или сдал до этого или не сдал вовсе
-                neighborExamInput.attr('disabled', true);
-            } else {
-                var needEnable = false;
-                if (failedStudy)// задолженник или задолженник до сих пор
-                {
-                    if (firstInARow)
-                        neighborExamInput.attr('disabled', true);
-                    else
-                        needEnable = true;
-                } else
-                    needEnable = true;
-
-                if (needEnable) {
-                    neighborExamInput.removeAttr('disabled');
-                    curExamRate = +neighborExamInput.val();
-                    if ((neighborExamInput.val() === '') || (curExamRate >= 22)) { // не приступал к сдаче или уже сдал
-                        followingExamsDisabled = true;
-                    }
-                }
-            }
-
-            firstInARow = false;
-        });*/
     }
 
     function controlVisualization() {
@@ -281,14 +237,12 @@ $(function () {
         if (groupID == 0) {
             $('.studentsRate tbody')
                 .children()
-                .each(function () {
-                    $(this).show();
-                });
+                .each((_, elem) => $(elem).show());
         } else {
             $('.studentsRate tbody')
                 .children(':gt(2)')
                 .each(function () {
-                    if ($(this).hasClass('group_' + groupID))
+                    if ($(this).hasClass(`group_${groupID}`))
                         $(this).show();
                     else
                         $(this).hide();
@@ -296,47 +250,40 @@ $(function () {
         }
     }
 
+    var setCursorLocation = function (jThis) {
+        g_col = parseInt(jThis.attr('id').substr(4));
+        g_row = parseInt(jThis.parent('tr').attr('id').substr(4))
+    };
+
+    var setRowBackground = function (color) {
+        let $cols = $(`td#col_${g_col}`);
+        let $rows = $(`tr#row_${g_row}`);
+        let $rowStatic = $rows.find('.staticCell');
+
+        $cols.filter('.commonCell')
+            .add($cols.filter('.staticCell'))
+            .add($rows.find('.commonCell'))
+            .add($rowStatic)
+            .children('input')
+            .add($rowStatic)
+            .each((_, elem) => $(elem).css('background-color', color));
+    };
+
+    var defaultCellBackground = '#fff';
+    var focusCellBackground = '#f1f1f1';
+
     // Ставим подстветку
     function TdFocus(jThis) {
-        g_col = jThis.attr('id');
-        g_col = parseInt(g_col.substr(4));
-        g_row = jThis.parent('tr').attr('id');
-        g_row = parseInt(g_row.substr(4));
-
+        setCursorLocation(jThis);
         g_oldRateCell = jThis.children('input').val();
-        $('td#col_' + g_col + '.commonCell').each(function () {
-            $(this).children('input').css('background-color', '#f1f1f1');
-        });
-        $('td#col_' + g_col + '.staticCell').each(function () {
-            $(this).children('input').css('background-color', '#f1f1f1');
-        });
 
-        $('tr#row_' + g_row + ' .commonCell').each(function () {
-            $(this).children('input').css('background-color', '#f1f1f1');
-        });
-        $('tr#row_' + g_row + ' .staticCell').each(function () {
-            $(this).css('background-color', '#f1f1f1');
-            $(this).children('input').css('background-color', '#f1f1f1');
-        });
-        jThis.children('input').css('background-color', '#fff');
+        setRowBackground(focusCellBackground);
+        jThis.children('input').css('background-color', defaultCellBackground);
     }
 
     // Убираем подстветку
     function TdUnFocus() {
-        $('td#col_' + g_col + '.commonCell').each(function () {
-            $(this).children('input').css('background-color', '#fff');
-        });
-        $('td#col_' + g_col + '.staticCell').each(function () {
-            $(this).children('input').css('background-color', '#fff');
-        });
-
-        $('tr#row_' + g_row + ' .commonCell').each(function () {
-            $(this).children('input').css('background-color', '#fff');
-        });
-        $('tr#row_' + g_row + ' .staticCell').each(function () {
-            $(this).css('background-color', '#fff');
-            $(this).children('input').css('background-color', '#fff');
-        });
+        setRowBackground(defaultCellBackground);
     }
 
     function TdInfo(jThis) {
@@ -345,14 +292,14 @@ $(function () {
             disciplinePassRate = 38;
 
         // Получаем подмодуль
-        var jCurSubmoduleInfo = $('.RatingTableSubmodulesInfo .col_' + g_col + ':first');
-        var jCurSubmoduleHead = $('.RatingTableSubmodulesHead .col_' + g_col + ':first');
+        var jCurSubmoduleInfo = $(`.RatingTableSubmodulesInfo .col_${g_col}:first`);
+        var jCurSubmoduleHead = $(`.RatingTableSubmodulesHead .col_${g_col}:first`);
 
         g_submoduleID = parseInt(jCurSubmoduleInfo.attr('id'));
         g_submoduleTitle = jCurSubmoduleHead.text();
         if (jCurSubmoduleHead.length < 1 && $('.RatingTableModulesHead .bonus').length > 0)
             g_submoduleTitle = 'Бонусные баллы';
-        g_submoduleMaxRate = parseInt($('.RatingTableSubmodulesHeadMaxRate .col_' + g_col).text());
+        g_submoduleMaxRate = parseInt($(`.RatingTableSubmodulesHeadMaxRate .col_${g_col}`).text());
 
 
         // Проверяем допустимое значение (только для добора)
@@ -374,19 +321,59 @@ $(function () {
         jTdInfo.children('#student').children('b').html(g_stdName);
         jTdInfo.children('#submodule').children('b').html(g_submoduleTitle);
         jTdInfo.children('#maxRate').children('b').html(g_submoduleMaxRate);
-
-        //if (jThis.children('.tdInfo').length <= 0)
-        //  jThis.append('<div class='tdInfo'>'+g_submoduleTitle+'<br>'+g_stdName+'</div>');
     }
 
     function UnsetTdInfo(jThis) {
-        //jThis.children('.tdInfo').remove();
         jTdInfo_wrap.hide();
         g_submoduleID = null;
         g_studentID = null;
         g_submoduleMaxRate = 0;
     }
 
+    var setRate = function(newRate, jThis, oldRate, rateResult, bonus) {
+        $.postJSON(URLdir + 'handler/rating/setRate',
+            {
+                studentID: g_studentID, 
+                submoduleID: g_submoduleID,
+                rate: newRate
+            }
+        ).success(data => {
+            if (data.success !== true) {
+                jThis.children('input').val(oldRate);
+                EventInspector.error('Не удалось добавить/изменить балл');
+                return;
+            }
+
+            var correctRate = (rateResult + bonus > 100) ? '100+' : rateResult + bonus;
+            jThis.siblings('.rateResultCell').text(correctRate);
+
+            // Открываем доступ к след. ячейке добора баллов
+            if (jThis.hasClass('additionalCell')) {
+                nextAdditionalCell = $('#col_' + (g_col + 1) + '_row_' + g_row);
+                placeholderMaxVal = (rateResult < 60) ? (60 - rateResult) : 0;//(60 - oldRate);
+
+                if (nextAdditionalCell.hasClass('additionalCell')) {
+                    var placeholderMax = (placeholderMaxVal > 0) ? placeholderMax = 'макс. ' + placeholderMaxVal : '---';
+                    nextAdditionalCell.find('input').attr('placeholder', placeholderMax);
+                }
+            }
+            EventInspector.success('Балл добавлен/изменен');
+        }).fail(jqXHR => {
+            jThis.children('input').val(oldRate);
+            switch (jqXHR.status) {
+                case 400:
+                    EventInspector.error(optionsViewData[option].messageFail);
+                    break;
+                case 403:
+                    EventInspector.error('Сессия истекла');
+                    window.location.replace(URLdir);
+                    break;
+                default:
+                    EventInspector.error(' ' + jqXHR.status);
+            }
+        });
+    };
+
     function Rating(jThis, oldRate) {
         oldRate = parseInt(oldRate);
 
@@ -425,44 +412,7 @@ $(function () {
         }
 
         if (newRate <= g_submoduleMaxRate) {
-            $.ajax({
-                type: 'POST',
-                url: URLdir + 'handler/rating/setRate',
-                data: 'studentID=' + g_studentID + '&submoduleID=' + g_submoduleID + '&rate=' + newRate,
-                complete: function (jqXHR, textStatus) {
-                    switch (jqXHR.status) {
-                        case  403:
-                            EventInspector.error('Сессия истекла');
-                            jThis.children('input').val(oldRate);
-
-                            window.location.replace(URLdir);
-                            break;
-                        case 200:
-                            data = $.parseJSON(jqXHR.responseText);
-                            if (data.success === true) {
-                                var correctRate = (rateResult + bonus > 100) ? '100+' : rateResult + bonus;
-                                jThis.siblings('.rateResultCell').text(correctRate);
-
-                                // Открываем доступ к след. ячейке добора баллов
-                                if (jThis.hasClass('additionalCell')) {
-                                    nextAdditionalCell = $('#col_' + (g_col + 1) + '_row_' + g_row);
-                                    placeholderMaxVal = (rateResult < 60) ? (60 - rateResult) : 0;//(60 - oldRate);
-
-                                    if (nextAdditionalCell.hasClass('additionalCell')) {
-                                        var placeholderMax = (placeholderMaxVal > 0) ? placeholderMax = 'макс. ' + placeholderMaxVal : '---';
-                                        nextAdditionalCell.find('input').attr('placeholder', placeholderMax);
-                                    }
-                                }
-
-                                EventInspector.success('Балл добавлен/изменен');
-                            }
-                            else EventInspector.error('Не удалось добавить/изменить балл');
-                            break;
-                        default:
-                            EventInspector.error(' ' + jqXHR.status);
-                    }
-                }
-            });
+            setRate(newRate, jThis, oldRate, rateResult, bonus);
         }
         else {
             if (oldRate <= g_submoduleMaxRate) {
@@ -531,28 +481,28 @@ $(function () {
             case Direction.Up:
                 do {
                     row--;
-                    currentCell = $('tr#row_' + row + ' td#col_' + g_col + '.commonCell')
+                    currentCell = $(`tr#row_${row} td#col_${g_col}.commonCell`)
                 } while ((currentCell.length > 0) &&
                 (currentCell.children('input').attr('disabled') == 'disabled'));
                 return currentCell;
             case Direction.Right:
                 do {
                     col++;
-                    currentCell = $('tr#row_' + g_row + ' td#col_' + col + '.commonCell')
+                    currentCell = $(`tr#row_${g_row} td#col_${col}.commonCell`)
                 } while ((currentCell.length > 0) &&
                 (currentCell.children('input').attr('disabled') == 'disabled'));
                 return currentCell;
             case Direction.Down:
                 do {
                     row++;
-                    currentCell = $('tr#row_' + row + ' td#col_' + g_col + '.commonCell')
+                    currentCell = $(`tr#row_${row} td#col_${g_col}.commonCell`)
                 } while ((currentCell.length > 0) &&
                 (currentCell.children('input').attr('disabled') == 'disabled'));
                 return currentCell;
             case Direction.Left:
                 do {
                     col--;
-                    currentCell = $('tr#row_' + g_row + ' td#col_' + col + '.commonCell')
+                    currentCell = $(`tr#row_${g_row} td#col_${col}.commonCell`)
                 } while ((currentCell.length > 0) &&
                 (currentCell.children('input').attr('disabled') == 'disabled'));
                 return currentCell;
@@ -653,35 +603,28 @@ $(function () {
 
     function setExamPeriodOption(jThis, option) {
         jThis.attr('disabled', true);
-        var statusCode = 0;
-        $.ajax({
-            type: 'POST',
-            url: URLdir + 'handler/rating/SetExamPeriodOption',
-            data: 'studentID=' + g_studentID + '&submoduleID=' + g_submoduleID +
-            '&option=' + optionsViewData[option].sendingOption,
-            complete: function (jqXHR, textStatus) {
-                statusCode = jqXHR.status;
-                switch (jqXHR.status) {
-                    case  403:
-                        EventInspector.error('Сессия истекла');
-                        window.location.replace(URLdir);
-                        break;
-                    case 200:
-                        data = $.parseJSON(jqXHR.responseText);
-                        if (data.success === true) {
-                            EventInspector.success(optionsViewData[option].messageOK);
-                            statusCode = 0;
-                        }
-                        else
-                            EventInspector.error(optionsViewData[option].messageFail);
-                        break;
-                    default:
-                        EventInspector.error(' ' + jqXHR.status);
-                }
+
+        $.postJSON(URLdir + 'handler/rating/SetExamPeriodOption',
+            {
+                studentID: g_studentID,
+                submoduleID: g_submoduleID,
+                option: '' + optionsViewData[option].sendingOption // cast null to "null"
+            })
+        .done(data => EventInspector.success(optionsViewData[option].messageOK))
+        .fail(jqXHR => {
+            jThis.prop("checked", !jThis.prop("checked"));
+            switch (jqXHR.status) {
+                case 400:
+                    EventInspector.error(optionsViewData[option].messageFail);
+                    break;
+                case 403:
+                    EventInspector.error('Сессия истекла');
+                    window.location.replace(URLdir);
+                    break;
+                default:
+                    EventInspector.error(' ' + jqXHR.status);
             }
-        });
-        jThis.removeAttr('disabled');
-        return statusCode;
+        }).always(() => jThis.removeAttr('disabled'));
     }
 
     // Фильтр по группе
@@ -704,15 +647,9 @@ $(function () {
     $('.downloadExcel').click(function () {
         $.fileDownload(URLdir + 'handler/FileCreator/GenerateExcelRatingTable', {
             httpMethod: 'POST',
-            data: {
-                'disciplineID': g_disciplineID
-            },
-            successCallback: function () {
-
-            },
-            failCallback: function () {
-
-            }
+            data: {'disciplineID': g_disciplineID},
+            successCallback: function () {},
+            failCallback: function () {}
         });
     });
 
diff --git a/media/js/discipline/rating/rate.js b/media/js/discipline/rating/rate.js
index b510b962d..92f63133f 100644
--- a/media/js/discipline/rating/rate.js
+++ b/media/js/discipline/rating/rate.js
@@ -237,7 +237,7 @@ $(function () {
 
         // Здесь jThis - div rateCell, а не input, который является дочкой
         if (cancelFlag) {
-            var str = ""
+            var str = "";
             if (oldRate != -1)
                 str = oldRate;
             jThis.children("input").val(str);
diff --git a/~dev_rating/application/classes/Controller/Handler/Rating.php b/~dev_rating/application/classes/Controller/Handler/Rating.php
index f92556368..891fa2e54 100644
--- a/~dev_rating/application/classes/Controller/Handler/Rating.php
+++ b/~dev_rating/application/classes/Controller/Handler/Rating.php
@@ -58,6 +58,8 @@ class Controller_Handler_Rating extends Controller_Handler
             if ($parametersCheckPassed) {
                 $result = Model_Rating::setExamPeriodOption($_POST['studentID'], $_POST['submoduleID'], $_POST['option']);
                 $res['success'] = !$result['ErrorCode'];
+                if (!$res['success'])
+                    throw HTTP_Exception::factory(400)->request($this->request);
             }
         }
 
-- 
GitLab