rework prof data using dataclass, change database code, fix bugs

This commit is contained in:
WorldTeacher
2024-09-23 15:45:42 +02:00
parent e91a40695a
commit cd74214c17
10 changed files with 150 additions and 65 deletions

View File

@@ -2,4 +2,4 @@ from .admin_console import AdminCommands
from .create_file import recreateElsaFile, recreateFile
from .database import Database
from .delete_temp_contents import delete_temp_contents as tempdelete
from .semester import generateSemesterByDate
from .semester import generateSemesterByDate, generateSemesterByOffset

View File

@@ -1,7 +1,7 @@
import hashlib
import random
from src.backend.database import Database
from .database import Database
# change passwords for apparats, change passwords for users, list users, create and delete users etc

View File

@@ -4,7 +4,6 @@ import sqlite3 as sql
import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import shutil
# from icecream import ic
from omegaconf import OmegaConf
@@ -23,11 +22,10 @@ from src.backend.db import (
CREATE_TABLE_USER,
)
from src.errors import AppPresentError, NoResultError
from src.logic import ApparatData, BookData, Prof, MyLogger
from src.logic.constants import SEMAP_MEDIA_ACCOUNTS
from src.logic.dataclass import ApparatData, BookData
from src.logic.log import MyLogger
from src.utils import create_blob, dump_pickle, load_pickle
from src.backend.semester import generateSemesterByDate
from .semester import generateSemesterByDate
from icecream import ic
config = OmegaConf.load("config.yaml")
@@ -217,6 +215,8 @@ class Database:
app_id (str): The apparat id where the book should be added to
prof_id (str): The id of the professor where the book should be added to.
"""
if app_id is None or prof_id is None:
raise ValueError("Apparate ID or Prof ID is None")
conn = self.connect()
cursor = conn.cursor()
t_query = (
@@ -553,7 +553,7 @@ class Database:
"Musik",
"Philosophie",
"Physik",
"Poitikwissenschaft",
"Politikwissenschaft",
"Prorektorat Lehre und Studium",
"Psychologie",
"Soziologie",
@@ -717,23 +717,25 @@ class Database:
tuple: the mail, telephone number and title of the professor
"""
data = self.query_db(
"SELECT mail, telnr, titel FROM prof WHERE fullname=?",
"SELECT * FROM prof WHERE fullname=?",
(profname.replace(",", ""),),
one=True,
)
return data
print(data)
person = Prof()
return person.from_tuple(data)
def getProfs(self) -> list[tuple]:
def getProfs(self) -> list[Prof]:
"""Return all the professors in the database
Returns:
list[tuple]: a list containing all the professors in individual tuples
tuple: (id, titel, fname, lname, fullname, mail, telnr)
"""
return self.query_db("SELECT * FROM prof")
profs = self.query_db("SELECT * FROM prof")
return [Prof().from_tuple(prof) for prof in profs]
# Apparat
def getAllAparats(self, deleted=0) -> list[tuple]:
"""Get all the apparats in the database
@@ -774,9 +776,9 @@ class Database:
apparat.dauerapp = True if result[7] == 1 else False
prof_data = self.getProfData(self.getProfNameById(result[2]))
apparat.profname = self.getProfNameById(result[2])
apparat.prof_mail = prof_data[0]
apparat.prof_tel = prof_data[1]
apparat.prof_title = prof_data[2]
apparat.prof_mail = prof_data.mail
apparat.prof_tel = prof_data.telnr
apparat.prof_title = prof_data.title
apparat.app_fach = result[3]
apparat.erstellsemester = result[5]
apparat.semester = result[8]
@@ -848,15 +850,16 @@ class Database:
Optional[int]: the id of the apparat
"""
ic(apparat)
prof_id = self.getProfByName(apparat.get_prof_details()["fullname"])
prof = self.getProfByName(apparat.prof_details.fullname)
prof_id = prof.id
ic(prof_id, apparat.profname)
if prof_id:
prof_id = prof_id[0]
app_id = self.getApparatId(apparat.appname)
if app_id:
return AppPresentError(app_id)
if not prof_id:
prof_id = self.createProf(apparat.get_prof_details())
print("prof id not present, creating prof with data", apparat.prof_details)
prof_id = self.createProf(apparat.prof_details)
# self.getProfId(apparat.profname)
ic(prof_id)
query = f"INSERT OR IGNORE INTO semesterapparat (appnr, name, erstellsemester, dauer, prof_id, fach,deletion_status,konto) VALUES ('{apparat.appnr}', '{apparat.appname}', '{apparat.semester}', '{apparat.dauerapp}', {prof_id}, '{apparat.app_fach}', '{0}', '{SEMAP_MEDIA_ACCOUNTS[apparat.appnr]}')"
@@ -1000,7 +1003,7 @@ class Database:
apparat_data.appname,
apparat_data.app_fach,
apparat_data.dauerapp,
self.getProfId(apparat_data.profname),
self.getProfData(apparat_data.prof_details.fullname).id,
apparat_data.prof_adis_id,
apparat_data.apparat_adis_id,
apparat_data.appnr,
@@ -1458,15 +1461,17 @@ class Database:
def createProf(self, profdata):
def createProf(self, profdata:Prof):
print("createProf")
ic(profdata)
conn = self.connect()
cursor = conn.cursor()
fname = profdata["profname"].split(", ")[1].strip()
lname = profdata["profname"].split(", ")[0].strip()
fname = profdata.firstname#profdata["profname"].split(", ")[1].strip()
lname = profdata.lastname#profdata["profname"].split(", ")[0].strip()
fullname = f"{lname} {fname}"
mail = profdata["prof_mail"]
telnr = profdata["prof_tel"]
title = profdata["title"]
mail = profdata.mail#profdata["prof_mail"]
telnr = profdata.telnr#profdata["prof_tel"]
title = profdata.title #profdata["title"]
query = f"INSERT INTO prof (fname, lname, fullname, mail, telnr,titel) VALUES ('{fname}','{lname}','{fullname}','{mail}','{telnr}','{title}')"
self.logger.log_info(query)
@@ -1476,12 +1481,15 @@ class Database:
conn.close()
return self.getProfId(profdata)
def getProfId(self, profdata):
def getProfId(self, profdata: dict|Prof):
conn = self.connect()
cursor = conn.cursor()
fname = profdata["profname"].split(", ")[1].strip()
lname = profdata["profname"].split(", ")[0].strip()
fullname = f"{lname} {fname}"
if isinstance(profdata, Prof):
fullname = profdata.fullname
else:
fname = profdata["profname"].split(", ")[1].strip()
lname = profdata["profname"].split(", ")[0].strip()
fullname = f"{lname} {fname}"
query = f"SELECT id FROM prof WHERE fullname = '{fullname}'"
self.logger.log_info(query)
@@ -1504,8 +1512,8 @@ class Database:
result = cursor.execute(query).fetchone()
if result:
return result
else: return None
return Prof().from_tuple(result)
else: return Prof()
def getProfNameByApparat(self, apprarat_id):
query = f"SELECT prof_id from semesterapparat WHERE appnr = '{apprarat_id}'"
data = self.query_db(query)

View File

@@ -1,10 +1,15 @@
import datetime
def generateSemesterByDate():
def generateSemesterByDate(next:bool = False):
currentYear = datetime.datetime.now().year
currentYear = int(str(currentYear)[-2:])
month = datetime.datetime.now().month
if next:
month += 1
if month > 12:
month = 1
currentYear += 1
if month >= 4 and month <= 9:
return "SoSe " + str(currentYear)
else:
@@ -12,3 +17,25 @@ def generateSemesterByDate():
return f"WiSe {currentYear}/{currentYear+1}"
else:
return f"WiSe {currentYear-1}/{currentYear}"
def generateSemesterByOffset(offset):
currentYear = datetime.datetime.now().year
currentYear = int(str(currentYear)[-2:])
month = datetime.datetime.now().month
#offset represents a single semester
semester = generateSemesterByDate()
if offset == 1:
if semester.startswith("SoSe"):
return f"WiSe {currentYear}/{currentYear+1}"
else:
return f"SoSe {currentYear+1}"
else:
#if offset is even, increase the currentyear by offset
if offset % 2 == 0:
if semester.startswith("SoSe"):
return f"SoSe {currentYear+offset//2}"
else:
return f"WiSe {currentYear+1}/{currentYear+2}"
else:
return f"WiSe {currentYear+offset//2}/{currentYear+1+offset//2}"