Rathapoom commited on
Commit
34da3fd
·
verified ·
1 Parent(s): b6e9426

Update sheets_integration.py

Browse files
Files changed (1) hide show
  1. sheets_integration.py +71 -41
sheets_integration.py CHANGED
@@ -1,53 +1,83 @@
1
- # sheets_integration.py
2
  import os
3
  import json
4
- from google.oauth2.credentials import Credentials
5
  from google.oauth2 import service_account
6
- from googleapiclient.discovery import build
7
- from google.oauth2.credentials import Credentials
8
- import pandas as pd
9
 
10
- class SheetsManager:
11
- def __init__(self, credentials_path, spreadsheet_id):
12
- self.credentials_path = credentials_path
13
- self.spreadsheet_id = spreadsheet_id
14
- self.credentials = None
15
- self.service = None
16
- self.initialize_service()
17
-
18
- def initialize_service(self):
19
- """Initialize Google Sheets API service"""
20
- self.credentials = service_account.Credentials.from_service_account_file(
21
- self.credentials_path,
22
- scopes=['https://www.googleapis.com/auth/spreadsheets']
23
- )
24
- self.service = build('sheets', 'v4', credentials=self.credentials)
25
-
26
- def append_row(self, row_data):
27
- """Append a row to the spreadsheet"""
28
  try:
29
- body = {
30
- 'values': [list(row_data.values())]
31
- }
32
- result = self.service.spreadsheets().values().append(
33
- spreadsheetId=self.spreadsheet_id,
34
- range='Sheet1!A:I', # Adjust range as needed
35
- valueInputOption='RAW',
36
- body=body
37
- ).execute()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  return True
 
39
  except Exception as e:
40
- print(f"Error appending to sheet: {str(e)}")
41
  return False
42
-
43
  def get_all_requests(self):
44
- """Get all requests from the spreadsheet"""
 
 
 
45
  try:
46
- result = self.service.spreadsheets().values().get(
47
- spreadsheetId=self.spreadsheet_id,
48
- range='Sheet1!A:I' # Adjust range as needed
49
- ).execute()
50
- return pd.DataFrame(result.get('values', []))
51
  except Exception as e:
52
- print(f"Error reading sheet: {str(e)}")
53
  return None
 
 
1
  import os
2
  import json
3
+ import gspread
4
  from google.oauth2 import service_account
5
+ from datetime import datetime
 
 
6
 
7
+ class SheetsLogger:
8
+ def __init__(self):
9
+ self.gc = None
10
+ self.sheet = None
11
+ self.initialize_client()
12
+
13
+ def initialize_client(self):
14
+ """Initialize Google Sheets client"""
 
 
 
 
 
 
 
 
 
 
15
  try:
16
+ # Get credentials from environment variable
17
+ creds_json = os.getenv('GOOGLE_SHEETS_CREDS')
18
+ if not creds_json:
19
+ raise ValueError("Google Sheets credentials not found in environment")
20
+
21
+ # Parse credentials JSON
22
+ creds_dict = json.loads(creds_json)
23
+
24
+ # Create credentials object
25
+ credentials = service_account.Credentials.from_service_account_info(
26
+ creds_dict,
27
+ scopes=['https://spreadsheets.google.com/feeds',
28
+ 'https://www.googleapis.com/auth/spreadsheets',
29
+ 'https://www.googleapis.com/auth/drive']
30
+ )
31
+
32
+ # Initialize gspread client
33
+ self.gc = gspread.authorize(credentials)
34
+
35
+ # Open spreadsheet by ID (get this from your sheet's URL)
36
+ SHEET_ID = os.getenv('GOOGLE_SHEET_ID')
37
+ self.sheet = self.gc.open_by_key(SHEET_ID).sheet1
38
+
39
+ except Exception as e:
40
+ print(f"Error initializing Google Sheets client: {str(e)}")
41
+ self.gc = None
42
+ self.sheet = None
43
+
44
+ def log_request(self, request_data):
45
+ """Log a request to Google Sheets"""
46
+ if not self.sheet:
47
+ print("Sheet not initialized")
48
+ return False
49
+
50
+ try:
51
+ # Prepare row data
52
+ row = [
53
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S"), # Timestamp
54
+ request_data.get('name', ''),
55
+ request_data.get('employee_id', ''),
56
+ request_data.get('email', ''),
57
+ request_data.get('department', ''),
58
+ request_data.get('request_details', ''),
59
+ request_data.get('frequency', ''),
60
+ request_data.get('urgency', ''),
61
+ request_data.get('system_response', '')
62
+ ]
63
+
64
+ # Append row to sheet
65
+ self.sheet.append_row(row)
66
  return True
67
+
68
  except Exception as e:
69
+ print(f"Error logging to sheet: {str(e)}")
70
  return False
71
+
72
  def get_all_requests(self):
73
+ """Get all requests from the sheet"""
74
+ if not self.sheet:
75
+ return None
76
+
77
  try:
78
+ # Get all records
79
+ records = self.sheet.get_all_records()
80
+ return records
 
 
81
  except Exception as e:
82
+ print(f"Error getting records: {str(e)}")
83
  return None