Button Functions.py
Button Functions.py
import datetime
from pathlib import Path
from PyQt5.QtWidgets import QMessageBox
from Logger import setup_logger
from Word import WordHandler
from constants import WIRLogFilePath, WordFilePath
class ButtonFunctions:
def __init__(self, main_window, ui):
self.main_window = main_window
self.ui = ui
self.logger = setup_logger()
self.file_path = Path(WIRLogFilePath)
self.headers = [
'WIR No', 'Revision', 'Activity', 'Sub Activity',
'Description', 'Villa No', 'Level', 'Part',
'Created Date', 'Inspection Date', 'Status'
]
# Ensure CSV file exists with headers
if not self.file_path.exists():
with open(self.file_path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(self.headers)
def save_to_WIRLog(self):
try:
data = self._get_ui_data()
if not self._validate_inputs(data):
return
if self._is_duplicate(data):
self._show_dialog("Duplicate Entry", "This WIR Already exists!
Kindly make Revision",
QMessageBox.Warning)
return
# Fetch next WIR number and revision (assuming you track revisions)
next_wir_number = self._next_wir_number()-1
revision = 0 # Adjust this logic if revisions are tracked dynamically
self._clear_ui_fields()
self._show_dialog("Success", f"WIR #{new_row[0]} saved successfully!",
QMessageBox.Information)
except PermissionError:
self._show_dialog("Error", "Please close the CSV file before saving!",
QMessageBox.Critical)
except Exception as e:
self._show_dialog("Error", f"An unexpected error occurred: {str(e)}",
QMessageBox.Critical)
def _get_ui_data(self):
activity_index = self.ui.Activity_QCB1.currentIndex()
villa_text = self.ui.Villa_QCB1.currentText().strip()
return {
'activity': self.ui.Activity_QCB1.currentText().strip(),
'sub_activity': self.ui.Sub_Activity_QCB1.currentText().strip(),
'description': self.ui.Description_QTE1.toPlainText().strip(),
'villa' : f"Plot # {villa_text}" if activity_index < 5 else f"Villa #
{villa_text}",
'level': self.ui.Level_QCB1.currentText().strip(),
'part': self.ui.Part_QCB1.currentText().strip(),
'Inspection_Date':
self._parse_date(self.ui.Inspection_Date_QCB1.currentText().strip()),
}
return True
def _prepare_row(self, data):
return [
self._next_wir_number(),
0,
data['activity'],
data['sub_activity'],
data['description'],
data['villa'],
data['level'],
data['part'],
datetime.date.today().strftime('%d %b %Y'),
data['Inspection_Date'].strftime('%d %b %Y'),
"",
"Under Review",
]
def _next_wir_number(self):
try:
with open(self.file_path, 'r', newline='') as f:
reader = csv.reader(f)
next(reader) # Skip header
wir_numbers = [int(row[0]) for row in reader if row]
return max(wir_numbers) + 1 if wir_numbers else 1
except FileNotFoundError:
return 1
except FileNotFoundError:
pass
return False
def _clear_ui_fields(self):
for combo in [
self.ui.Activity_QCB1,
self.ui.Sub_Activity_QCB1,
self.ui.Villa_QCB1,
self.ui.Level_QCB1,
self.ui.Part_QCB1,
self.ui.Inspection_Date_QCB1
]:
combo.setCurrentIndex(-1)
self.ui.Description_QTE1.clear()