From 4fb53b4872a931b5e749f79fedb19a6bb4613800 Mon Sep 17 00:00:00 2001
From: Roman Steinberg <roman.accs@gmail.com>
Date: Wed, 7 Sep 2016 19:16:47 +0300
Subject: [PATCH] CHG: user errors notifications for credit; FIX: hardcode.

---
 media/js/discipline/rating/common.js          |   3 +-
 media/js/discipline/rating/exam.js            |   4 +-
 .../classes/Controller/Handler/Rating.php     |   2 +-
 .../application/classes/Model/Rating.php      | 127 ++++++++++++++----
 4 files changed, 105 insertions(+), 31 deletions(-)

diff --git a/media/js/discipline/rating/common.js b/media/js/discipline/rating/common.js
index e76654d4e..18bae7493 100644
--- a/media/js/discipline/rating/common.js
+++ b/media/js/discipline/rating/common.js
@@ -314,7 +314,8 @@ function Rating() {
 
 
     var postRate = function (rate, $this, oldRate, rateResult, studentID, submoduleID) {
-        $.postJSON(URLdir + 'handler/rating/setRate', {studentID, submoduleID, rate})
+        const disciplineID = settings.disciplineID;
+        $.postJSON(URLdir + 'handler/rating/setRate', {studentID, disciplineID, submoduleID, rate})
             .success(() => {
                 let correctRate = (rateResult > 100) ? '100+' : rateResult;
                 $this.siblings('.rateResultCell').text(correctRate);
diff --git a/media/js/discipline/rating/exam.js b/media/js/discipline/rating/exam.js
index 50d75f637..00ef09938 100644
--- a/media/js/discipline/rating/exam.js
+++ b/media/js/discipline/rating/exam.js
@@ -82,8 +82,8 @@ $(function () {
     function controlRowVisualization(jRow) {
         if (R.cursor.isEmpty())
             return;
-        // if (R.settings.Type !== 'exam')
-        //     return;
+        if (R.settings.Type !== 'exam')
+            return;
 
         var jAutoPassCheckBox = jRow.children('.autoPass').children('.autoPassCheck');
         var jAbsenceCheckBoxes = jRow.children('.absenceCell').children('.absenceCheck');
diff --git a/~dev_rating/application/classes/Controller/Handler/Rating.php b/~dev_rating/application/classes/Controller/Handler/Rating.php
index 161ad5ea8..2f33edcb1 100644
--- a/~dev_rating/application/classes/Controller/Handler/Rating.php
+++ b/~dev_rating/application/classes/Controller/Handler/Rating.php
@@ -20,7 +20,7 @@ class Controller_Handler_Rating extends Controller_Handler
             ->rule('rate', 'range', [':value', -2, 100]);
 
         if ($this->post->check()) {
-            $response = Model_Rating::SetStudentRate($this->user->TeacherID, $_POST['studentID'], 1911, $_POST['submoduleID'], $_POST['rate']);
+            $response = Model_Rating::SetStudentRate($this->user->TeacherID, $_POST['studentID'], $_POST['disciplineID'], $_POST['submoduleID'], $_POST['rate']);
         }
 
         if (!$response['success']) {
diff --git a/~dev_rating/application/classes/Model/Rating.php b/~dev_rating/application/classes/Model/Rating.php
index 50c54e5b2..49cdfc0b7 100644
--- a/~dev_rating/application/classes/Model/Rating.php
+++ b/~dev_rating/application/classes/Model/Rating.php
@@ -52,17 +52,20 @@ class Model_Rating extends Model
             ->execute();
     }
 
-    private static function checkRateChanges($studentId, $disciplineId, $submoduleId, $rate) {
+    private static function checkRateChanges($studentId, $disciplineId, $submoduleId, $rate)
+    {
         $studentsRates = Model_Rating::getRatesAll($disciplineId, $studentId);
 //        echo Debug::vars($studentsRates);
 
         $change = ['type' => '', 'rate' => 0];
         $ratesByType = [];
         function getKey($part1, $part2) {
-            return $part1 == 'exam' ? $part1.$part2 : $part1;
+            return ($part1 == 'exam' or $part1 === 'extra') ? $part1 . $part2 : $part1;
         }
 
+        $hasExam = false;
         foreach ($studentsRates as $rateInfo) {
+            $hasExam = ($hasExam or ($rateInfo['ModuleType'] === 'exam'));
             $key = getKey($rateInfo['ModuleType'], $rateInfo['SubmoduleOrderNum']);
 
             // запоминаем оценки по типам
@@ -70,14 +73,11 @@ class Model_Rating extends Model
             if (is_null($ratesByType[$rateInfo['ModuleType']])) {
                 if ($rateInfo['ExamPeriodOption'] == 'absence') {
                     $ratesByType[$key] = 0;
-                }
-                elseif ($rateInfo['ExamPeriodOption'] == 'pass') {
+                } elseif ($rateInfo['ExamPeriodOption'] == 'pass') {
                     $ratesByType[$key] = 40;
-                }
-                else
+                } else
                     $ratesByType[$key] = $rateInfo['Rate'] == null ? null : $iRate;
-            }
-            else {
+            } else {
                 $ratesByType[$key] += $iRate;
             }
 
@@ -88,7 +88,11 @@ class Model_Rating extends Model
             }
         }
 
-        return RateStatesModel::checkTransitionForExam($ratesByType, $change);
+        if ($hasExam) {
+            return RateStatesModel::checkTransitionForExam($ratesByType, $change);
+        } else {
+            return RateStatesModel::checkTransitionForCredit($ratesByType, $change);
+        }
     }
 
     public static function SetStudentRate($teacherId, $studentId, $disciplineId, $submoduleId, $rate) {
@@ -229,7 +233,7 @@ class States
 {
     const __default = self::beforeLimit;
 
-    const beforeLimit = 0; // не достигнут порог 38
+    const beforeLimit = 0; // не достигнут порог (38 или 60)
     const semesterAccepted = 1;     // допущен к сдаче
     const notPassed1 = 2;  // не сдал один раз (завалил основную сдачу)
     const notPassed2 = 3;  // не сдал дважды (завалил первую пересдачу)
@@ -329,22 +333,22 @@ class RateStatesModel
         if ($iSemester + $iGain < 38) {
             $this->forward = States::beforeLimit;
         }
-        else if ($examAttempts[0] === null) {
+        elseif ($examAttempts[0] === null) {
             $this->forward = States::semesterAccepted;
         }
-        else if ($iExamAttempts[0] >= 22) {
+        elseif ($iExamAttempts[0] >= 22) {
             $this->forward = States::passed1;
         }
-        else if ($examAttempts[1] === null) {
+        elseif ($examAttempts[1] === null) {
             $this->forward = States::notPassed1;
         }
-        else if ($iExamAttempts[1] >= 22) {
+        elseif ($iExamAttempts[1] >= 22) {
             $this->forward = States::passed2;
         }
-        else if ($examAttempts[2] === null) {
+        elseif ($examAttempts[2] === null) {
             $this->forward = States::notPassed2;
         }
-        else if ($iExamAttempts[2] >= 22) {
+        elseif ($iExamAttempts[2] >= 22) {
             $this->forward = States::passed3;
         }
         else {
@@ -359,7 +363,7 @@ class RateStatesModel
                 $this->backward = States::passed3;
             }
         }
-        else if ($examAttempts[1] !== null) {
+        elseif ($examAttempts[1] !== null) {
             if ($iExamAttempts[1] < 22) {
                 $this->backward = States::notPassed2;
             }
@@ -367,7 +371,7 @@ class RateStatesModel
                 $this->backward = States::passed2;
             }
         }
-        else if ($examAttempts[0] !== null) {
+        elseif ($examAttempts[0] !== null) {
             if ($iExamAttempts[0] < 22) {
                 $this->backward = States::notPassed1;
             }
@@ -375,7 +379,7 @@ class RateStatesModel
                 $this->backward = States::passed1;
             }
         }
-        else if ($iSemester + $iGain < 38) {
+        elseif ($iSemester + $iGain < 38) {
             $this->backward = States::beforeLimit;
         }
         else {
@@ -401,24 +405,93 @@ class RateStatesModel
         return $res1.$res2;
     }
 
-    public static function checkTransitionForExam($ratesByType, $change) { // ($previousState, $semester, $gain='', $examAttempts) {
+    public static function checkTransitionForExam($ratesBySubmodules, $change) {
         // определить предыдущее состояние
         $model = new RateStatesModel();
-        $model->fillForExam($ratesByType['regular'], $ratesByType['extra'],
-            [$ratesByType['exam1'], $ratesByType['exam2'], $ratesByType['exam3']]);
+        $model->fillForExam($ratesBySubmodules['regular'], $ratesBySubmodules['extra'],
+            [$ratesBySubmodules['exam1'], $ratesBySubmodules['exam2'], $ratesBySubmodules['exam3']]);
         $previousState = $model->forward;
 //        echo Debug::vars($ratesByType);
 //        echo Debug::vars('Forward: ', $model);
 
         // определить текущее состояние
-        $ratesByType[$change['type']] += $change['rate'];
-        if ($ratesByType[$change['type']] == -1) {
-            $ratesByType[$change['type']] = null;
+        $ratesBySubmodules[$change['type']] += $change['rate'];
+        if ($ratesBySubmodules[$change['type']] == -1) {
+            $ratesBySubmodules[$change['type']] = null;
         }
-        $model->fillForExam($ratesByType['regular'], $ratesByType['extra'],
-            [$ratesByType['exam1'], $ratesByType['exam2'], $ratesByType['exam3']]);
+        $model->fillForExam($ratesBySubmodules['regular'], $ratesBySubmodules['extra'],
+            [$ratesBySubmodules['exam1'], $ratesBySubmodules['exam2'], $ratesBySubmodules['exam3']]);
 //        echo Debug::vars('Backward: ', $model);
         // анализ ошибок
         return $model->checkTransitionPermission($previousState);
     }
+
+    public static function checkTransitionForCredit($ratesBySubmodules, $change) {
+        $state = States::beforeLimit;
+        $totalRate = $ratesBySubmodules['regular'] + $ratesBySubmodules['extra1'] + $ratesBySubmodules['extra2'];
+        if ($ratesBySubmodules['extra2'] !== null) {
+            if ($totalRate >= 60) {
+                $state = States::passed3;
+            }
+            else {
+                $state = States::notPassed3;
+            }
+        }
+        elseif ($ratesBySubmodules['extra1'] !== null) {
+            if ($totalRate >= 60) {
+                $state = States::passed2;
+            }
+            else {
+                $state = States::notPassed2;
+            }
+        }
+        else {
+            if ($totalRate >= 60) {
+                $state = States::passed1;
+            }
+            else {
+                $state = States::beforeLimit; // or not passed1 but it doesn't metter
+            }
+        }
+
+        // анализируем возможные ошибки
+        $result = '';
+        if ($state == States::beforeLimit and $change['type'] == 'extra2') {
+            $result = 'Невозможно выставить баллы за второй этап добора баллов до первого добора!';
+        }
+        elseif ($state == States::beforeLimit and
+            ($change['type'] == 'extra1' or $change['type'] == 'extra2') and
+            $totalRate + $change['rate'] > 60) {
+            $result = 'Невозможно выставить задолжнику более 60 баллов по дисциплине!';
+        }
+        elseif ($state == States::passed1 and ($change['type'] == 'extra1' or $change['type'] == 'extra2')) {
+            $result = 'Невозможно выставить добор баллов для студента, сдавшего зачет!';
+        }
+        elseif ($state == States::passed3 and
+            $change['type'] == 'extra1' and
+            $ratesBySubmodules['extra1'] + $change['rate'] == 0) {
+            $result = 'Невозможно удалить баллы за первый этап добора, если уже выставлены баллы' .
+                'за второй этап добора!';
+        }
+        elseif ($state == States::notPassed3 and
+            $change['type'] == 'extra1' and
+            $ratesBySubmodules['extra1'] + $change['rate'] == 0) {
+            $result = 'Невозможно удалить баллы за первый этап добора, если уже выставлены баллы' .
+                'за второй этап добора!';
+        }
+        elseif ($state == States::passed2 and $totalRate + $change['rate'] > 60) {
+            $result = 'Невозможно выставить задолжнику более 60 баллов по дисциплине!';
+        }
+        elseif ($state == States::notPassed2 and $totalRate + $change['rate'] > 60) {
+            $result = 'Невозможно выставить задолжнику более 60 баллов по дисциплине!';
+        }
+        elseif ($state == States::passed3 and $totalRate + $change['rate'] > 60) {
+            $result = 'Невозможно выставить задолжнику более 60 баллов по дисциплине!';
+        }
+        elseif ($state == States::notPassed3 and $totalRate + $change['rate'] > 60) {
+            $result = 'Невозможно выставить задолжнику более 60 баллов по дисциплине!';
+        }
+
+        return $result;
+    }
 };
-- 
GitLab