From 19d5ce088e0fd406e6034caf6322551ee14f2a3b Mon Sep 17 00:00:00 2001 From: Anton Kamalov Date: Thu, 14 Nov 2024 19:19:48 +0300 Subject: [PATCH] Fix in Requests + in Report part --- App/Report/__init__.py | 60 +++++++++++++++++++++++--- App/Report/access/1.json | 7 +++ App/Report/db/DBconnect.py | 34 +++++++++++++++ App/Report/db/__init__.py | 0 App/Report/db/sql_provider.py | 14 ++++++ App/Report/db/work.py | 23 ++++++++++ App/Report/reports.json | 2 +- App/Report/sql/check_report.sql | 4 ++ App/Report/sql/report1.sql | 11 ----- App/Report/sql/view_report.sql | 5 +++ App/Report/templates/OK.html | 15 +++++++ App/Report/templates/quaterly.html | 18 -------- App/Report/templates/report_basic.html | 45 +++++++++++++++++++ App/Report/templates/report_menu.html | 9 ++-- App/Requests/requests_model.py | 4 +- App/app.py | 4 +- App/data/db_access.json | 14 ++++-- App/templates/main_menu.html | 7 +-- 18 files changed, 222 insertions(+), 54 deletions(-) create mode 100644 App/Report/access/1.json create mode 100644 App/Report/db/DBconnect.py create mode 100644 App/Report/db/__init__.py create mode 100644 App/Report/db/sql_provider.py create mode 100644 App/Report/db/work.py create mode 100644 App/Report/sql/check_report.sql delete mode 100644 App/Report/sql/report1.sql create mode 100644 App/Report/sql/view_report.sql create mode 100644 App/Report/templates/OK.html delete mode 100644 App/Report/templates/quaterly.html create mode 100644 App/Report/templates/report_basic.html diff --git a/App/Report/__init__.py b/App/Report/__init__.py index 068da0c..10c12e9 100644 --- a/App/Report/__init__.py +++ b/App/Report/__init__.py @@ -1,21 +1,67 @@ -from flask import request, Blueprint, render_template +from flask import request, Blueprint, render_template, session, url_for from checker import check_auth from os import path +from .report_model import sales_report, make_report import json with open(path.join(path.dirname(__file__), 'reports.json')) as f: report_list = json.load(f) + report_bp = Blueprint('report_bp', __name__, template_folder='templates') -@report_bp.route('/', methods=['GET', 'POST']) +@report_bp.route('/menu') @check_auth def menu(): if request.method == 'GET': - return render_template('report_menu.html', options=report_list) - -@report_bp.route('/quaterly', methods=['GET', 'POST']) + return render_template('report_menu.html') + +@report_bp.route('/create', methods=['GET', 'POST']) @check_auth -def quaterly(): +def create(): if request.method == 'GET': - return render_template('quaterly.html') + return render_template('report_basic.html', + write=True, + title='Создание отчета', + items = report_list) + else: + data = dict(month=request.form.get('month'), year=request.form.get('year')) + id = request.form.get('category') + with open(path.join(path.dirname(__file__), f'access/{id}.json')) as f: + report_access = json.load(f) + + if session['role'] in report_access['write']: + proc_name = report_access['procedure'] + ready_report = make_report(data, proc_name) + if ready_report.status: + return render_template("OK.html") + else: + return render_template("error.html", error_message=ready_report.error_message) + else: + return render_template("error.html", error_message='Недостаточно прав для создания данного отчета!') + +@report_bp.route('/view', methods=['GET', 'POST']) +@check_auth +def view(): + if request.method == 'GET': + return render_template('report_basic.html', + write=False, + title='Просмотр отчета', + items = report_list) + else: + data = dict(month=request.form.get('month'), year=request.form.get('year')) + id = request.form.get('category') + with open(path.join(path.dirname(__file__), f'access/{id}.json')) as f: + report_access = json.load(f) + + if session['role'] in report_access['read']: + ready_report = sales_report(data, report_access['view']) + if ready_report.status: + title= f'{report_access["title"]} за {data["month"]}-{data["year"]}' + return render_template("output.html", items=ready_report.result, + header=title, + link = url_for('report_bp.menu')) + else: + return render_template("error.html", error_message=ready_report.error_message) + else: + return render_template("error.html", error_message='Недосточно прав для чтения данного отчета!') \ No newline at end of file diff --git a/App/Report/access/1.json b/App/Report/access/1.json new file mode 100644 index 0000000..b719ab9 --- /dev/null +++ b/App/Report/access/1.json @@ -0,0 +1,7 @@ +{ + "title" : "Отчет о продажах", + "write" : ["Менеджер"], + "read" : ["Управляющий"], + "view" : "view_report", + "procedure" : "generate_report" +} \ No newline at end of file diff --git a/App/Report/db/DBconnect.py b/App/Report/db/DBconnect.py new file mode 100644 index 0000000..b335654 --- /dev/null +++ b/App/Report/db/DBconnect.py @@ -0,0 +1,34 @@ +import pymysql +from pymysql.err import * +class DBContextManager: + def __init__(self, db_config : dict): + self.db_config = db_config + self.connection = None + self.cursor = None + + def __enter__(self): + try: + self.connection = pymysql.connect( + host=self.db_config['host'], + port=self.db_config['port'], + user=self.db_config['user'], + password=self.db_config['password'], + db=self.db_config['db'] + ) + self.cursor = self.connection.cursor() + return self.cursor + except (OperationalError, KeyError) as err: + print(err.args) + return None + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.connection and self.cursor: + if exc_type: + print(exc_type, '\n', exc_val) + self.connection.rollback() + else: + self.connection.commit() + self.cursor.close() + self.connection.close() + return True + \ No newline at end of file diff --git a/App/Report/db/__init__.py b/App/Report/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/App/Report/db/sql_provider.py b/App/Report/db/sql_provider.py new file mode 100644 index 0000000..a3a1855 --- /dev/null +++ b/App/Report/db/sql_provider.py @@ -0,0 +1,14 @@ +import os +from string import Template + +class SQLProvider: + def __init__(self, file_path): + self.scripts = {} + for file in os.listdir(file_path): + _sql = open(f'{file_path}/{file}').read() + self.scripts[file] = Template(_sql) + + def get(self, name, params) -> dict: + if name not in self.scripts: + raise ValueError(f'SQL template {name} not found') + return self.scripts[name].substitute(**params) \ No newline at end of file diff --git a/App/Report/db/work.py b/App/Report/db/work.py new file mode 100644 index 0000000..2fd1ff3 --- /dev/null +++ b/App/Report/db/work.py @@ -0,0 +1,23 @@ +from .DBconnect import DBContextManager + +def select_list(db_config, sql) -> list: + with DBContextManager(db_config) as cursor: + if cursor is None: + raise ValueError("Cursor not created") + else: + cursor.execute(sql) + result = cursor.fetchall() + schema = [item[0] for item in cursor.description] + lst = [dict(zip(schema, row)) for row in result] + return lst + +def procedure(db_config, name, args: tuple): + with DBContextManager(db_config) as cursor: + if cursor is None: + raise ValueError("Cursor not created") + else: + cursor.callproc(name, args) + result = cursor.fetchall()[0] + schema = cursor.description[0] + lst = dict(zip(schema, result)) + return lst \ No newline at end of file diff --git a/App/Report/reports.json b/App/Report/reports.json index 04f2742..9c9d5b0 100644 --- a/App/Report/reports.json +++ b/App/Report/reports.json @@ -1,3 +1,3 @@ [ - {"name": "Квартальный отчет передвижений заготовок", "url": "report_bp.quaterly"} + {"id": 1, "name": "Покупки за месяц", "json_file": "access/sales.json"} ] \ No newline at end of file diff --git a/App/Report/sql/check_report.sql b/App/Report/sql/check_report.sql new file mode 100644 index 0000000..3c42460 --- /dev/null +++ b/App/Report/sql/check_report.sql @@ -0,0 +1,4 @@ +SELECT EXISTS ( + SELECT 1 FROM reports + WHERE month = $month AND year = $year +) AS exist; \ No newline at end of file diff --git a/App/Report/sql/report1.sql b/App/Report/sql/report1.sql deleted file mode 100644 index bac1519..0000000 --- a/App/Report/sql/report1.sql +++ /dev/null @@ -1,11 +0,0 @@ -SELECT sellers.name AS 'Поставщик', - w.date_of_delivery AS 'Дата поставки', - SUM(wl.count) AS 'Общее количество заготовок', - SUM(wl.price) AS 'Общая стоимость поставленных заготовок' -FROM waybill w -JOIN waybill_lines wl USING(waybill_id) -JOIN workpiece USING(work_id) -JOIN sellers USING(sel_id) -WHERE workpiece.material = '${material}' -AND (w.date_of_delivery BETWEEN '${date_from}' AND '${date_to}') -GROUP BY sellers.name, w.date_of_delivery; diff --git a/App/Report/sql/view_report.sql b/App/Report/sql/view_report.sql new file mode 100644 index 0000000..230f9c6 --- /dev/null +++ b/App/Report/sql/view_report.sql @@ -0,0 +1,5 @@ +SELECT name_of_product AS 'Наименование', + count_of_bought AS 'Количество', + sum AS 'Общая стоимость' +FROM reports +WHERE month = '$month' AND year = '$year'; \ No newline at end of file diff --git a/App/Report/templates/OK.html b/App/Report/templates/OK.html new file mode 100644 index 0000000..bbb836c --- /dev/null +++ b/App/Report/templates/OK.html @@ -0,0 +1,15 @@ + + + + + Успех + + + + +

Успешно!

+

Отчет успешно добавлен в базу данных!

+ + + + \ No newline at end of file diff --git a/App/Report/templates/quaterly.html b/App/Report/templates/quaterly.html deleted file mode 100644 index 5698b30..0000000 --- a/App/Report/templates/quaterly.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Квартальный отчет - - - -
- -
- -

Заглушка для квартального отчета

-
- -
- - \ No newline at end of file diff --git a/App/Report/templates/report_basic.html b/App/Report/templates/report_basic.html new file mode 100644 index 0000000..9faef9f --- /dev/null +++ b/App/Report/templates/report_basic.html @@ -0,0 +1,45 @@ + + + + + {{ title }} + + + +
+ +
+

{{ title }}

+ +
+ {% for item in items %} + + {% endfor %} + + + {% if write %} + + {% else %} + + {% endif %} +
+
+ +
+ + \ No newline at end of file diff --git a/App/Report/templates/report_menu.html b/App/Report/templates/report_menu.html index e604a1b..53906e3 100644 --- a/App/Report/templates/report_menu.html +++ b/App/Report/templates/report_menu.html @@ -10,11 +10,10 @@

Выберите вариант отчетов

- +
+ + +
diff --git a/App/Requests/requests_model.py b/App/Requests/requests_model.py index 813be3d..f1443f6 100644 --- a/App/Requests/requests_model.py +++ b/App/Requests/requests_model.py @@ -1,6 +1,6 @@ from dataclasses import dataclass -from db.select import select_list -from db.sql_provider import SQLProvider +from .db.select import select_list +from .db.sql_provider import SQLProvider from flask import current_app from os import path diff --git a/App/app.py b/App/app.py index 887facd..cd4ad61 100644 --- a/App/app.py +++ b/App/app.py @@ -26,4 +26,6 @@ def index(): def logout(): session.clear() return render_template('main_menu.html', ses=session) -app.run(port=5002, host='0.0.0.0') \ No newline at end of file + +if __name__ == '__main__': + app.run(port=5002, host='0.0.0.0') \ No newline at end of file diff --git a/App/data/db_access.json b/App/data/db_access.json index 24d1e7e..a64f3e9 100644 --- a/App/data/db_access.json +++ b/App/data/db_access.json @@ -1,5 +1,11 @@ { - "Менеджер": ["auth_bp", "requests_bp"], - "Управляющий": ["auth_bp", "requests_bp", "report_bp"], - "Поставщик": ["auth_bp", "waybill_bp"] - } \ No newline at end of file + "Менеджер": [ + "requests_bp", + "report_bp"], + "Управляющий": [ + "requests_bp", + "report_bp"], + "Поставщик": [ + "waybill_bp"] + +} \ No newline at end of file diff --git a/App/templates/main_menu.html b/App/templates/main_menu.html index 479e5e0..288fbd0 100644 --- a/App/templates/main_menu.html +++ b/App/templates/main_menu.html @@ -11,18 +11,15 @@

Здравствуйте, {{ ses['login'] }}!

-

Ваша роль: {{ ses['role'] }}

{% if ses['access_user'] == 'internal_users' %} +

Ваша роль: {{ ses['role'] }}

{% else %} - +

Not implemented

{% endif %} {% else %}