lokeshloki143 commited on
Commit
997d665
·
verified ·
1 Parent(s): 30719a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -91
app.py CHANGED
@@ -7,10 +7,10 @@ from flask import Flask, jsonify, request, render_template, redirect, url_for
7
 
8
  # Configure logging with more detail
9
  logging.basicConfig(
10
- level=logging.DEBUG, # Set to DEBUG for detailed logs
11
  format='%(asctime)s - %(levelname)s - %(message)s',
12
  handlers=[
13
- logging.StreamHandler() # Output logs to console
14
  ]
15
  )
16
  logger = logging.getLogger(__name__)
@@ -52,43 +52,37 @@ def test_salesforce_connection():
52
  domain=SALESFORCE_DOMAIN
53
  )
54
  logger.info("Successfully connected to Salesforce. Session ID: %s", sf.session_id)
55
- # Test a simple query to verify object access
56
  sf.query("SELECT Id FROM Account LIMIT 1")
57
  logger.info("Successfully queried Account object. Connection is working.")
58
- return True, None
59
  except SalesforceAuthenticationFailed as e:
60
  logger.error("Salesforce authentication failed: %s", e)
61
- return False, f"Salesforce authentication failed: {str(e)}"
62
  except Exception as e:
63
  logger.error("Salesforce connection error: %s", e)
64
- return False, f"Salesforce connection error: {str(e)}"
65
 
66
- def fetch_salesforce_input(supervisor_id, project_id):
67
  """
68
- Fetch input data from Salesforce for a given supervisor and project.
69
  """
70
- try:
71
- logger.debug("Connecting to Salesforce to fetch input data")
72
- sf = Salesforce(
73
- username=SALESFORCE_USERNAME,
74
- password=SALESFORCE_PASSWORD,
75
- security_token=SALESFORCE_SECURITY_TOKEN,
76
- domain=SALESFORCE_DOMAIN
77
- )
78
- logger.info("Connected to Salesforce for input fetch")
79
 
 
 
80
  query = f"""
81
  SELECT Supervisor_ID__c, Role__c, Project_ID__c, Weather__c, Milestones__c, Reflection_Log__c
82
- FROM Supervisor_AI_Coaching__c
83
- WHERE Supervisor_ID__c = '{supervisor_id}' AND Project_ID__c = '{project_id}'
84
- ORDER BY Generated_Date__c DESC
85
  LIMIT 1
86
  """
87
  logger.debug("Executing Salesforce query: %s", query)
88
  result = sf.query(query)
89
  if result['totalSize'] > 0:
90
  record = result['records'][0]
91
- logger.info("Fetched record from Salesforce: %s", record)
92
  return {
93
  'supervisor_id': record['Supervisor_ID__c'] or '',
94
  'role': record['Role__c'] or '',
@@ -98,8 +92,8 @@ def fetch_salesforce_input(supervisor_id, project_id):
98
  'reflection': record['Reflection_Log__c'] or ''
99
  }, None
100
  else:
101
- logger.info("No input data found for supervisor %s and project %s", supervisor_id, project_id)
102
- return None, "No input data found in Salesforce."
103
 
104
  except Exception as e:
105
  logger.error("Salesforce fetch error: %s", e)
@@ -137,7 +131,7 @@ Format the response as JSON:
137
  "max_length": 200,
138
  "temperature": 0.7,
139
  "top_p": 0.9,
140
- "debug": True # Debug mode is already enabled
141
  }
142
  }
143
 
@@ -170,24 +164,20 @@ Format the response as JSON:
170
  logger.error("Unexpected error in Hugging Face API call: %s", e)
171
  return None, f"Unexpected error in Hugging Face API call: {str(e)}"
172
 
173
- def save_to_salesforce(output, supervisor_id, project_id):
174
  """
175
- Save coaching output to Salesforce Supervisor_AI_Coaching__c object.
176
  """
177
  if not output:
178
  logger.error("No coaching output to save")
179
  return False, "No coaching output to save."
180
 
181
- try:
182
- logger.debug("Connecting to Salesforce to save output")
183
- sf = Salesforce(
184
- username=SALESFORCE_USERNAME,
185
- password=SALESFORCE_PASSWORD,
186
- security_token=SALESFORCE_SECURITY_TOKEN,
187
- domain=SALESFORCE_DOMAIN
188
- )
189
- logger.info("Connected to Salesforce for saving output")
190
 
 
 
191
  coaching_record = {
192
  "Supervisor_ID__c": supervisor_id,
193
  "Project_ID__c": project_id,
@@ -196,85 +186,116 @@ def save_to_salesforce(output, supervisor_id, project_id):
196
  "Quote__c": output["quote"],
197
  "Generated_Date__c": datetime.now().strftime("%Y-%m-%d")
198
  }
199
- logger.debug("Saving record to Salesforce: %s", coaching_record)
200
 
201
- sf.Supervisor_AI_Coaching__c.upsert(
202
- f"Supervisor_ID__c/{supervisor_id}_{datetime.now().strftime('%Y-%m-%d')}",
203
- coaching_record
204
- )
205
- logger.info("Successfully saved coaching record to Salesforce for supervisor %s", supervisor_id)
206
  return True, None
207
 
208
  except Exception as e:
209
  logger.error("Salesforce save error: %s", e)
210
  return False, f"Salesforce save error: {str(e)}"
211
 
212
- @app.route('/', methods=['GET'])
213
- def redirect_to_ui():
214
  """
215
- Redirect root URL to the UI.
216
  """
217
- return redirect(url_for('ui'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
  @app.route('/ui', methods=['GET'])
220
  def ui():
221
  """
222
- Serve the HTML user interface, fetch input from Salesforce, generate output, and save to Salesforce.
223
  """
224
  form_data = {}
225
  output = {}
226
  error = ""
227
 
228
- # Test Salesforce connection first
229
- success, conn_error = test_salesforce_connection()
230
  if not success:
231
- logger.error("Salesforce connection test failed: %s", conn_error)
232
- return render_template('index.html', form_data={}, output={}, error=conn_error)
233
-
234
- # Hardcoded supervisor_id and project_id for demonstration
235
- supervisor_id = "SUP-001"
236
- project_id = "PROJ-123"
237
 
238
- # Fetch input data from Salesforce
239
- logger.info("Fetching input data from Salesforce for supervisor %s and project %s", supervisor_id, project_id)
240
- sf_input, fetch_error = fetch_salesforce_input(supervisor_id, project_id)
241
- if fetch_error:
242
- logger.error("Failed to fetch input data: %s", fetch_error)
243
- return render_template('index.html', form_data={}, output={}, error=fetch_error)
244
-
245
- if sf_input:
246
- form_data = sf_input
247
- # Prepare data for generating output
248
- data = {
249
- 'supervisor_id': form_data['supervisor_id'],
250
- 'role': form_data['role'],
251
- 'project_id': form_data['project_id'],
252
- 'milestones': [m.strip() for m in form_data['milestones'].split(',') if m.strip()],
253
- 'reflection_log': form_data['reflection'],
254
- 'weather': form_data['weather']
255
- }
256
- # Generate output automatically
257
- logger.info("Generating output for fetched Salesforce data")
258
- coaching_output, gen_error = generate_coaching_output(data)
259
- if gen_error:
260
- logger.error("Failed to generate coaching output: %s", gen_error)
261
- return render_template('index.html', form_data=form_data, output={}, error=gen_error)
262
-
263
- if coaching_output:
264
- # Save the generated output to Salesforce
265
- logger.info("Saving generated output to Salesforce")
266
- success, save_error = save_to_salesforce(coaching_output, supervisor_id, project_id)
267
- if success:
268
- output = coaching_output
269
- else:
270
- logger.error("Failed to save generated output to Salesforce: %s", save_error)
271
- return render_template('index.html', form_data=form_data, output={}, error=save_error)
272
- else:
273
- logger.warning("No input data found in Salesforce. Displaying empty fields.")
274
- error = "No input data found in Salesforce for the given Supervisor ID and Project ID."
275
 
276
  return render_template('index.html', form_data=form_data, output=output, error=error)
277
 
 
 
 
 
 
 
 
278
  @app.route('/health', methods=['GET'])
279
  def health_check():
280
  """
 
7
 
8
  # Configure logging with more detail
9
  logging.basicConfig(
10
+ level=logging.DEBUG,
11
  format='%(asctime)s - %(levelname)s - %(message)s',
12
  handlers=[
13
+ logging.StreamHandler()
14
  ]
15
  )
16
  logger = logging.getLogger(__name__)
 
52
  domain=SALESFORCE_DOMAIN
53
  )
54
  logger.info("Successfully connected to Salesforce. Session ID: %s", sf.session_id)
 
55
  sf.query("SELECT Id FROM Account LIMIT 1")
56
  logger.info("Successfully queried Account object. Connection is working.")
57
+ return True, None, sf
58
  except SalesforceAuthenticationFailed as e:
59
  logger.error("Salesforce authentication failed: %s", e)
60
+ return False, f"Salesforce authentication failed: {str(e)}", None
61
  except Exception as e:
62
  logger.error("Salesforce connection error: %s", e)
63
+ return False, f"Salesforce connection error: {str(e)}", None
64
 
65
+ def fetch_project_data(project_id):
66
  """
67
+ Fetch data from the Project__c object in Salesforce.
68
  """
69
+ success, error, sf = test_salesforce_connection()
70
+ if not success:
71
+ return None, error
 
 
 
 
 
 
72
 
73
+ try:
74
+ logger.debug("Fetching Project__c record with Id: %s", project_id)
75
  query = f"""
76
  SELECT Supervisor_ID__c, Role__c, Project_ID__c, Weather__c, Milestones__c, Reflection_Log__c
77
+ FROM Project__c
78
+ WHERE Id = '{project_id}'
 
79
  LIMIT 1
80
  """
81
  logger.debug("Executing Salesforce query: %s", query)
82
  result = sf.query(query)
83
  if result['totalSize'] > 0:
84
  record = result['records'][0]
85
+ logger.info("Fetched Project__c record: %s", record)
86
  return {
87
  'supervisor_id': record['Supervisor_ID__c'] or '',
88
  'role': record['Role__c'] or '',
 
92
  'reflection': record['Reflection_Log__c'] or ''
93
  }, None
94
  else:
95
+ logger.info("No Project__c record found for Id: %s", project_id)
96
+ return None, "No Project__c record found for the given Id."
97
 
98
  except Exception as e:
99
  logger.error("Salesforce fetch error: %s", e)
 
131
  "max_length": 200,
132
  "temperature": 0.7,
133
  "top_p": 0.9,
134
+ "debug": True
135
  }
136
  }
137
 
 
164
  logger.error("Unexpected error in Hugging Face API call: %s", e)
165
  return None, f"Unexpected error in Hugging Face API call: {str(e)}"
166
 
167
+ def save_to_coaching_log(output, supervisor_id, project_id):
168
  """
169
+ Save coaching output to the Coaching_Log__c object in Salesforce.
170
  """
171
  if not output:
172
  logger.error("No coaching output to save")
173
  return False, "No coaching output to save."
174
 
175
+ success, error, sf = test_salesforce_connection()
176
+ if not success:
177
+ return False, error
 
 
 
 
 
 
178
 
179
+ try:
180
+ logger.debug("Saving to Coaching_Log__c")
181
  coaching_record = {
182
  "Supervisor_ID__c": supervisor_id,
183
  "Project_ID__c": project_id,
 
186
  "Quote__c": output["quote"],
187
  "Generated_Date__c": datetime.now().strftime("%Y-%m-%d")
188
  }
189
+ logger.debug("Saving record to Coaching_Log__c: %s", coaching_record)
190
 
191
+ sf.Coaching_Log__c.create(coaching_record)
192
+ logger.info("Successfully saved coaching record to Coaching_Log__c for supervisor %s", supervisor_id)
 
 
 
193
  return True, None
194
 
195
  except Exception as e:
196
  logger.error("Salesforce save error: %s", e)
197
  return False, f"Salesforce save error: {str(e)}"
198
 
199
+ @app.route('/process_new_project', methods=['POST'])
200
+ def process_new_project():
201
  """
202
+ Endpoint called by Salesforce when a new Project__c record is created.
203
  """
204
+ data = request.get_json()
205
+ if not data or 'projectId' not in data:
206
+ logger.error("Invalid request: projectId not provided")
207
+ return jsonify({"status": "error", "message": "projectId not provided"}), 400
208
+
209
+ project_id = data['projectId']
210
+ logger.info("Received new Project__c record with Id: %s", project_id)
211
+
212
+ # Fetch project data
213
+ project_data, fetch_error = fetch_project_data(project_id)
214
+ if fetch_error:
215
+ logger.error("Failed to fetch project data: %s", fetch_error)
216
+ return jsonify({"status": "error", "message": fetch_error}), 500
217
+
218
+ if not project_data:
219
+ logger.error("No project data found for Id: %s", project_id)
220
+ return jsonify({"status": "error", "message": "No project data found"}), 404
221
+
222
+ # Prepare data for Hugging Face
223
+ data = {
224
+ 'supervisor_id': project_data['supervisor_id'],
225
+ 'role': project_data['role'],
226
+ 'project_id': project_data['project_id'],
227
+ 'milestones': [m.strip() for m in project_data['milestones'].split(',') if m.strip()],
228
+ 'reflection_log': project_data['reflection'],
229
+ 'weather': project_data['weather']
230
+ }
231
+
232
+ # Generate coaching output
233
+ coaching_output, gen_error = generate_coaching_output(data)
234
+ if gen_error:
235
+ logger.error("Failed to generate coaching output: %s", gen_error)
236
+ return jsonify({"status": "error", "message": gen_error}), 500
237
+
238
+ if not coaching_output:
239
+ logger.error("No coaching output generated")
240
+ return jsonify({"status": "error", "message": "No coaching output generated"}), 500
241
+
242
+ # Save to Coaching_Log__c
243
+ success, save_error = save_to_coaching_log(coaching_output, project_data['supervisor_id'], project_data['project_id'])
244
+ if not success:
245
+ logger.error("Failed to save to Coaching_Log__c: %s", save_error)
246
+ return jsonify({"status": "error", "message": save_error}), 500
247
+
248
+ return jsonify({"status": "success", "message": "Coaching log generated and saved successfully"}), 200
249
 
250
  @app.route('/ui', methods=['GET'])
251
  def ui():
252
  """
253
+ Serve the HTML user interface to display the latest processed record.
254
  """
255
  form_data = {}
256
  output = {}
257
  error = ""
258
 
259
+ # Fetch the latest Coaching_Log__c record for display
260
+ success, error, sf = test_salesforce_connection()
261
  if not success:
262
+ logger.error("Salesforce connection test failed: %s", error)
263
+ return render_template('index.html', form_data={}, output={}, error=error)
 
 
 
 
264
 
265
+ try:
266
+ query = """
267
+ SELECT Supervisor_ID__c, Project_ID__c, Daily_Checklist__c, Suggested_Tips__c, Quote__c
268
+ FROM Coaching_Log__c
269
+ ORDER BY Generated_Date__c DESC
270
+ LIMIT 1
271
+ """
272
+ result = sf.query(query)
273
+ if result['totalSize'] > 0:
274
+ record = result['records'][0]
275
+ form_data = {
276
+ 'supervisor_id': record['Supervisor_ID__c'] or '',
277
+ 'project_id': record['Project_ID__c'] or ''
278
+ }
279
+ output = {
280
+ 'checklist': record['Daily_Checklist__c'].split('\n') if record['Daily_Checklist__c'] else [],
281
+ 'tips': record['Suggested_Tips__c'].split('\n') if record['Suggested_Tips__c'] else [],
282
+ 'quote': record['Quote__c'] or ''
283
+ }
284
+ else:
285
+ error = "No coaching log records found."
286
+ except Exception as e:
287
+ logger.error("Error fetching Coaching_Log__c: %s", e)
288
+ error = f"Error fetching Coaching_Log__c: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
290
  return render_template('index.html', form_data=form_data, output=output, error=error)
291
 
292
+ @app.route('/', methods=['GET'])
293
+ def redirect_to_ui():
294
+ """
295
+ Redirect root URL to the UI.
296
+ """
297
+ return redirect(url_for('ui'))
298
+
299
  @app.route('/health', methods=['GET'])
300
  def health_check():
301
  """