# sheets_integration.py import os import json from datetime import datetime from enum import Enum import gspread from google.oauth2 import service_account import traceback class RequestStatus(Enum): NEW = "New" IN_PROGRESS = "In Progress" PENDING_INFO = "Pending Additional Info" DATA_COLLECTION = "Data Collection" READY_FOR_REVIEW = "Ready for Review" COMPLETED = "Completed" CANCELLED = "Cancelled" ON_HOLD = "On Hold" class SheetsLogger: def __init__(self): print("Initializing SheetsLogger") self.gc = None self.sheet = None self.initialize_client() def initialize_client(self): """Initialize Google Sheets client""" print("=== Debug: Initializing Google Sheets Client ===") try: # Get credentials from environment variable creds_json = os.getenv('GOOGLE_SHEETS_CREDS') if not creds_json: print("Google Sheets credentials not found in environment") return # Parse credentials JSON try: creds_dict = json.loads(creds_json) print("Credentials JSON parsed successfully") except json.JSONDecodeError as e: print(f"Error parsing credentials JSON: {e}") return # Create credentials object credentials = service_account.Credentials.from_service_account_info( creds_dict, scopes=['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'] ) # Initialize gspread client self.gc = gspread.authorize(credentials) # Open spreadsheet by ID sheet_id = os.getenv('GOOGLE_SHEET_ID') if not sheet_id: print("Google Sheet ID not found in environment") return self.sheet = self.gc.open_by_key(sheet_id).sheet1 print("Sheet connected successfully") # Initialize headers if needed self.initialize_sheet() except Exception as e: print(f"Error initializing Google Sheets client: {str(e)}") print(traceback.format_exc()) self.gc = None self.sheet = None def initialize_sheet(self): """Initialize sheet with headers if needed""" headers = [ "Timestamp", "Name", "Employee ID", "Email", "Department", "Request Details", "Frequency", "Urgency", "User Summary", "Technical Analysis", "Status", "Notes", "Last Updated" ] try: # Check if headers exist existing_headers = self.sheet.row_values(1) if not existing_headers: print("Adding headers to sheet") self.sheet.insert_row(headers, 1) # Format header row self.sheet.format('A1:M1', { "backgroundColor": {"red": 0.2, "green": 0.2, "blue": 0.2}, "textFormat": {"bold": True, "foregroundColor": {"red": 1, "green": 1, "blue": 1}} }) else: print("Headers already exist") except Exception as e: print(f"Error initializing headers: {str(e)}") print(traceback.format_exc()) def log_request(self, data: dict) -> bool: """Log a request to Google Sheets""" print("=== Debug: Logging to Google Sheets ===") print(f"Prepared data: {data}") if not self.sheet: print("Sheet not initialized") return False try: # Prepare row data row = [ datetime.now().strftime("%Y-%m-%d %H:%M:%S"), # Timestamp data.get('name', ''), data.get('employee_id', ''), data.get('email', ''), data.get('department', ''), data.get('request_details', ''), data.get('frequency', ''), data.get('urgency', ''), data.get('user_summary', ''), data.get('system_analysis', ''), RequestStatus.NEW.value, # Initial status '', # Empty notes datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Last updated ] # Append row to sheet print("Appending row to sheet") self.sheet.append_row(row) # Get the row number that was just added last_row = len(self.sheet.get_all_values()) # Apply conditional formatting for status print("Applying status formatting") self.apply_status_formatting(last_row) print(f"Successfully logged request to row {last_row}") return True except Exception as e: print(f"Error logging to sheet: {str(e)}") print(traceback.format_exc()) return False def apply_status_formatting(self, row_number: int): """Apply conditional formatting based on status""" status_cell = f'K{row_number}' formats = { RequestStatus.NEW.value: {"backgroundColor": {"red": 1, "green": 1, "blue": 0.8}}, RequestStatus.IN_PROGRESS.value: {"backgroundColor": {"red": 0.8, "green": 0.9, "blue": 1}}, RequestStatus.PENDING_INFO.value: {"backgroundColor": {"red": 1, "green": 0.8, "blue": 0.8}}, RequestStatus.DATA_COLLECTION.value: {"backgroundColor": {"red": 0.8, "green": 1, "blue": 0.8}}, RequestStatus.READY_FOR_REVIEW.value: {"backgroundColor": {"red": 0.9, "green": 0.9, "blue": 1}}, RequestStatus.COMPLETED.value: {"backgroundColor": {"red": 0.9, "green": 1, "blue": 0.9}} } try: status = self.sheet.acell(status_cell).value if status in formats: self.sheet.format(status_cell, formats[status]) except Exception as e: print(f"Error applying formatting: {str(e)}")