closes #3, fix bug with user creation

This commit is contained in:
WorldTeacher
2024-09-16 13:51:44 +02:00
parent f5bb5d3adc
commit e5816b40d2
2 changed files with 52 additions and 29 deletions

View File

@@ -25,12 +25,12 @@ class Database:
try: try:
os.makedirs(config.database.path) os.makedirs(config.database.path)
except FileNotFoundError: except FileNotFoundError:
print(self.db_path) dbg(self.db_path)
if not os.path.exists(config.database.backupLocation): if not os.path.exists(config.database.backupLocation):
os.makedirs(config.database.backupLocation) os.makedirs(config.database.backupLocation)
#if main path does not exist, try to create it. if that fails, use the backuplocation #if main path does not exist, try to create it. if that fails, use the backuplocation
print(self.db_path) dbg(self.db_path)
self.checkDatabaseStatus() self.checkDatabaseStatus()
def handle_folder_reachability(self, original_path, backup_path): def handle_folder_reachability(self, original_path, backup_path):
@@ -59,7 +59,7 @@ class Database:
return backup_path +"/" + FILE return backup_path +"/" + FILE
else: else:
print("Original Path Exists, ") dbg("Original Path Exists, using this path")
# Original folder is reachable, check for backup # Original folder is reachable, check for backup
if os.path.exists(backup_file): if os.path.exists(backup_file):
# Restore backup # Restore backup
@@ -125,7 +125,7 @@ class Database:
def createDatabase(self): def createDatabase(self):
log.info("Creating Database") log.info("Creating Database")
# print("Creating Database") #print("Creating Database")
if not os.path.exists(self.db_path): if not os.path.exists(self.db_path):
os.makedirs(self.db_path) os.makedirs(self.db_path)
conn = self.connect() conn = self.connect()
@@ -197,6 +197,15 @@ class Database:
return False return False
self.close_connection(conn) self.close_connection(conn)
return True return True
def getUserBy(self, key, value) -> User:
conn = self.connect()
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM users WHERE {key} = '{value}'")
result = cursor.fetchone()
self.close_connection(conn)
user = User(userid=result[1], username=result[2], email=result[3], id=result[0])
return user
def getUser(self, user_id) -> User: def getUser(self, user_id) -> User:
conn = self.connect() conn = self.connect()
@@ -204,9 +213,9 @@ class Database:
cursor.execute(f"SELECT * FROM users") cursor.execute(f"SELECT * FROM users")
result = cursor.fetchall() result = cursor.fetchall()
self.close_connection(conn) self.close_connection(conn)
print(result)
for res in result: for res in result:
if res[0] == user_id: if res[1] == user_id:
user = User(userid=res[1], username=res[2], email=res[3], id=res[0]) user = User(userid=res[1], username=res[2], email=res[3], id=res[0])
dbg(f"Returning User {user}") dbg(f"Returning User {user}")
log.info(f"Returning User {user}") log.info(f"Returning User {user}")
@@ -332,7 +341,7 @@ class Database:
cursor.execute(query) cursor.execute(query)
result = cursor.fetchone() result = cursor.fetchone()
signature = result[1] signature = result[1]
# print(signature) #print(signature)
query = f"SELECT * FROM media WHERE signature LIKE '%{signature}%'" query = f"SELECT * FROM media WHERE signature LIKE '%{signature}%'"
cursor.execute(query) cursor.execute(query)
result = cursor.fetchall() result = cursor.fetchall()
@@ -452,7 +461,7 @@ class Database:
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute(query) cursor.execute(query)
result = cursor.fetchone() result = cursor.fetchone()
print(result) dbg("Result", response=result)
self.close_connection(conn) self.close_connection(conn)
if result is not None: if result is not None:
return result[0] return result[0]

View File

@@ -106,14 +106,16 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
log.info("Showing Settings") log.info("Showing Settings")
settings = Settings() settings = Settings()
settings.exec() settings.exec()
if settings.settingschanged:
# reload settings # reload settings
print(config) #print(config)
def changeMode(self): def changeMode(self):
log.info("Changing Mode") log.info("Changing Mode")
dbg(f"Current mode: {self.activeState}") dbg(f"Current mode: {self.activeState}")
self.input_username.clear() self.input_username.clear()
stayReturn = False
if self.userdata.toPlainText() != "":
stayReturn = True
self.userdata.clear() self.userdata.clear()
self.input_userno.clear() self.input_userno.clear()
self.btn_show_lentmedia.setText("") self.btn_show_lentmedia.setText("")
@@ -123,7 +125,10 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
self.mediaOverview.setRowCount(0) self.mediaOverview.setRowCount(0)
self.activeUser = None #! remove if last user should be kept self.activeUser = None #! remove if last user should be kept
if self.activeState == "Rückgabe": if self.activeState == "Rückgabe":
self.activateLoanMode() if stayReturn:
self.activateReturnMode()
else: self.activateLoanMode()
else: else:
self.activateReturnMode() self.activateReturnMode()
@@ -190,9 +195,10 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
user = CreateUser(fieldname="id", data="") user = CreateUser(fieldname="id", data="")
user.exec() user.exec()
userid = user.userid userid = user.userid
print(userid)
if userid: if userid:
log.info(f"User created {userid}") log.info(f"User created {userid}")
data = self.db.getUser(userid) data = self.db.getUserBy("user_id", userid)
self.activeUser = data self.activeUser = data
# set user to active user # set user to active user
self.setUserData() self.setUserData()
@@ -204,7 +210,7 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
def checkUser(self, fieldname, data): def checkUser(self, fieldname, data):
log.info(f"Checking User {fieldname}, {data}") log.info(f"Checking User {fieldname}, {data}")
# print("Checking User", fieldname, data) #print("Checking User", fieldname, data)
# set fieldname as key and data as variable # set fieldname as key and data as variable
user = self.db.checkUserExists(fieldname, data) user = self.db.checkUserExists(fieldname, data)
if not user: if not user:
@@ -224,16 +230,16 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
multi.exec() multi.exec()
self.activeUser = multi.userdata self.activeUser = multi.userdata
else: else:
# print("User found", user[0]) #print("User found", user[0])
self.activeUser = user[0] self.activeUser = user[0]
if self.activeUser is not None: if self.activeUser is not None:
log.info(f"User found {self.activeUser}") log.info(f"User found {self.activeUser}")
# print("User found", self.activeUser) #print("User found", self.activeUser)
self.setUserData() self.setUserData()
self.input_file_ident.setFocus() self.input_file_ident.setFocus()
self.mode.setText("Ausleihe") self.mode.setText("Ausleihe")
print(self.activeUser.__dict__) #print(self.activeUser.__dict__)
loans = self.db.getActiveLoans(self.activeUser.id) loans = self.db.getActiveLoans(self.activeUser.id)
dbg(loans=loans) dbg(loans=loans)
self.btn_show_lentmedia.setText(loans) self.btn_show_lentmedia.setText(loans)
@@ -298,7 +304,7 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
elif book_id: elif book_id:
if isinstance(book_id, list) and len(book_id) > 1: if isinstance(book_id, list) and len(book_id) > 1:
print("Multiple Books found") #print("Multiple Books found")
# TODO: implement book selection dialog # TODO: implement book selection dialog
return return
else: else:
@@ -307,7 +313,7 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
# check if book is already loaned # check if book is already loaned
loaned = self.db.checkLoanState(book_id[0]) loaned = self.db.checkLoanState(book_id[0])
if loaned: if loaned:
# print("Book already loaned") #print("Book already loaned")
self.setStatusTipMessage("Buch bereits entliehen") self.setStatusTipMessage("Buch bereits entliehen")
# dialog with yes no to create new entry # dialog with yes no to create new entry
dialog = QtWidgets.QMessageBox() dialog = QtWidgets.QMessageBox()
@@ -329,7 +335,7 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
newentry = NewEntry([book_id[0]]) newentry = NewEntry([book_id[0]])
newentry.exec() newentry.exec()
self.setStatusTipMessage("Neues Exemplar hinzugefügt") self.setStatusTipMessage("Neues Exemplar hinzugefügt")
# print(created_ids) #print(created_ids)
self.input_file_ident.setEnabled(True) self.input_file_ident.setEnabled(True)
newentries = newentry.newIds newentries = newentry.newIds
if newentries: if newentries:
@@ -339,7 +345,7 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
dbg("inserted duplicated book into database") dbg("inserted duplicated book into database")
return return
else: else:
# print("Book not loaned, loaning now") #print("Book not loaned, loaning now")
self.loanMedia(user_id, book_id) self.loanMedia(user_id, book_id)
def loanMedia(self, user_id, book_id): def loanMedia(self, user_id, book_id):
@@ -350,7 +356,7 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
self.duedate.date().toString("yyyy-MM-dd"), self.duedate.date().toString("yyyy-MM-dd"),
) )
media = self.db.getMedia(book_id[0]) media = self.db.getMedia(book_id[0])
print(media) #print(media)
self.mediaOverview.insertRow(0) self.mediaOverview.insertRow(0)
self.mediaOverview.setItem(0, 0, QtWidgets.QTableWidgetItem(media.signature)) self.mediaOverview.setItem(0, 0, QtWidgets.QTableWidgetItem(media.signature))
self.mediaOverview.setItem(0, 1, QtWidgets.QTableWidgetItem(media.title)) self.mediaOverview.setItem(0, 1, QtWidgets.QTableWidgetItem(media.title))
@@ -366,19 +372,19 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
self.input_file_ident.setEnabled(True) self.input_file_ident.setEnabled(True)
def returnMedia(self, identifier): def returnMedia(self, identifier):
# print("Returning Media", identifier) #print("Returning Media", identifier)
# get book id from database # get book id from database
# self. # self.
identifier = Book( identifier = Book(
isbn=identifier, title=identifier, signature=identifier, ppn=identifier isbn=identifier, title=identifier, signature=identifier, ppn=identifier
) )
book_id = self.db.checkMediaExists(identifier) book_id = self.db.checkMediaExists(identifier)
# print(book_id) #print(book_id)
if book_id: if book_id:
# check if book is already loaned # check if book is already loaned
loaned = self.db.checkLoanState(book_id[0]) loaned = self.db.checkLoanState(book_id[0])
if loaned: if loaned:
# print("Book already loaned, returning now") #print("Book already loaned, returning now")
user = self.db.getUserByLoan(book_id[0]) user = self.db.getUserByLoan(book_id[0])
# set userdata in lineedits # set userdata in lineedits
self.activeUser = user self.activeUser = user
@@ -397,11 +403,12 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
self.db.getActiveLoans(self.activeUser.id) self.db.getActiveLoans(self.activeUser.id)
) )
else: else:
# print("Book not loaned") #print("Book not loaned")
self.setStatusTipMessage("Buch nicht entliehen") self.setStatusTipMessage("Buch nicht entliehen")
self.input_file_ident.clear() self.input_file_ident.clear()
else: else:
print("Book not found") dbg("Book not found")
#print("Book not found")
#self.input_file_ident.setPlaceholderText(f"Buch {identifier} nicht gefunden") #self.input_file_ident.setPlaceholderText(f"Buch {identifier} nicht gefunden")
def setStatusTipMessage(self, message): def setStatusTipMessage(self, message):
@@ -414,7 +421,7 @@ class MainUI(QtWidgets.QMainWindow, Ui_MainWindow):
def exit_handler(): def exit_handler():
dbg("Exiting, creating backup") dbg("Exiting, creating backup")
app = QtWidgets.QApplication(sys.argv) app = QtWidgets.QApplication(sys.argv)
print(backup.backup) #print(backup.backup)
# generate report if monday # generate report if monday
if datetime.datetime.now().weekday() == config.report.report_day: if datetime.datetime.now().weekday() == config.report.report_day:
generate_report() generate_report()
@@ -446,8 +453,15 @@ def exit_handler():
dialog.setWindowTitle("Backup nicht möglich") dialog.setWindowTitle("Backup nicht möglich")
dialog.setText("Backup konnte nicht erstellt werden\nGrund: {}".format(reason)) dialog.setText("Backup konnte nicht erstellt werden\nGrund: {}".format(reason))
dialog.exec() dialog.exec()
def launch(options = None): def launch(*argv):
app = QtWidgets.QApplication(sys.argv if options is None else [options]) options = sys.argv
if argv:
options += [arg for arg in argv]
options = [arg for arg in options if arg.startswith("--")]
#print("Launching Main UI")
#print(options)
app = QtWidgets.QApplication([])
main_ui = MainUI() main_ui = MainUI()
atexit.register(exit_handler) atexit.register(exit_handler)
sys.exit(app.exec()) sys.exit(app.exec())