IAMTFRMZA commited on
Commit
fd030cb
Β·
verified Β·
1 Parent(s): 2d5ccec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -41
app.py CHANGED
@@ -4,74 +4,88 @@ import gspread
4
  from oauth2client.service_account import ServiceAccountCredentials
5
  from datetime import datetime
6
 
7
- # -- Login Setup --
8
  USER_CREDENTIALS = {"[email protected]": "Pass.123"}
9
 
10
- # -- Load Google Sheets Data --
11
  def get_sheet_data():
12
  scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
13
  creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
14
  client = gspread.authorize(creds)
15
- sheet = client.open_by_title("userAccess (6)").worksheet("Field Sales")
 
 
16
  data = pd.DataFrame(sheet.get_all_records())
17
  return data
18
 
19
- # -- Reporting Logic --
20
  def generate_report(data, period="Daily"):
21
- data["Date"] = pd.to_datetime(data.get("Date", datetime.today()))
22
-
23
- now = pd.Timestamp.today()
24
- if period == "Weekly":
25
- data = data[data["Date"] >= now - pd.Timedelta(days=7)]
26
- elif period == "Monthly":
27
- data = data[data["Date"].dt.month == now.month]
28
- elif period == "Yearly":
29
- data = data[data["Date"].dt.year == now.year]
30
 
31
- total_visits = len(data)
32
- current = len(data[data["Current/Prospect Custor"] == "Current"])
33
- new = len(data[data["Current/Prospect Custor"] == "Prospect"])
34
- second_hand = len(data[data["Customer Type"].str.contains("Second", na=False)])
35
- telesales = len(data[data["Source"] == "TeleSales"])
36
- oem_visits = len(data[data["Source"] == "OEM Visit"])
37
- orders = len(data[data["Order Received"] == "Yes"])
38
- order_value = data["Order Value"].sum()
39
 
40
- return (
41
- f"### {period} Report\n"
42
- f"- Total Visits: {total_visits}\n"
43
- f"- Current Dealerships: {current}\n"
44
- f"- New Dealerships: {new}\n"
45
- f"- % Current: {current / total_visits * 100:.1f}% | % New: {new / total_visits * 100:.1f}%\n"
46
- f"- Second-hand Dealerships: {second_hand}\n"
47
- f"- TeleSales Calls: {telesales}\n"
48
- f"- OEM Visits: {oem_visits}\n"
49
- f"- Orders Received: {orders}\n"
50
- f"- Total Order Value: ${order_value:,.2f}"
51
- )
52
 
53
- # -- Login Handler --
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  def login(email, password):
55
  if USER_CREDENTIALS.get(email) == password:
56
  return gr.update(visible=True), gr.update(visible=False), ""
57
  else:
58
- return gr.update(visible=False), gr.update(visible=True), "❌ Invalid credentials"
59
 
60
- # -- UI Logic --
61
  def report(period):
62
- data = get_sheet_data()
63
- return generate_report(data, period)
 
 
 
 
 
64
 
65
- # -- Gradio App --
66
  with gr.Blocks() as app:
67
  with gr.Row(visible=True) as login_row:
68
  email = gr.Textbox(label="Email")
69
  password = gr.Textbox(label="Password", type="password")
70
  login_btn = gr.Button("Login")
71
  login_error = gr.Textbox(label="", visible=False)
72
-
73
  with gr.Row(visible=False) as dashboard:
74
- period_dropdown = gr.Dropdown(["Daily", "Weekly", "Monthly", "Yearly"], value="Daily", label="Select Report Period")
75
  report_btn = gr.Button("Generate Report")
76
  report_output = gr.Markdown()
77
 
 
4
  from oauth2client.service_account import ServiceAccountCredentials
5
  from datetime import datetime
6
 
7
+ # -- Login credentials --
8
  USER_CREDENTIALS = {"[email protected]": "Pass.123"}
9
 
10
+ # -- Load Google Sheets data --
11
  def get_sheet_data():
12
  scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
13
  creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
14
  client = gspread.authorize(creds)
15
+
16
+ # βœ… Fixed sheet name here:
17
+ sheet = client.open_by_title("userAccess").worksheet("Field Sales")
18
  data = pd.DataFrame(sheet.get_all_records())
19
  return data
20
 
21
+ # -- Generate report based on selected period --
22
  def generate_report(data, period="Daily"):
23
+ try:
24
+ if "Date" not in data.columns:
25
+ return "❌ Column 'Date' not found in the sheet."
26
+
27
+ data["Date"] = pd.to_datetime(data["Date"], errors='coerce')
28
+ data = data.dropna(subset=["Date"])
29
+ now = pd.Timestamp.today()
 
 
30
 
31
+ if period == "Weekly":
32
+ data = data[data["Date"] >= now - pd.Timedelta(days=7)]
33
+ elif period == "Monthly":
34
+ data = data[data["Date"].dt.month == now.month]
35
+ elif period == "Yearly":
36
+ data = data[data["Date"].dt.year == now.year]
 
 
37
 
38
+ total_visits = len(data)
39
+ current = len(data[data["Current/Prospect Custor"] == "Current"])
40
+ new = len(data[data["Current/Prospect Custor"] == "Prospect"])
41
+ second_hand = len(data[data["Customer Type"].str.contains("Second", na=False)])
42
+ telesales = len(data[data["Source"] == "TeleSales"])
43
+ oem_visits = len(data[data["Source"] == "OEM Visit"])
44
+ orders = len(data[data["Order Received"] == "Yes"])
45
+ order_value = data["Order Value"].sum() if "Order Value" in data.columns else 0
 
 
 
 
46
 
47
+ return (
48
+ f"### {period} Report\n"
49
+ f"- **Total Visits:** {total_visits}\n"
50
+ f"- **Current Dealerships:** {current}\n"
51
+ f"- **New Dealerships:** {new}\n"
52
+ f"- **% Current:** {current / total_visits * 100:.1f}% | **% New:** {new / total_visits * 100:.1f}%\n"
53
+ f"- **Second-hand Dealerships:** {second_hand}\n"
54
+ f"- **TeleSales Calls:** {telesales}\n"
55
+ f"- **OEM Visits:** {oem_visits}\n"
56
+ f"- **Orders Received:** {orders}\n"
57
+ f"- **Total Order Value:** ${order_value:,.2f}"
58
+ )
59
+ except Exception as e:
60
+ return f"❌ Error during report generation: {str(e)}"
61
+
62
+ # -- Login function --
63
  def login(email, password):
64
  if USER_CREDENTIALS.get(email) == password:
65
  return gr.update(visible=True), gr.update(visible=False), ""
66
  else:
67
+ return gr.update(visible=False), gr.update(visible=True), "❌ Invalid email or password"
68
 
69
+ # -- Report trigger --
70
  def report(period):
71
+ try:
72
+ data = get_sheet_data()
73
+ if data.empty:
74
+ return "⚠️ No data found in the sheet."
75
+ return generate_report(data, period)
76
+ except Exception as e:
77
+ return f"❌ Failed to load sheet: {str(e)}"
78
 
79
+ # -- Gradio UI --
80
  with gr.Blocks() as app:
81
  with gr.Row(visible=True) as login_row:
82
  email = gr.Textbox(label="Email")
83
  password = gr.Textbox(label="Password", type="password")
84
  login_btn = gr.Button("Login")
85
  login_error = gr.Textbox(label="", visible=False)
86
+
87
  with gr.Row(visible=False) as dashboard:
88
+ period_dropdown = gr.Dropdown(["Daily", "Weekly", "Monthly", "Yearly"], value="Weekly", label="Select Report Period")
89
  report_btn = gr.Button("Generate Report")
90
  report_output = gr.Markdown()
91