File size: 8,084 Bytes
06faff1
44e7320
 
fa1e3ad
93be3f3
1051212
b52ede6
7074721
06faff1
9424917
 
fa1e3ad
9424917
b52ede6
 
 
dfbe477
01139ed
b52ede6
 
9424917
b52ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1051212
06faff1
b52ede6
1051212
b52ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc61590
a40135d
bc61590
b52ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0222536
fa1e3ad
b52ede6
1c4332a
d3b24ed
fa1e3ad
b52ede6
d3b24ed
b52ede6
 
 
fa1e3ad
b52ede6
fa1e3ad
b52ede6
1c4332a
b52ede6
6903ce6
fa1e3ad
 
6903ce6
 
 
b52ede6
 
fa1e3ad
6903ce6
fa1e3ad
6903ce6
2e0be03
 
6475632
b1c35dc
b52ede6
 
 
 
 
6475632
b52ede6
 
 
 
 
 
a40135d
1c4332a
fa1e3ad
9a4695e
b52ede6
 
 
 
 
 
 
 
 
b1c35dc
01139ed
b52ede6
fa1e3ad
01139ed
fa1e3ad
9a4695e
a40135d
b52ede6
01139ed
a40135d
b52ede6
 
2e0be03
06faff1
b52ede6
2f4c490
b52ede6
 
 
 
 
 
 
 
 
 
 
 
 
2f4c490
b52ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f4c490
b52ede6
 
 
 
d3b24ed
b52ede6
6903ce6
b52ede6
 
 
6903ce6
b52ede6
a40135d
b52ede6
9424917
b52ede6
 
 
a40135d
b52ede6
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import gradio as gr
import pandas as pd
import gspread
from gspread_dataframe import set_with_dataframe
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime, timedelta
from collections import Counter

# -------------------- AUTH --------------------
scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/drive"
]
creds = ServiceAccountCredentials.from_json_keyfile_name(
    "deep-mile-461309-t8-0e90103411e0.json", scope
)
client = gspread.authorize(creds)

# YOUR SPREADSHEET URL
SHEET_URL = "https://docs.google.com/spreadsheets/d/1if4KoVQvw5ZbhknfdZbzMkcTiPfsD6bz9V3a1th-bwQ"

# -------------------- UTILS --------------------
def normalize_columns(cols):
    return [c.strip().title() for c in cols]

def load_sheet_df(name):
    """
    Load a sheet into a DataFrame without confusing duplicates in
    the header row. We fetch all values, dedupe the first row,
    then build a DataFrame.
    """
    ws = client.open_by_url(SHEET_URL).worksheet(name)
    data = ws.get_all_values()
    if not data:
        return pd.DataFrame()
    raw_header, *rows = data
    # make header unique
    counts = Counter()
    header = []
    for col in raw_header:
        counts[col] += 1
        if counts[col] > 1:
            header.append(f"{col}_{counts[col]}")
        else:
            header.append(col)
    header = normalize_columns(header)
    return pd.DataFrame(rows, columns=header)

def get_current_week_range():
    today = datetime.now().date()
    start = today - timedelta(days=today.weekday())
    end = start + timedelta(days=6)
    return start, end

def filter_by_week(df, date_col, rep=None):
    if date_col not in df.columns:
        return pd.DataFrame([{"Error": f"Missing '{date_col}' column"}])
    df = df.copy()
    df[date_col] = pd.to_datetime(df[date_col], errors="coerce").dt.date
    start, end = get_current_week_range()
    m = df[date_col].between(start, end)
    if rep:
        m &= df.get("Rep", pd.Series()).astype(str) == rep
    return df[m]

def filter_by_date(df, date_col, y, m, d, rep=None):
    try:
        target = datetime(int(y), int(m), int(d)).date()
    except:
        return pd.DataFrame([{"Error": "Invalid date"}])
    if date_col not in df.columns:
        return pd.DataFrame([{"Error": f"Missing '{date_col}' column"}])
    df = df.copy()
    df[date_col] = pd.to_datetime(df[date_col], errors="coerce").dt.date
    m = df[date_col] == target
    if rep:
        m &= df.get("Rep", pd.Series()).astype(str) == rep
    return df[m]

def rep_choices(sheet, col="Rep"):
    df = load_sheet_df(sheet)
    return sorted(df[col].dropna().unique().tolist()) if col in df else []

# -------------------- REPORT FUNCTIONS --------------------
def get_calls(rep=None):
    df = load_sheet_df("Calls")
    return filter_by_week(df, "Call Date", rep)

def get_appointments(rep=None):
    df = load_sheet_df("Appointments")
    return filter_by_week(df, "Appointment Date", rep)

def search_calls(y, m, d, rep=None):
    df = load_sheet_df("Calls")
    return filter_by_date(df, "Call Date", y, m, d, rep)

def search_appointments(y, m, d, rep=None):
    df = load_sheet_df("Appointments")
    return filter_by_date(df, "Appointment Date", y, m, d, rep)

# -------------------- LEADS --------------------
def get_leads_detail():
    df = load_sheet_df("AllocatedLeads")
    return df

def get_leads_summary():
    df = get_leads_detail()
    if "Assigned Rep" not in df:
        return pd.DataFrame([{"Error": "Missing 'Assigned Rep'"}])
    return df.groupby("Assigned Rep").size().reset_index(name="Leads Count")

# -------------------- INSIGHTS --------------------
def compute_insights():
    calls = get_calls()
    appts = get_appointments()
    leads = get_leads_detail()

    def top(df, col="Rep"):
        if col in df and not df.empty:
            vc = df[col].value_counts()
            return vc.idxmax() if not vc.empty else "N/A"
        return "N/A"

    data = [
        {"Metric": "Most Calls This Week",        "Rep": top(calls, "Rep")},
        {"Metric": "Most Appointments This Week", "Rep": top(appts, "Rep")},
        {"Metric": "Most Leads Allocated",        "Rep": top(leads, "Assigned Rep")},
    ]
    return pd.DataFrame(data)

# -------------------- USER MANAGEMENT --------------------
def load_users():
    df = load_sheet_df("Users")
    # select & rename your columns as needed
    want = [
        "Id", "Email", "Name", "Business", "Role",
        "Daily Phone Call Target", "Daily Phone Appointment Target",
        "Daily Quote Number Target", "Daily Quote Revenue Target",
        "Weekly Phone Call Target", "Weekly Phone Appointment Target",
        "Weekly Quote Number Target", "Weekly Quote Revenue Target",
        "Monthly Phone Call Target", "Monthly Phone Appointment Target",
        "Monthly Quote Number Target", "Monthly Quote Revenue Target",
        "Monthly Sales Revenue Target"
    ]
    exist = [c for c in want if c in df.columns]
    return df[exist]

def save_users(df):
    ws = client.open_by_url(SHEET_URL).worksheet("Users")
    ws.clear()
    set_with_dataframe(ws, df)  # writes headers + data
    return "โœ… Users saved!"

# -------------------- UI LAYOUT --------------------
with gr.Blocks(title="Graffiti Admin Dashboard") as app:
    gr.Markdown("# ๐Ÿ“† Graffiti Admin Dashboard")

    # -- Calls Tab --
    with gr.Tab("Calls Report"):
        rep_c = gr.Dropdown(choices=rep_choices("Calls"), label="Filter by Rep", allow_custom_value=True)
        btn_c = gr.Button("Load This Weekโ€™s Calls")
        tbl_c = gr.Dataframe()
        btn_c.click(get_calls, rep_c, tbl_c)

        gr.Markdown("### Search Calls by Date")
        y1, m1, d1 = gr.Textbox(label="Year"), gr.Textbox(label="Month"), gr.Textbox(label="Day")
        rep_c2 = gr.Dropdown(choices=rep_choices("Calls"), label="Filter by Rep", allow_custom_value=True)
        btn_c2 = gr.Button("Search")
        tbl_c2 = gr.Dataframe()
        btn_c2.click(search_calls, [y1, m1, d1, rep_c2], tbl_c2)

    # -- Appointments Tab --
    with gr.Tab("Appointments Report"):
        rep_a = gr.Dropdown(choices=rep_choices("Appointments"), label="Filter by Rep", allow_custom_value=True)
        btn_a = gr.Button("Load This Weekโ€™s Appts")
        sum_a = gr.Dataframe(label="๐Ÿ“Š Appts by Rep")
        tbl_a = gr.Dataframe()
        def _load_appts(r):
            df = get_appointments(r)
            return df.groupby("Rep").size().reset_index(name="Count"), df
        btn_a.click(_load_appts, rep_a, [sum_a, tbl_a])

        gr.Markdown("### Search Appts by Date")
        y2, m2, d2 = gr.Textbox(label="Year"), gr.Textbox(label="Month"), gr.Textbox(label="Day")
        rep_a2 = gr.Dropdown(choices=rep_choices("Appointments"), label="Filter by Rep", allow_custom_value=True)
        btn_a2 = gr.Button("Search")
        sum_a2 = gr.Dataframe(label="๐Ÿ“Š Appts by Rep")
        tbl_a2 = gr.Dataframe()
        def _search_appts(y,m,d,r):
            df = search_appointments(y,m,d,r)
            return df.groupby("Rep").size().reset_index(name="Count"), df
        btn_a2.click(_search_appts, [y2,m2,d2,rep_a2], [sum_a2, tbl_a2])

    # -- Appointed Leads --
    with gr.Tab("Appointed Leads"):
        btn_l = gr.Button("View Leads")
        sum_l = gr.Dataframe(label="๐Ÿ“Š Leads by Rep")
        det_l = gr.Dataframe(label="๐Ÿ”Ž Details")
        btn_l.click(lambda: (get_leads_summary(), get_leads_detail()), None, [sum_l, det_l])

    # -- Insights --
    with gr.Tab("Insights"):
        btn_i = gr.Button("Generate Insights")
        out_i = gr.Dataframe()
        btn_i.click(compute_insights, None, out_i)

    # -- User Management --
    with gr.Tab("User Management"):
        gr.Markdown("## ๐Ÿ‘ค Manage Users\nEdit the grid below then click **Save Users** to push back to the sheet.")
        users_tbl = gr.Dataframe(value=load_users(), interactive=True)
        save_btn = gr.Button("Save Users")
        save_out = gr.Textbox()
        save_btn.click(save_users, users_tbl, save_out)

    app.launch()