From 4b11f8abe1af96aa061b3f02323c09e738dc864d Mon Sep 17 00:00:00 2001
From: Korvin <korvin96@gmail.com>
Date: Sat, 18 Aug 2018 10:50:41 +0300
Subject: [PATCH] add new semester button in admin regulatory menu (closes #2)

---
 db/migrations/stored/R__functions.sql         | 33 +++++++++++++++++
 deploy/phpConfig/sidePanel/admin.json         |  2 +-
 media/js/office/regulatory.js                 | 32 ++++++++++++++++
 media/js/semesterSwitcher.js                  |  2 +-
 .../classes/Controller/Handler/Regulatory.php | 37 +++++++++++++++++++
 .../classes/Controller/Office/Regulatory.php  |  8 ++++
 .../application/classes/Model/Semesters.php   |  7 ++++
 .../views/office/regulatory/index.twig        | 20 ++++++++++
 8 files changed, 139 insertions(+), 2 deletions(-)
 create mode 100644 media/js/office/regulatory.js
 create mode 100644 ~dev_rating/application/classes/Controller/Handler/Regulatory.php
 create mode 100644 ~dev_rating/application/classes/Controller/Office/Regulatory.php
 create mode 100644 ~dev_rating/application/views/office/regulatory/index.twig

diff --git a/db/migrations/stored/R__functions.sql b/db/migrations/stored/R__functions.sql
index 562f2b1ad..917d0d7a7 100644
--- a/db/migrations/stored/R__functions.sql
+++ b/db/migrations/stored/R__functions.sql
@@ -2762,3 +2762,36 @@ NO SQL
     END //
 
 DELIMITER ;
+
+# -------------------------------------------------------------------------------------------
+# Label: Semesters
+# -------------------------------------------------------------------------------------------
+
+DELIMITER //
+DROP FUNCTION IF EXISTS CreateSemester//
+CREATE FUNCTION CreateSemester() RETURNS int(11)
+NO SQL
+BEGIN
+	DECLARE last_sem_id INTEGER;
+    DECLARE sem_num INTEGER;
+    DECLARE sem_year INTEGER;
+    DECLARE vSemesterID INTEGER;
+
+    SELECT MAX(ID) INTO last_sem_id FROM `semesters`;
+    SELECT `Num` INTO sem_num FROM `semesters` WHERE `id`=last_sem_id;
+    SELECT `Year` INTO sem_year FROM `semesters` WHERE `id`=last_sem_id;
+
+    IF (sem_num = '2') THEN
+    	SET sem_year = sem_year + 1;
+        INSERT INTO years(Num) VALUES (sem_year);
+        SET sem_num = '1';
+    ELSE
+    	SET sem_num = '2';
+    END IF;
+
+	INSERT INTO semesters(`Year`, `Num`) VALUES (sem_year, sem_num);
+    SET vSemesterID = LAST_INSERT_ID();
+	RETURN vSemesterID;
+END//
+
+DELIMITER ;
\ No newline at end of file
diff --git a/deploy/phpConfig/sidePanel/admin.json b/deploy/phpConfig/sidePanel/admin.json
index 1946188dc..71bba2b42 100644
--- a/deploy/phpConfig/sidePanel/admin.json
+++ b/deploy/phpConfig/sidePanel/admin.json
@@ -15,7 +15,7 @@
 			{ "Title": "Предметы", "Anchor": "subjects" },
 			{ "Title": "Дисциплины", "Anchor": "disciplines" },
 			{ "Title": "Семестры", "Anchor": "semesters" },
-			{ "Title": "Регламентные", "Anchor": "#", "Disabled": "true" }
+			{ "Title": "Регламентные", "Anchor": "regulatory" }
 		]
 	},
 	{
diff --git a/media/js/office/regulatory.js b/media/js/office/regulatory.js
new file mode 100644
index 000000000..65f7a1f72
--- /dev/null
+++ b/media/js/office/regulatory.js
@@ -0,0 +1,32 @@
+/*
+    Добавление нового семестра в semesterSwitcher может сломаться при изменении его представления,
+    так как данный код использует данные о семестрах из HTML-документа. На работу backend-а влиять не должно.
+ */
+
+$(() => {
+    $('#new_semester_button').click(function (e) {
+        $(this).prop('disabled', true);
+        $.post(URLdir + 'handler/regulatory/new').done(result => {
+            let last_sem = $(".semesterSwitcher ul:first-child a");
+            let last_sem_html = last_sem.html();
+            let season = last_sem_html.slice(0, 5);
+            let year = last_sem_html.slice(6, 10);
+            let id = parseInt(last_sem.attr("id").slice(2))+1;
+            let string_id = last_sem.attr("id").slice(0, 2) + id.toString();
+            if (season === "Весна") {
+                season = "Осень";
+            }
+            else {
+                season = "Весна";
+                year++;
+            }
+            $('.semesterSwitcher ul').prepend('<li><a href=\"#\" id=\"' + string_id + '\" class=\"switchSemester\">'+ season + ' ' + year + '</a></li>');
+            Popup.success('Семестр добавлен');
+
+        }).fail(result => {
+            Popup.error('Ошибка при добавлении семестра');
+        }).always(result => {
+            $(this).prop('disabled', false);
+        });
+    });
+});
diff --git a/media/js/semesterSwitcher.js b/media/js/semesterSwitcher.js
index 4a4aeff57..0fadcf551 100644
--- a/media/js/semesterSwitcher.js
+++ b/media/js/semesterSwitcher.js
@@ -16,5 +16,5 @@ $(function () {
     });
 
     getSemester = () => parseID($semesters);
-});
 
+});
diff --git a/~dev_rating/application/classes/Controller/Handler/Regulatory.php b/~dev_rating/application/classes/Controller/Handler/Regulatory.php
new file mode 100644
index 000000000..e24251259
--- /dev/null
+++ b/~dev_rating/application/classes/Controller/Handler/Regulatory.php
@@ -0,0 +1,37 @@
+<?php defined('SYSPATH') || die('No direct script access.');
+
+class Controller_Handler_Regulatory extends Controller_Handler_Api
+{
+
+    /** @var  Model_Semesters */
+    protected $model;
+
+    public function before() {
+        parent::before();
+
+        $this->user->checkAccess(User::RIGHTS_ADMIN);
+        $this->model = new Model_Semesters([]);
+    }
+
+    public function action_new() {
+
+        $this->user->checkAccess(User::RIGHTS_ADMIN);
+
+        $semester = $this->model->create();
+
+        if (is_null($semester)) {
+            HTTP_API_Exception::factory(500, 'Ошибка приложения');
+        }
+
+
+        $string = file_get_contents(APPPATH . "/config/general.json");
+        $json_a = json_decode($string, true);
+        $json_a['SemesterID']=$semester->ID;
+
+        $string = json_encode($json_a, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK);
+        file_put_contents(APPPATH . "/config/general.json", $string);
+
+    }
+
+
+}
diff --git a/~dev_rating/application/classes/Controller/Office/Regulatory.php b/~dev_rating/application/classes/Controller/Office/Regulatory.php
new file mode 100644
index 000000000..3be4ad339
--- /dev/null
+++ b/~dev_rating/application/classes/Controller/Office/Regulatory.php
@@ -0,0 +1,8 @@
+<?php
+
+class Controller_Office_Regulatory extends Controller_Environment_Office {
+    public function action_index() {
+        $this->user->checkAccess(User::RIGHTS_ADMIN);
+        $this->twig->set_filename(self::OFFICE . 'regulatory/index');
+    }
+}
diff --git a/~dev_rating/application/classes/Model/Semesters.php b/~dev_rating/application/classes/Model/Semesters.php
index d80175c10..5ccd07aa4 100644
--- a/~dev_rating/application/classes/Model/Semesters.php
+++ b/~dev_rating/application/classes/Model/Semesters.php
@@ -25,6 +25,13 @@ class Model_Semesters extends Model
         return $this->data[$name];
     }
 
+    public function create() {
+
+        $sql = 'SELECT `CreateSemester`() AS `ID`';
+        $id = DB::query(Database::SELECT, $sql)
+            ->execute()->get('ID');
+        return self::load($id);
+    }
 
     public static function load($id) {
         $data = DB::query(Database::SELECT, 'CALL `GetSemestersInfo`(:id)')
diff --git a/~dev_rating/application/views/office/regulatory/index.twig b/~dev_rating/application/views/office/regulatory/index.twig
new file mode 100644
index 000000000..af9a3cced
--- /dev/null
+++ b/~dev_rating/application/views/office/regulatory/index.twig
@@ -0,0 +1,20 @@
+{% extends 'office/base' %}
+
+{% block title %}Регламентные{% endblock %}
+
+{% block office_media %} {# head -> css, js #}
+    {#{{ parent() }}#}   {# fixme #}
+    {{ HTML.style('static/css/common/forms.css')|raw }}
+    {{ HTML.script('static/js/office/regulatory.js')|raw }}
+{% endblock %}
+
+
+{% block office_content %}
+
+    <button class="defaultForm BlueButton P2Width" id="new_semester_button">
+        Новый семестр
+    </button>
+
+    <p>По нажатию кнопки в базе данных будет создан новый семестр. Он станет текущим в конфигурации системы.</p>
+
+{% endblock %}
-- 
GitLab