0% found this document useful (0 votes)
29 views5 pages

New Text Document

The document outlines a Python class named SearchEditing that manages the search and editing of WIR (Work Inspection Report) logs using a GUI. It includes methods for searching logs, saving updates, and handling user interactions, along with error logging and validation. The class utilizes CSV file handling for data storage and retrieval, and integrates with a WordHandler for document updates.

Uploaded by

HQHome
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views5 pages

New Text Document

The document outlines a Python class named SearchEditing that manages the search and editing of WIR (Work Inspection Report) logs using a GUI. It includes methods for searching logs, saving updates, and handling user interactions, along with error logging and validation. The class utilizes CSV file handling for data storage and retrieval, and integrates with a WordHandler for document updates.

Uploaded by

HQHome
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import csv

import datetime
from pathlib import Path
from PyQt5.QtWidgets import QMessageBox
from Logger import setup_logger
from Word import WordHandler
from constants import WIRLogFilePath
from load_combobox_items_1 import ComboBoxLoader

class SearchEditing:
def __init__(self, main_window, ui):
self.main_window = main_window
self.ui = ui
self.logger = setup_logger() # New Line: Initialize logging
self.file_path = Path(WIRLogFilePath)
self.combo_loader = ComboBoxLoader()
self.combo_loader.load_activities(self.ui.Activity_QCB2)
self.combo_loader.load_data(self.ui.Villa_QCB2, 0)
self.combo_loader.load_dates(self.ui.Inspection_Date_QCB2, 27)

def Search_WIRLog(self):
try:
# Ensure inputs are strings before calling .strip()
wir_no_to_find = (self.ui.WIRNo_QLE2.text() or "").strip() # Modified
rev_to_find = (self.ui.Rev_QCB2.currentText() or "").strip() #
Modified

self.ui.WIRNo_QLE2.setEnabled(False)
self.ui.Rev_QCB2.setEnabled(False)

if not wir_no_to_find:
self.logger.warning("Search attempted without entering WIR No.") #
New Line
self._show_dialog("Error", "Please enter WIR No to search.",
QMessageBox.Warning)
self.ui.WIRNo_QLE2.setEnabled(True)
self.ui.Rev_QCB2.setEnabled(True)
return

try:
wir_no_int = int(wir_no_to_find)
except ValueError:
self.logger.error(f"Invalid WIR No entered: {wir_no_to_find}") #
New Line
self._show_dialog("Error", "Invalid WIR No. Please enter a valid
number.", QMessageBox.Warning)
self.ui.WIRNo_QLE2.setEnabled(True)
self.ui.Rev_QCB2.setEnabled(True)
return

latest_revision = None
found_record = None
revisions = [] # Store all revisions for the WIR No

if self.file_path.exists(): # New Line: Check if file exists


with open(self.file_path, 'r', newline='') as f:
reader = csv.DictReader(f)
for row in reader:
current_wir_no = (row.get('WIR No', '') or "").strip() #
Modified
current_rev = (row.get('Revision', '') or "").strip() #
Modified

if current_wir_no == wir_no_to_find:
try:
revisions.append(int(current_rev))
except ValueError:
self.logger.error(f"Invalid revision format:
{current_rev}") # New Line
else:
self.logger.error("WIR Log file not found!") # New Line
self._show_dialog("Error", "WIR Log file not found!",
QMessageBox.Critical)
self.ui.WIRNo_QLE2.setEnabled(True)
self.ui.Rev_QCB2.setEnabled(True)
return

if revisions:
latest_revision = str(max(revisions))

if not rev_to_find:
if latest_revision:
self.logger.info(f"Auto-selecting latest revision
{latest_revision} for WIR No {wir_no_to_find}.") # New Line
self._show_dialog(
"Information",
f"No revision selected. The latest revision for WIR No
{wir_no_to_find} is {latest_revision}.",
QMessageBox.Information
)
self.ui.Rev_QCB2.setCurrentText(latest_revision)
self.ui.WIRNo_QLE2.setEnabled(True)
self.ui.Rev_QCB2.setEnabled(True)
return

with open(self.file_path, 'r', newline='') as f:


reader = csv.DictReader(f)
for row in reader:
if (row.get('WIR No', '') or "").strip() == wir_no_to_find and
(
row.get('Revision', '') or "").strip() == rev_to_find:
found_record = row
break

if found_record:
self.logger.info(f"Record found for WIR No {wir_no_to_find},
Revision {rev_to_find}.") # New Line
self.ui.groupBox_2.setEnabled(True)
self.ui.WIRNo_QLE2.setEnabled(False)
self.ui.Rev_QCB2.setEnabled(False)
self._populate_ui_fields(found_record)
else:
self.logger.warning(f"WIR No {wir_no_to_find} Rev {rev_to_find} not
found.") # New Line
self._show_dialog("Information", f"WIR No {wir_no_to_find} Rev
{rev_to_find} not found.", QMessageBox.Information)
self.ui.groupBox_2.setEnabled(False)
self.ui.WIRNo_QLE2.setEnabled(True)
self.ui.Rev_QCB2.setEnabled(True)

except Exception as e:
self.logger.exception(f"Unexpected error during search: {str(e)}") #
New Line
self._show_dialog("Error", f"An unexpected error occurred during
search: {str(e)}", QMessageBox.Critical)
self.ui.WIRNo_QLE2.setEnabled(True)
self.ui.Rev_QCB2.setEnabled(True)

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


QMessageBox(icon, title, message, QMessageBox.Ok).exec_()

def _populate_ui_fields(self, record):


"""Populates UI fields with the data from the found record."""

def set_combo_value(combo_box, value):


value = f" {value.strip()}" if value else ""
if value and combo_box.findText(value) == -1:
combo_box.addItem(value)
combo_box.setCurrentText(value)

Villa_value = record.get('Villa No', '')


if Villa_value.startswith(("Plot #", "Villa #")):
Villa_value = Villa_value.split('#', 1)[-1]

set_combo_value(self.ui.Activity_QCB2, record.get('Activity', ''))


set_combo_value(self.ui.Sub_Activity_QCB2, record.get('Sub Activity', ''))
set_combo_value(self.ui.Villa_QCB2, Villa_value)
set_combo_value(self.ui.Level_QCB2, record.get('Level', ''))
set_combo_value(self.ui.Part_QCB2, record.get('Part', ''))

self.ui.Description_QTE2.setPlainText(record.get('Description', ''))

# Handle Date - Ensure correct format


inspection_date_str_csv = record.get('Inspection Date', '')
if inspection_date_str_csv:
try:
inspection_date_obj =
datetime.datetime.strptime(inspection_date_str_csv.strip(), '%d %b %Y')
formatted_date = inspection_date_obj.strftime('%d %b %Y')
set_combo_value(self.ui.Inspection_Date_QCB2, formatted_date)
except ValueError as e:
self.logger.error(f"Error parsing date: {e}") # New Line
self.ui.Inspection_Date_QCB2.setCurrentText('')

def Save_WIRLog(self):
wir_no_to_update = self.ui.WIRNo_QLE2.text().strip()
rev_to_update = self.ui.Rev_QCB2.currentText().strip()

# Validate required fields


if not wir_no_to_update:
self._show_dialog("Error", "WIR No. is missing. Search for a WIR to
edit first.", QMessageBox.Warning)
return

activity_index = self.ui.Activity_QCB2.currentIndex()
villa_text = self.ui.Villa_QCB2.currentText().strip()
# Collect data from controls
updated_record = {
'WIR No': wir_no_to_update,
'Revision': rev_to_update,
'Activity': self.ui.Activity_QCB2.currentText().strip(),
'Sub Activity': self.ui.Sub_Activity_QCB2.currentText().strip(),
'Description': self.ui.Description_QTE2.toPlainText().strip(),
'Villa': f"Plot # {villa_text}" if activity_index < 5 else f"Villa #
{villa_text}",
'Level': self.ui.Level_QCB2.currentText().strip(),
'Part': self.ui.Part_QCB2.currentText().strip(),
'Created Date':datetime.date.today().strftime('%d %b %Y'),
'Inspection Date': self.ui.Inspection_Date_QCB2.currentText().strip(),
'Status': "Under Review",
}
print(f" villa # {'Villa'}")
# Remove empty fields
updated_record = {k: v for k, v in updated_record.items() if v}

# Read the existing file to get field names


try:
with open(self.file_path, 'r', newline='') as readFile:
reader = csv.DictReader(readFile)
fieldnames = reader.fieldnames # Original fieldnames from file

if not fieldnames:
self._show_dialog("Error", "CSV file is missing headers!",
QMessageBox.Critical)
return

# Ensure updated_record only contains valid field names


updated_record = {k: v for k, v in updated_record.items() if k in
fieldnames}

if len(updated_record) < 3: # Ensure at least WIR No, Rev, and


some data exist
self._show_dialog("Error", "No valid data to update the WIR
Log.", QMessageBox.Warning)
return

all_records = []
record_updated = False

for row in reader:


current_wir_no = row['WIR No'].strip()
current_rev = row['Revision'].strip()
if current_wir_no == wir_no_to_update and current_rev ==
rev_to_update:
all_records.append(updated_record) # Replace with updated
record
record_updated = True
else:
all_records.append(row) # Keep existing record

if record_updated:
with open(self.file_path, 'w', newline='') as writeFile:
writer = csv.DictWriter(writeFile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(all_records)
self._show_dialog("Success", f"WIR No {wir_no_to_update} Rev
{rev_to_update} updated successfully!",
QMessageBox.Information)

word_handler = WordHandler(wir_no_to_update, rev_to_update)


word_handler.update_bookmarks(updated_record)

self.ui.groupBox_2.setEnabled(False)
self.ui.WIRNo_QLE2.setEnabled(True)
self.ui.Rev_QCB2.setEnabled(True)
self._clear_ui_fields()
else:
self._show_dialog("Error", f"WIR No {wir_no_to_update} Rev
{rev_to_update} not found for update!",
QMessageBox.Warning)

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

def Cancel_SearchWIR(self):
"""Resets the Search WIR tab to its initial state."""
self.ui.groupBox_2.setEnabled(False) # Disable the group box
self.ui.WIRNo_QLE2.setEnabled(True) # Re-enable WIR No input
self.ui.Rev_QCB2.setEnabled(True) # Re-enable Revision input

self._clear_ui_fields() # Clear populated UI fields

def _clear_ui_fields(self):
"""Clears the UI fields in Tab 3."""
self.ui.WIRNo_QLE2.clear() # Clear WIR No input field (optional)
self.ui.Rev_QCB2.setCurrentIndex(0) # Reset Revision Combobox to default
(index 0, which is "") (optional)
self.ui.Activity_QCB2.setCurrentIndex(-1) # or setCurrentText("") to clear
without triggering currentIndexChanged signal if needed
self.ui.Sub_Activity_QCB2.setCurrentIndex(-1)
self.ui.Description_QTE2.clear()
self.ui.Villa_QCB2.setCurrentIndex(-1)
self.ui.Level_QCB2.setCurrentIndex(-1)
self.ui.Part_QCB2.setCurrentIndex(-1)
self.ui.Inspection_Date_QCB2.setCurrentIndex(-1)

def _show_dialog(self, title, message, icon=QMessageBox.Warning):


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

You might also like