Restructured project, renamed modules, removed geruecht as it is dead.
This commit is contained in:
parent
58302595f3
commit
a5d3b837cd
|
@ -10,4 +10,5 @@ from werkzeug.local import LocalProxy
|
|||
|
||||
__version__ = pkg_resources.get_distribution("flaschengeist").version
|
||||
_module_path = Path(__file__).parent
|
||||
logger = LocalProxy(lambda: logging.getLogger(__name__))
|
||||
|
||||
logger: logging.Logger = LocalProxy(lambda: logging.getLogger(__name__))
|
||||
|
|
|
@ -6,9 +6,9 @@ from flask.json import JSONEncoder, jsonify
|
|||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from . import logger
|
||||
from .modules import AuthPlugin
|
||||
from .system.config import config, configure_app
|
||||
from .system.controller import roleController
|
||||
from .plugins import AuthPlugin
|
||||
from flaschengeist.config import config, configure_app
|
||||
from flaschengeist.controller import roleController
|
||||
|
||||
|
||||
class CustomJSONEncoder(JSONEncoder):
|
||||
|
@ -56,8 +56,7 @@ def __load_plugins(app):
|
|||
|
||||
|
||||
def install_all():
|
||||
from flaschengeist.system.database import db
|
||||
from flaschengeist.system.models import user, event, session
|
||||
from flaschengeist.database import db
|
||||
|
||||
db.create_all()
|
||||
db.session.commit()
|
||||
|
@ -77,7 +76,7 @@ def create_app():
|
|||
CORS(app)
|
||||
|
||||
with app.app_context():
|
||||
from .system.database import db
|
||||
from flaschengeist.database import db
|
||||
|
||||
configure_app(app)
|
||||
db.init_app(app)
|
||||
|
|
|
@ -3,7 +3,7 @@ import os
|
|||
import toml
|
||||
from pathlib import Path
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
from .. import _module_path, logger
|
||||
from flaschengeist import _module_path, logger
|
||||
|
||||
# Default config:
|
||||
config = {}
|
|
@ -2,8 +2,8 @@ from werkzeug.exceptions import BadRequest, NotFound
|
|||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.system.database import db
|
||||
from flaschengeist.system.models.event import EventKind, Event, EventSlot, JobSlot, JobKind
|
||||
from flaschengeist.database import db
|
||||
from flaschengeist.models.event import EventKind, Event, EventSlot, JobSlot, JobKind
|
||||
|
||||
|
||||
def get_event(id):
|
|
@ -1,6 +1,5 @@
|
|||
from flaschengeist import logger
|
||||
from flaschengeist.system.hook import Hook
|
||||
from flaschengeist.system.models.user import User, Role
|
||||
from flaschengeist.hook import Hook
|
||||
from flaschengeist.models.user import User, Role
|
||||
|
||||
|
||||
class Message:
|
|
@ -1,8 +1,8 @@
|
|||
from sqlalchemy.exc import IntegrityError
|
||||
from werkzeug.exceptions import BadRequest, NotFound
|
||||
|
||||
from flaschengeist.system.models.user import Role, Permission
|
||||
from flaschengeist.system.database import db
|
||||
from flaschengeist.models.user import Role, Permission
|
||||
from flaschengeist.database import db
|
||||
from flaschengeist import logger
|
||||
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import secrets
|
||||
from ..models.session import Session
|
||||
from flaschengeist.system.database import db
|
||||
from flaschengeist.models.session import Session
|
||||
from flaschengeist.database import db
|
||||
from flaschengeist import logger
|
||||
from werkzeug.exceptions import Forbidden
|
||||
from datetime import datetime, timezone
|
|
@ -1,8 +1,8 @@
|
|||
from flask import current_app
|
||||
from werkzeug.exceptions import NotFound, BadRequest
|
||||
|
||||
from flaschengeist.system.models.user import User, Role
|
||||
from flaschengeist.system.database import db
|
||||
from flaschengeist.models.user import User, Role
|
||||
from flaschengeist.database import db
|
||||
from flaschengeist import logger
|
||||
|
||||
|
|
@ -3,7 +3,7 @@ from flask import request
|
|||
from werkzeug.exceptions import Unauthorized
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.system.controller import sessionController
|
||||
from flaschengeist.controller import sessionController
|
||||
|
||||
|
||||
def login_required(permission=None):
|
|
@ -3,7 +3,7 @@ from typing import Optional
|
|||
|
||||
from . import ModelSerializeMixin
|
||||
from .user import User
|
||||
from ..database import db
|
||||
from flaschengeist.database import db
|
||||
|
||||
|
||||
class EventSlot(db.Model, ModelSerializeMixin):
|
|
@ -2,7 +2,7 @@ from datetime import datetime, timedelta, timezone
|
|||
|
||||
from . import ModelSerializeMixin, UtcDateTime
|
||||
from .user import User
|
||||
from ..database import db
|
||||
from flaschengeist.database import db
|
||||
from secrets import compare_digest
|
||||
from flaschengeist import logger
|
||||
|
|
@ -1,10 +1,7 @@
|
|||
from typing import List
|
||||
|
||||
from sqlalchemy.orm.collections import attribute_mapped_collection
|
||||
|
||||
from . import ModelSerializeMixin
|
||||
from ..database import db
|
||||
from ... import logger
|
||||
from flaschengeist.database import db
|
||||
|
||||
association_table = db.Table(
|
||||
"user_x_role",
|
|
@ -1,224 +0,0 @@
|
|||
from flask import Blueprint, request, jsonify
|
||||
import geruecht.controller.ldapController as lc
|
||||
import geruecht.controller.mainController as mc
|
||||
import geruecht.controller.accesTokenController as ac
|
||||
from datetime import datetime
|
||||
from geruecht.model import BAR, MONEY, USER, VORSTAND, EXTERN
|
||||
from geruecht.decorator import login_required
|
||||
from geruecht.logger import getDebugLogger, getCreditLogger
|
||||
|
||||
debug = getDebugLogger()
|
||||
creditL = getCreditLogger()
|
||||
|
||||
baruser = Blueprint("baruser", __name__)
|
||||
|
||||
ldap = lc.LDAPController()
|
||||
mainController = mc.MainController()
|
||||
accesTokenController = ac.AccesTokenController()
|
||||
|
||||
|
||||
@baruser.route("/bar")
|
||||
@login_required(groups=[BAR], bar=True)
|
||||
def _bar(**kwargs):
|
||||
""" Main function for Baruser
|
||||
|
||||
Returns JSON-file with all Users, who hast amounts in this month.
|
||||
|
||||
Returns:
|
||||
JSON-File with Users, who has amounts in this month
|
||||
or ERROR 401 Permission Denied
|
||||
"""
|
||||
debug.info("/bar")
|
||||
try:
|
||||
dic = {}
|
||||
users = mainController.getAllUsersfromDB()
|
||||
for user in users:
|
||||
geruecht = None
|
||||
geruecht = user.getGeruecht(datetime.now().year)
|
||||
if geruecht is not None:
|
||||
all = geruecht.getSchulden()
|
||||
if all != 0:
|
||||
if all >= 0:
|
||||
type = 'credit'
|
||||
else:
|
||||
type = 'amount'
|
||||
dic[user.userid] = {"username": user.userid,
|
||||
"firstname": user.firstname,
|
||||
"lastname": user.lastname,
|
||||
"amount": all,
|
||||
"locked": user.locked,
|
||||
"type": type,
|
||||
"limit": user.limit,
|
||||
"autoLock": user.autoLock
|
||||
}
|
||||
dic[user.userid]['last_seen'] = {"year": user.last_seen.year, "month": user.last_seen.month, "day": user.last_seen.day, "hour": user.last_seen.hour, "minute": user.last_seen.minute, "second": user.last_seen.second} if user.last_seen else None
|
||||
debug.debug("return {{ {} }}".format(dic))
|
||||
return jsonify(dic)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@baruser.route("/baradd", methods=['POST'])
|
||||
@login_required(groups=[BAR], bar=True)
|
||||
def _baradd(**kwargs):
|
||||
""" Function for Baruser to add amount
|
||||
|
||||
This function added to the user with the posted userID the posted amount.
|
||||
|
||||
Returns:
|
||||
JSON-File with userID and the amount
|
||||
or ERROR 401 Permission Denied
|
||||
"""
|
||||
debug.info("/baradd")
|
||||
try:
|
||||
data = request.get_json()
|
||||
userID = data['userId']
|
||||
amount = int(data['amount'])
|
||||
amountl = amount
|
||||
date = datetime.now()
|
||||
mainController.addAmount(
|
||||
userID, amount, year=date.year, month=date.month, bar=True)
|
||||
user = mainController.getUser(userID)
|
||||
geruecht = user.getGeruecht(year=date.year)
|
||||
month = geruecht.getMonth(month=date.month)
|
||||
amount = abs(month[0] - month[1])
|
||||
all = geruecht.getSchulden()
|
||||
if all >= 0:
|
||||
type = 'credit'
|
||||
else:
|
||||
type = 'amount'
|
||||
dic = user.toJSON()
|
||||
dic['amount'] = all
|
||||
dic['type'] = type
|
||||
dic['last_seen'] = {"year": user.last_seen.year, "month": user.last_seen.month, "day": user.last_seen.day, "hour": user.last_seen.hour, "minute": user.last_seen.minute, "second": user.last_seen.second} if user.last_seen else None
|
||||
debug.debug("return {{ {} }}".format(dic))
|
||||
creditL.info("{} Baruser {} {} fügt {} {} {} € Schulden hinzu.".format(
|
||||
date, kwargs['accToken'].user.firstname, kwargs['accToken'].user.lastname, user.firstname, user.lastname, amountl/100))
|
||||
return jsonify(dic)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@baruser.route("/barGetUsers")
|
||||
@login_required(groups=[BAR, MONEY], bar=True)
|
||||
def _getUsers(**kwargs):
|
||||
""" Get Users without amount
|
||||
|
||||
This Function returns all Users, who hasn't an amount in this month.
|
||||
|
||||
Returns:
|
||||
JSON-File with Users
|
||||
or ERROR 401 Permission Denied
|
||||
"""
|
||||
debug.info("/barGetUsers")
|
||||
try:
|
||||
retVal = {}
|
||||
retVal = ldap.getAllUser()
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@baruser.route("/bar/storno", methods=['POST'])
|
||||
@login_required(groups=[BAR], bar=True)
|
||||
def _storno(**kwargs):
|
||||
""" Function for Baruser to storno amount
|
||||
|
||||
This function added to the user with the posted userID the posted amount.
|
||||
|
||||
Returns:
|
||||
JSON-File with userID and the amount
|
||||
or ERROR 401 Permission Denied
|
||||
"""
|
||||
debug.info("/bar/storno")
|
||||
try:
|
||||
data = request.get_json()
|
||||
userID = data['userId']
|
||||
amount = int(data['amount'])
|
||||
amountl = amount
|
||||
date = datetime.now()
|
||||
mainController.addCredit(
|
||||
userID, amount, year=date.year, month=date.month)
|
||||
user = mainController.getUser(userID)
|
||||
geruecht = user.getGeruecht(year=date.year)
|
||||
month = geruecht.getMonth(month=date.month)
|
||||
amount = abs(month[0] - month[1])
|
||||
all = geruecht.getSchulden()
|
||||
if all >= 0:
|
||||
type = 'credit'
|
||||
else:
|
||||
type = 'amount'
|
||||
dic = user.toJSON()
|
||||
dic['amount'] = all
|
||||
dic['type'] = type
|
||||
dic['last_seen'] = {"year": user.last_seen.year, "month": user.last_seen.month, "day": user.last_seen.day,
|
||||
"hour": user.last_seen.hour, "minute": user.last_seen.minute,
|
||||
"second": user.last_seen.second} if user.last_seen else None
|
||||
debug.debug("return {{ {} }}".format(dic))
|
||||
creditL.info("{} Baruser {} {} storniert {} € von {} {}".format(
|
||||
date, kwargs['accToken'].user.firstname, kwargs['accToken'].user.lastname, amountl/100, user.firstname, user.lastname))
|
||||
return jsonify(dic)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@baruser.route("/barGetUser", methods=['POST'])
|
||||
@login_required(groups=[BAR], bar=True)
|
||||
def _getUser(**kwargs):
|
||||
debug.info("/barGetUser")
|
||||
try:
|
||||
data = request.get_json()
|
||||
username = data['userId']
|
||||
user = mainController.getUser(username)
|
||||
amount = user.getGeruecht(datetime.now().year).getSchulden()
|
||||
if amount >= 0:
|
||||
type = 'credit'
|
||||
else:
|
||||
type = 'amount'
|
||||
|
||||
retVal = user.toJSON()
|
||||
retVal['amount'] = amount
|
||||
retVal['type'] = type
|
||||
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@baruser.route("/search", methods=['GET'])
|
||||
@login_required(groups=[BAR, MONEY, USER, VORSTAND], bar=True)
|
||||
def _search(**kwargs):
|
||||
debug.info("/search")
|
||||
try:
|
||||
retVal = ldap.getAllUser()
|
||||
for user in retVal:
|
||||
if user['username'] == 'extern':
|
||||
retVal.remove(user)
|
||||
break
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@baruser.route("/bar/lock", methods=['GET', 'POST'])
|
||||
@login_required(groups=[BAR], bar=True)
|
||||
def _lockbar(**kwargs):
|
||||
|
||||
debug.info('/bar/lock')
|
||||
accToken = kwargs['accToken']
|
||||
if request.method == "POST":
|
||||
data = request.get_json()
|
||||
accToken.lock_bar = data['value']
|
||||
accToken = accesTokenController.updateAccessToken(accToken)
|
||||
accToken = accesTokenController.validateAccessToken(accToken.token, [USER, EXTERN])
|
||||
debug.debug('return {{ "value": {} }}'.format(accToken.lock_bar))
|
||||
return jsonify({'value': accToken.lock_bar})
|
||||
|
|
@ -1,324 +0,0 @@
|
|||
from datetime import datetime
|
||||
from geruecht.logger import getDebugLogger
|
||||
|
||||
debug = getDebugLogger()
|
||||
|
||||
def create_empty_data():
|
||||
empty_data = {'id': 0,
|
||||
'jan_guthaben': 0,
|
||||
'jan_schulden': 0,
|
||||
'feb_guthaben': 0,
|
||||
'feb_schulden': 0,
|
||||
'maer_guthaben': 0,
|
||||
'maer_schulden': 0,
|
||||
'apr_guthaben': 0,
|
||||
'apr_schulden': 0,
|
||||
'mai_guthaben': 0,
|
||||
'mai_schulden': 0,
|
||||
'jun_guthaben': 0,
|
||||
'jun_schulden': 0,
|
||||
'jul_guthaben': 0,
|
||||
'jul_schulden': 0,
|
||||
'aug_guthaben': 0,
|
||||
'aug_schulden': 0,
|
||||
'sep_guthaben': 0,
|
||||
'sep_schulden': 0,
|
||||
'okt_guthaben': 0,
|
||||
'okt_schulden': 0,
|
||||
'nov_guthaben': 0,
|
||||
'nov_schulden': 0,
|
||||
'dez_guthaben': 0,
|
||||
'dez_schulden': 0,
|
||||
'last_schulden': 0,
|
||||
'year_date': datetime.now().year,
|
||||
'user_id': 0}
|
||||
return empty_data
|
||||
|
||||
class CreditList():
|
||||
""" DataBase Object Credit List:
|
||||
|
||||
Attributes:
|
||||
id: id in Database. Is the Primary Key
|
||||
<month>_guthaben: Credit of the Month.
|
||||
<month>_schulden: Debt of the Month.
|
||||
|
||||
last_schulden: Debt or Credit of last Year.
|
||||
year: Year of all Credits and Debts.
|
||||
user_id: id from the User.
|
||||
"""
|
||||
def __init__(self, data):
|
||||
debug.debug("init creditlist")
|
||||
self.id = int(data['id'])
|
||||
|
||||
self.jan_guthaben = int(data['jan_guthaben'])
|
||||
self.jan_schulden = int(data['jan_schulden'])
|
||||
|
||||
self.feb_guthaben = int(data['feb_guthaben'])
|
||||
self.feb_schulden = int(data['feb_schulden'])
|
||||
|
||||
self.maer_guthaben = int(data['maer_guthaben'])
|
||||
self.maer_schulden = int(data['maer_schulden'])
|
||||
|
||||
self.apr_guthaben = int(data['apr_guthaben'])
|
||||
self.apr_schulden = int(data['apr_schulden'])
|
||||
|
||||
self.mai_guthaben = int(data['mai_guthaben'])
|
||||
self.mai_schulden = int(data['mai_schulden'])
|
||||
|
||||
self.jun_guthaben = int(data['jun_guthaben'])
|
||||
self.jun_schulden = int(data['jun_schulden'])
|
||||
|
||||
self.jul_guthaben = int(data['jul_guthaben'])
|
||||
self.jul_schulden = int(data['jul_schulden'])
|
||||
|
||||
self.aug_guthaben = int(data['aug_guthaben'])
|
||||
self.aug_schulden = int(data['aug_schulden'])
|
||||
|
||||
self.sep_guthaben = int(data['sep_guthaben'])
|
||||
self.sep_schulden = int(data['sep_schulden'])
|
||||
|
||||
self.okt_guthaben = int(data['okt_guthaben'])
|
||||
self.okt_schulden = int(data['okt_schulden'])
|
||||
|
||||
self.nov_guthaben = int(data['nov_guthaben'])
|
||||
self.nov_schulden = int(data['nov_schulden'])
|
||||
|
||||
self.dez_guthaben = int(data['dez_guthaben'])
|
||||
self.dez_schulden = int(data['dez_schulden'])
|
||||
|
||||
self.last_schulden = int(data['last_schulden'])
|
||||
|
||||
self.year = int(data['year_date'])
|
||||
|
||||
self.user_id = int(data['user_id'])
|
||||
|
||||
debug.debug("credit list is {{ {} }}".format(self))
|
||||
|
||||
def getSchulden(self):
|
||||
""" Get Schulden
|
||||
|
||||
This function calculate the total amount of them self.
|
||||
From the Credit of the Month will the Amount of the Month subtract.
|
||||
Finaly all Month will added together.
|
||||
At Last the amount from last year will be subtract.
|
||||
|
||||
If the Return Value is negativ, the User has an Credit, else the User has an amount.
|
||||
|
||||
Returns:
|
||||
double of the calculated amount
|
||||
"""
|
||||
debug.info("calculate amount")
|
||||
jan = self.jan_guthaben - self.jan_schulden
|
||||
feb = self.feb_guthaben - self.feb_schulden
|
||||
maer = self.maer_guthaben - self.maer_schulden
|
||||
apr = self.apr_guthaben - self.apr_schulden
|
||||
mai = self.mai_guthaben - self.mai_schulden
|
||||
jun = self.jun_guthaben - self.jun_schulden
|
||||
jul = self.jul_guthaben - self.jul_schulden
|
||||
aug = self.aug_guthaben - self.aug_schulden
|
||||
sep = self.sep_guthaben - self.sep_schulden
|
||||
okt = self.okt_guthaben - self.okt_schulden
|
||||
nov = self.nov_guthaben - self.nov_schulden
|
||||
dez = self.dez_guthaben - self.dez_schulden
|
||||
|
||||
sum = jan + feb + maer + apr + mai + jun + jul + aug + sep + okt + nov + dez - self.last_schulden
|
||||
debug.debug("amount is {{ {} }}".format(sum))
|
||||
return sum
|
||||
|
||||
def getMonth(self, month=datetime.now().month):
|
||||
""" Get Amount from month
|
||||
|
||||
This function returns the amount and credit of the month.
|
||||
By default is month the actual month
|
||||
|
||||
Args:
|
||||
month: which month you want to get the amount(1-12)
|
||||
|
||||
Returns:
|
||||
double (credit, amount)
|
||||
"""
|
||||
debug.info("get credit and amount from month {{ {} }}".format(month))
|
||||
retValue = None
|
||||
|
||||
if month == 1:
|
||||
retValue = (self.jan_guthaben, self.jan_schulden)
|
||||
elif month == 2:
|
||||
retValue = (self.feb_guthaben, self.feb_schulden)
|
||||
elif month == 3:
|
||||
retValue = (self.maer_guthaben, self.maer_schulden)
|
||||
elif month == 4:
|
||||
retValue = (self.apr_guthaben, self.apr_schulden)
|
||||
elif month == 5:
|
||||
retValue = (self.mai_guthaben, self.mai_schulden)
|
||||
elif month == 6:
|
||||
retValue = (self.jun_guthaben, self.jun_schulden)
|
||||
elif month == 7:
|
||||
retValue = (self.jul_guthaben, self.jul_schulden)
|
||||
elif month == 8:
|
||||
retValue = (self.aug_guthaben, self.aug_schulden)
|
||||
elif month == 9:
|
||||
retValue = (self.sep_guthaben, self.sep_schulden)
|
||||
elif month == 10:
|
||||
retValue = (self.okt_guthaben, self.okt_schulden)
|
||||
elif month == 11:
|
||||
retValue = (self.nov_guthaben, self.nov_schulden)
|
||||
elif month == 12:
|
||||
retValue = (self.dez_guthaben, self.dez_schulden)
|
||||
debug.debug("credit and amount is {{ {} }}".format(retValue))
|
||||
return retValue
|
||||
|
||||
def addAmount(self, amount, month=datetime.now().month):
|
||||
""" Add Amount
|
||||
|
||||
This function add an amount to a month and returns the credit and amount of the month.
|
||||
By default is month the actual month.
|
||||
|
||||
Args:
|
||||
amount: the amount which is to add
|
||||
month: in which month to add the amount (1-12)
|
||||
|
||||
Returns:
|
||||
double (credit, amount)
|
||||
"""
|
||||
debug.info("add amount in month {{ {} }}".format(month))
|
||||
if month == 1:
|
||||
self.jan_schulden += amount
|
||||
retValue = (self.jan_guthaben, self.jan_schulden)
|
||||
elif month == 2:
|
||||
self.feb_schulden += amount
|
||||
retValue = (self.feb_guthaben, self.feb_schulden)
|
||||
elif month == 3:
|
||||
self.maer_schulden += amount
|
||||
retValue = (self.maer_guthaben, self.maer_schulden)
|
||||
elif month == 4:
|
||||
self.apr_schulden += amount
|
||||
retValue = (self.apr_guthaben, self.apr_schulden)
|
||||
elif month == 5:
|
||||
self.mai_schulden += amount
|
||||
retValue = (self.mai_guthaben, self.mai_schulden)
|
||||
elif month == 6:
|
||||
self.jun_schulden += amount
|
||||
retValue = (self.jun_guthaben, self.jun_schulden)
|
||||
elif month == 7:
|
||||
self.jul_schulden += amount
|
||||
retValue = (self.jul_guthaben, self.jul_schulden)
|
||||
elif month == 8:
|
||||
self.aug_schulden += amount
|
||||
retValue = (self.aug_guthaben, self.aug_schulden)
|
||||
elif month == 9:
|
||||
self.sep_schulden += amount
|
||||
retValue = (self.sep_guthaben, self.sep_schulden)
|
||||
elif month == 10:
|
||||
self.okt_schulden += amount
|
||||
retValue = (self.okt_guthaben, self.okt_schulden)
|
||||
elif month == 11:
|
||||
self.nov_schulden += amount
|
||||
retValue = (self.nov_guthaben, self.nov_schulden)
|
||||
elif month == 12:
|
||||
self.dez_schulden += amount
|
||||
retValue = (self.dez_guthaben, self.dez_schulden)
|
||||
debug.debug("credit and amount is {{ {} }}".format(retValue))
|
||||
return retValue
|
||||
|
||||
def addCredit(self, credit, month=datetime.now().month):
|
||||
""" Add Credit
|
||||
|
||||
This function add an credit to a month and returns the credit and amount of the month.
|
||||
By default is month the actual month.
|
||||
|
||||
Args:
|
||||
credit: the credit which is to add
|
||||
month: in which month to add the credit (1-12)
|
||||
|
||||
Returns:
|
||||
double (credit, amount)
|
||||
"""
|
||||
debug.info("add credit in month {{ {} }}".format(month))
|
||||
if month == 1:
|
||||
self.jan_guthaben += credit
|
||||
retValue = (self.jan_guthaben, self.jan_schulden)
|
||||
elif month == 2:
|
||||
self.feb_guthaben += credit
|
||||
retValue = (self.feb_guthaben, self.feb_schulden)
|
||||
elif month == 3:
|
||||
self.maer_guthaben += credit
|
||||
retValue = (self.maer_guthaben, self.maer_schulden)
|
||||
elif month == 4:
|
||||
self.apr_guthaben += credit
|
||||
retValue = (self.apr_guthaben, self.apr_schulden)
|
||||
elif month == 5:
|
||||
self.mai_guthaben += credit
|
||||
retValue = (self.mai_guthaben, self.mai_schulden)
|
||||
elif month == 6:
|
||||
self.jun_guthaben += credit
|
||||
retValue = (self.jun_guthaben, self.jun_schulden)
|
||||
elif month == 7:
|
||||
self.jul_guthaben += credit
|
||||
retValue = (self.jul_guthaben, self.jul_schulden)
|
||||
elif month == 8:
|
||||
self.aug_guthaben += credit
|
||||
retValue = (self.aug_guthaben, self.aug_schulden)
|
||||
elif month == 9:
|
||||
self.sep_guthaben += credit
|
||||
retValue = (self.sep_guthaben, self.sep_schulden)
|
||||
elif month == 10:
|
||||
self.okt_guthaben += credit
|
||||
retValue = (self.okt_guthaben, self.okt_schulden)
|
||||
elif month == 11:
|
||||
self.nov_guthaben += credit
|
||||
retValue = (self.nov_guthaben, self.nov_schulden)
|
||||
elif month == 12:
|
||||
self.dez_guthaben += credit
|
||||
retValue = (self.dez_guthaben, self.dez_schulden)
|
||||
debug.debug("credit and amount is {{ {} }}".format(retValue))
|
||||
return retValue
|
||||
|
||||
def toJSON(self):
|
||||
""" Create Dic to dump in JSON
|
||||
|
||||
Returns:
|
||||
A Dic with static Attributes.
|
||||
"""
|
||||
dic = {
|
||||
"jan": {
|
||||
"credit": self.jan_guthaben,
|
||||
"depts": self.jan_schulden},
|
||||
"feb": {
|
||||
"credit": self.feb_guthaben,
|
||||
"depts": self.feb_schulden},
|
||||
"maer": {
|
||||
"credit": self.maer_guthaben,
|
||||
"depts": self.maer_schulden},
|
||||
"apr": {
|
||||
"credit": self.apr_guthaben,
|
||||
"depts": self.apr_schulden},
|
||||
"mai": {
|
||||
"credit": self.mai_guthaben,
|
||||
"depts": self.mai_schulden},
|
||||
"jun": {
|
||||
"credit": self.jun_guthaben,
|
||||
"depts": self.jun_schulden},
|
||||
"jul": {
|
||||
"credit": self.jul_guthaben,
|
||||
"depts": self.jul_schulden},
|
||||
"aug": {
|
||||
"credit": self.aug_guthaben,
|
||||
"depts": self.aug_schulden},
|
||||
"sep": {
|
||||
"credit": self.sep_guthaben,
|
||||
"depts": self.sep_schulden},
|
||||
"okt": {
|
||||
"credit": self.okt_guthaben,
|
||||
"depts": self.okt_schulden},
|
||||
"nov": {
|
||||
"credit": self.nov_guthaben,
|
||||
"depts": self.nov_schulden},
|
||||
"dez": {
|
||||
"credit": self.dez_guthaben,
|
||||
"depts": self.dez_schulden},
|
||||
"last": self.last_schulden
|
||||
}
|
||||
return dic
|
||||
|
||||
def __repr__(self):
|
||||
return "CreditList(year: {}, userID: {}, amount: {})".format(self.year, self.user_id, self.toJSON())
|
|
@ -1,72 +0,0 @@
|
|||
from flaschengeist.modules.geruecht.mainController import Singleton
|
||||
from geruecht import db
|
||||
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
|
||||
|
||||
class DatabaseController(dbUserController.Base,
|
||||
dbCreditListController.Base,
|
||||
dbWorkerController.Base,
|
||||
dbWorkgroupController.Base,
|
||||
dbPricelistController.Base,
|
||||
dbJobKindController.Base,
|
||||
dbJobInviteController.Base,
|
||||
dbJobRequesController.Base,
|
||||
dbAccessTokenController.Base,
|
||||
dbRegistrationController.Base,
|
||||
dbFreeDrinkListConfigController.Base,
|
||||
metaclass=Singleton):
|
||||
'''
|
||||
DatabaesController
|
||||
|
||||
Connect to the Database and execute sql-executions
|
||||
'''
|
||||
|
||||
def __init__(self):
|
||||
self.db = db
|
||||
|
||||
def getLockedDay(self, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from locked_days where daydate='{}'".format(date))
|
||||
data = cursor.fetchone()
|
||||
return data
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def setLockedDay(self, date, locked, hard=False):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
sql = "insert into locked_days (daydate, locked) VALUES ('{}', {})".format(date, locked)
|
||||
cursor.execute(sql)
|
||||
self.db.connection.commit()
|
||||
return self.getLockedDay(date)
|
||||
except IntegrityError as err:
|
||||
self.db.connection.rollback()
|
||||
try:
|
||||
exists = self.getLockedDay(date)
|
||||
if hard:
|
||||
sql = "update locked_days set locked={} where id={}".format(locked, exists['id'])
|
||||
else:
|
||||
sql = False
|
||||
if sql:
|
||||
cursor.execute(sql)
|
||||
self.db.connection.commit()
|
||||
return self.getLockedDay(date)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
db = DatabaseController()
|
||||
user = db.getUser('jhille')
|
||||
db.getCreditListFromUser(user, year=2018)
|
|
@ -1,82 +0,0 @@
|
|||
import traceback
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
from geruecht.model.accessToken import AccessToken
|
||||
|
||||
|
||||
class Base:
|
||||
|
||||
def getAccessToken(self, item):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if type(item) == str:
|
||||
sql = "select * from session where token='{}'".format(item)
|
||||
elif type(item) == int:
|
||||
sql = 'select * from session where id={}'.format(item)
|
||||
else:
|
||||
raise DatabaseExecption("item as no type int or str. name={}, type={}".format(item, type(item)))
|
||||
cursor.execute(sql)
|
||||
session = cursor.fetchone()
|
||||
retVal = AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], lock_bar=bool(session['lock_bar']),timestamp=session['timestamp'], browser=session['browser'], platform=session['platform']) if session != None else None
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def getAccessTokensFromUser(self, user):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from session where user={}".format(user.id))
|
||||
sessions = cursor.fetchall()
|
||||
retVal = [
|
||||
AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'],
|
||||
lock_bar=bool(session['lock_bar']), timestamp=session['timestamp'], browser=session['browser'], platform=session['platform']) for session in sessions]
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getAccessTokens(self):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from session")
|
||||
sessions = cursor.fetchall()
|
||||
retVal = [AccessToken(session['id'], self.getUserById(session['user']), session['token'], session['lifetime'], lock_bar=bool(session['lock_bar']),timestamp=session['timestamp'], browser=session['browser'], platform=session['platform']) for session in sessions]
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def createAccessToken(self, user, token, lifetime, timestamp, lock_bar, user_agent=None):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into session (user, timestamp, lock_bar, token, lifetime, browser, platform) VALUES ({}, '{}', {}, '{}', {}, '{}', '{}')".format(user.id, timestamp, lock_bar, token, lifetime, user_agent.browser if user_agent else 'NULL', user_agent.platform if user_agent else 'NULL'))
|
||||
self.db.connection.commit()
|
||||
return self.getAccessToken(token)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def updateAccessToken(self, accToken):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update session set timestamp='{}', lock_bar={}, lifetime={} where id={}".format(accToken.timestamp, accToken.lock_bar, accToken.lifetime, accToken.id))
|
||||
self.db.connection.commit()
|
||||
return self.getAccessToken(accToken.id)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def deleteAccessToken(self, accToken):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from session where id={}".format(accToken.id))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
|
@ -1,73 +0,0 @@
|
|||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
from geruecht.model.creditList import CreditList
|
||||
from geruecht.model.user import User
|
||||
|
||||
|
||||
class Base:
|
||||
def getCreditListFromUser(self, user, **kwargs):
|
||||
try:
|
||||
if type(user) is User:
|
||||
if user.userid == 'extern':
|
||||
return []
|
||||
cursor = self.db.connection.cursor()
|
||||
if 'year' in kwargs:
|
||||
sql = "select * from creditList where user_id={} and year_date={}".format(user.id if type(user) is User else user, kwargs['year'])
|
||||
else:
|
||||
sql = "select * from creditList where user_id={}".format(user.id if type(user) is User else user)
|
||||
cursor.execute(sql)
|
||||
data = cursor.fetchall()
|
||||
if len(data) == 0:
|
||||
return self.createCreditList(user_id=user.id, year=datetime.now().year)
|
||||
elif len(data) == 1:
|
||||
return [CreditList(data[0])]
|
||||
else:
|
||||
return [CreditList(value) for value in data]
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
|
||||
def createCreditList(self, user_id, year=datetime.now().year):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id))
|
||||
self.db.connection.commit()
|
||||
return self.getCreditListFromUser(user_id)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
|
||||
def updateCreditList(self, creditlist):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year))
|
||||
data = cursor.fetchall()
|
||||
if len(data) == 0:
|
||||
self.createCreditList(creditlist.user_id, creditlist.year)
|
||||
sql = "update creditList set jan_guthaben={}, jan_schulden={},feb_guthaben={}, feb_schulden={}, maer_guthaben={}, maer_schulden={}, apr_guthaben={}, apr_schulden={}, mai_guthaben={}, mai_schulden={}, jun_guthaben={}, jun_schulden={}, jul_guthaben={}, jul_schulden={}, aug_guthaben={}, aug_schulden={},sep_guthaben={}, sep_schulden={},okt_guthaben={}, okt_schulden={}, nov_guthaben={}, nov_schulden={}, dez_guthaben={}, dez_schulden={}, last_schulden={} where year_date={} and user_id={}".format(creditlist.jan_guthaben, creditlist.jan_schulden,
|
||||
creditlist.feb_guthaben, creditlist.feb_schulden,
|
||||
creditlist.maer_guthaben, creditlist.maer_schulden,
|
||||
creditlist.apr_guthaben, creditlist.apr_schulden,
|
||||
creditlist.mai_guthaben, creditlist.mai_schulden,
|
||||
creditlist.jun_guthaben, creditlist.jun_schulden,
|
||||
creditlist.jul_guthaben, creditlist.jul_schulden,
|
||||
creditlist.aug_guthaben, creditlist.aug_schulden,
|
||||
creditlist.sep_guthaben, creditlist.sep_schulden,
|
||||
creditlist.okt_guthaben, creditlist.okt_schulden,
|
||||
creditlist.nov_guthaben, creditlist.nov_schulden,
|
||||
creditlist.dez_guthaben, creditlist.dez_schulden,
|
||||
creditlist.last_schulden, creditlist.year, creditlist.user_id)
|
||||
print(sql)
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute(sql)
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
|
@ -1,256 +0,0 @@
|
|||
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))
|
|
@ -1,84 +0,0 @@
|
|||
import traceback
|
||||
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
|
||||
|
||||
class Base:
|
||||
def getJobInvite(self, from_user, to_user, date, id=None):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if id:
|
||||
cursor.execute("select * from job_invites where id={}".format(id))
|
||||
else:
|
||||
cursor.execute("select * from job_invites where from_user={} and to_user={} and on_date='{}'".format(from_user['id'], to_user['id'], date))
|
||||
retVal = cursor.fetchone()
|
||||
retVal['to_user'] = self.getUserById(retVal['to_user']).toJSON()
|
||||
retVal['from_user'] = self.getUserById(retVal['from_user']).toJSON()
|
||||
retVal['on_date'] = {'year': retVal['on_date'].year, 'month': retVal['on_date'].month, 'day': retVal['on_date'].day}
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getJobInvitesFromUser(self, from_user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from job_invites where from_user={} and on_date>='{}'".format(from_user['id'], date))
|
||||
retVal = cursor.fetchall()
|
||||
for item in retVal:
|
||||
item['from_user'] = from_user
|
||||
item['to_user'] = self.getUserById(item['to_user']).toJSON()
|
||||
item['on_date'] = {'year': item['on_date'].year, 'month': item['on_date'].month, 'day': item['on_date'].day}
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getJobInvitesToUser(self, to_user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from job_invites where to_user={} and on_date>='{}'".format(to_user['id'], date))
|
||||
retVal = cursor.fetchall()
|
||||
for item in retVal:
|
||||
item['from_user'] = self.getUserById(item['from_user']).toJSON()
|
||||
item['to_user'] = to_user
|
||||
item['on_date'] = {'year': item['on_date'].year, 'month': item['on_date'].month, 'day': item['on_date'].day}
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def setJobInvite(self, from_user, to_user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into job_invites (from_user, to_user, on_date) values ({}, {}, '{}')".format(from_user['id'], to_user['id'], date))
|
||||
self.db.connection.commit()
|
||||
return self.getJobInvite(from_user, to_user, date)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def updateJobInvite(self, jobinvite):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update job_invites set watched={} where id={}".format(jobinvite['watched'], jobinvite['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getJobInvite(None, None, None, jobinvite['id'])
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def deleteJobInvite(self, jobinvite):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from job_invites where id={}".format(jobinvite['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
|
@ -1,132 +0,0 @@
|
|||
import traceback
|
||||
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
|
||||
|
||||
class Base:
|
||||
def getAllJobKinds(self):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute('select * from job_kind')
|
||||
list = cursor.fetchall()
|
||||
for item in list:
|
||||
item['workgroup'] = self.getWorkgroup(item['workgroup']) if item['workgroup'] != None else None
|
||||
return list
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def getJobKind(self, name):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if type(name) == str:
|
||||
sql = "select * from job_kind where name='{}'".format(name)
|
||||
elif type(name) == int:
|
||||
sql = 'select * from job_kind where id={}'.format(name)
|
||||
else:
|
||||
raise DatabaseExecption("name as no type int or str. name={}, type={}".format(name, type(name)))
|
||||
cursor.execute(sql)
|
||||
retVal = cursor.fetchone()
|
||||
retVal['workgroup'] = self.getWorkgroup(retVal['workgroup']) if retVal['workgroup'] != None else None
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def setJobKind(self, name, workgroup_id):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into job_kind (name, workgroup) values ('{}', {})".format(name, workgroup_id if workgroup_id != None else 'NULL'))
|
||||
self.db.connection.commit()
|
||||
return self.getJobKind(name)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def updateJobKind(self, jobkind):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update job_kind set name='{}', workgroup={} where id={}".format(jobkind['name'], jobkind['workgroup']['id'] if jobkind['workgroup'] != None else 'NULL', jobkind['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getJobKind(jobkind['id'])
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def deleteJobKind(self, jobkind):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from job_kind where id={}".format(jobkind['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def setJobKindDates(self, date, jobkind, maxpersons):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into job_kind_dates (daydate, job_kind, maxpersons) values ('{}', {}, {})".format(date, jobkind['id'] if jobkind != None else 'NULL', maxpersons))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def updateJobKindDates(self, jobkindDate):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update job_kind_dates set job_kind={}, maxpersons='{}' where id={}".format(jobkindDate['job_kind']['id'] if jobkindDate['job_kind'] != None else 'NULL', jobkindDate['maxpersons'], jobkindDate['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def getJobKindDates(self, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from job_kind_dates where daydate='{}'".format(date))
|
||||
list = cursor.fetchall()
|
||||
for item in list:
|
||||
item['job_kind'] = self.getJobKind(item['job_kind']) if item['job_kind'] != None else None
|
||||
item['daydate'] = {'year': item['daydate'].year, 'month': item['daydate'].month, 'day': item['daydate'].day}
|
||||
return list
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def getJobKindDate(self, date, job_kind):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from job_kind_dates where daydate='{}' and job_kind={}".format(date, job_kind['id']))
|
||||
item = cursor.fetchone()
|
||||
if item:
|
||||
item['job_kind'] = self.getJobKind(item['job_kind']) if item['job_kind'] != None else None
|
||||
item['daydate'] = {'year': item['daydate'].year, 'month': item['daydate'].month, 'day': item['daydate'].day}
|
||||
else:
|
||||
item = {
|
||||
'job_kind': self.getJobKind(1),
|
||||
'daydate': {'year': date.year, 'month': date.month, 'day': date.day},
|
||||
'maxpersons': 2
|
||||
}
|
||||
return item
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def deleteJobKindDates(self, jobkinddates):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from job_kind_dates where id={}".format(jobkinddates['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
|
@ -1,97 +0,0 @@
|
|||
import traceback
|
||||
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
|
||||
|
||||
class Base:
|
||||
def getJobRequest(self, from_user, to_user, date, id=None):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if id:
|
||||
cursor.execute("select * from job_request where id={}".format(id))
|
||||
else:
|
||||
cursor.execute("select * from job_request where from_user={} and to_user={} and on_date='{}'".format(from_user['id'], to_user['id'], date))
|
||||
retVal = cursor.fetchone()
|
||||
retVal['to_user'] = self.getUserById(retVal['to_user']).toJSON()
|
||||
retVal['from_user'] = self.getUserById(retVal['from_user']).toJSON()
|
||||
retVal['on_date'] = {'year': retVal['on_date'].year, 'month': retVal['on_date'].month, 'day': retVal['on_date'].day}
|
||||
retVal['job_kind'] = self.getJobKind(retVal['job_kind'])
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getJobRequestsFromUser(self, from_user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from job_request where from_user={} and on_date>='{}'".format(from_user['id'], date))
|
||||
retVal = cursor.fetchall()
|
||||
for item in retVal:
|
||||
item['from_user'] = from_user
|
||||
item['to_user'] = self.getUserById(item['to_user']).toJSON()
|
||||
item['on_date'] = {'year': item['on_date'].year, 'month': item['on_date'].month, 'day': item['on_date'].day}
|
||||
item['job_kind'] = self.getJobKind(item['job_kind'])
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getJobRequestsToUser(self, to_user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from job_request where to_user={} and on_date>='{}'".format(to_user['id'], date))
|
||||
retVal = cursor.fetchall()
|
||||
for item in retVal:
|
||||
item['from_user'] = self.getUserById(item['from_user']).toJSON()
|
||||
item['to_user'] = to_user
|
||||
item['on_date'] = {'year': item['on_date'].year, 'month': item['on_date'].month, 'day': item['on_date'].day}
|
||||
item['job_kind'] = self.getJobKind(item['job_kind'])
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def setJobRequest(self, from_user, to_user, date, job_kind):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into job_request (from_user, to_user, on_date, job_kind) values ({}, {}, '{}', {})".format(from_user['id'], to_user['id'], date, job_kind['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getJobRequest(from_user, to_user, date)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def updateJobRequest(self, jobrequest):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update job_request set watched={}, answered={}, accepted={} where id={}".format(jobrequest['watched'], jobrequest['answered'], jobrequest['accepted'], jobrequest['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getJobRequest(None, None, None, jobrequest['id'])
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def updateAllJobRequest(self, jobrequest):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update job_request set answered={} where from_user={} and on_date='{}'".format(jobrequest['answered'], jobrequest['from_user']['id'], jobrequest['on_date']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def deleteJobRequest(self, jobrequest):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from job_request where id={}".format(jobrequest['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
|
@ -1,134 +0,0 @@
|
|||
import traceback
|
||||
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
|
||||
|
||||
class Base:
|
||||
def getPriceList(self):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from pricelist")
|
||||
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()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def getDrinkPrice(self, name):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if type(name) == str:
|
||||
sql = "select * from pricelist where name='{}'".format(name)
|
||||
elif type(name) == int:
|
||||
sql = 'select * from pricelist where id={}'.format(name)
|
||||
else:
|
||||
raise DatabaseExecption("name as no type int or str. name={}, type={}".format(name, type(name)))
|
||||
cursor.execute(sql)
|
||||
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()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def setDrinkPrice(self, drink):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute(
|
||||
"insert into pricelist (name, price, price_big, price_club, price_club_big, premium, premium_club, price_extern_club, type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
(
|
||||
drink['name'], drink['price'], drink['price_big'], drink['price_club'], drink['price_club_big'],
|
||||
drink['premium'], drink['premium_club'], drink['price_extern_club'], drink['type']))
|
||||
self.db.connection.commit()
|
||||
return self.getDrinkPrice(str(drink['name']))
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def updateDrinkPrice(self, drink):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update pricelist set name=%s, price=%s, price_big=%s, price_club=%s, price_club_big=%s, premium=%s, premium_club=%s, price_extern_club=%s, type=%s where id=%s",
|
||||
(
|
||||
drink['name'], drink['price'], drink['price_big'], drink['price_club'], drink['price_club_big'], drink['premium'], drink['premium_club'], drink['price_extern_club'], drink['type'], drink['id']
|
||||
))
|
||||
self.db.connection.commit()
|
||||
return self.getDrinkPrice(drink['id'])
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def deleteDrink(self, drink):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from pricelist where id={}".format(drink['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Database: {}".format(err))
|
||||
|
||||
def getDrinkType(self, name):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if type(name) == str:
|
||||
sql = "select * from drink_type where name='{}'".format(name)
|
||||
elif type(name) == int:
|
||||
sql = 'select * from drink_type where id={}'.format(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 setDrinkType(self, name):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into drink_type (name) values ('{}')".format(name))
|
||||
self.db.connection.commit()
|
||||
return self.getDrinkType(name)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Database: {}".format(err))
|
||||
|
||||
def updateDrinkType(self, type):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update drink_type set name='{}' where id={}".format(type['name'], type['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getDrinkType(type['id'])
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Database: {}".format(err))
|
||||
|
||||
def deleteDrinkType(self, type):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from drink_type where id={}".format(type['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def getAllDrinkTypes(self):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute('select * from drink_type')
|
||||
return cursor.fetchall()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Database: {}".format(err))
|
|
@ -1,32 +0,0 @@
|
|||
import traceback
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
|
||||
class Base:
|
||||
def setNewRegistration(self, data):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if data['entryDate']:
|
||||
sql = "insert into registration_list (firstname, lastname, clubname, email, keynumber, birthdate, entrydate) VALUES ('{}', '{}', '{}', '{}', {}, '{}', '{}')".format(
|
||||
data['firstName'],
|
||||
data['lastName'],
|
||||
data['clubName'] if data['clubName'] else 'NULL',
|
||||
data['mail'],
|
||||
data['keynumber'] if data['keynumber'] else 'NULL',
|
||||
data['birthDate'],
|
||||
data['entryDate']
|
||||
)
|
||||
else:
|
||||
sql = "insert into registration_list (firstname, lastname, clubname, email, keynumber, birthdate) VALUES ('{}', '{}', '{}', '{}', {}, '{}')".format(
|
||||
data['firstName'],
|
||||
data['lastName'],
|
||||
data['clubName'] if data['clubName'] else 'NULL',
|
||||
data['mail'],
|
||||
data['keynumber'] if data['keynumber'] else 'NULL',
|
||||
data['birthDate']
|
||||
)
|
||||
cursor.execute(sql)
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
|
@ -1,215 +0,0 @@
|
|||
from geruecht.exceptions import DatabaseExecption, UsernameExistDB
|
||||
from geruecht.model.user import User
|
||||
import traceback
|
||||
|
||||
class Base:
|
||||
def getAllUser(self, extern=False, workgroups=True):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from user")
|
||||
data = cursor.fetchall()
|
||||
|
||||
if data:
|
||||
retVal = []
|
||||
for value in data:
|
||||
if extern and value['uid'] == 'extern':
|
||||
continue
|
||||
user = User(value)
|
||||
creditLists = self.getCreditListFromUser(user)
|
||||
user.initGeruechte(creditLists)
|
||||
if workgroups:
|
||||
user.workgroups = self.getWorkgroupsOfUser(user.id)
|
||||
retVal.append(user)
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getUser(self, username, workgroups=True):
|
||||
try:
|
||||
retVal = None
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from user where uid='{}'".format(username))
|
||||
data = cursor.fetchone()
|
||||
if data:
|
||||
retVal = User(data)
|
||||
creditLists = self.getCreditListFromUser(retVal)
|
||||
retVal.initGeruechte(creditLists)
|
||||
if workgroups:
|
||||
retVal.workgroups = self.getWorkgroupsOfUser(retVal.id)
|
||||
if retVal:
|
||||
if retVal.uid == username:
|
||||
return retVal
|
||||
else:
|
||||
return None
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getUserById(self, id, workgroups=True, geruecht=True):
|
||||
try:
|
||||
retVal = None
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from user where id={}".format(id))
|
||||
data = cursor.fetchone()
|
||||
if data:
|
||||
retVal = User(data)
|
||||
if geruecht:
|
||||
creditLists = self.getCreditListFromUser(retVal)
|
||||
retVal.initGeruechte(creditLists)
|
||||
if workgroups:
|
||||
retVal.workgroups = self.getWorkgroupsOfUser(retVal.id)
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def _convertGroupToString(self, groups):
|
||||
retVal = ''
|
||||
print('groups: {}'.format(groups))
|
||||
if groups:
|
||||
for group in groups:
|
||||
if len(retVal) != 0:
|
||||
retVal += ','
|
||||
retVal += group
|
||||
return retVal
|
||||
|
||||
|
||||
def insertUser(self, user):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
groups = self._convertGroupToString(user.group)
|
||||
cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe, lockLimit, locked, autoLock, mail) VALUES ('{}','{}','{}','{}','{}',{},{},{},'{}')".format(
|
||||
user.userid, user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
|
||||
def updateUser(self, user):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
groups = self._convertGroupToString(user.group)
|
||||
sql = "update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}', lockLimit={}, locked={}, autoLock={}, mail='{}' where uid='{}'".format(
|
||||
user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail, user.userid)
|
||||
print(sql)
|
||||
cursor.execute(sql)
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def updateLastSeen(self, user, time):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
sql = "update user set last_seen='{}' where uid='{}'".format(
|
||||
time, user.userid)
|
||||
print(sql)
|
||||
cursor.execute(sql)
|
||||
self.db.connection.commit()
|
||||
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def changeUsername(self, user, newUsername):
|
||||
try:
|
||||
cursor= self.db.connection.cursor()
|
||||
cursor.execute("select * from user where uid='{}'".format(newUsername))
|
||||
data = cursor.fetchall()
|
||||
if data:
|
||||
raise UsernameExistDB("Username already exists")
|
||||
else:
|
||||
cursor.execute("update user set uid='{}' where id={}".format(newUsername, user.id))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getAllStatus(self):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute('select * from statusgroup')
|
||||
return cursor.fetchall()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def getStatus(self, name):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if type(name) == str:
|
||||
sql = "select * from statusgroup where name='{}'".format(name)
|
||||
elif type(name) == int:
|
||||
sql = 'select * from statusgroup where id={}'.format(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 worng with Databes: {}".format(err))
|
||||
|
||||
def setStatus(self, name):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into statusgroup (name) values ('{}')".format(name))
|
||||
self.db.connection.commit()
|
||||
return self.getStatus(name)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def updateStatus(self, status):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update statusgroup set name='{}' where id={}".format(status['name'], status['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getStatus(status['id'])
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def deleteStatus(self, status):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from statusgroup where id={}".format(status['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def updateStatusOfUser(self, username, status):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update user set statusgroup={} where uid='{}'".format(status['id'], username))
|
||||
self.db.connection.commit()
|
||||
return self.getUser(username)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def updateVotingOfUser(self, username, voting):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update user set voting={} where uid='{}'".format(voting, username))
|
||||
self.db.connection.commit()
|
||||
return self.getUser(username)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
|
@ -1,81 +0,0 @@
|
|||
import traceback
|
||||
from datetime import timedelta
|
||||
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
|
||||
|
||||
class Base:
|
||||
def getWorker(self, user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
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:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getWorkers(self, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from bardienste where startdatetime='{}'".format(date))
|
||||
data = cursor.fetchall()
|
||||
retVal = []
|
||||
return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime'], "start": { "year": work['startdatetime'].year, "month": work['startdatetime'].month, "day": work['startdatetime'].day}, "job_kind": self.getJobKind(work['job_kind']) if work['job_kind'] != None else None} for work in data]
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def getWorkersWithJobKind(self, date, job_kind):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from bardienste where startdatetime='{}' and job_kind={} {}".format(date, job_kind['id'], "or job_kind='null'" if job_kind['id'] is 1 else ''))
|
||||
data = cursor.fetchall()
|
||||
retVal = []
|
||||
return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime'], "start": { "year": work['startdatetime'].year, "month": work['startdatetime'].month, "day": work['startdatetime'].day}, "job_kind": self.getJobKind(work['job_kind']) if work['job_kind'] != None else None} for work in data]
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def setWorker(self, user, date, job_kind=None):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime, job_kind) values ({},'{}','{}', {})".format(user.id, date, date + timedelta(days=1), job_kind['id'] if job_kind != None else 'NULL'))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def changeWorker(self, from_user, to_user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update bardienste set user_id={} where user_id={} and startdatetime='{}'".format(to_user['id'], from_user['id'], date))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
||||
|
||||
def deleteAllWorkerWithJobKind(self, date, job_kind):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from bardienste where startdatetime='{}' and job_kind={}".format(date, job_kind['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def deleteWorker(self, user, date):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Datatabase: {}".format(err))
|
|
@ -1,126 +0,0 @@
|
|||
import traceback
|
||||
|
||||
from geruecht.exceptions import DatabaseExecption
|
||||
|
||||
|
||||
class Base:
|
||||
def getAllWorkgroups(self):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute('select * from workgroup')
|
||||
list = cursor.fetchall()
|
||||
for item in list:
|
||||
if item['boss'] != None:
|
||||
item['boss']=self.getUserById(item['boss'], workgroups=False).toJSON()
|
||||
return list
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def getWorkgroup(self, name):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
if type(name) == str:
|
||||
sql = "select * from workgroup where name='{}'".format(name)
|
||||
elif type(name) == int:
|
||||
sql = 'select * from workgroup where id={}'.format(name)
|
||||
else:
|
||||
raise DatabaseExecption("name as no type int or str. name={}, type={}".format(name, type(name)))
|
||||
cursor.execute(sql)
|
||||
retVal = cursor.fetchone()
|
||||
retVal['boss'] = self.getUserById(retVal['boss'], workgroups=False).toJSON() if retVal['boss'] != None else None
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def setWorkgroup(self, name, boss):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into workgroup (name, boss) values ('{}', {})".format(name, boss['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getWorkgroup(name)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def updateWorkgroup(self, workgroup):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("update workgroup set name='{}', boss={} where id={}".format(workgroup['name'], workgroup['boss']['id'], workgroup['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getWorkgroup(workgroup['id'])
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def deleteWorkgroup(self, workgroup):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from workgroup where id={}".format(workgroup['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went worng with Databes: {}".format(err))
|
||||
|
||||
def getWorkgroupsOfUser(self, userid):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from user_workgroup where user_id={} ".format(userid))
|
||||
knots = cursor.fetchall()
|
||||
retVal = [self.getWorkgroup(knot['workgroup_id']) for knot in knots]
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def getUsersOfWorkgroups(self, workgroupid):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from user_workgroup where workgroup_id={}".format(workgroupid))
|
||||
knots = cursor.fetchall()
|
||||
retVal = [self.getUserById(knot['user_id'], workgroups=False).toJSON() for knot in knots]
|
||||
return retVal
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def getUserWorkgroup(self, user, workgroup):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("select * from user_workgroup where workgroup_id={} and user_id={}".format(workgroup['id'], user['id']))
|
||||
knot = cursor.fetchone()
|
||||
retVal = {"workgroup": self.getWorkgroup(workgroup['id']), "user": self.getUserById(user['id'], workgroups=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 setUserWorkgroup(self, user, workgroup):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("insert into user_workgroup (user_id, workgroup_id) VALUES ({}, {})".format(user['id'], workgroup['id']))
|
||||
self.db.connection.commit()
|
||||
return self.getUserWorkgroup(user, workgroup)
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
||||
|
||||
def deleteWorkgroupsOfUser(self, user):
|
||||
try:
|
||||
cursor = self.db.connection.cursor()
|
||||
cursor.execute("delete from user_workgroup where user_id={}".format(user['id']))
|
||||
self.db.connection.commit()
|
||||
except Exception as err:
|
||||
traceback.print_exc()
|
||||
self.db.connection.rollback()
|
||||
raise DatabaseExecption("Something went wrong with Database: {}".format(err))
|
|
@ -1 +0,0 @@
|
|||
|
|
@ -1,206 +0,0 @@
|
|||
from flask import Blueprint, request, jsonify
|
||||
from datetime import datetime
|
||||
import geruecht.controller.mainController as mc
|
||||
from geruecht.model import MONEY
|
||||
from geruecht.decorator import login_required
|
||||
from geruecht.logger import getDebugLogger, getCreditLogger
|
||||
|
||||
debug = getDebugLogger()
|
||||
creditL = getCreditLogger()
|
||||
|
||||
finanzer = Blueprint("finanzer", __name__)
|
||||
|
||||
mainController = mc.MainController()
|
||||
|
||||
|
||||
@finanzer.route("/getFinanzerMain")
|
||||
@login_required(groups=[MONEY])
|
||||
def _getFinanzer(**kwargs):
|
||||
""" Function for /getFinanzerMain
|
||||
|
||||
Retrieves all User for the groupe 'moneymaster'
|
||||
|
||||
Returns:
|
||||
A JSON-File with Users
|
||||
or ERROR 401 Permission Denied.
|
||||
"""
|
||||
debug.info("/getFinanzerMain")
|
||||
try:
|
||||
users = mainController.getAllUsersfromDB()
|
||||
dic = {}
|
||||
for user in users:
|
||||
dic[user.userid] = user.toJSON()
|
||||
dic[user.userid]['creditList'] = {
|
||||
credit.year: credit.toJSON() for credit in user.geruechte}
|
||||
debug.debug("return {{ {} }}".format(dic))
|
||||
return jsonify(dic)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@finanzer.route("/finanzerAddAmount", methods=['POST'])
|
||||
@login_required(groups=[MONEY])
|
||||
def _addAmount(**kwargs):
|
||||
""" Add Amount to User
|
||||
|
||||
This Function add an amount to the user with posted userID.
|
||||
If year is not posted the default is the actual Year.
|
||||
If month is not posted the default is the actual Month.
|
||||
|
||||
Returns:
|
||||
JSON-File with geruecht of year
|
||||
or ERROR 401 Permission Denied
|
||||
"""
|
||||
debug.info("/finanzerAddAmount")
|
||||
try:
|
||||
data = request.get_json()
|
||||
userID = data['userId']
|
||||
amount = int(data['amount'])
|
||||
try:
|
||||
year = int(data['year'])
|
||||
except KeyError:
|
||||
year = datetime.now().year
|
||||
try:
|
||||
month = int(data['month'])
|
||||
except KeyError:
|
||||
month = datetime.now().month
|
||||
mainController.addAmount(
|
||||
userID, amount, year=year, month=month, finanzer=True)
|
||||
user = mainController.getUser(userID)
|
||||
retVal = {str(geruecht.year): geruecht.toJSON()
|
||||
for geruecht in user.geruechte}
|
||||
retVal['locked'] = user.locked
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
creditL.info("{} Finanzer {} {} fügt {} {} {} € Schulden hinzu.".format(datetime(year, month, 1).date(
|
||||
), kwargs['accToken'].user.firstname, kwargs['accToken'].user.lastname, user.firstname, user.lastname, amount/100))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@finanzer.route("/finanzerAddCredit", methods=['POST'])
|
||||
@login_required(groups=[MONEY])
|
||||
def _addCredit(**kwargs):
|
||||
""" Add Credit to User
|
||||
|
||||
This Function add an credit to the user with posted userID.
|
||||
If year is not posted the default is the actual Year.
|
||||
If month is not posted the default is the actual Month.
|
||||
|
||||
Returns:
|
||||
JSON-File with geruecht of year
|
||||
or ERROR 401 Permission Denied
|
||||
"""
|
||||
debug.info("/finanzerAddCredit")
|
||||
try:
|
||||
data = request.get_json()
|
||||
userID = data['userId']
|
||||
credit = int(data['credit'])
|
||||
|
||||
try:
|
||||
year = int(data['year'])
|
||||
except KeyError:
|
||||
year = datetime.now().year
|
||||
try:
|
||||
month = int(data['month'])
|
||||
except KeyError:
|
||||
month = datetime.now().month
|
||||
|
||||
mainController.addCredit(
|
||||
userID, credit, year=year, month=month).toJSON()
|
||||
user = mainController.getUser(userID)
|
||||
retVal = {str(geruecht.year): geruecht.toJSON()
|
||||
for geruecht in user.geruechte}
|
||||
retVal['locked'] = user.locked
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
creditL.info("{} Finanzer {} {} fügt {} {} {} € Guthaben hinzu.".format(datetime(year, month, 1).date(
|
||||
), kwargs['accToken'].user.firstname, kwargs['accToken'].user.lastname, user.firstname, user.lastname, credit / 100))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@finanzer.route("/finanzerLock", methods=['POST'])
|
||||
@login_required(groups=[MONEY])
|
||||
def _finanzerLock(**kwargs):
|
||||
debug.info("/finanzerLock")
|
||||
try:
|
||||
data = request.get_json()
|
||||
username = data['userId']
|
||||
locked = bool(data['locked'])
|
||||
retVal = mainController.lockUser(username, locked).toJSON()
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@finanzer.route("/finanzerSetConfig", methods=['POST'])
|
||||
@login_required(groups=[MONEY])
|
||||
def _finanzerSetConfig(**kwargs):
|
||||
debug.info("/finanzerSetConfig")
|
||||
try:
|
||||
data = request.get_json()
|
||||
username = data['userId']
|
||||
autoLock = bool(data['autoLock'])
|
||||
limit = int(data['limit'])
|
||||
retVal = mainController.updateConfig(
|
||||
username, {'lockLimit': limit, 'autoLock': autoLock}).toJSON()
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@finanzer.route("/finanzerAddUser", methods=['POST'])
|
||||
@login_required(groups=[MONEY])
|
||||
def _finanzerAddUser(**kwargs):
|
||||
debug.info("/finanzerAddUser")
|
||||
try:
|
||||
data = request.get_json()
|
||||
username = data['userId']
|
||||
mainController.getUser(username)
|
||||
users = mainController.getAllUsersfromDB()
|
||||
dic = {}
|
||||
for user in users:
|
||||
dic[user.userid] = user.toJSON()
|
||||
dic[user.userid]['creditList'] = {
|
||||
credit.year: credit.toJSON() for credit in user.geruechte}
|
||||
debug.debug("return {{ {} }}".format(dic))
|
||||
return jsonify(dic), 200
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@finanzer.route("/finanzerSendOneMail", methods=['POST'])
|
||||
@login_required(groups=[MONEY])
|
||||
def _finanzerSendOneMail(**kwargs):
|
||||
debug.info("/finanzerSendOneMail")
|
||||
try:
|
||||
data = request.get_json()
|
||||
username = data['userId']
|
||||
retVal = mainController.sendMail(username)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@finanzer.route("/finanzerSendAllMail", methods=['GET'])
|
||||
@login_required(groups=[MONEY])
|
||||
def _finanzerSendAllMail(**kwargs):
|
||||
debug.info("/finanzerSendAllMail")
|
||||
try:
|
||||
retVal = mainController.sendAllMail()
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
|
@ -1,97 +0,0 @@
|
|||
from flask import request, jsonify, Blueprint
|
||||
from geruecht.decorator import login_required
|
||||
import geruecht.controller.mainController as mc
|
||||
from geruecht.model import GASTRO
|
||||
from geruecht.logger import getCreditLogger, getDebugLogger
|
||||
|
||||
debug = getDebugLogger()
|
||||
|
||||
gastrouser = Blueprint('gastrouser', __name__)
|
||||
|
||||
mainController = mc.MainController()
|
||||
|
||||
|
||||
@gastrouser.route('/gastro/setDrink', methods=['POST'])
|
||||
@login_required(groups=[GASTRO])
|
||||
def setDrink(**kwargs):
|
||||
debug.info("/gastro/setDrink")
|
||||
try:
|
||||
data = request.get_json()
|
||||
retVal = mainController.setDrinkPrice(data)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@gastrouser.route('/gastro/updateDrink', methods=['POST'])
|
||||
@login_required(groups=[GASTRO])
|
||||
def updateDrink(**kwargs):
|
||||
debug.info("/gastro/updateDrink")
|
||||
try:
|
||||
data = request.get_json()
|
||||
retVal = mainController.updateDrinkPrice(data)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@gastrouser.route('/gastro/deleteDrink', methods=['POST'])
|
||||
@login_required(groups=[GASTRO])
|
||||
def deleteDrink(**kwargs):
|
||||
debug.info("/gastro/dleteDrink")
|
||||
try:
|
||||
data = request.get_json()
|
||||
id = data['id']
|
||||
mainController.deletDrinkPrice({"id": id})
|
||||
debug.debug("return ok")
|
||||
return jsonify({"ok": "ok"})
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@gastrouser.route('/gastro/setDrinkType', methods=['POST'])
|
||||
@login_required(groups=[GASTRO])
|
||||
def setType(**kwark):
|
||||
debug.info("/gastro/setDrinkType")
|
||||
try:
|
||||
data = request.get_json()
|
||||
name = data['name']
|
||||
retVal = mainController.setDrinkType(name)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@gastrouser.route('/gastro/updateDrinkType', methods=['POST'])
|
||||
@login_required(groups=[GASTRO])
|
||||
def updateType(**kwargs):
|
||||
debug.info("/gastro/updateDrinkType")
|
||||
try:
|
||||
data = request.get_json()
|
||||
retVal = mainController.updateDrinkType(data)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@gastrouser.route('/gastro/deleteDrinkType', methods=['POST'])
|
||||
@login_required(groups=[GASTRO])
|
||||
def deleteType(**kwargs):
|
||||
debug.info("/gastro/deleteDrinkType")
|
||||
try:
|
||||
data = request.get_json()
|
||||
mainController.deleteDrinkType(data)
|
||||
debug.debug("return ok")
|
||||
return jsonify({"ok": "ok"})
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
|
@ -1,144 +0,0 @@
|
|||
from flaschengeist.system.controller import Singleton, userController
|
||||
from flaschengeist.system.models.user import User
|
||||
from datetime import datetime, timedelta
|
||||
from flaschengeist.system.database import db
|
||||
from flask import current_app
|
||||
from werkzeug.local import LocalProxy
|
||||
logger = LocalProxy(lambda: current_app.logger)
|
||||
|
||||
class MainController(#mainJobKindController.Base,
|
||||
#mainCreditListController.Base,
|
||||
#mainPricelistController.Base,
|
||||
#mainWorkerController.Base,
|
||||
#mainWorkgroupController.Base,
|
||||
#mainJobInviteController.Base,
|
||||
#mainJobRequestController.Base,
|
||||
#mainRegistrationController.Base,
|
||||
#mainPasswordReset.Base,
|
||||
#mainFreeDrinkListConfigController.Base,
|
||||
metaclass=Singleton):
|
||||
|
||||
def __init__(self):
|
||||
logger.debug("init UserController")
|
||||
pass
|
||||
|
||||
def setLockedDay(self, date, locked, hard=False):
|
||||
logger.info(
|
||||
"set day locked on {{ {} }} with state {{ {} }}".format(date, locked))
|
||||
retVal = db.setLockedDay(date.date(), locked, hard)
|
||||
logger.debug("seted day locked is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getLockedDays(self, from_date, to_date):
|
||||
logger.info("get locked days from {{ {} }} to {{ {} }}".format(
|
||||
from_date.date(), to_date.date()))
|
||||
oneDay = timedelta(1)
|
||||
delta = to_date.date() - from_date.date()
|
||||
retVal = []
|
||||
startdate = from_date - oneDay
|
||||
for _ in range(delta.days + 1):
|
||||
startdate += oneDay
|
||||
lockday = self.getLockedDay(startdate)
|
||||
retVal.append(lockday)
|
||||
logger.debug("lock days are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getLockedDaysFromList(self, date_list):
|
||||
logger.info("get locked days from list {{ {} }}".format(date_list))
|
||||
retVal = []
|
||||
for on_date in date_list:
|
||||
day = datetime(on_date['on_date']['year'], on_date['on_date']['month'], on_date['on_date']['day'], 12)
|
||||
retVal.append(self.getLockedDay(day))
|
||||
return retVal
|
||||
|
||||
def getLockedDay(self, date):
|
||||
logger.info("get locked day on {{ {} }}".format(date))
|
||||
now = datetime.now()
|
||||
logger.debug("now is {{ {} }}".format(now))
|
||||
oldMonth = False
|
||||
logger.debug("check if date old month or current month")
|
||||
for i in range(1, 8):
|
||||
if datetime(now.year, now.month, i).weekday() == 2:
|
||||
if now.day < i:
|
||||
oldMonth = True
|
||||
break
|
||||
logger.debug("oldMonth is {{ {} }}".format(oldMonth))
|
||||
lockedYear = now.year
|
||||
lockedMonth = now.month if now.month < now.month else now.month - \
|
||||
1 if oldMonth else now.month
|
||||
endDay = 1
|
||||
logger.debug("calculate end day of month")
|
||||
lockedYear = lockedYear if lockedMonth != 12 else (lockedYear + 1)
|
||||
lockedMonth = (lockedMonth + 1) if lockedMonth != 12 else 1
|
||||
for i in range(1, 8):
|
||||
nextMonth = datetime(lockedYear, lockedMonth, i)
|
||||
if nextMonth.weekday() == 2:
|
||||
endDay = i
|
||||
break
|
||||
|
||||
monthLockedEndDate = datetime(
|
||||
lockedYear, lockedMonth, endDay) - timedelta(1)
|
||||
logger.debug("get lock day from database")
|
||||
retVal = db.getLockedDay(date.date())
|
||||
if not retVal:
|
||||
logger.debug(
|
||||
"lock day not exists, retVal is {{ {} }}".format(retVal))
|
||||
if date.date() <= monthLockedEndDate.date():
|
||||
logger.debug("lock day {{ {} }}".format(date.date()))
|
||||
self.setLockedDay(date, True)
|
||||
retVal = db.getLockedDay(date.date())
|
||||
else:
|
||||
retVal = {"daydate": date.date(), "locked": False}
|
||||
logger.debug("locked day is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def __updateDataFromLDAP(self, user):
|
||||
logger.info("update data from ldap for user {{ {} }}".format(user))
|
||||
groups = ldap.getGroup(user.userid)
|
||||
logger.debug("ldap gorups are {{ {} }}".format(groups))
|
||||
user_data = ldap.getUserData(user.userid)
|
||||
logger.debug("ldap data is {{ {} }}".format(user_data))
|
||||
user_data['gruppe'] = groups
|
||||
user_data['group'] = groups
|
||||
user.updateData(user_data)
|
||||
db.updateUser(user)
|
||||
|
||||
def checkBarUser(self, user):
|
||||
logger.info("check if user {{ {} }} is baruser")
|
||||
date = datetime.now()
|
||||
zero = date.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
end = zero + timedelta(hours=12)
|
||||
startdatetime = date.replace(
|
||||
hour=12, minute=0, second=0, microsecond=0)
|
||||
if date > zero and end > date:
|
||||
startdatetime = startdatetime - timedelta(days=1)
|
||||
enddatetime = startdatetime + timedelta(days=1)
|
||||
logger.debug("startdatetime is {{ {} }} and enddatetime is {{ {} }}".format(
|
||||
startdatetime, end))
|
||||
result = False
|
||||
if date >= startdatetime and date < enddatetime:
|
||||
result = db.getWorker(user, startdatetime)
|
||||
logger.debug("worker is {{ {} }}".format(result))
|
||||
return True if result else False
|
||||
|
||||
def sendMail(self, username):
|
||||
logger.info("send mail to user {{ {} }}".format(username))
|
||||
if type(username) == User:
|
||||
user = username
|
||||
if type(username) == str:
|
||||
user = db.getUser(username)
|
||||
retVal = emailController.sendMail(user)
|
||||
logger.debug("send mail is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def sendAllMail(self):
|
||||
debug.info("send mail to all users")
|
||||
retVal = []
|
||||
users = db.getAllUser()
|
||||
debug.debug("users are {{ {} }}".format(users))
|
||||
for user in users:
|
||||
retVal.append(self.sendMail(user))
|
||||
debug.debug("send mails are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
from datetime import datetime
|
||||
|
||||
import geruecht.controller.databaseController as dc
|
||||
import geruecht.controller.emailController as ec
|
||||
from geruecht.logger import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
emailController = ec.EmailController()
|
||||
debug = getDebugLogger()
|
||||
|
||||
class Base:
|
||||
def autoLock(self, user):
|
||||
debug.info("start autolock of user {{ {} }}".format(user))
|
||||
if user.autoLock:
|
||||
debug.debug("autolock is active")
|
||||
credit = user.getGeruecht(year=datetime.now().year).getSchulden()
|
||||
limit = -1*user.limit
|
||||
if credit <= limit:
|
||||
debug.debug(
|
||||
"credit {{ {} }} is more than user limit {{ {} }}".format(credit, limit))
|
||||
debug.debug("lock user")
|
||||
user.updateData({'locked': True})
|
||||
debug.debug("send mail to user")
|
||||
emailController.sendMail(user)
|
||||
else:
|
||||
debug.debug(
|
||||
"cretid {{ {} }} is less than user limit {{ {} }}".format(credit, limit))
|
||||
debug.debug("unlock user")
|
||||
user.updateData({'locked': False})
|
||||
db.updateUser(user)
|
||||
|
||||
def addAmount(self, username, amount, year, month, finanzer=False, bar=False):
|
||||
debug.info("add amount {{ {} }} to user {{ {} }} no month {{ {} }}, year {{ {} }}".format(
|
||||
amount, username, month, year))
|
||||
user = self.getUser(username)
|
||||
debug.debug("user is {{ {} }}".format(user))
|
||||
if user.userid == 'extern':
|
||||
debug.debug("user is extern user, so exit add amount")
|
||||
return
|
||||
if not user.locked or finanzer:
|
||||
debug.debug("user is not locked {{ {} }} or is finanzer execution {{ {} }}".format(
|
||||
user.locked, finanzer))
|
||||
user.addAmount(amount, year=year, month=month)
|
||||
if bar:
|
||||
user.last_seen = datetime.now()
|
||||
db.updateLastSeen(user, user.last_seen)
|
||||
creditLists = user.updateGeruecht()
|
||||
debug.debug("creditList is {{ {} }}".format(creditLists))
|
||||
for creditList in creditLists:
|
||||
debug.debug("update creditlist {{ {} }}".format(creditList))
|
||||
db.updateCreditList(creditList)
|
||||
debug.debug("do autolock")
|
||||
self.autoLock(user)
|
||||
retVal = user.getGeruecht(year)
|
||||
debug.debug("updated creditlists is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def addCredit(self, username, credit, year, month):
|
||||
debug.info("add credit {{ {} }} to user {{ {} }} on month {{ {} }}, year {{ {} }}".format(
|
||||
credit, username, month, year))
|
||||
user = self.getUser(username)
|
||||
debug.debug("user is {{ {} }}".format(user))
|
||||
if user.userid == 'extern':
|
||||
debug.debug("user is extern user, so exit add credit")
|
||||
return
|
||||
user.addCredit(credit, year=year, month=month)
|
||||
creditLists = user.updateGeruecht()
|
||||
debug.debug("creditlists are {{ {} }}".format(creditLists))
|
||||
for creditList in creditLists:
|
||||
debug.debug("update creditlist {{ {} }}".format(creditList))
|
||||
db.updateCreditList(creditList)
|
||||
debug.debug("do autolock")
|
||||
self.autoLock(user)
|
||||
retVal = user.getGeruecht(year)
|
||||
debug.debug("updated creditlists are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def __updateGeruechte(self, user):
|
||||
debug.debug("update creditlists")
|
||||
user.getGeruecht(datetime.now().year)
|
||||
creditLists = user.updateGeruecht()
|
||||
debug.debug("creditlists are {{ {} }}".format(creditLists))
|
||||
if user.getGeruecht(datetime.now().year).getSchulden() != 0:
|
||||
for creditList in creditLists:
|
||||
debug.debug("update creditlist {{ {} }}".format(creditList))
|
||||
db.updateCreditList(creditList)
|
|
@ -1,52 +0,0 @@
|
|||
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()
|
|
@ -1,42 +0,0 @@
|
|||
from datetime import date
|
||||
|
||||
import geruecht.controller.databaseController as dc
|
||||
import geruecht.controller.emailController as ec
|
||||
from geruecht import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
debug = getDebugLogger()
|
||||
emailController = ec.EmailController()
|
||||
|
||||
class Base:
|
||||
def getJobInvites(self, from_user, to_user, date):
|
||||
debug.info("get JobInvites from_user {{ {} }} to_user {{ {} }} on date {{ {} }}".format(from_user, to_user, date))
|
||||
if from_user is None:
|
||||
retVal = db.getJobInvitesToUser(to_user, date)
|
||||
elif to_user is None:
|
||||
retVal = db.getJobInvitesFromUser(from_user, date)
|
||||
else:
|
||||
raise Exception("from_user {{ {} }} and to_user {{ {} }} are None".format(from_user, to_user))
|
||||
return retVal
|
||||
|
||||
def setJobInvites(self, data):
|
||||
debug.info("set new JobInvites data {{ {} }}".format(data))
|
||||
retVal = []
|
||||
for jobInvite in data:
|
||||
from_user = jobInvite['from_user']
|
||||
to_user = jobInvite['to_user']
|
||||
on_date = date(jobInvite['date']['year'], jobInvite['date']['month'], jobInvite['date']['day'])
|
||||
debug.info("set new JobInvite from_user {{ {} }}, to_user {{ {} }}, on_date {{ {} }}")
|
||||
setJobInvite = db.setJobInvite(from_user, to_user, on_date)
|
||||
retVal.append(setJobInvite)
|
||||
emailController.sendMail(db.getUserById(to_user['id'], False), type='jobinvite', jobtransact=setJobInvite)
|
||||
debug.debug("seted JobInvites are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def updateJobInvites(self, data):
|
||||
debug.info("update JobInvites data {{ {} }}".format(data))
|
||||
return db.updateJobInvite(data)
|
||||
|
||||
def deleteJobInvite(self, jobInvite):
|
||||
debug.info("delete JobInvite {{ {} }}".format(jobInvite))
|
||||
db.deleteJobInvite(jobInvite)
|
|
@ -1,90 +0,0 @@
|
|||
from datetime import date, timedelta, datetime, time
|
||||
import geruecht.controller.databaseController as dc
|
||||
from geruecht.logger import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
debug = getDebugLogger()
|
||||
|
||||
class Base:
|
||||
def getAllJobKinds(self):
|
||||
debug.info("get all jobkinds")
|
||||
retVal = db.getAllJobKinds()
|
||||
debug.debug("jobkinds are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getJobKind(self, name):
|
||||
debug.info("get jobkinds {{ {} }}".format(name))
|
||||
retVal = db.getJobKind(name)
|
||||
debug.debug("jobkind is {{ {} }} is {{ {} }}".format(name, retVal))
|
||||
return retVal
|
||||
|
||||
def setJobKind(self, name, workgroup=None):
|
||||
debug.info("set jobkind {{ {} }} ".format(name))
|
||||
retVal = db.setJobKind(name, workgroup)
|
||||
debug.debug(
|
||||
"seted jobkind {{ {} }} is {{ {} }}".format(name, retVal))
|
||||
return retVal
|
||||
|
||||
def deleteJobKind(self, jobkind):
|
||||
debug.info("delete jobkind {{ {} }}".format(jobkind))
|
||||
db.deleteJobKind(jobkind)
|
||||
|
||||
def updateJobKind(self, jobkind):
|
||||
debug.info("update workgroup {{ {} }}".format(jobkind))
|
||||
retVal = db.updateJobKind(jobkind)
|
||||
debug.debug("updated jobkind is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getJobKindDates(self, date):
|
||||
debug.info("get jobkinddates on {{ {} }}".format(date))
|
||||
retVal = db.getJobKindDates(date)
|
||||
debug.debug("jobkinddates are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def updateJobKindDates(self, jobkindDate):
|
||||
debug.info("update jobkinddate {{ {} }}".format(jobkindDate))
|
||||
retVal = db.updateJobKindDates(jobkindDate)
|
||||
debug.debug("updated jobkind is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def deleteJobKindDates(self, jobkinddates):
|
||||
debug.info("delete jobkinddates {{ {} }}".format(jobkinddates))
|
||||
db.deleteJobKindDates(jobkinddates)
|
||||
|
||||
def setJobKindDates(self, datum, jobkind, maxpersons):
|
||||
debug.info("set jobkinddates with {{ {}, {}, {}, }}".format(datum, jobkind, maxpersons))
|
||||
retVal = db.setJobKindDates(datum, jobkind, maxpersons)
|
||||
debug.debug("seted jobkinddates is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def controllJobKindDates(self, jobkinddates):
|
||||
debug.info("controll jobkinddates {{ {} }}".format(jobkinddates))
|
||||
datum = None
|
||||
for jobkinddate in jobkinddates:
|
||||
datum = date(jobkinddate['daydate']['year'], jobkinddate['daydate']['month'], jobkinddate['daydate']['day'])
|
||||
if jobkinddate['id'] == -1:
|
||||
if jobkinddate['job_kind']:
|
||||
self.setJobKindDates(datum, jobkinddate['job_kind'], jobkinddate['maxpersons'])
|
||||
if jobkinddate['id'] == 0:
|
||||
jobkinddate['id'] = jobkinddate['backupid']
|
||||
db.deleteAllWorkerWithJobKind(datetime.combine(datum, time(12)), jobkinddate['job_kind'])
|
||||
self.deleteJobKindDates(jobkinddate)
|
||||
if jobkinddate['id'] >= 1:
|
||||
self.updateJobKindDates(jobkinddate)
|
||||
retVal = self.getJobKindDates(datum) if datum != None else []
|
||||
debug.debug("controlled jobkinddates {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getJobKindDatesFromTo(self, from_date, to_date):
|
||||
debug.info("get locked days from {{ {} }} to {{ {} }}".format(
|
||||
from_date.date(), to_date.date()))
|
||||
oneDay = timedelta(1)
|
||||
delta = to_date.date() - from_date.date()
|
||||
retVal = []
|
||||
startdate = from_date - oneDay
|
||||
for _ in range(delta.days + 1):
|
||||
startdate += oneDay
|
||||
jobkinddate = self.getJobKindDates(startdate)
|
||||
retVal.append(jobkinddate)
|
||||
debug.debug("lock days are {{ {} }}".format(retVal))
|
||||
return retVal
|
|
@ -1,46 +0,0 @@
|
|||
from datetime import date, time, datetime
|
||||
import geruecht.controller.emailController as ec
|
||||
import geruecht.controller.databaseController as dc
|
||||
from geruecht import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
debug = getDebugLogger()
|
||||
emailController = ec.EmailController()
|
||||
|
||||
class Base:
|
||||
def getJobRequests(self, from_user, to_user, date):
|
||||
debug.info("get JobRequests from_user {{ {} }} to_user {{ {} }} on date {{ {} }}".format(from_user, to_user, date))
|
||||
if from_user is None:
|
||||
retVal = db.getJobRequestsToUser(to_user, date)
|
||||
elif to_user is None:
|
||||
retVal = db.getJobRequestsFromUser(from_user, date)
|
||||
else:
|
||||
raise Exception("from_user {{ {} }} and to_user {{ {} }} are None".format(from_user, to_user))
|
||||
return retVal
|
||||
|
||||
def setJobRequests(self, data):
|
||||
debug.info("set new JobRequests data {{ {} }}".format(data))
|
||||
retVal = []
|
||||
for jobRequest in data:
|
||||
from_user = jobRequest['from_user']
|
||||
to_user = jobRequest['to_user']
|
||||
on_date = date(jobRequest['date']['year'], jobRequest['date']['month'], jobRequest['date']['day'])
|
||||
job_kind = jobRequest['job_kind']
|
||||
debug.info("set new JobRequest from_user {{ {} }}, to_user {{ {} }}, on_date {{ {} }}")
|
||||
setJobRequest = db.setJobRequest(from_user, to_user, on_date, job_kind)
|
||||
retVal.append(setJobRequest)
|
||||
emailController.sendMail(db.getUserById(to_user['id']), type='jobtransact', jobtransact=setJobRequest)
|
||||
|
||||
debug.debug("seted JobRequests are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def updateJobRequests(self, data):
|
||||
debug.info("update JobRequest data {{ {} }}".format(data))
|
||||
if data['accepted']:
|
||||
self.changeWorker(data['from_user'], data['to_user'], datetime.combine(data['on_date'], time(12)))
|
||||
db.updateAllJobRequest(data)
|
||||
return db.updateJobRequest(data)
|
||||
|
||||
def deleteJobRequest(self, jobRequest):
|
||||
debug.info("delete JobRequest {{ {} }}".format(jobRequest))
|
||||
db.deleteJobRequest(jobRequest)
|
|
@ -1,39 +0,0 @@
|
|||
from geruecht import ldap, ldapConfig, getDebugLogger
|
||||
import geruecht.controller.emailController as ec
|
||||
from ldap3.utils.hashed import hashed
|
||||
from ldap3 import HASHED_SALTED_MD5, MODIFY_REPLACE
|
||||
import string
|
||||
import random
|
||||
|
||||
emailController = ec.EmailController()
|
||||
debug = getDebugLogger()
|
||||
|
||||
def randomString(stringLength=8):
|
||||
letters = string.ascii_letters + string.digits
|
||||
return ''.join(random.choice(letters) for i in range(stringLength))
|
||||
|
||||
class Base:
|
||||
def resetPassword(self, data):
|
||||
debug.info("forgot password {{ {} }}".format(data))
|
||||
adminConn = ldap.connect(ldapConfig['ADMIN_DN'], ldapConfig['ADMIN_SECRET'])
|
||||
if 'username' in data:
|
||||
search = 'uid={}'.format(data['username'].lower())
|
||||
elif 'mail' in data:
|
||||
search = 'mail={}'.format(data['mail'].lower())
|
||||
else:
|
||||
debug.error("username or mail not set")
|
||||
raise Exception('username or mail not set')
|
||||
adminConn.search(ldapConfig['DN'], '(&(objectClass=person)({}))'.format(search),
|
||||
attributes=['cn', 'sn', 'givenName', 'uid', 'mail'])
|
||||
for user in adminConn.response:
|
||||
user_dn = user['dn']
|
||||
uid = user['attributes']['uid'][0]
|
||||
mail = user['attributes']['mail'][0]
|
||||
mody = {}
|
||||
password = randomString()
|
||||
salted_password = hashed(HASHED_SALTED_MD5, password)
|
||||
mody['userPassword'] = [(MODIFY_REPLACE, [salted_password])]
|
||||
debug.info("reset password for {{ {} }}".format(user_dn))
|
||||
adminConn.modify(user_dn, mody)
|
||||
emailController.sendMail(self.getUser(uid), type='passwordReset', password=password)
|
||||
return mail
|
|
@ -1,50 +0,0 @@
|
|||
import geruecht.controller.databaseController as dc
|
||||
from geruecht.logger import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
debug = getDebugLogger()
|
||||
|
||||
class Base:
|
||||
def deleteDrinkType(self, type):
|
||||
debug.info("delete drink type {{ {} }}".format(type))
|
||||
db.deleteDrinkType(type)
|
||||
|
||||
def updateDrinkType(self, type):
|
||||
debug.info("update drink type {{ {} }}".format(type))
|
||||
retVal = db.updateDrinkType(type)
|
||||
debug.debug("updated drink type is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def setDrinkType(self, type):
|
||||
debug.info("set drink type {{ {} }}".format(type))
|
||||
retVal = db.setDrinkType(type)
|
||||
debug.debug("seted drink type is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def deletDrinkPrice(self, drink):
|
||||
debug.info("delete drink {{ {} }}".format(drink))
|
||||
db.deleteDrink(drink)
|
||||
|
||||
def setDrinkPrice(self, drink):
|
||||
debug.info("set drink {{ {} }}".format(drink))
|
||||
retVal = db.setDrinkPrice(drink)
|
||||
debug.debug("seted drink is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def updateDrinkPrice(self, drink):
|
||||
debug.info("update drink {{ {} }}".format(drink))
|
||||
retVal = db.updateDrinkPrice(drink)
|
||||
debug.debug("updated drink is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getAllDrinkTypes(self):
|
||||
debug.info("get all drink types")
|
||||
retVal = db.getAllDrinkTypes()
|
||||
debug.debug("all drink types are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getPricelist(self):
|
||||
debug.info("get all drinks")
|
||||
list = db.getPriceList()
|
||||
debug.debug("all drinks are {{ {} }}".format(list))
|
||||
return list
|
|
@ -1,14 +0,0 @@
|
|||
from datetime import date
|
||||
|
||||
import geruecht.controller.databaseController as dc
|
||||
from geruecht.logger import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
debug = getDebugLogger()
|
||||
|
||||
class Base:
|
||||
def setNewRegistration(self, data):
|
||||
debug.info("set new registration {{ {} }}".format(data))
|
||||
data['birthDate'] = date(int(data['birthDate']['year']), int(data['birthDate']['month']), int(data['birthDate']['day']))
|
||||
data['entryDate'] = date(int(data['entryDate']['year']), int(data['entryDate']['month']), int(data['entryDate']['day'])) if data['entryDate'] else None
|
||||
db.setNewRegistration(data)
|
|
@ -1,58 +0,0 @@
|
|||
from datetime import time, datetime
|
||||
|
||||
import geruecht.controller.databaseController as dc
|
||||
from geruecht.exceptions import DayLocked
|
||||
from geruecht.logger import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
debug = getDebugLogger()
|
||||
|
||||
class Base:
|
||||
def getWorker(self, date, username=None):
|
||||
debug.info("get worker {{ {} }} on {{ {} }}".format(username, date))
|
||||
if (username):
|
||||
user = self.getUser(username)
|
||||
debug.debug("user is {{ {} }}".format(user))
|
||||
retVal = [db.getWorker(user, date)]
|
||||
debug.debug("worker is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
retVal = db.getWorkers(date)
|
||||
debug.debug("workers are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def addWorker(self, username, date, job_kind=None, userExc=False):
|
||||
debug.info("add job user {{ {} }} on {{ {} }} with job_kind {{ {} }}".format(username, date, job_kind))
|
||||
if (userExc):
|
||||
debug.debug("this is a user execution, check if day is locked")
|
||||
lockedDay = self.getLockedDay(date)
|
||||
if lockedDay:
|
||||
if lockedDay['locked']:
|
||||
debug.debug("day is lockey. user cant get job")
|
||||
raise DayLocked("Day is locked. You can't get the Job")
|
||||
user = self.getUser(username)
|
||||
debug.debug("user is {{ {} }}".format(user))
|
||||
debug.debug("check if user has job on date")
|
||||
if (not db.getWorker(user, date) and len(db.getWorkersWithJobKind(date, job_kind)) < db.getJobKindDate(date.date(), job_kind)['maxpersons']):
|
||||
debug.debug("set job to user")
|
||||
db.setWorker(user, date, job_kind=job_kind)
|
||||
retVal = self.getWorker(date, username=username)
|
||||
debug.debug("worker on date is {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def changeWorker(self, from_user, to_user, date):
|
||||
debug.info("change worker from {{ {} }} to {{ {} }} on {{ {} }}".format(from_user, to_user, date))
|
||||
db.changeWorker(from_user, to_user, date)
|
||||
|
||||
def deleteWorker(self, username, date, userExc=False):
|
||||
debug.info(
|
||||
"delete worker {{ {} }} on date {{ {} }}".format(username, date))
|
||||
user = self.getUser(username)
|
||||
debug.debug("user is {{ {} }}".format(user))
|
||||
if userExc:
|
||||
debug.debug("is user execution, check if day locked")
|
||||
lockedDay = self.getLockedDay(date)
|
||||
if lockedDay:
|
||||
if lockedDay['locked']:
|
||||
raise DayLocked(
|
||||
"Day is locked. You can't delete the Job")
|
||||
db.deleteWorker(user, date)
|
|
@ -1,42 +0,0 @@
|
|||
import geruecht.controller.databaseController as dc
|
||||
from geruecht.logger import getDebugLogger
|
||||
|
||||
db = dc.DatabaseController()
|
||||
debug = getDebugLogger()
|
||||
|
||||
class Base:
|
||||
def updateWorkgroupsOfUser(self, user, workgroups):
|
||||
debug.info("update workgroups {{ {} }} of user {{ {} }}".format(workgroups, user))
|
||||
db.deleteWorkgroupsOfUser(user)
|
||||
for workgroup in workgroups:
|
||||
db.setUserWorkgroup(user, workgroup)
|
||||
return db.getWorkgroupsOfUser(user['id'])
|
||||
|
||||
def getAllWorkgroups(self):
|
||||
debug.info("get all workgroups")
|
||||
retVal = db.getAllWorkgroups()
|
||||
debug.debug("workgroups are {{ {} }}".format(retVal))
|
||||
return retVal
|
||||
|
||||
def getWorkgroups(self, name):
|
||||
debug.info("get Workgroup {{ {} }}".format(name))
|
||||
retVal = db.getWorkgroup(name)
|
||||
debug.debug("workgroup is {{ {} }} is {{ {} }}".format(name, retVal))
|
||||
return retVal
|
||||
|
||||
def setWorkgroup(self, name, boss):
|
||||
debug.info("set workgroup {{ {} }} with boss {{ {} }}".format(name, boss))
|
||||
retVal = db.setWorkgroup(name, boss)
|
||||
debug.debug(
|
||||
"seted workgroup {{ {} }} is {{ {} }}".format(name, retVal))
|
||||
return retVal
|
||||
|
||||
def deleteWorkgroup(self, workgroup):
|
||||
debug.info("delete workgroup {{ {} }}".format(workgroup))
|
||||
db.deleteWorkgroup(workgroup)
|
||||
|
||||
def updateWorkgroup(self, workgroup):
|
||||
debug.info("update workgroup {{ {} }}".format(workgroup))
|
||||
retVal = db.updateWorkgroup(workgroup)
|
||||
debug.debug("updated workgroup is {{ {} }}".format(retVal))
|
||||
return retVal
|
|
@ -1,380 +0,0 @@
|
|||
from flask import Blueprint, request, jsonify
|
||||
from datetime import datetime, time, date
|
||||
import geruecht.controller.mainController as mc
|
||||
import geruecht.controller.ldapController as lc
|
||||
from geruecht.decorator import login_required
|
||||
from geruecht.model import MONEY, GASTRO, VORSTAND
|
||||
from geruecht.logger import getDebugLogger, getJobsLogger
|
||||
|
||||
debug = getDebugLogger()
|
||||
jobL = getJobsLogger()
|
||||
|
||||
vorstand = Blueprint("vorstand", __name__)
|
||||
mainController = mc.MainController()
|
||||
ldap = lc.LDAPController()
|
||||
|
||||
|
||||
@vorstand.route('/um/setStatus', methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _setStatus(**kwargs):
|
||||
debug.info("/um/setStatus")
|
||||
try:
|
||||
data = request.get_json()
|
||||
name = data['name']
|
||||
retVal = mainController.setStatus(name)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@vorstand.route('/um/updateStatus', methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _updateStatus(**kwargs):
|
||||
debug.info("/um/updateStatus")
|
||||
try:
|
||||
data = request.get_json()
|
||||
retVal = mainController.updateStatus(data)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@vorstand.route('/um/deleteStatus', methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _deleteStatus(**kwargs):
|
||||
debug.info("/um/deleteStatus")
|
||||
try:
|
||||
data = request.get_json()
|
||||
mainController.deleteStatus(data)
|
||||
debug.debug("return ok")
|
||||
return jsonify({"ok": "ok"})
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 409
|
||||
|
||||
|
||||
@vorstand.route('/um/updateStatusUser', methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _updateStatusUser(**kwargs):
|
||||
debug.info("/um/updateStatusUser")
|
||||
try:
|
||||
data = request.get_json()
|
||||
username = data['username']
|
||||
status = data['status']
|
||||
retVal = mainController.updateStatusOfUser(username, status).toJSON()
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@vorstand.route('/um/updateVoting', methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _updateVoting(**kwargs):
|
||||
debug.info("/um/updateVoting")
|
||||
try:
|
||||
data = request.get_json()
|
||||
username = data['username']
|
||||
voting = data['voting']
|
||||
retVal = mainController.updateVotingOfUser(username, voting).toJSON()
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route('/um/updateWorkgroups', methods=['POST'])
|
||||
@login_required(groups=[VORSTAND])
|
||||
def _updateWorkgroups(**kwargs):
|
||||
debug.info("/um/updateWorkgroups")
|
||||
try:
|
||||
data = request.get_json()
|
||||
retVal = mainController.updateWorkgroupsOfUser({"id": data['id']}, data['workgroups'])
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal), 200
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/sm/addUser", methods=['POST', 'GET'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _addUser(**kwargs):
|
||||
debug.info("/sm/addUser")
|
||||
try:
|
||||
data = request.get_json()
|
||||
user = data['user']
|
||||
day = data['day']
|
||||
month = data['month']
|
||||
year = data['year']
|
||||
date = datetime(year, month, day, 12)
|
||||
job_kind = None
|
||||
if 'job_kind' in data:
|
||||
job_kind = data['job_kind']
|
||||
retVal = mainController.addWorker(user['username'], date, job_kind=job_kind)
|
||||
debug.debug("retrun {{ {} }}".format(retVal))
|
||||
userl = mainController.getUser(user['username'])
|
||||
jobL.info("Vorstand {} {} schreibt Mitglied {} {} am {} zum Dienst ein".format(
|
||||
kwargs['accToken'].user.firstname, kwargs['accToken'].user.lastname, userl.firstname, userl.lastname, date.date()))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@vorstand.route("/sm/getUser", methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _getUser(**kwargs):
|
||||
debug.info("/sm/getUser")
|
||||
try:
|
||||
data = request.get_json()
|
||||
day = data['day']
|
||||
month = data['month']
|
||||
year = data['year']
|
||||
date = datetime(year, month, day, 12)
|
||||
lockedDay = mainController.getLockedDay(date)
|
||||
lockedDay = {
|
||||
'date': {
|
||||
'year': year,
|
||||
'month': month,
|
||||
'day': day
|
||||
},
|
||||
'locked': lockedDay['locked']
|
||||
}
|
||||
retVal = {
|
||||
'worker': mainController.getWorker(date),
|
||||
'day': lockedDay
|
||||
}
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
|
||||
@vorstand.route("/sm/deleteUser", methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _deletUser(**kwargs):
|
||||
debug.info("/sm/deletUser")
|
||||
try:
|
||||
data = request.get_json()
|
||||
user = data['user']
|
||||
day = data['day']
|
||||
month = data['month']
|
||||
year = data['year']
|
||||
date = datetime(year, month, day, 12)
|
||||
mainController.deleteWorker(user['username'], date)
|
||||
debug.debug("return ok")
|
||||
user = mainController.getUser(user['username'])
|
||||
jobL.info("Vorstand {} {} entfernt Mitglied {} {} am {} vom Dienst".format(
|
||||
kwargs['accToken'].user.firstname, kwargs['accToken'].user.lastname, user.firstname, user.lastname, date.date()))
|
||||
return jsonify({"ok": "ok"})
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/wgm/getAllWorkgroups", methods=['GET'])
|
||||
@login_required(bar=True)
|
||||
def _getAllWorkgroups(**kwargs):
|
||||
try:
|
||||
debug.info("get all workgroups")
|
||||
retVal = mainController.getAllWorkgroups()
|
||||
debug.info("return all workgroups {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.warning("exception in get all workgroups.", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/wgm/getWorkgroup", methods=['POST'])
|
||||
@login_required(bar=True)
|
||||
def _getWorkgroup(**kwargs):
|
||||
try:
|
||||
debug.info("get workgroup")
|
||||
data = request.get_json()
|
||||
name = data['name']
|
||||
debug.info("get workgroup {{ {} }}".format(name))
|
||||
retVal = mainController.getWorkgroups(name)
|
||||
debug.info(
|
||||
"return workgroup {{ {} }} : {{ {} }}".format(name, retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.warning("exception in get workgroup.", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/wgm/workgroup", methods=['POST', 'PUT', 'DELETE'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _workgroup(**kwargs):
|
||||
debug.info("/wgm/workgroup")
|
||||
try:
|
||||
data = request.get_json()
|
||||
if request.method == 'PUT':
|
||||
name = data['name']
|
||||
boss = None
|
||||
if 'boss' in data:
|
||||
boss = data['boss']
|
||||
retVal = mainController.setWorkgroup(name, boss)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
if request.method == 'POST':
|
||||
retVal = mainController.updateWorkgroup(data)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/wgm/deleteWorkgroup", methods=['POST'])
|
||||
@login_required(groups=[VORSTAND])
|
||||
def _deleteWorkgroup(**kwargs):
|
||||
try:
|
||||
data = request.get_json()
|
||||
debug.info("/wgm/deleteWorkgroup")
|
||||
mainController.deleteWorkgroup(data)
|
||||
retVal = {"ok": "ok"}
|
||||
debug.debug("return ok")
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/sm/getAllJobKinds", methods=['GET'])
|
||||
@login_required(bar=True)
|
||||
def _getAllJobKinds(**kwargs):
|
||||
try:
|
||||
debug.info("get all jobkinds")
|
||||
retVal = mainController.getAllJobKinds()
|
||||
debug.info("return all jobkinds {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.warning("exception in get all workgroups.", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/sm/getJobKind", methods=['POST'])
|
||||
@login_required(bar=True)
|
||||
def _getJobKinds(**kwargs):
|
||||
try:
|
||||
debug.info("get jobkind")
|
||||
data = request.get_json()
|
||||
name = data['name']
|
||||
debug.info("get jobkind {{ {} }}".format(name))
|
||||
retVal = mainController.getJobKind(name)
|
||||
debug.info(
|
||||
"return workgroup {{ {} }} : {{ {} }}".format(name, retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.warning("exception in get workgroup.", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/sm/JobKind", methods=['POST', 'PUT', 'DELETE'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _JobKinds(**kwargs):
|
||||
debug.info("/sm/JobKind")
|
||||
try:
|
||||
data = request.get_json()
|
||||
if request.method == 'PUT':
|
||||
name = data['name']
|
||||
workgroup = None
|
||||
if 'workgroup' in data:
|
||||
workgroup = data['workgroup']
|
||||
retVal = mainController.setJobKind(name, workgroup)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
if request.method == 'POST':
|
||||
retVal = mainController.updateJobKind(data)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/sm/deleteJobKind", methods=['POST'])
|
||||
@login_required(groups=[VORSTAND])
|
||||
def _deleteJobKind(**kwargs):
|
||||
try:
|
||||
data = request.get_json()
|
||||
debug.info("/sm/deleteJobKind")
|
||||
mainController.deleteJobKind(data)
|
||||
retVal = {"ok": "ok"}
|
||||
debug.debug("return ok")
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/jk/getJobKindDates", methods=['POST'])
|
||||
@login_required()
|
||||
def _getJobKindDates(**kwargs):
|
||||
try:
|
||||
debug.info("/jk/getJobKindDates")
|
||||
data = request.get_json()
|
||||
datum = date(data['year'], data['month'], data['day'])
|
||||
retVal = mainController.getJobKindDates(datum)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/jk/JobKindDate", methods=['POST'])
|
||||
@login_required(groups=[VORSTAND])
|
||||
def _jobKindDates(**kwargs):
|
||||
try:
|
||||
debug.info("/jk/JobKindDate")
|
||||
data = request.get_json()
|
||||
retVal = mainController.controllJobKindDates(data)
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
||||
|
||||
@vorstand.route("/sm/lockDay", methods=['POST'])
|
||||
@login_required(groups=[MONEY, GASTRO, VORSTAND])
|
||||
def _lockDay(**kwargs):
|
||||
debug.info("/sm/lockDay")
|
||||
try:
|
||||
data = request.get_json()
|
||||
year = data['year']
|
||||
month = data['month']
|
||||
day = data['day']
|
||||
locked = data['locked']
|
||||
date = datetime(year, month, day, 12)
|
||||
lockedDay = mainController.setLockedDay(date, locked, True)
|
||||
if not lockedDay:
|
||||
retVal = {
|
||||
'date': {
|
||||
'year': year,
|
||||
'month': month,
|
||||
'day': day
|
||||
},
|
||||
'locked': False
|
||||
}
|
||||
else:
|
||||
retVal = {
|
||||
'date': {
|
||||
'year': year,
|
||||
'month': month,
|
||||
'day': day
|
||||
},
|
||||
'locked': lockedDay['locked']
|
||||
}
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({'error': err}), 409
|
||||
|
||||
|
||||
@vorstand.route("/sm/searchWithExtern", methods=['GET'])
|
||||
@login_required(groups=[VORSTAND])
|
||||
def _search(**kwargs):
|
||||
debug.info("/sm/searchWithExtern")
|
||||
try:
|
||||
retVal = ldap.getAllUser()
|
||||
debug.debug("return {{ {} }}".format(retVal))
|
||||
return jsonify(retVal)
|
||||
except Exception as err:
|
||||
debug.debug("exception", exc_info=True)
|
||||
return jsonify({"error": str(err)}), 500
|
|
@ -1,6 +1,6 @@
|
|||
import pkg_resources
|
||||
|
||||
from flaschengeist.system.hook import HookCall
|
||||
from flaschengeist.hook import HookCall
|
||||
|
||||
send_message_hook = HookCall("send_message")
|
||||
|
|
@ -7,9 +7,9 @@ from flask import Blueprint, request, jsonify
|
|||
from werkzeug.exceptions import Forbidden, BadRequest, Unauthorized
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.modules import Plugin
|
||||
from flaschengeist.system.decorator import login_required
|
||||
from flaschengeist.system.controller import sessionController, userController
|
||||
from flaschengeist.plugins import Plugin
|
||||
from flaschengeist.decorator import login_required
|
||||
from flaschengeist.controller import sessionController, userController
|
||||
|
||||
auth_bp = Blueprint("auth", __name__)
|
||||
|
|
@ -6,9 +6,9 @@ from flask import current_app as app
|
|||
from flask_ldapconn import LDAPConn
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
from flaschengeist.modules import AuthPlugin
|
||||
from flaschengeist.system.models.user import User
|
||||
import flaschengeist.system.controller.userController as userController
|
||||
from flaschengeist.plugins import AuthPlugin
|
||||
from flaschengeist.models.user import User
|
||||
import flaschengeist.controller.userController as userController
|
||||
|
||||
|
||||
class AuthLDAP(AuthPlugin):
|
|
@ -4,8 +4,8 @@ import os
|
|||
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
from flaschengeist.modules import AuthPlugin
|
||||
from flaschengeist.system.models.user import User
|
||||
from flaschengeist.plugins import AuthPlugin
|
||||
from flaschengeist.models.user import User
|
||||
|
||||
|
||||
def _hash_password(password):
|
|
@ -3,9 +3,9 @@ from email.mime.multipart import MIMEMultipart
|
|||
from email.mime.text import MIMEText
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.system.models.user import User
|
||||
from flaschengeist.system.controller import userController
|
||||
from flaschengeist.system.controller.messageController import Message
|
||||
from flaschengeist.models.user import User
|
||||
from flaschengeist.controller import userController
|
||||
from flaschengeist.controller.messageController import Message
|
||||
|
||||
from . import Plugin, send_message_hook
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
from flask import Blueprint, request, jsonify
|
||||
from werkzeug.exceptions import NotFound, BadRequest
|
||||
|
||||
from flaschengeist.modules import Plugin
|
||||
from flaschengeist.system.decorator import login_required
|
||||
from flaschengeist.system.controller import roleController
|
||||
from flaschengeist.plugins import Plugin
|
||||
from flaschengeist.decorator import login_required
|
||||
from flaschengeist.controller import roleController
|
||||
|
||||
roles_bp = Blueprint("roles", __name__)
|
||||
_permission_edit = "roles_edit"
|
|
@ -3,11 +3,11 @@ from datetime import datetime, timedelta
|
|||
from flask import Blueprint, request, jsonify
|
||||
from werkzeug.exceptions import BadRequest, NotFound
|
||||
|
||||
from flaschengeist.modules import Plugin
|
||||
from flaschengeist.system.database import db
|
||||
from flaschengeist.system.models.event import EventKind
|
||||
from flaschengeist.system.decorator import login_required
|
||||
from flaschengeist.system.controller import eventController
|
||||
from flaschengeist.plugins import Plugin
|
||||
from flaschengeist.database import db
|
||||
from flaschengeist.models.event import EventKind
|
||||
from flaschengeist.decorator import login_required
|
||||
from flaschengeist.controller import eventController
|
||||
|
||||
schedule_bp = Blueprint("schedule", __name__, url_prefix="/schedule")
|
||||
_permission_edit_type = "schedule_edit_type"
|
|
@ -2,9 +2,9 @@ from flask import Blueprint, request, jsonify
|
|||
from werkzeug.exceptions import NotFound, BadRequest, Forbidden
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.modules import Plugin
|
||||
from flaschengeist.system.decorator import login_required
|
||||
from flaschengeist.system.controller import userController
|
||||
from flaschengeist.plugins import Plugin
|
||||
from flaschengeist.decorator import login_required
|
||||
from flaschengeist.controller import userController
|
||||
|
||||
users_bp = Blueprint("users", __name__)
|
||||
_permission_edit = "users_edit_other"
|
|
@ -5,7 +5,6 @@ import argparse
|
|||
|
||||
def install(arguments):
|
||||
from flaschengeist.app import create_app, install_all
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
install_all()
|
||||
|
@ -27,7 +26,7 @@ def run(arguments):
|
|||
|
||||
|
||||
def export(arguments):
|
||||
import flaschengeist.system.models as models
|
||||
import flaschengeist.models as models
|
||||
|
||||
known = []
|
||||
classes = {}
|
||||
|
|
14
setup.py
14
setup.py
|
@ -22,13 +22,13 @@ setup(
|
|||
extras_require={"ldap": ["flask_ldapconn", "ldap3"], "bjoern": ["bjoern"]},
|
||||
entry_points={
|
||||
"flaschengeist.plugin": [
|
||||
"auth = flaschengeist.modules.auth:AuthRoutePlugin",
|
||||
"users = flaschengeist.modules.users:UsersPlugin",
|
||||
"roles = flaschengeist.modules.roles:RolesPlugin",
|
||||
"schedule = flaschengeist.modules.schedule:SchedulePlugin",
|
||||
"mail = flaschengeist.modules.message_mail:MailMessagePlugin",
|
||||
"auth_plain = flaschengeist.modules.auth_plain:AuthPlain",
|
||||
"auth_ldap = flaschengeist.modules.auth_ldap:AuthLDAP [ldap]",
|
||||
"auth = flaschengeist.plugins.auth:AuthRoutePlugin",
|
||||
"users = flaschengeist.plugins.users:UsersPlugin",
|
||||
"roles = flaschengeist.plugins.roles:RolesPlugin",
|
||||
"schedule = flaschengeist.plugins.schedule:SchedulePlugin",
|
||||
"mail = flaschengeist.plugins.message_mail:MailMessagePlugin",
|
||||
"auth_plain = flaschengeist.plugins.auth_plain:AuthPlain",
|
||||
"auth_ldap = flaschengeist.plugins.auth_ldap:AuthLDAP [ldap]",
|
||||
],
|
||||
},
|
||||
)
|
||||
|
|
Loading…
Reference in New Issue