update code to allow both txt and csv generation
This commit is contained in:
66
src/utils/reportThread.py
Normal file
66
src/utils/reportThread.py
Normal file
@@ -0,0 +1,66 @@
|
||||
from PyQt6.QtCore import QThread, pyqtSignal, QDate
|
||||
from prettytable import PrettyTable
|
||||
from src.logic import Database
|
||||
from src.utils import stringToDate
|
||||
import sqlite3 as sql
|
||||
|
||||
|
||||
class ReportThread(QThread):
|
||||
report_signal = pyqtSignal(str)
|
||||
report_progress_signal = pyqtSignal(int)
|
||||
report_nums_signal = pyqtSignal(int)
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super(ReportThread, self).__init__(parent)
|
||||
self.days = None
|
||||
self.format = "txt"
|
||||
|
||||
def setFormat(self, format):
|
||||
self.format = format
|
||||
|
||||
def setDays(self, days):
|
||||
self.days = days
|
||||
|
||||
def run(self):
|
||||
db = Database()
|
||||
|
||||
path = db.db_path
|
||||
day = QDate.currentDate().addDays(-self.days).toString("yyyy-MM-dd")
|
||||
query = f"""SELECT * FROM loans WHERE loan_date >= '{day}';"""
|
||||
print(query)
|
||||
colnames = ["UserId", "Title", "Action", "Datum"]
|
||||
table = PrettyTable(colnames)
|
||||
table.align[colnames[0]] = "l"
|
||||
table.align[colnames[1]] = "l"
|
||||
table.align[colnames[2]] = "l"
|
||||
|
||||
with sql.connect(path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(query)
|
||||
loans = cursor.fetchall()
|
||||
self.report_nums_signal.emit(len(loans))
|
||||
counter = 0
|
||||
for loan in loans:
|
||||
counter += 1
|
||||
self.report_progress_signal.emit(counter)
|
||||
loan_action = "Ausleihe" if loan[5] == 0 else "Rückgabe"
|
||||
loan_action_date = stringToDate(
|
||||
loan[3] if loan[5] == 0 else loan[6]
|
||||
).toString("dd.MM.yyyy")
|
||||
table.add_row(
|
||||
[
|
||||
loan[1],
|
||||
db.getMedia(loan[2]).title,
|
||||
loan_action,
|
||||
loan_action_date,
|
||||
]
|
||||
)
|
||||
# # print(table)
|
||||
# # wruitng the table to a file
|
||||
if self.format == "csv":
|
||||
with open("report.csv", "w", encoding="utf-8") as f:
|
||||
f.write(table.get_csv_string())
|
||||
else:
|
||||
with open("report.txt", "w", encoding="utf-8") as f:
|
||||
f.write(str(table))
|
||||
self.report_signal.emit("Report generated successfully.")
|
||||
Reference in New Issue
Block a user