File size: 3,874 Bytes
88ff990
 
 
 
 
 
fd030cb
88ff990
 
fd030cb
88ff990
 
 
 
fd030cb
 
 
88ff990
 
 
fd030cb
88ff990
fd030cb
 
 
 
 
 
 
88ff990
fd030cb
 
 
 
 
 
88ff990
fd030cb
 
 
 
 
 
 
 
88ff990
fd030cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88ff990
 
 
 
fd030cb
88ff990
fd030cb
88ff990
fd030cb
 
 
 
 
 
 
88ff990
fd030cb
268f142
88ff990
 
 
 
 
fd030cb
88ff990
fd030cb
88ff990
268f142
88ff990
 
 
 
268f142
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import gradio as gr
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime

# -- Login credentials --
USER_CREDENTIALS = {"[email protected]": "Pass.123"}

# -- Load Google Sheets data --
def get_sheet_data():
    scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
    creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
    client = gspread.authorize(creds)

    # βœ… Fixed sheet name here:
    sheet = client.open_by_title("userAccess").worksheet("Field Sales")
    data = pd.DataFrame(sheet.get_all_records())
    return data

# -- Generate report based on selected period --
def generate_report(data, period="Daily"):
    try:
        if "Date" not in data.columns:
            return "❌ Column 'Date' not found in the sheet."

        data["Date"] = pd.to_datetime(data["Date"], errors='coerce')
        data = data.dropna(subset=["Date"])
        now = pd.Timestamp.today()

        if period == "Weekly":
            data = data[data["Date"] >= now - pd.Timedelta(days=7)]
        elif period == "Monthly":
            data = data[data["Date"].dt.month == now.month]
        elif period == "Yearly":
            data = data[data["Date"].dt.year == now.year]

        total_visits = len(data)
        current = len(data[data["Current/Prospect Custor"] == "Current"])
        new = len(data[data["Current/Prospect Custor"] == "Prospect"])
        second_hand = len(data[data["Customer Type"].str.contains("Second", na=False)])
        telesales = len(data[data["Source"] == "TeleSales"])
        oem_visits = len(data[data["Source"] == "OEM Visit"])
        orders = len(data[data["Order Received"] == "Yes"])
        order_value = data["Order Value"].sum() if "Order Value" in data.columns else 0

        return (
            f"### {period} Report\n"
            f"- **Total Visits:** {total_visits}\n"
            f"- **Current Dealerships:** {current}\n"
            f"- **New Dealerships:** {new}\n"
            f"- **% Current:** {current / total_visits * 100:.1f}% | **% New:** {new / total_visits * 100:.1f}%\n"
            f"- **Second-hand Dealerships:** {second_hand}\n"
            f"- **TeleSales Calls:** {telesales}\n"
            f"- **OEM Visits:** {oem_visits}\n"
            f"- **Orders Received:** {orders}\n"
            f"- **Total Order Value:** ${order_value:,.2f}"
        )
    except Exception as e:
        return f"❌ Error during report generation: {str(e)}"

# -- Login function --
def login(email, password):
    if USER_CREDENTIALS.get(email) == password:
        return gr.update(visible=True), gr.update(visible=False), ""
    else:
        return gr.update(visible=False), gr.update(visible=True), "❌ Invalid email or password"

# -- Report trigger --
def report(period):
    try:
        data = get_sheet_data()
        if data.empty:
            return "⚠️ No data found in the sheet."
        return generate_report(data, period)
    except Exception as e:
        return f"❌ Failed to load sheet: {str(e)}"

# -- Gradio UI --
with gr.Blocks() as app:
    with gr.Row(visible=True) as login_row:
        email = gr.Textbox(label="Email")
        password = gr.Textbox(label="Password", type="password")
        login_btn = gr.Button("Login")
        login_error = gr.Textbox(label="", visible=False)

    with gr.Row(visible=False) as dashboard:
        period_dropdown = gr.Dropdown(["Daily", "Weekly", "Monthly", "Yearly"], value="Weekly", label="Select Report Period")
        report_btn = gr.Button("Generate Report")
        report_output = gr.Markdown()

    login_btn.click(fn=login, inputs=[email, password], outputs=[dashboard, login_error, login_error])
    report_btn.click(fn=report, inputs=[period_dropdown], outputs=report_output)

app.launch()