Yaswanth56 commited on
Commit
590c509
·
verified ·
1 Parent(s): 3c7c2d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -61
app.py CHANGED
@@ -1,102 +1,127 @@
1
- import gradio as gr
2
  from simple_salesforce import Salesforce
3
  from dotenv import load_dotenv
4
  import os
 
5
 
6
- # Load environment variables
 
 
 
7
  load_dotenv()
8
 
 
 
 
 
 
 
 
 
9
  # Salesforce connection
10
  try:
11
- sf = Salesforce(
12
- username=os.getenv("SF_USERNAME"),
13
- password=os.getenv("SF_PASSWORD"),
14
- security_token=os.getenv("SF_SECURITY_TOKEN"),
15
- domain="login" # Use "test" for sandbox
16
- )
17
- print("Salesforce connection successful!")
18
  except Exception as e:
19
- print(f"Salesforce connection failed: {e}")
20
  sf = None
21
 
22
- # Function to handle user authentication and Salesforce login
23
- def authenticate_user(email, password):
 
 
 
 
 
 
 
 
 
24
  if not sf:
25
- return "Salesforce connection failed. Please check credentials and try again.", None, None, gr.update(visible=False), gr.update(visible=False)
 
26
 
27
  try:
28
- query = f"SELECT Id, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{email}' AND Password__c = '{password}'"
 
29
  result = sf.query(query)
30
 
31
  if result['totalSize'] == 0:
32
- return "Invalid Login Details", None, None, gr.update(visible=False), gr.update(visible=False)
 
33
 
34
  customer = result['records'][0]
35
  reward_points = customer['Reward_Points__c']
36
 
37
- return f"Welcome, you have {reward_points} points. Proceed to rewards.", customer['Id'], reward_points, gr.update(visible=True), gr.update(visible=True)
 
 
38
  except Exception as e:
39
- return f"Error during authentication: {e}", None, None, gr.update(visible=False), gr.update(visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- # Function to handle reward points logic
42
- def handle_rewards(customer_id, bill_amount, apply_rewards):
43
  try:
44
  customer = sf.Customer_Login__c.get(customer_id)
45
  points = customer['Reward_Points__c']
46
  gst = 0.18 * bill_amount
 
47
 
48
  if points >= 500 and apply_rewards:
49
  discount = 0.1 * bill_amount
50
  final_bill = bill_amount - discount + gst
51
  updated_points = points - 500
 
 
 
52
  message = "You saved 10% on your total bill!"
53
  else:
 
54
  discount = 0
55
  earned_points = 0.1 * bill_amount
56
  final_bill = bill_amount + gst
57
  updated_points = points + earned_points
58
- message = f"You earned {earned_points:.2f} reward points!"
59
 
60
- # Update the customer's reward points in Salesforce
61
- sf.Customer_Login__c.update(customer_id, {'Reward_Points__c': updated_points})
 
62
 
63
- return message, final_bill, updated_points
 
 
 
 
 
 
 
 
 
64
  except Exception as e:
65
- return f"Error applying rewards: {e}", 0, 0
66
-
67
- # Define the Gradio interface
68
- def create_interface():
69
- with gr.Blocks() as demo:
70
- # Login section
71
- gr.Markdown("### Login to your account")
72
- email_input = gr.Textbox(label="Email", placeholder="Enter your email")
73
- password_input = gr.Textbox(label="Password", placeholder="Enter your password", type="password")
74
- login_button = gr.Button("Login")
75
- login_output = gr.Textbox(label="Status")
76
- customer_id_output = gr.Textbox(label="Customer ID", visible=False) # Hidden
77
- reward_points_output = gr.Textbox(label="Available Reward Points", visible=False) # Hidden
78
-
79
- # Reward points section (Initially hidden)
80
- reward_section = gr.Column(visible=False)
81
- gr.Markdown("### Reward Points Section", elem_id="reward_section")
82
- bill_amount_input = gr.Number(label="Enter Bill Amount", value=0)
83
- apply_rewards_checkbox = gr.Checkbox(label="Apply Reward Points", value=True)
84
- rewards_button = gr.Button("Calculate Bill")
85
- rewards_message = gr.Textbox(label="Message")
86
- final_bill_output = gr.Textbox(label="Final Bill Amount")
87
- remaining_points_output = gr.Textbox(label="Remaining Points")
88
-
89
- # Action for login button
90
- login_button.click(authenticate_user, inputs=[email_input, password_input], outputs=[login_output, customer_id_output, reward_points_output, reward_section, bill_amount_input])
91
-
92
- # Action for rewards calculation
93
- rewards_button.click(handle_rewards,
94
- inputs=[customer_id_output, bill_amount_input, apply_rewards_checkbox],
95
- outputs=[rewards_message, final_bill_output, remaining_points_output])
96
-
97
- return demo
98
-
99
- # Run the Gradio interface
100
- if __name__ == "__main__":
101
- demo = create_interface()
102
- demo.launch()
 
1
+ from flask import Flask, render_template, redirect, request, url_for
2
  from simple_salesforce import Salesforce
3
  from dotenv import load_dotenv
4
  import os
5
+ import logging
6
 
7
+ # Set up logging
8
+ logging.basicConfig(level=logging.DEBUG)
9
+
10
+ # Load environment variables from .env file
11
  load_dotenv()
12
 
13
+ app = Flask(__name__)
14
+
15
+ # Get Salesforce credentials from environment variables
16
+ SF_USERNAME = os.getenv('SF_USERNAME')
17
+ SF_PASSWORD = os.getenv('SF_PASSWORD')
18
+ SF_SECURITY_TOKEN = os.getenv('SF_SECURITY_TOKEN')
19
+ SF_DOMAIN = os.getenv('SF_DOMAIN')
20
+
21
  # Salesforce connection
22
  try:
23
+ app.logger.debug("Attempting Salesforce connection...")
24
+ sf = Salesforce(username=SF_USERNAME,
25
+ password=SF_PASSWORD,
26
+ security_token=SF_SECURITY_TOKEN,
27
+ domain=SF_DOMAIN)
28
+ app.logger.debug("Salesforce connection successful!")
 
29
  except Exception as e:
30
+ app.logger.error(f"Salesforce connection failed: {e}")
31
  sf = None
32
 
33
+ # Route for login page
34
+ @app.route('/')
35
+ def login():
36
+ return render_template('login.html')
37
+
38
+ # Route to process login
39
+ @app.route('/auth', methods=['POST'])
40
+ def auth():
41
+ email = request.form['email']
42
+ password = request.form['password']
43
+
44
  if not sf:
45
+ app.logger.error("Salesforce connection failed. Please check credentials and try again.")
46
+ return "Salesforce connection failed. Please check credentials and try again."
47
 
48
  try:
49
+ # Query Salesforce for user authentication
50
+ query = f"SELECT Id, Reward_Points__c FROM Customer_Login__c WHERE Email__c = '{email}' AND Password__c = '{password}' LIMIT 1"
51
  result = sf.query(query)
52
 
53
  if result['totalSize'] == 0:
54
+ app.logger.error("Invalid Login Details")
55
+ return "Invalid Login Details"
56
 
57
  customer = result['records'][0]
58
  reward_points = customer['Reward_Points__c']
59
 
60
+ # Redirect to rewards page
61
+ app.logger.debug(f"Redirecting to rewards page with customer_id: {customer['Id']} and points: {reward_points}")
62
+ return redirect(url_for('rewards', customer_id=customer['Id'], points=reward_points))
63
  except Exception as e:
64
+ app.logger.error(f"Error during authentication: {e}")
65
+ return f"Error during authentication: {e}"
66
+
67
+ # Route to display rewards page
68
+ @app.route('/rewards/<customer_id>')
69
+ def rewards(customer_id):
70
+ try:
71
+ customer = sf.Customer_Login__c.get(customer_id)
72
+ points = customer['Reward_Points__c']
73
+ app.logger.debug(f"Fetched reward points: {points} for customer_id: {customer_id}")
74
+ # Render the rewards page
75
+ return render_template('rewards.html', points=points, customer_id=customer_id)
76
+ except Exception as e:
77
+ app.logger.error(f"Error fetching rewards: {e}")
78
+ return f"Error fetching rewards: {e}"
79
+
80
+ # Route to apply rewards
81
+ @app.route('/apply_rewards', methods=['POST'])
82
+ def apply_rewards():
83
+ customer_id = request.form['customer_id']
84
+ bill_amount = float(request.form['bill_amount'])
85
+ apply_rewards = request.form.get('apply_rewards')
86
 
 
 
87
  try:
88
  customer = sf.Customer_Login__c.get(customer_id)
89
  points = customer['Reward_Points__c']
90
  gst = 0.18 * bill_amount
91
+ app.logger.debug(f"Processing bill amount: {bill_amount}, GST: {gst}, Points: {points}")
92
 
93
  if points >= 500 and apply_rewards:
94
  discount = 0.1 * bill_amount
95
  final_bill = bill_amount - discount + gst
96
  updated_points = points - 500
97
+
98
+ # Update the customer's reward points in Salesforce
99
+ sf.Customer_Login__c.update(customer_id, {'Reward_Points__c': updated_points})
100
  message = "You saved 10% on your total bill!"
101
  else:
102
+ # Customers with below 500 points earn 10% of their bill amount as reward points
103
  discount = 0
104
  earned_points = 0.1 * bill_amount
105
  final_bill = bill_amount + gst
106
  updated_points = points + earned_points
 
107
 
108
+ # Update the customer's reward points in Salesforce
109
+ sf.Customer_Login__c.update(customer_id, {'Reward_Points__c': updated_points})
110
+ message = f"You earned 10% of your bill amount ({earned_points} points) as reward points!"
111
 
112
+ # Render the summary page
113
+ return render_template(
114
+ 'apply_rewards.html',
115
+ original_bill=bill_amount,
116
+ discount=discount,
117
+ gst=gst,
118
+ final_bill=final_bill,
119
+ updated_points=updated_points,
120
+ message=message
121
+ )
122
  except Exception as e:
123
+ app.logger.error(f"Error applying rewards: {e}")
124
+ return f"Error applying rewards: {e}"
125
+
126
+ if __name__ == '__main__':
127
+ app.run(debug=True, host="0.0.0.0", port=5000)