diff --git a/geruecht/controller/databaseController/__init__.py b/geruecht/controller/databaseController/__init__.py index 8f783fd..e53e75b 100644 --- a/geruecht/controller/databaseController/__init__.py +++ b/geruecht/controller/databaseController/__init__.py @@ -1,6 +1,6 @@ from ..mainController import Singleton from geruecht import db -from ..databaseController import dbUserController, dbCreditListController, dbJobKindController, dbPricelistController, dbWorkerController, dbWorkgroupController, dbJobInviteController, dbJobRequesController, dbAccessTokenController, dbRegistrationController +from ..databaseController import dbUserController, dbCreditListController, dbJobKindController, dbPricelistController, dbWorkerController, dbWorkgroupController, dbJobInviteController, dbJobRequesController, dbAccessTokenController, dbRegistrationController, dbFreeDrinkListConfigController from geruecht.exceptions import DatabaseExecption import traceback from MySQLdb._exceptions import IntegrityError @@ -15,6 +15,7 @@ class DatabaseController(dbUserController.Base, dbJobRequesController.Base, dbAccessTokenController.Base, dbRegistrationController.Base, + dbFreeDrinkListConfigController.Base, metaclass=Singleton): ''' DatabaesController diff --git a/geruecht/controller/databaseController/dbFreeDrinkListConfigController.py b/geruecht/controller/databaseController/dbFreeDrinkListConfigController.py new file mode 100644 index 0000000..5844e54 --- /dev/null +++ b/geruecht/controller/databaseController/dbFreeDrinkListConfigController.py @@ -0,0 +1,256 @@ +import traceback +from datetime import datetime +from datetime import timedelta +from geruecht.exceptions import DatabaseExecption + +class Base: + def get_free_drink_list_config(self, id): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'select * from free_drink_list_config where id={id}') + data = cursor.fetchone() + if data['drink_id'] != None: + data['drink'] = self.getDrinkPrice(data['drink_id']) + data['free_drink_types'] = self.get_free_drink_list_types_for_drink(data['id']) + return data + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_configs(self): + try: + cursor = self.db.connection.cursor() + cursor.execute("select * from free_drink_list_config") + retVal = cursor.fetchall() + for data in retVal: + if data['drink_id'] != None: + data['drink'] = self.getDrinkPrice(data['drink_id']) + data['free_drink_types'] = self.get_free_drink_list_types_for_drink(data['id']) + + return retVal + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def set_free_drink_list_config(self, free_drink_list_config): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'insert into free_drink_list_config (drink_id, label, price) values ({free_drink_list_config["drink"]["id"]}, "{free_drink_list_config["label"]}", {free_drink_list_config["price"]})') + self.db.connection.commit() + cursor.execute(f'select id from free_drink_list_config where drink_id={free_drink_list_config["drink"]["id"]} and label="{free_drink_list_config["label"]}" and price={free_drink_list_config["price"]}') + data = cursor.fetchone() + for free_drink_type in free_drink_list_config["free_drink_types"]: + cursor.execute( + f'insert into free_drink_list_type_config (free_drink_list_config_id, free_drink_list_type_id) values ({data["id"]},{free_drink_type["id"]})') + self.db.connection.commit() + return self.get_free_drink_list_configs() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def update_free_drink_list_config(self, free_drink_list_config): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'update free_drink_list_config set drink_id={free_drink_list_config["drink"]["id"]}, label="{free_drink_list_config["label"]}", price={free_drink_list_config["price"]} where id={free_drink_list_config["id"]}') + cursor.execute(f'delete from free_drink_list_type_config where free_drink_list_config_id={free_drink_list_config["id"]}') + for free_drink_type in free_drink_list_config["free_drink_types"]: + cursor.execute(f'insert into free_drink_list_type_config (free_drink_list_config_id, free_drink_list_type_id) values ({free_drink_list_config["id"]},{free_drink_type["id"]})') + self.db.connection.commit() + return self.get_free_drink_list_configs() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def delete_free_drink_list_config(self, free_drink_list_config): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'delete from free_drink_list_type_config where free_drink_list_config_id={free_drink_list_config["id"]}') + cursor.execute(f'delete from free_drink_list_history where free_drink_config_id={free_drink_list_config["id"]}') + cursor.execute(f'delete from free_drink_list_config where id={free_drink_list_config["id"]}') + self.db.connection.commit() + return self.get_free_drink_list_configs() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_types(self): + try: + cursor = self.db.connection.cursor() + cursor.execute('select * from free_drink_list_type') + return cursor.fetchall() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_types_for_drink(self, id): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'select a.* from free_drink_list_type a, free_drink_list_type_config b where free_drink_list_config_id={id} and b.free_drink_list_type_id=a.id') + return cursor.fetchall() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_type(self, name): + try: + cursor = self.db.connection.cursor() + if type(name) == str: + sql = f'select * from free_drink_list_type where name={name}' + elif type(name) == int: + sql = f'select * from free_drink_list_type where id={name}' + else: + raise DatabaseExecption("name as no type int or str. name={}, type={}".format(name, type(name))) + cursor.execute(sql) + return cursor.fetchone() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def set_free_drink_list_history(self, user, free_drink_list_config): + try: + cursor = self.db.connection.cursor() + if 'free_drink_list_reason_id' in free_drink_list_config and 'description' in free_drink_list_config: + sql = f'insert into free_drink_list_history (timestamp, free_drink_config_id, user_id, free_drink_type_id, free_drink_list_reason_id, description) values ("{datetime.now()}", {free_drink_list_config["id"]}, {user.id}, {free_drink_list_config["free_drink_type_id"]}, {free_drink_list_config["free_drink_list_reason_id"]}, "{free_drink_list_config["description"]}")' + else: + sql = f'insert into free_drink_list_history (timestamp, free_drink_config_id, user_id, free_drink_type_id) values ("{datetime.now()}", {free_drink_list_config["id"]}, {user.id}, {free_drink_list_config["free_drink_type_id"]})' + cursor.execute(sql) + self.db.connection.commit() + return self.get_free_drink_list_history_by_user(user) + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_history_by_user(self, user): + try: + cursor = self.db.connection.cursor() + now = datetime.now() + worker = self.getWorker(user, now) + if worker: + timestamp = worker["startdatetime"] + else: + timestamp = datetime.now() - timedelta(minutes=30) + cursor.execute(f'select * from free_drink_list_history where timestamp>="{timestamp}" and (user_id={user.id} or free_drink_type_id=3)') + retVal = cursor.fetchall() + for data in retVal: + data['timestamp'] = {'year': data['timestamp'].year, + 'month': data['timestamp'].month, + 'day': data['timestamp'].day, + 'hour': data['timestamp'].hour, + 'minute': data['timestamp'].minute, + 'second': data['timestamp'].second} + data['free_drink_config'] = self.get_free_drink_list_config(data['free_drink_config_id']) + data['free_drink_type'] = self.get_free_drink_list_type(data['free_drink_type_id']) + data['free_drink_list_reason'] = self.get_free_drink_list_reason(data['free_drink_list_reason_id']) if data['free_drink_list_reason_id'] else None + return retVal + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_history_from_to(self, from_date, to_date): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'select * from free_drink_list_history where timestamp>="{from_date}" and timestamp<="{to_date}"') + retVal = cursor.fetchall() + for data in retVal: + data['timestamp'] = {'year': data['timestamp'].year, + 'month': data['timestamp'].month, + 'day': data['timestamp'].day, + 'hour': data['timestamp'].hour, + 'minute': data['timestamp'].minute, + 'second': data['timestamp'].second} + data['free_drink_config'] = self.get_free_drink_list_config(data['free_drink_config_id']) + data['free_drink_type'] = self.get_free_drink_list_type(data['free_drink_type_id']) + data['free_drink_list_reason'] = self.get_free_drink_list_reason(data['free_drink_list_reason_id']) if \ + data['free_drink_list_reason_id'] else None + data['user'] = self.getUserById(data['user_id'], workgroups=False, geruecht=False).toJSON() + return retVal + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def update_free_drink_list_history(self, free_drink_list_history): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'update free_drink_list_history set canceled={free_drink_list_history["canceled"]} where id={free_drink_list_history["id"]}') + self.db.connection.commit() + return True + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def delete_free_drink_list_history(self, free_drink_list_history): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'delete from free_drink_list_history where id={free_drink_list_history["id"]}') + self.db.connection.commit() + return True + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_reason(self, id): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'select * from free_drink_list_reason where id={id}') + return cursor.fetchone() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def get_free_drink_list_reasons(self): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'select * from free_drink_list_reason') + return cursor.fetchall() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def set_free_drink_list_reason(self, free_drink_list_reason): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'insert into free_drink_list_reason (name) values ("{free_drink_list_reason["name"]}")') + self.db.connection.commit() + return self.get_free_drink_list_reasons() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def update_free_drink_list_reason(self, free_drink_list_reason): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'update free_drink_list_reason set name="{free_drink_list_reason["name"]}" where id={free_drink_list_reason["id"]}') + self.db.connection.commit() + return self.get_free_drink_list_reasons() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) + + def delete_free_drink_list_reason(self, free_drink_list_reason): + try: + cursor = self.db.connection.cursor() + cursor.execute(f'update free_drink_list_history set free_drink_list_reason_id=NULL where free_drink_list_reason_id={free_drink_list_reason["id"]}') + cursor.execute(f'delete from free_drink_list_reason where id={free_drink_list_reason["id"]}') + self.db.connection.commit() + return self.get_free_drink_list_reasons() + except Exception as err: + traceback.print_exc() + self.db.connection.rollback() + raise DatabaseExecption("Something went wrong with Database: {}".format(err)) \ No newline at end of file diff --git a/geruecht/controller/databaseController/dbPricelistController.py b/geruecht/controller/databaseController/dbPricelistController.py index 2b0c749..11f23d1 100644 --- a/geruecht/controller/databaseController/dbPricelistController.py +++ b/geruecht/controller/databaseController/dbPricelistController.py @@ -8,7 +8,10 @@ class Base: try: cursor = self.db.connection.cursor() cursor.execute("select * from pricelist") - return cursor.fetchall() + retVal = cursor.fetchall() + for data in retVal: + data['drink_type'] = self.getDrinkType(data['type']) + return retVal except Exception as err: traceback.print_exc() self.db.connection.rollback() @@ -24,7 +27,10 @@ class Base: else: raise DatabaseExecption("name as no type int or str. name={}, type={}".format(name, type(name))) cursor.execute(sql) - return cursor.fetchone() + retVal = cursor.fetchone() + if retVal: + retVal['drink_type'] = self.getDrinkType(retVal['type']) + return retVal except Exception as err: traceback.print_exc() self.db.connection.rollback() diff --git a/geruecht/controller/databaseController/dbUserController.py b/geruecht/controller/databaseController/dbUserController.py index 3e419d4..4c1dd1c 100644 --- a/geruecht/controller/databaseController/dbUserController.py +++ b/geruecht/controller/databaseController/dbUserController.py @@ -48,7 +48,7 @@ class Base: self.db.connection.rollback() raise DatabaseExecption("Something went worng with Datatabase: {}".format(err)) - def getUserById(self, id, workgroups=True): + def getUserById(self, id, workgroups=True, geruecht=True): try: retVal = None cursor = self.db.connection.cursor() @@ -56,8 +56,9 @@ class Base: data = cursor.fetchone() if data: retVal = User(data) - creditLists = self.getCreditListFromUser(retVal) - retVal.initGeruechte(creditLists) + if geruecht: + creditLists = self.getCreditListFromUser(retVal) + retVal.initGeruechte(creditLists) if workgroups: retVal.workgroups = self.getWorkgroupsOfUser(retVal.id) return retVal diff --git a/geruecht/controller/databaseController/dbWorkerController.py b/geruecht/controller/databaseController/dbWorkerController.py index 3d7652d..c54f16d 100644 --- a/geruecht/controller/databaseController/dbWorkerController.py +++ b/geruecht/controller/databaseController/dbWorkerController.py @@ -8,7 +8,7 @@ class Base: def getWorker(self, user, date): try: cursor = self.db.connection.cursor() - cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date)) + cursor.execute("select * from bardienste where user_id={} and startdatetime<='{}' and enddatetime>='{}'".format(user.id, date, date)) data = cursor.fetchone() return {"user": user.toJSON(), "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime'], "start": { "year": data['startdatetime'].year, "month": data['startdatetime'].month, "day": data['startdatetime'].day}, "job_kind": self.getJobKind(data['job_kind']) if data['job_kind'] != None else None} if data else None except Exception as err: diff --git a/geruecht/controller/mainController/__init__.py b/geruecht/controller/mainController/__init__.py index ae3f73a..aabd653 100644 --- a/geruecht/controller/mainController/__init__.py +++ b/geruecht/controller/mainController/__init__.py @@ -5,7 +5,7 @@ import geruecht.controller.emailController as ec from geruecht.model.user import User from datetime import datetime, timedelta from geruecht.logger import getDebugLogger -from ..mainController import mainJobKindController, mainCreditListController, mainPricelistController, mainUserController, mainWorkerController, mainWorkgroupController, mainJobInviteController, mainJobRequestController, mainRegistrationController, mainPasswordReset +from ..mainController import mainJobKindController, mainCreditListController, mainPricelistController, mainUserController, mainWorkerController, mainWorkgroupController, mainJobInviteController, mainJobRequestController, mainRegistrationController, mainPasswordReset, mainFreeDrinkListConfigController db = dc.DatabaseController() ldap = lc.LDAPController() @@ -24,6 +24,7 @@ class MainController(mainJobKindController.Base, mainJobRequestController.Base, mainRegistrationController.Base, mainPasswordReset.Base, + mainFreeDrinkListConfigController.Base, metaclass=Singleton): def __init__(self): diff --git a/geruecht/controller/mainController/mainFreeDrinkListConfigController.py b/geruecht/controller/mainController/mainFreeDrinkListConfigController.py new file mode 100644 index 0000000..1e8fe9e --- /dev/null +++ b/geruecht/controller/mainController/mainFreeDrinkListConfigController.py @@ -0,0 +1,52 @@ +import geruecht.controller.databaseController as dc +from geruecht.logger import getDebugLogger +from datetime import datetime + +db = dc.DatabaseController() +debug = getDebugLogger() + +class Base: + def get_free_drink_list_configs(self): + return db.get_free_drink_list_configs() + + def set_free_drink_list_config(self, data): + return db.set_free_drink_list_config(data) + + def update_free_drink_list_config(self, data): + return db.update_free_drink_list_config(data) + + def delete_free_drink_list_config(self, data): + return db.delete_free_drink_list_config(data) + + def set_free_drink_list_history(self, user, data): + return db.set_free_drink_list_history(user, data) + + def get_free_drink_list_history(self, user): + return db.get_free_drink_list_history_by_user(user) + + def delete_free_drink_list_history(self, data): + return db.delete_free_drink_list_history(data) + + def update_free_drink_list_history(self, user, data): + db.update_free_drink_list_history(data) + return db.get_free_drink_list_history_by_user(user) + + def get_free_drink_list_history_from_to(self, data): + from_date = datetime(data["from_date"]["year"], data["from_date"]["month"], data["from_date"]["day"]) + to_date = datetime(data["to_date"]["year"], data["to_date"]["month"], data["to_date"]["day"]) + return db.get_free_drink_list_history_from_to(from_date, to_date) + + def get_free_drink_list_reasons(self): + return db.get_free_drink_list_reasons() + + def set_free_drink_list_reason(self, data): + return db.set_free_drink_list_reason(data) + + def update_free_drink_list_reason(self, data): + return db.update_free_drink_list_reason(data) + + def delete_free_drink_list_reason(self, data): + return db.delete_free_drink_list_reason(data) + + def get_free_drink_types(self): + return db.get_free_drink_list_types() \ No newline at end of file diff --git a/geruecht/routes.py b/geruecht/routes.py index 07b78ce..810b141 100644 --- a/geruecht/routes.py +++ b/geruecht/routes.py @@ -26,6 +26,124 @@ def _valid(**kwargs): debug.warning("exception in valide.", exc_info=True) return jsonify({"error": str(err)}), 500 +@app.route("/freeDrinkListConfig", methods=['GET', 'POST', 'PUT']) +@login_required() +def _free_drink_list_config(**kwargs): + try: + debug.info("get free_drink_list_config") + if request.method == 'GET': + retVal = mainController.get_free_drink_list_configs() + if request.method == 'POST': + data = request.get_json() + retVal = mainController.set_free_drink_list_config(data) + if request.method == 'PUT': + data = request.get_json() + retVal = mainController.update_free_drink_list_config(data) + debug.info("return free_drink_list_config {{ {} }}".format(retVal)) + return jsonify(retVal) + except Exception as err: + debug.warning("exception in get free_dirnk_list_config.", exc_info=True) + return jsonify({"error": str(err)}), 500 + +@app.route("/deleteFreeDrinkListConfig", methods=['POST']) +@login_required() +def _delete_free_drink_list_config(**kwargs): + try: + debug.info("delete free_drink_list_config") + data = request.get_json() + retVal = mainController.delete_free_drink_list_config(data) + debug.info("return delete_free_drink_list_config {{ {} }}".format(retVal)) + return jsonify(retVal) + except Exception as err: + debug.warning("exception in delete_free_dirnk_list_config.", exc_info=True) + return jsonify({"error": str(err)}), 500 + +@app.route("/freeDrinkListHistory", methods=['GET', 'POST', 'PUT']) +@login_required() +def _free_drink_list_history(**kwargs): + try: + debug.info("set free_drink_list_history") + user = kwargs['accToken'].user + if request.method == 'GET': + retVal = mainController.get_free_drink_list_history(user) + if request.method == 'POST' or request.method == 'PUT': + data = request.get_json() + if request.method == 'POST': + retVal = mainController.set_free_drink_list_history(user, data) + else: + retVal = mainController.update_free_drink_list_history(user, data) + debug.debug(f'return free_drink_list_history {{{retVal}}}') + return jsonify(retVal) + except Exception as err: + debug.warning("exception in get free_dirnk_list_config.", exc_info=True) + return jsonify({"error": str(err)}), 500 + +@app.route("/freeDrinkListHistoryFromTo", methods=['POST']) +@login_required(groups=[VORSTAND]) +def _free_drink_list_history_from_to(**kwargs): + try: + debug.info("get free_drink_list_history") + data = request.get_json() + retVal = mainController.get_free_drink_list_history_from_to(data) + debug.debug(f'return free_drink_list_history {{{retVal}}}') + return jsonify(retVal) + except Exception as err: + debug.warning("exception in get free_dirnk_list_history.", exc_info=True) + return jsonify({"error": str(err)}), 500 + +@app.route("/deleteDrinkListHistory", methods=['POST']) +@login_required() +def _delete_free_drink_list_history(**kwargs): + try: + debug.info("delete free_drink_list_history") + data = request.get_json() + retVal = mainController.delete_free_drink_list_history(data) + return jsonify({"ok": retVal}) + except Exception as err: + debug.warning("exception in delete free_dirnk_list_config.", exc_info=True) + return jsonify({"error": str(err)}), 500 + +@app.route("/freeDrinkListReasons", methods=['GET', 'POST', 'PUT']) +@login_required() +def _free_drink_list_reasons(**kwargs): + try: + debug.info("get free_drink_list_reasons") + if request.method == 'GET': + retVal = mainController.get_free_drink_list_reasons() + elif request.method == 'POST' or request.method == 'PUT': + data = request.get_json() + if request.method == 'POST': + retVal = mainController.set_free_drink_list_reason(data) + else: + retVal = mainController.update_free_drink_list_reason(data) + return jsonify(retVal) + except Exception as err: + debug.warning("exception in delete free_dirnk_list_reasons.", exc_info=True) + return jsonify({"error": str(err)}), 500 + +@app.route("/deleteFreeDrinkListReason", methods=['POST']) +@login_required(groups=[VORSTAND]) +def __delete_free_drink_list_reason(**kwargs): + try: + debug.info("delete free_drink_list_reason") + data = request.get_json() + retVal = mainController.delete_free_drink_list_reason(data) + return jsonify(retVal) + except Exception as err: + debug.warning("exception in delete free_dirnk_list_reasons.", exc_info=True) + return jsonify({"error": str(err)}), 500 + +@app.route("/freeDrinkTypes", methods=['GET', 'POST']) +@login_required() +def _free_drink_types(**kwargs): + try: + debug.info("get free_drnik_types") + retVal = mainController.get_free_drink_types() + return jsonify(retVal) + except Exception as err: + debug.warning("exception in free_dirnk_types.", exc_info=True) + return jsonify({"error": str(err)}), 500 + @app.route("/pricelist", methods=['GET']) def _getPricelist(): try: @@ -37,7 +155,6 @@ def _getPricelist(): debug.warning("exception in get pricelist.", exc_info=True) return jsonify({"error": str(err)}), 500 - @app.route('/drinkTypes', methods=['GET']) def getTypes(): try: