0% found this document useful (0 votes)
4 views

RevStatus.py

The document outlines a Python class, SearchRevStatus, which manages the search, creation, and updating of WIR (Work Inspection Request) logs using a CSV file. It includes methods for searching logs, creating new revisions, updating statuses, and populating a UI table with the retrieved data. The class also handles error management and user notifications through message boxes.

Uploaded by

HQHome
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

RevStatus.py

The document outlines a Python class, SearchRevStatus, which manages the search, creation, and updating of WIR (Work Inspection Request) logs using a CSV file. It includes methods for searching logs, creating new revisions, updating statuses, and populating a UI table with the retrieved data. The class also handles error management and user notifications through message boxes.

Uploaded by

HQHome
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

import csv

import datetime
from pathlib import Path
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox, QTableWidgetItem
from Logger import setup_logger
from constants import WIRLogFilePath
from Word import WordHandler

class SearchRevStatus:
def __init__(self, main_window, ui):
self.main_window = main_window
if not ui or type(ui) == bool:
print("Error: UI object is invalid.")
return

self.ui = ui
self.logger = setup_logger()
self.file_path = Path(WIRLogFilePath)

def Search_WIRLog(self):
wir_no_to_find = self.ui.WIRNo_QLE1.text().strip()
rev_to_find = self.ui.Rev_QCB1.currentText().strip() or '0'

if not wir_no_to_find:
self._show_dialog("Error", "Please enter WIR No to search.",
QMessageBox.Warning)
return

try:
int(wir_no_to_find) # Validate WIR number as integer
except ValueError:
self._show_dialog("Error", "Invalid WIR No. Please enter a valid
number.", QMessageBox.Warning)
return

try:
found_records = [row for row in csv.DictReader(open(self.file_path,
'r', newline=''))
if row['WIR No'].strip() == wir_no_to_find]
if found_records:
self._populate_table_view(found_records)
else:
self._show_dialog("Information", f"WIR No {wir_no_to_find} not
found.", QMessageBox.Information)
except FileNotFoundError:
self._show_dialog("Error", "WIR Log file not found!",
QMessageBox.Critical)
except Exception as e:
self._show_dialog("Error", f"Unexpected error: {str(e)}",
QMessageBox.Critical)

def _populate_table_view(self, records):


table = self.ui.tableWidget
table.clearContents()
table.setRowCount(len(records))
table.setColumnCount(6)
table.setHorizontalHeaderLabels(["WIR No -Rev", "Sub Activity", "Location
P-F-P", "Status", "Insp. Date", "Description"])
table.verticalHeader().setVisible(False)

for row_index, record in enumerate(records):

items = [
f"{record.get('WIR No', '').strip()} - {record.get('Revision',
'').strip()}",
record.get('Sub Activity', '').strip(),
f"P.{record.get('Villa No', 'N/A').strip()}- {record.get('Level',
'N/A').strip()}- {record.get('Part', 'N/A').strip()}",
record.get('Status', '').strip(),
record.get('Inspection Date', '').strip(),
record.get('Description', '').strip()

for col_index, text in enumerate(items):


text = text if text else "N/A" # Ensure no empty strings
item = QTableWidgetItem(text)
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
table.setItem(row_index, col_index, item)

# Set column widths


col_widths = [75, 190, 170, 147, 90, 700]
for i, width in enumerate(col_widths):
table.setColumnWidth(i, width)

def create_revision(self):
wir_no_to_find = self.ui.WIRNo_QLE1.text().strip()
rev_to_find = self.ui.Rev_QCB2.currentText().strip()
if not wir_no_to_find:
self._show_dialog("Error", "Please enter WIR No to create revision.",
QMessageBox.Warning)
return

try:
all_records = list(csv.DictReader(open(self.file_path, 'r',
newline='')))
found_records = [row for row in all_records if row['WIR No'].strip() ==
wir_no_to_find]
if not found_records:
self._show_dialog("Error", f"WIR No {wir_no_to_find} not found.",
QMessageBox.Warning)
return

max_revision = max(int(row['Revision'].strip()) for row in


found_records)
new_revision = max_revision + 1

new_record = found_records[-1].copy()
new_record.update({
'Revision': str(new_revision),
'Created Date': datetime.datetime.now().strftime('%d %b %Y'),
'Inspection Date':
self.ui.Inspection_Date_QCB3.currentText().strip(),
'Status': "Under Review"
})
all_records.insert(0, new_record)
self._overwrite_csv(all_records)
self._populate_table_view([new_record] + found_records)

# **Trigger Word document update**


word_handler = WordHandler(wir_no_to_find, new_revision)
word_handler.update_bookmarks(new_record)

self._show_dialog("Success", f"New revision (Revision {new_revision})


created successfully.",
QMessageBox.Information)
self._clear_ui_fields()

except FileNotFoundError:
self._show_dialog("Error", "WIR Log file not found!",
QMessageBox.Critical)
except Exception as e:
self._show_dialog("Error", f"An error occurred: {str(e)}",
QMessageBox.Critical)

def _overwrite_csv(self, records):


try:
with open(self.file_path, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=records[0].keys())
writer.writeheader()
writer.writerows(records)
except Exception as e:
self._show_dialog("Error", f"Error saving revision: {str(e)}",
QMessageBox.Critical)

def update_wir_status_and_comment(self):
wir_no_to_update = self.ui.WIRNo_QLE1.text().strip()
rev_to_update = self.ui.Rev_QCB1.currentText().strip()
new_status = self.ui.Status_QCB.currentText().strip()
new_comment_date = self.ui.CommentDate_QCB.currentText().strip()

if not wir_no_to_update or not rev_to_update:


self._show_dialog("Error", "Please enter WIR No and select a
revision.", QMessageBox.Warning)
return

updated_records = []
record_found = False

try:
with open(self.file_path, 'r', newline='') as f:
reader = csv.DictReader(f)
fieldnames = reader.fieldnames
for row in reader:
if row['WIR No'].strip() == wir_no_to_update and
row['Revision'].strip() == rev_to_update:
row['Status'] = new_status
row['Comment Date'] = new_comment_date
record_found = True
updated_records.append(row)

if record_found:
with open(self.file_path, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(updated_records)
self._show_dialog("Success", f"WIR No {wir_no_to_update} Rev
{rev_to_update} updated successfully!",
QMessageBox.Information)
self.Search_WIRLog() # Refresh the table view
else:
self._show_dialog("Error", f"WIR No {wir_no_to_update} Rev
{rev_to_update} not found.",
QMessageBox.Warning)
self._clear_ui_fields()
except FileNotFoundError:
self._show_dialog("Error", "WIR Log file not found!",
QMessageBox.Critical)
except Exception as e:
self._show_dialog("Error", f"An error occurred: {str(e)}",
QMessageBox.Critical)

def _clear_ui_fields(self):
self.ui.WIRNo_QLE1.clear()
self.ui.Rev_QCB1.setCurrentIndex(-1)
self.ui.Inspection_Date_QCB3.setCurrentIndex(-1)
self.ui.Status_QCB.setCurrentIndex(-1)
self.ui.CommentDate_QCB.setCurrentIndex(-1)
for row in range(self.ui.tableWidget.rowCount()):
for col in range(self.ui.tableWidget.columnCount()):
item = self.ui.tableWidget.item(row, col)
if item:
item.setText("")

def _show_dialog(self, title, message, icon):


msg = QMessageBox(self.main_window)
msg.setIcon(icon)
msg.setText(message)
msg.setWindowTitle(title)
msg.exec_()

You might also like