From 14f10a5298597867cbe58854de3735c9f902eab5 Mon Sep 17 00:00:00 2001
From: xamgore <xamgore@ya.ru>
Date: Fri, 19 Jun 2015 14:54:19 +0300
Subject: [PATCH] Refactoring of teachers upload page

---
 .../classes/Controller/Admin/Teachers.php     |  6 +-
 .../application/classes/FileParser.php        | 66 ++++++++++---------
 .../application/classes/Model/Account.php     | 12 ++--
 .../views/admin/teachers/upload.twig          | 45 +++++++++----
 ~dev_rating/system/classes/Kohana/UTF8.php    | 11 ++++
 5 files changed, 88 insertions(+), 52 deletions(-)

diff --git a/~dev_rating/application/classes/Controller/Admin/Teachers.php b/~dev_rating/application/classes/Controller/Admin/Teachers.php
index 051570cae..be647e34a 100644
--- a/~dev_rating/application/classes/Controller/Admin/Teachers.php
+++ b/~dev_rating/application/classes/Controller/Admin/Teachers.php
@@ -15,15 +15,15 @@ class Controller_Admin_Teachers extends Controller_Environment_Admin
     }
 
     public function action_upload() {
-        $result['success'] = false;
+        $errors = [];
 
         if (!empty($_FILES['teachers']) && $this->request->method() == 'POST') {
             $file = $_FILES["teachers"]["tmp_name"];
-            $result = FileParser::TeachersList($file);
+            $errors = FileParser::uploadTeachers($file, $_POST['facultyID']);
         }
 
         $this->twig->set([
-            'UploadingResult' => $result,
+            'Errors'          => $errors,
             'Faculties'       => Model_Faculties::load(),
         ])->set_filename('admin/teachers/upload');
     }
diff --git a/~dev_rating/application/classes/FileParser.php b/~dev_rating/application/classes/FileParser.php
index b5a7ddc63..e1ed67f2c 100644
--- a/~dev_rating/application/classes/FileParser.php
+++ b/~dev_rating/application/classes/FileParser.php
@@ -74,40 +74,46 @@ class FileParser
         ];
     }
 
-    public static function TeachersList($filename)
-    {
-        // get faculties list
-        $dbFaculties = Model_Faculties::load();
-        foreach ($dbFaculties as $rec) {
-            $name = trim($rec['Name']);
-            $id = $rec['ID'];
-            $faculties[$name] = $id;
-        }
 
-        if(File::mime($filename) != 'text/plain')
-            return true;
+    /**
+     * Parse teachers' info & synchronize it with database.
+     * @param $filename  string File with source data
+     * @param $facultyID int
+     * @return array
+     */
+    public static function uploadTeachers($filename, $facultyID) {
+        if (File::mime($filename) != 'text/plain')
+            return [];
+
+//        $faculties = [];
+//        foreach (Model_Faculties::load() as $faculty) {
+//            $name = trim($faculty['Name']);
+//            $faculties[$name] = $faculty['ID'];
+//        }
+
+        $count = 0;
+        $errors = [];
         $file = fopen($filename, "r");
-        $i = $j = 0;
-        while ($line = fgetcsv($file, 0, ";"))
-        {
-            // Имя, фамилия, отчество
-            list($lastName, $firstName, $secondName) = self::parsePeopleName($line[0]);
-            $departmentName = $line[1];
-            $facultyID = 6;  // TODO fix facultyID hardcode
-            if ($line[2])
-                $facultyID = $faculties[trim($line[2])];
-            $attempt = Account::instance()
-                ->createTeacherByDepName($lastName, $firstName, $secondName, $departmentName, $facultyID);
-
-            if($attempt == -1)
-            {
-                $resultArr[$j]['Row'] = $i;
-                $resultArr[$j]['Info'] = implode(';', $line);
-                $j++;
+
+        while ($line = fgetcsv($file, 0, ";")) {
+            list($name, $department, $facultyName) = UTF8::clear($line);
+
+            // Фамилия, имя, отчество
+            list($lastName, $firstName, $secondName) = self::parsePeopleName($name);
+
+//            if ($facultyName)
+//                $facultyID = $faculties[trim($facultyName)];
+
+            $attempt = Model_Account::createTeacherByDepName($lastName, $firstName, $secondName, $department, $facultyID);
+
+            if ($attempt == -1) {
+                $errors[] = ['Row' => $count, 'Info' => implode(';', $line)];
             }
-            $i++;
+
+            $count++;
         }
-        return ($j > 0) ? false : $resultArr;
+
+        return $errors;
     }
 
     private static function parsePeopleName($name) {
diff --git a/~dev_rating/application/classes/Model/Account.php b/~dev_rating/application/classes/Model/Account.php
index cd8c907e0..00b2725ce 100644
--- a/~dev_rating/application/classes/Model/Account.php
+++ b/~dev_rating/application/classes/Model/Account.php
@@ -45,18 +45,18 @@ class Model_Account extends Model
         return $response == -1 ? -1 : $code;
     }
 
-    public static function createTeacherByDepName($lastName, $firstName, $secondName, $departmentID, $facultyID) {
-        if ($departmentID == '') return -1;
+    public static function createTeacherByDepName($lastName, $firstName, $secondName, $department, $facultyID) {
+        if ($department == '') return -1;
 
         $code = self::generateActivationCode();
 
         $sql = "SELECT `CreateTeacherByDepName`(:last, :first, :second, :department, :faculty, :code) AS `UserID`;";
         $response = DB::query(Database::SELECT, $sql)
             ->parameters([
-                ':last' => $lastName,
-                ':first' => $firstName,
-                ':second' => $secondName,
-                ':department' => $departmentID,
+                ':last' => trim($lastName),
+                ':first' => trim($firstName),
+                ':second' => trim($secondName),
+                ':department' => $department,
                 ':faculty' => $facultyID,
                 ':code' => $code,
             ])->execute()->get('UserID');
diff --git a/~dev_rating/application/views/admin/teachers/upload.twig b/~dev_rating/application/views/admin/teachers/upload.twig
index 9e3a042ca..cd4744053 100644
--- a/~dev_rating/application/views/admin/teachers/upload.twig
+++ b/~dev_rating/application/views/admin/teachers/upload.twig
@@ -9,22 +9,41 @@
 {% endblock %}
     
 {% block main_content %}
-    {% if UploadingResult is not empty %}
-        {% set res = '<ul>' %}
-        {% for item in UploadingResult %}
-            {{ res ~ '<li>Строка #' ~ item.Row ~ ': ' ~ item.Info ~ '</li>' }}
-        {% endfor %}
-        {{ admin.message(warning, 'Возникли проблемы!', res ~ '</ul>') }}
+    {% if Errors is not empty %}
+        {% set res %}
+            {% for item in Errors %}
+                <li>Строка #{{ item.Row }}: {{ item.Info }}</li>
+            {% endfor %}
+        {% endset %}
+
+        {{ admin.message(warning, 'Возникли проблемы!', '<ul>' ~ res ~ '</ul>') }}
     {% endif %}
+
     <form enctype="multipart/form-data" action="" method="POST">
-    <div class="stepBox" id="FirstStep">
-        <div class="step_title">
-            <span class='step_title_count'>Шаг 1:</span> <span class='step_title_description'>Выберите файл для загрузки</span>
+        <div class="stepBox" id="FirstStep">
+            <div class="step_title">
+                <span class='step_title_count'>Шаг 1:</span>
+                <span class='step_title_description'>Выберите подразделение университета</span>
+            </div>
+            <div class="step_body">
+                <select id="facultySelect" name="facultyID">
+                    <option value="0" selected="selected">— Подразделение ЮФУ —</option>
+                    {% for row in Faculties %}
+                        <option value="{{ row.ID }}">{{ row.Name }} ({{ row.Abbr }})</option>
+                    {% endfor %}
+                </select>
+            </div>
         </div>
-        <div class="step_body">
-            <input name="teachers" type="file">
-            <input type="submit" value="Send">
+
+        <div class="stepBox" id="SecondStep">
+            <div class="step_title">
+                <span class='step_title_count'>Шаг 2:</span>
+                <span class='step_title_description'>Выберите файл для загрузки</span>
+            </div>
+            <div class="step_body">
+                  <input name="teachers" type="file">
+                  <input type="submit" value="Send">
+            </div>
         </div>
-    </div>
     </form>
 {% endblock %}            
\ No newline at end of file
diff --git a/~dev_rating/system/classes/Kohana/UTF8.php b/~dev_rating/system/classes/Kohana/UTF8.php
index ca5e315a8..8f18610f0 100644
--- a/~dev_rating/system/classes/Kohana/UTF8.php
+++ b/~dev_rating/system/classes/Kohana/UTF8.php
@@ -33,6 +33,17 @@ class Kohana_UTF8 {
 	 */
 	public static $called = array();
 
+    public static function clear(&$str) {
+        if (is_array($str)) {
+            foreach ($str as &$value) {
+                $value = self::clear($value);
+            }
+            return $str;
+        }
+
+        return trim(preg_replace('/[^\P{C}\n]+/u', '', $str));
+    }
+
 	/**
 	 * Recursively cleans arrays, objects, and strings. Removes ASCII control
 	 * codes and converts to the requested charset while silently discarding
-- 
GitLab