From 7830c458d7ec1e794b4064f18424708b64cb7cf5 Mon Sep 17 00:00:00 2001
From: Roman Steinberg <roman.accs@gmail.com>
Date: Sat, 4 Aug 2018 17:50:22 +0300
Subject: [PATCH] FIX: magic 0 problem # 132.

---
 media/js/discipline/rating.js                 | 48 ++++++++++---------
 .../classes/Controller/Handler/Rating.php     | 12 +++--
 .../application/classes/Model/Rating.php      |  3 ++
 3 files changed, 37 insertions(+), 26 deletions(-)

diff --git a/media/js/discipline/rating.js b/media/js/discipline/rating.js
index 33738b57b..5ca45a50f 100644
--- a/media/js/discipline/rating.js
+++ b/media/js/discipline/rating.js
@@ -29,11 +29,9 @@ class Base {
         let disciplineRaw = $.parseJSON($discipline.html() || '{}');
         Object.keys(disciplineRaw).forEach((keyRaw) => {
             let key = keyRaw.slice(0, 1).toLowerCase() + keyRaw.slice(1);
-            if (keyRaw == "ID") key = 'id';
+            if (keyRaw === "ID") key = 'id';
 
-            let value = disciplineRaw[keyRaw];
-
-            settings.discipline[key] = value;
+            settings.discipline[key] = +disciplineRaw[keyRaw];
         });
 
         $discipline.remove();
@@ -79,7 +77,7 @@ class Cursor {
     }
 
     isEmpty() {
-        return (this.col == 0) && (this.row == 0);
+        return (this.col === 0) && (this.row === 0);
     }
 }
 
@@ -290,10 +288,10 @@ class Rating {
 
         let $cell;
         do {
-            if (direction == this.Direction.Left)  col--;
-            if (direction == this.Direction.Right) col++;
-            if (direction == this.Direction.Up)    row--;
-            if (direction == this.Direction.Down)  row++;
+            if (direction === this.Direction.Left)  col--;
+            if (direction === this.Direction.Right) col++;
+            if (direction === this.Direction.Up)    row--;
+            if (direction === this.Direction.Down)  row++;
             $cell = $(`#col_row_${col}_${row}`);
         } while ($cell.length && !$cell.hasClass('rate'));
         return $cell;
@@ -310,16 +308,16 @@ class Rating {
     setRate($cell, oldInputVal) {
         let scoreInputVal = $cell.children('input').val();
 
-        if (scoreInputVal == oldInputVal) return;
+        if (scoreInputVal === oldInputVal) return;
 
         let rate = Base.parseRate($cell, true);
 
         let successText;
         let errorText;
-        if (scoreInputVal != '' && oldInputVal != '') {
+        if (scoreInputVal !== '' && oldInputVal !== '') {
             successText = 'Балл обновлен';
             errorText = 'Не удалось обновить балл';
-        } else if (scoreInputVal != '' && oldInputVal == '') {
+        } else if (scoreInputVal !== '' && oldInputVal === '') {
             successText = 'Балл добавлен';
             errorText = 'Не удалось добавить балл';
         } else {
@@ -374,7 +372,11 @@ class Rating {
     sendRate($cell, url, data, reset, successText, errorText) {
         let $input = $cell.children('input');
 
+        // Действия необходимые для безопасной обработки в асинхронном режиме
         $input.turnOff();
+        window.onbeforeunload = () => {
+            return "Запрос на добавление/изменение/удалени баллов еще не обработан!";
+        };
 
         data.recordBookID = this.cell.recordBook;
         data.disciplineID = this.settings.discipline.id;
@@ -383,17 +385,19 @@ class Rating {
         $.postJSON(URLdir + url, data).success(() => {
             this.recountScores($cell, data.submoduleID);
             Popup.success(successText);
-        }).fail(jqXHR => {
+            window.onbeforeunload = undefined;
+        }).fail((jqXHR) => {
             reset($input);
-            let status = parseInt(jqXHR.status);
+            const status = parseInt(jqXHR.status);
+            let message = errorText;
             try {
-                if (status != 400) throw null;
-                let message = JSON.parse(jqXHR.responseText).message;
-                if (!message) throw null;
-                Popup.error(message);
-            } catch (error) {
-                Popup.error(errorText);
+                if (status === 400)
+                    message = JSON.parse(jqXHR.responseText).message;
+            } catch(error) {
             }
+            if (status !== 0)
+                Popup.error(message);
+            window.onbeforeunload = undefined;
         }).always(() => $input.turnOn());
     }
 
@@ -444,10 +448,10 @@ class Rating {
         if ($cell.hasClass('extra')) {
             let $nextExtraCell = $cell.next('.extra');
             if ($nextExtraCell.length) {
-                let maxExtraRate = this.settings.discipline.type == 'exam' ? 38 : 60;
+                let maxExtraRate = this.settings.discipline.type === 'exam' ? 38 : 60;
                 let curRate = Base.parseRate($cell, true);
                 let maxVal = maxExtraRate - semesterRate - curRate;
-                if (maxVal > 0 && curRate != -1) {
+                if (maxVal > 0 && curRate !== -1) {
                     $nextExtraCell.find('input').attr('placeholder', 'макс. ' + maxVal);
                 } else {
                     $nextExtraCell.find('input').attr('placeholder', '–').val('');
diff --git a/~dev_rating/application/classes/Controller/Handler/Rating.php b/~dev_rating/application/classes/Controller/Handler/Rating.php
index 88d9eff9f..a69542356 100644
--- a/~dev_rating/application/classes/Controller/Handler/Rating.php
+++ b/~dev_rating/application/classes/Controller/Handler/Rating.php
@@ -19,7 +19,8 @@ class Controller_Handler_Rating extends Controller_Handler
             ->rule('submoduleID', 'digit')
             ->rule('rate', 'numeric')
             ->rule('rate', 'range', [':value', -1, 100]);
-        if (!$this->post->check()) HTTP_API_Exception::factory(400, null);
+        if (!$this->post->check())
+            throw new HTTP_Exception_400('Неверные параметры запроса SetRate!');
 
         $error = Model_Rating::SetRate(
             $this->user->TeacherID,
@@ -28,7 +29,8 @@ class Controller_Handler_Rating extends Controller_Handler
             $_POST['submoduleID'],
             $_POST['rate']
         );
-        if (!is_null($error)) throw HTTP_API_Exception::factory($error['code'], $error['message']);
+        if (!is_null($error))
+            throw HTTP_Exception::factory($error['code'], $error['message']);
 
         $this->response->body(json_encode([ 'success' => true ]));
     }
@@ -39,7 +41,8 @@ class Controller_Handler_Rating extends Controller_Handler
             ->rule('disciplineID', 'digit')
             ->rule('submoduleID', 'digit')
             ->rule('option', 'in_array', array(':value', array('null', 'absence', 'pass')));
-        if (!$this->post->check()) HTTP_API_Exception::factory(400, null);
+        if (!$this->post->check())
+            throw new HTTP_Exception_400('Неверные параметры запроса SetExamPeriodOption!');
 
         $error = Model_Rating::SetExamPeriodOption(
             $this->user->TeacherID,
@@ -48,7 +51,8 @@ class Controller_Handler_Rating extends Controller_Handler
             $_POST['submoduleID'],
             $_POST['option']
         );
-        if (!is_null($error)) throw HTTP_API_Exception::factory($error['code'], $error['message']);
+        if (!is_null($error))
+            throw HTTP_Exception::factory($error['code'], $error['message']);
 
         $this->response->body(json_encode([ 'success' => true ]));
     }
diff --git a/~dev_rating/application/classes/Model/Rating.php b/~dev_rating/application/classes/Model/Rating.php
index 688a5fe5b..bfcddd7fc 100644
--- a/~dev_rating/application/classes/Model/Rating.php
+++ b/~dev_rating/application/classes/Model/Rating.php
@@ -208,6 +208,7 @@ class Model_Rating extends Model
             case 'bonus':
                 break;
         }
+        return null;
     }
 
     public static function SetRate($teacherID, $recordBookID, $disciplineID, $submoduleID, $rate) {
@@ -219,6 +220,7 @@ class Model_Rating extends Model
 
         $error = Model_Rating::SetExamPeriodOptionSQL($recordBookID, $submoduleID, 'null');
         if (!is_null($error)) return $error;
+        return null;
     }
 
     public static function SetExamPeriodOption($teacherID, $recordBookID, $disciplineID, $submoduleID, $option) {
@@ -230,6 +232,7 @@ class Model_Rating extends Model
 
         $error = Model_Rating::SetExamPeriodOptionSQL($recordBookID, $submoduleID, $option);
         if (!is_null($error)) return $error;
+        return null;
     }
 
     public static function SetRateSQL($teacherID, $recordBookID, $submoduleID, $rate) {
-- 
GitLab