Refactor MedTrackerApp and UI components for improved structure and readability

- Simplified initialization logic in init.py
- Consolidated testing_mode assignment
- Removed unnecessary else statements
- Created UIManager class to handle UI-related tasks
- Modularized input frame creation, table frame creation, and graph frame creation
- Enhanced edit window creation with better organization and error handling
- Updated data management methods to improve clarity and maintainability
- Improved logging for better debugging and tracking of application flow
This commit is contained in:
William Valentin
2025-07-23 16:10:22 -07:00
parent 4ba4b1b7c5
commit 2142db7093
15 changed files with 1063 additions and 578 deletions
+120
View File
@@ -0,0 +1,120 @@
import os
import csv
import logging
from typing import List, Union
import pandas as pd
class DataManager:
"""Handle all data operations for the application."""
def __init__(self, filename: str, logger: logging.Logger) -> None:
self.filename: str = filename
self.logger: logging.Logger = logger
self.initialize_csv()
def initialize_csv(self) -> None:
"""Create CSV file with headers if it doesn't exist."""
if not os.path.exists(self.filename):
with open(self.filename, mode="w", newline="") as file:
writer = csv.writer(file)
writer.writerow(
[
"date",
"depression",
"anxiety",
"sleep",
"appetite",
"bupropion",
"hydroxyzine",
"gabapentin",
"propranolol",
"note",
]
)
def load_data(self) -> pd.DataFrame:
"""Load data from CSV file."""
if (
not os.path.exists(self.filename)
or os.path.getsize(self.filename) == 0
):
self.logger.warning(
"CSV file is empty or doesn't exist. No data to load."
)
return pd.DataFrame()
try:
df: pd.DataFrame = pd.read_csv(
self.filename,
dtype={
"depression": int,
"anxiety": int,
"sleep": int,
"appetite": int,
"bupropion": int,
"hydroxyzine": int,
"gabapentin": int,
"propranolol": int,
"note": str,
"date": str,
},
).fillna("")
return df.sort_values(by="date").reset_index(drop=True)
except pd.errors.EmptyDataError:
self.logger.warning("CSV file is empty. No data to load.")
return pd.DataFrame()
except Exception as e:
self.logger.error(f"Error loading data: {str(e)}")
return pd.DataFrame()
def add_entry(self, entry_data: List[Union[str, int]]) -> bool:
"""Add a new entry to the CSV file."""
try:
with open(self.filename, mode="a", newline="") as file:
writer = csv.writer(file)
writer.writerow(entry_data)
return True
except Exception as e:
self.logger.error(f"Error adding entry: {str(e)}")
return False
def update_entry(self, date: str, values: List[Union[str, int]]) -> bool:
"""Update an existing entry identified by date."""
try:
df: pd.DataFrame = self.load_data()
# Find the row to update using date as a unique identifier
df.loc[
df["date"] == date,
[
"date",
"depression",
"anxiety",
"sleep",
"appetite",
"bupropion",
"hydroxyzine",
"gabapentin",
"propranolol",
"note",
],
] = values
df.to_csv(self.filename, index=False)
return True
except Exception as e:
self.logger.error(f"Error updating entry: {str(e)}")
return False
def delete_entry(self, date: str) -> bool:
"""Delete an entry identified by date."""
try:
df: pd.DataFrame = self.load_data()
# Remove the row with the matching date
df = df[df["date"] != date]
# Write the updated dataframe back to the CSV
df.to_csv(self.filename, index=False)
return True
except Exception as e:
self.logger.error(f"Error deleting entry: {str(e)}")
return False