jithenderchoudary commited on
Commit
fe712d9
·
verified ·
1 Parent(s): 12099f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -1
app.py CHANGED
@@ -4,7 +4,190 @@ from dotenv import load_dotenv
4
  import os
5
  import logging
6
 
7
- # Set up logging to capture detailed errors
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  logging.basicConfig(level=logging.DEBUG)
9
  logger = logging.getLogger(__name__)
10
 
 
4
  import os
5
  import logging
6
 
7
+ # Set up logginfrom fastapi import FastAPI, Request, HTTPException
8
+ from fastapi.responses import HTMLResponse, FileResponse
9
+ from fastapi.staticfiles import StaticFiles
10
+ from fastapi.templating import Jinja2Templates
11
+ from simple_salesforce import Salesforce
12
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
13
+ import sqlite3
14
+ import os
15
+ import logging
16
+
17
+ # Set up logging
18
+ logging.basicConfig(level=logging.DEBUG)
19
+ logger = logging.getLogger(__name__)
20
+
21
+ app = FastAPI()
22
+
23
+ # Mount static files
24
+ app.mount("/static", StaticFiles(directory="static"), name="static")
25
+
26
+ # Set up templates
27
+ templates = Jinja2Templates(directory="templates")
28
+
29
+ # Initialize SQLite database
30
+ def init_db():
31
+ try:
32
+ conn = sqlite3.connect("cases.db")
33
+ cursor = conn.cursor()
34
+ cursor.execute("""
35
+ CREATE TABLE IF NOT EXISTS cases (
36
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
37
+ name TEXT NOT NULL,
38
+ mobile_number TEXT,
39
+ email TEXT NOT NULL,
40
+ issue_description TEXT NOT NULL,
41
+ synced INTEGER DEFAULT 0
42
+ )
43
+ """)
44
+ conn.commit()
45
+ conn.close()
46
+ logger.debug("SQLite database initialized successfully.")
47
+ except Exception as e:
48
+ logger.error(f"Error initializing SQLite database: {e}")
49
+ raise
50
+
51
+ # Run database initialization on startup
52
+ init_db()
53
+
54
+ # Salesforce connection (using Space Secrets)
55
+ def get_salesforce_connection():
56
+ try:
57
+ username = os.getenv("SFDC_USERNAME")
58
+ password = os.getenv("SFDC_PASSWORD")
59
+ security_token = os.getenv("SFDC_SECURITY_TOKEN")
60
+ domain = os.getenv("SFDC_DOMAIN", "login")
61
+
62
+ logger.debug(f"SFDC_USERNAME: {username}")
63
+ logger.debug(f"SFDC_SECURITY_TOKEN: {security_token}")
64
+
65
+ if not username or not password or not security_token:
66
+ logger.error("Missing Salesforce credentials.")
67
+ return None
68
+
69
+ sf = Salesforce(
70
+ username=username,
71
+ password=password,
72
+ security_token=security_token,
73
+ domain=domain
74
+ )
75
+ logger.debug("Salesforce connection successful.")
76
+ return sf
77
+ except Exception as e:
78
+ logger.error(f"Error connecting to Salesforce: {e}")
79
+ return None
80
+
81
+ # Sync function
82
+ async def sync_to_salesforce():
83
+ try:
84
+ sf = get_salesforce_connection()
85
+ if not sf:
86
+ logger.error("Cannot sync: Salesforce connection failed.")
87
+ return
88
+
89
+ conn = sqlite3.connect("cases.db")
90
+ cursor = conn.cursor()
91
+ cursor.execute("SELECT * FROM cases WHERE synced = 0")
92
+ cases = cursor.fetchall()
93
+
94
+ for case in cases:
95
+ case_id, name, mobile_number, email, issue_description, _ = case
96
+ case_data = {
97
+ "Name": name,
98
+ "Mobile_Number__c": mobile_number,
99
+ "Email__c": email,
100
+ "Issue_Description__c": issue_description
101
+ }
102
+ sf.Case__c.create(case_data)
103
+ cursor.execute("UPDATE cases SET synced = 1 WHERE id = ?", (case_id,))
104
+ conn.commit()
105
+ logger.debug(f"Synced case ID {case_id} to Salesforce.")
106
+ conn.close()
107
+ except Exception as e:
108
+ logger.error(f"Error syncing to Salesforce: {str(e)}")
109
+ raise # Raise the exception to see the error in the response
110
+
111
+ # Set up scheduler
112
+ scheduler = AsyncIOScheduler()
113
+ scheduler.add_job(sync_to_salesforce, "interval", hours=4)
114
+
115
+ @app.on_event("startup")
116
+ async def startup_event():
117
+ scheduler.start()
118
+ logger.debug("Scheduler started successfully.")
119
+
120
+ @app.on_event("shutdown")
121
+ async def shutdown_event():
122
+ scheduler.shutdown()
123
+ logger.debug("Scheduler shut down successfully.")
124
+
125
+ @app.get("/", response_class=HTMLResponse)
126
+ async def index(request: Request):
127
+ return templates.TemplateResponse("index.html", {"request": request})
128
+
129
+ @app.get("/static/{filename}")
130
+ async def serve_static(filename: str):
131
+ file_path = os.path.join("static", filename)
132
+ if not os.path.exists(file_path):
133
+ raise HTTPException(status_code=404, detail="File not found")
134
+ return FileResponse(file_path)
135
+
136
+ @app.post("/submit-case")
137
+ async def submit_case(request: Request):
138
+ try:
139
+ data = await request.json()
140
+ logger.debug(f"Received form data: {data}")
141
+
142
+ # Extract form data with default values
143
+ name = data.get("name", "")
144
+ mobile_number = data.get("mobileNumber", "")
145
+ email = data.get("email", "")
146
+ issue_description = data.get("issueDescription", "")
147
+
148
+ # Validate required fields
149
+ if not name or not email or not issue_description:
150
+ logger.error("Missing required fields in form data.")
151
+ raise HTTPException(status_code=400, detail="Missing required fields")
152
+
153
+ # Store in SQLite
154
+ conn = sqlite3.connect("cases.db")
155
+ cursor = conn.cursor()
156
+ cursor.execute(
157
+ """
158
+ INSERT INTO cases (name, mobile_number, email, issue_description)
159
+ VALUES (?, ?, ?, ?)
160
+ """,
161
+ (name, mobile_number, email, issue_description)
162
+ )
163
+ conn.commit()
164
+ conn.close()
165
+ logger.debug("Data successfully stored in SQLite.")
166
+
167
+ # Immediately trigger sync for testing
168
+ await sync_to_salesforce()
169
+
170
+ return {"success": True}
171
+ except Exception as e:
172
+ logger.error(f"Error processing request: {str(e)}")
173
+ raise HTTPException(status_code=500, detail=str(e))
174
+
175
+ @app.get("/debug-cases")
176
+ async def debug_cases():
177
+ try:
178
+ conn = sqlite3.connect("cases.db")
179
+ cursor = conn.cursor()
180
+ cursor.execute("SELECT * FROM cases")
181
+ cases = cursor.fetchall()
182
+ conn.close()
183
+ return {"cases": cases}
184
+ except Exception as e:
185
+ logger.error(f"Error retrieving cases: {str(e)}")
186
+ raise HTTPException(status_code=500, detail=str(e))
187
+
188
+ if __name__ == "__main__":
189
+ import uvicorn
190
+ uvicorn.run(app, host="0.0.0.0", port=7860)g to capture detailed errors
191
  logging.basicConfig(level=logging.DEBUG)
192
  logger = logging.getLogger(__name__)
193