File size: 6,439 Bytes
06414a4
4458876
 
c59bc01
 
34da3fd
4458876
06414a4
c59bc01
 
 
 
 
 
 
 
 
 
4458876
34da3fd
 
06414a4
34da3fd
 
 
 
 
 
3a49ab9
4458876
34da3fd
 
 
06414a4
 
 
34da3fd
06414a4
 
 
 
 
 
34da3fd
 
 
 
 
 
 
 
 
 
 
 
c59bc01
06414a4
 
 
 
c59bc01
06414a4
 
34da3fd
c59bc01
 
 
34da3fd
 
06414a4
34da3fd
 
c59bc01
21f7901
 
 
 
 
 
 
 
 
 
 
 
 
c59bc01
 
 
21f7901
 
 
 
 
 
06414a4
21f7901
c59bc01
 
 
 
 
06414a4
 
21f7901
 
06414a4
c59bc01
06414a4
34da3fd
ea04900
 
 
34da3fd
c59bc01
34da3fd
 
 
c59bc01
34da3fd
06414a4
21f7901
 
 
 
 
 
 
 
 
c59bc01
 
 
34da3fd
 
c59bc01
06414a4
34da3fd
c59bc01
 
 
 
 
06414a4
c59bc01
 
 
4458876
34da3fd
4458876
34da3fd
06414a4
c59bc01
34da3fd
06414a4
c59bc01
 
 
06414a4
 
 
 
 
 
c59bc01
 
 
 
 
 
 
06414a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# 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)}")