File size: 10,835 Bytes
06faff1
44e7320
 
9424917
93be3f3
1051212
9424917
c8f0059
 
d3b24ed
 
7074721
06faff1
9424917
 
 
 
d3b24ed
9424917
 
dfbe477
01139ed
d3b24ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9424917
 
 
 
 
 
d3b24ed
c8f0059
d3b24ed
2e0be03
9424917
c8f0059
 
1051212
9424917
d3b24ed
 
9424917
 
2e0be03
d3b24ed
06faff1
9424917
1051212
d3b24ed
9424917
2e0be03
9424917
2e0be03
6475632
2e0be03
9424917
2e0be03
c8f0059
 
b1c35dc
bc61590
a40135d
bc61590
9424917
2e0be03
 
9424917
2e0be03
c8f0059
 
9424917
0222536
9424917
c8f0059
 
9424917
0222536
9424917
 
 
c8f0059
9424917
1c4332a
d3b24ed
 
 
 
 
 
9424917
 
c8f0059
9424917
 
1c4332a
6903ce6
d3b24ed
6903ce6
 
 
9424917
 
d3b24ed
 
 
6903ce6
 
2e0be03
 
6475632
b1c35dc
9424917
 
6475632
9424917
 
 
 
 
 
 
 
6475632
9424917
 
 
 
 
a40135d
1c4332a
9424917
 
 
b1c35dc
 
 
 
 
 
 
01139ed
9424917
 
 
 
01139ed
9424917
 
a40135d
c8f0059
01139ed
a40135d
9424917
2e0be03
 
06faff1
d3b24ed
2f4c490
d3b24ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9424917
 
d3b24ed
 
 
 
 
 
9424917
 
d3b24ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f4c490
d3b24ed
 
 
 
 
 
 
 
 
 
 
9424917
d3b24ed
 
 
 
 
 
 
9424917
d3b24ed
9424917
 
 
d3b24ed
 
 
 
 
 
9424917
d3b24ed
 
 
 
 
 
 
9424917
 
d3b24ed
 
 
 
9424917
 
 
d3b24ed
9424917
 
d3b24ed
2f4c490
d3b24ed
 
 
 
 
 
 
 
 
 
 
 
c8f0059
d3b24ed
6903ce6
9424917
 
 
6903ce6
d3b24ed
a40135d
d3b24ed
9424917
 
 
 
a40135d
9424917
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
import gradio as gr
import pandas as pd
import gspread
from gspread.exceptions import WorksheetNotFound
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime, timedelta
from gspread_dataframe import set_with_dataframe

# -------------------- CONFIG --------------------
SHEET_URL        = "https://docs.google.com/spreadsheets/d/1if4KoVQvw5ZbhknfdZbzMkcTiPfsD6bz9V3a1th-bwQ"
USER_SHEET_NAME  = "Users"   # <-- must match (or contain) your β€œUsers” tab

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

# -------------------- FUZZY WORKSHEET LOOKUP --------------------
def open_ws_by_substring(substr: str):
    """
    Try exact match, then fall back to the first worksheet
    whose title contains `substr` (case-insensitive).
    """
    sh = client.open_by_url(SHEET_URL)
    try:
        return sh.worksheet(substr)
    except WorksheetNotFound:
        for ws in sh.worksheets():
            if substr.lower() in ws.title.lower():
                return ws
    raise WorksheetNotFound(f"No tab matching '{substr}'")

# -------------------- SHEET UTILS --------------------
def normalize_columns(df: pd.DataFrame) -> pd.DataFrame:
    df.columns = df.columns.str.strip().str.title()
    return df

def load_sheet(sheet_name: str) -> pd.DataFrame:
    """Return a DataFrame of the entire sheet, or an Error row."""
    try:
        ws = open_ws_by_substring(sheet_name)
        df = pd.DataFrame(ws.get_all_records())
        return normalize_columns(df)
    except Exception as e:
        return pd.DataFrame([{"Error": str(e)}])

def load_sheet_df(sheet_name: str) -> pd.DataFrame:
    """Like load_sheet, but lets WorksheetNotFound bubble up."""
    ws = open_ws_by_substring(sheet_name)
    df = pd.DataFrame(ws.get_all_records())
    return normalize_columns(df)

# -------------------- DATE FILTER HELPERS --------------------
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_week(df, date_col, rep_col=None, rep=None):
    df[date_col] = pd.to_datetime(df[date_col], errors="coerce").dt.date
    start, end = get_current_week_range()
    out = df[(df[date_col] >= start) & (df[date_col] <= end)]
    if rep:
        out = out[out[rep_col] == rep]
    return out

def filter_date(df, date_col, rep_col, y, m, d, rep):
    try:
        target = datetime(int(y), int(m), int(d)).date()
    except:
        return pd.DataFrame([{"Error": "Invalid date"}])
    df[date_col] = pd.to_datetime(df[date_col], errors="coerce").dt.date
    out = df[df[date_col] == target]
    if rep:
        out = out[out[rep_col] == rep]
    return out

# -------------------- REPORT FUNCTIONS --------------------
def get_calls(rep=None):
    df = load_sheet("Calls")
    if "Call Date" not in df.columns:
        return df
    return filter_week(df, "Call Date", "Rep", rep)

def search_calls_by_date(y, m, d, rep):
    df = load_sheet("Calls")
    if "Call Date" not in df.columns:
        return df
    return filter_date(df, "Call Date", "Rep", y, m, d, rep)

def get_appointments(rep=None):
    df = load_sheet("Appointments")
    if "Appointment Date" not in df.columns:
        return df
    return filter_week(df, "Appointment Date", "Rep", rep)

def search_appointments_by_date(y, m, d, rep):
    df = load_sheet("Appointments")
    if "Appointment Date" not in df.columns:
        return df
    return filter_date(df, "Appointment Date", "Rep", y, m, d, rep)

def get_leads_detail():
    return load_sheet("AllocatedLeads")

def get_leads_summary():
    df = get_leads_detail()
    if "Error" in df.columns:
        return df
    return df.groupby("Assigned Rep")\
             .size()\
             .reset_index(name="Leads Count")

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

    def top_rep(df, col):
        if "Error" in df.columns or df.empty or col not in df.columns:
            return "N/A"
        return df.groupby(col).size().idxmax()

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

def rep_options(sheet, col):
    df = load_sheet(sheet)
    if col in df.columns:
        return sorted(df[col].dropna().unique().tolist())
    return []

# -------------------- USER MANAGEMENT --------------------
def load_users() -> pd.DataFrame:
    cols = [
        "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"
    ]
    try:
        return load_sheet_df(USER_SHEET_NAME)
    except WorksheetNotFound:
        return pd.DataFrame(columns=cols)

def save_users(df: pd.DataFrame):
    ws = client.open_by_url(SHEET_URL).worksheet(USER_SHEET_NAME)
    ws.clear()
    set_with_dataframe(ws, df)
    return "βœ… Users saved!"

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

    # -- Calls Report --
    with gr.Tab("Calls Report"):
        rep_calls = gr.Dropdown(choices=rep_options("Calls","Rep"),
                                label="Optional Rep Filter",
                                allow_custom_value=True)
        calls_btn = gr.Button("Load Current Week Calls")

        with gr.Row():
            with gr.Column():
                calls_sum = gr.Dataframe(label="πŸ“Š Calls by Rep")
            with gr.Column():
                calls_det = gr.Dataframe(label="πŸ”Ž Detailed Calls")

        calls_btn.click(
            fn=lambda r: (
                get_calls(r).groupby("Rep")
                            .size()
                            .reset_index(name="Count"),
                get_calls(r)
            ),
            inputs=rep_calls,
            outputs=[calls_sum, calls_det]
        )

        gr.Markdown("### πŸ” Search Calls by Specific Date")
        y1 = gr.Textbox(label="Year")
        m1 = gr.Textbox(label="Month")
        d1 = gr.Textbox(label="Day")
        rep1 = gr.Dropdown(choices=rep_options("Calls","Rep"),
                           label="Optional Rep Filter",
                           allow_custom_value=True)
        calls_date_btn = gr.Button("Search Calls by Date")

        with gr.Row():
            with gr.Column():
                calls_date_sum = gr.Dataframe(label="πŸ“Š Calls by Rep on Date")
            with gr.Column():
                calls_date_det = gr.Dataframe(label="πŸ”Ž Detailed Calls on Date")

        calls_date_btn.click(
            fn=lambda y,m,d,r: (
                search_calls_by_date(y,m,d,r)
                  .groupby("Rep")
                  .size()
                  .reset_index(name="Count"),
                search_calls_by_date(y,m,d,r)
            ),
            inputs=[y1,m1,d1,rep1],
            outputs=[calls_date_sum, calls_date_det]
        )

    # -- Appointments Report --
    with gr.Tab("Appointments Report"):
        rep_appt = gr.Dropdown(choices=rep_options("Appointments","Rep"),
                               label="Optional Rep Filter",
                               allow_custom_value=True)
        appt_btn  = gr.Button("Load Current Week Appointments")

        with gr.Row():
            with gr.Column():
                appt_sum = gr.Dataframe(label="πŸ“Š Weekly Appointments Summary by Rep")
            with gr.Column():
                appt_det = gr.Dataframe(label="πŸ”Ž Detailed Appointments")

        appt_btn.click(
            fn=lambda r: (
                get_appointments(r)
                  .groupby("Rep")
                  .size()
                  .reset_index(name="Count"),
                get_appointments(r)
            ),
            inputs=rep_appt,
            outputs=[appt_sum, appt_det]
        )

        gr.Markdown("### πŸ” Search Appointments by Specific Date")
        y2 = gr.Textbox(label="Year")
        m2 = gr.Textbox(label="Month")
        d2 = gr.Textbox(label="Day")
        rep2 = gr.Dropdown(choices=rep_options("Appointments","Rep"),
                           label="Optional Rep Filter",
                           allow_custom_value=True)
        appt_date_btn = gr.Button("Search Appointments by Date")

        with gr.Row():
            with gr.Column():
                appt_date_sum = gr.Dataframe(label="πŸ“Š Appts by Rep on Date")
            with gr.Column():
                appt_date_det = gr.Dataframe(label="πŸ”Ž Detailed Appts on Date")

        appt_date_btn.click(
            fn=lambda y,m,d,r: (
                search_appointments_by_date(y,m,d,r)
                  .groupby("Rep")
                  .size()
                  .reset_index(name="Count"),
                search_appointments_by_date(y,m,d,r)
            ),
            inputs=[y2,m2,d2,rep2],
            outputs=[appt_date_sum, appt_date_det]
        )

    # -- Appointed Leads --
    with gr.Tab("Appointed Leads"):
        leads_btn = gr.Button("View Appointed Leads")

        with gr.Row():
            with gr.Column():
                leads_sum    = gr.Dataframe(label="πŸ“Š Leads Count by Rep")
            with gr.Column():
                leads_det    = gr.Dataframe(label="πŸ”Ž Detailed Leads")

        leads_btn.click(
            fn=lambda: (get_leads_summary(), get_leads_detail()),
            outputs=[leads_sum, leads_det]
        )

    # -- Insights --
    with gr.Tab("Insights"):
        insights_btn = gr.Button("Generate Insights")
        insights_tbl = gr.Dataframe()
        insights_btn.click(fn=compute_insights, outputs=insights_tbl)

    # -- User Management --
    with gr.Tab("User Management"):
        gr.Markdown("### πŸ™ Manage Users  \nEdit the grid and click **Save Users**.")
        users_tbl = gr.Dataframe(value=load_users(), interactive=True)
        save_btn  = gr.Button("Save Users")
        save_msg  = gr.Textbox(interactive=False)
        save_btn.click(fn=save_users, inputs=users_tbl, outputs=save_msg)

    app.launch()