File size: 12,699 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
05bbd5c
01139ed
a40135d
05bbd5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c8b92e
96ef08b
2c15b6c
0c8b92e
05bbd5c
5db7057
0b4d4e7
 
5db7057
 
 
 
2c15b6c
 
 
0c8b92e
 
96ef08b
 
2c15b6c
 
 
 
 
0c8b92e
2c15b6c
0c8b92e
05bbd5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c8b92e
 
2c15b6c
0c8b92e
 
 
 
2c15b6c
0c8b92e
 
b52ede6
 
2e0be03
06faff1
b52ede6
2f4c490
b52ede6
 
 
 
 
 
 
 
 
 
 
 
 
2f4c490
b52ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60870ef
b52ede6
 
 
 
d3b24ed
05bbd5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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)

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):
    ws = client.open_by_url(SHEET_URL).worksheet(name)
    data = ws.get_all_values()
    if not data:
        return pd.DataFrame()
    raw_header, *rows = data
    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")
    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)
    return "βœ… Users saved!"

# -------------------- QUOTES TAB UTILS --------------------
def get_quotes_df():
    df = load_sheet_df("LiveQuotes")
    df.columns = [c.strip() for c in df.columns]
    return df

def rep_choices_quotes():
    df = get_quotes_df()
    return sorted(df["Rep"].dropna().unique().tolist()) if "Rep" in df else []

def quote_year_choices():
    df = get_quotes_df()
    if "Year" in df.columns:
        years = sorted(df["Year"].dropna().unique().astype(str))
        return years
    if "Date" in df.columns:
        years = pd.to_datetime(df["Date"], errors="coerce").dt.year.dropna().unique()
        return sorted(years.astype(str))
    return []

def quote_month_choices(year=None):
    """
    Returns a sorted list of valid month strings for a given year, always at least [''].
    Also prints debug output to help troubleshoot.
    """
    df = get_quotes_df()
    if (
        year
        and "Year" in df.columns
        and "Month" in df.columns
        and not df.empty
    ):
        subset = df[df["Year"].astype(str) == str(year)]
        if subset.empty:
            print(f"[DEBUG] No quotes found for year {year}. Returning [''].")
            return [""]
        try:
            months = pd.to_numeric(subset["Month"], errors="coerce").dropna().astype(int)
            months = [str(m) for m in months if 1 <= m <= 12]
            months = sorted(set(months))
            result = [""] + months if months else [""]
            print(f"[DEBUG] Year {year}: Months dropdown = {result}")
            return result
        except Exception as e:
            print(f"[DEBUG] Exception in quote_month_choices for year {year}: {e}")
            return [""]
    print(f"[DEBUG] No valid year or columns missing. Returning [''].")
    return [""]

def quotes_summary(year=None, month=None):
    df = get_quotes_df()
    if "Rep" not in df.columns or "Total" not in df.columns:
        return pd.DataFrame([{"Error": "Missing Rep or Total column"}])
    if year and "Year" in df.columns:
        df = df[df["Year"].astype(str) == str(year)]
        if month and "Month" in df.columns:
            df = df[df["Month"].astype(str) == str(month)]
    df["Total"] = pd.to_numeric(df["Total"].astype(str).str.replace(",", ""), errors="coerce")
    summary = (
        df.groupby("Rep")
        .agg({"Document No.": "count", "Total": "sum"})
        .rename(columns={"Document No.": "Total Quotes", "Total": "Total Value"})
        .reset_index()
    )
    summary["Total Value"] = summary["Total Value"].fillna(0).round(2)
    return summary

def get_rep_quotes_filtered(rep, year=None, month=None):
    df = get_quotes_df()
    if "Rep" not in df.columns:
        return pd.DataFrame([{"Error": "Missing Rep column"}])
    df = df[df["Rep"] == rep]
    if year and "Year" in df.columns:
        df = df[df["Year"].astype(str) == str(year)]
        if month and "Month" in df.columns:
            df = df[df["Month"].astype(str) == str(month)]
    return df

def update_month_choices_summary(year):
    months = quote_month_choices(year)
    print(f"[DEBUG] update_month_choices_summary({year}) -> {months}")
    return gr.Dropdown.update(choices=months, value="")

def update_month_choices(year):
    months = quote_month_choices(year)
    print(f"[DEBUG] update_month_choices({year}) -> {months}")
    return gr.Dropdown.update(choices=months, value="")

# -------------------- 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("Allocated 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])

    # -- Quotes Tab (NEW) --
    with gr.Tab("Quotes"):
        gr.Markdown("### πŸ“ˆ Quotes Summary by Rep")
        year_qs = gr.Dropdown(choices=[""] + quote_year_choices(), label="Year (optional)", value="")
        month_qs = gr.Dropdown(choices=[""], label="Month (optional, needs year)", value="")
        btn_qs = gr.Button("Show Quotes Summary")
        sum_qs = gr.Dataframe(label="Summary by Rep")

        # Dynamic month options for summary
        year_qs.change(update_month_choices_summary, year_qs, month_qs)

        def quotes_summary_wrapper(year, month):
            return quotes_summary(year if year else None, month if month else None)
        btn_qs.click(quotes_summary_wrapper, [year_qs, month_qs], sum_qs)

        gr.Markdown("### πŸ”Ž View All Quotes for a Rep, Year, and Month")
        rep_q = gr.Dropdown(choices=rep_choices_quotes(), label="Select Rep")
        year_q = gr.Dropdown(choices=[""] + quote_year_choices(), label="Year (optional)", value="")
        month_q = gr.Dropdown(choices=[""], label="Month (optional, needs year)", value="")
        btn_qr = gr.Button("Show Quotes")
        tbl_qr = gr.Dataframe(label="Quotes for Selection")

        # Dynamic month options for rep quotes
        year_q.change(update_month_choices, year_q, month_q)

        def get_rep_quotes_filtered_wrapper(rep, year, month):
            return get_rep_quotes_filtered(rep, year if year else None, month if month else None)
        btn_qr.click(get_rep_quotes_filtered_wrapper, [rep_q, year_q, month_q], tbl_qr)

    # -- 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()