Sylvester1922 commited on
Commit
fc2d4fb
Β·
1 Parent(s): 83e29f1

Complete rewrite: pagination + date filter + JCC colors + full chat router

Browse files
Files changed (1) hide show
  1. app.py +584 -307
app.py CHANGED
@@ -1,130 +1,322 @@
1
- import os, json, time, warnings
2
  import gradio as gr
3
  import pandas as pd
4
  import numpy as np
5
  import plotly.graph_objects as go
6
-
7
- from datetime import datetime, timedelta
8
  import requests as _http
 
9
  warnings.filterwarnings('ignore')
10
- # ── Gradio 5.9.1 schema bug fix ──────────────────────────────────────────────
 
11
  try:
12
  import gradio_client.utils as _gcu
13
- _orig_j2p = _gcu._json_schema_to_python_type
14
- def _safe_j2p(schema, defs):
15
- if not isinstance(schema, dict): return "any"
16
- try: return _orig_j2p(schema, defs)
17
- except Exception: return "any"
18
- _gcu._json_schema_to_python_type = _safe_j2p
19
- except Exception: pass
20
- # ─────────────────────────────────────────────────────────────────────────────
21
 
 
22
  SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
23
  SUPABASE_KEY = os.environ.get("SUPABASE_KEY", "")
24
- GROWTH_RATE = 0.05
25
- CACHE_TTL = 300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  _cache = {'df': pd.DataFrame(), 'loaded_at': 0}
27
- COMPLEXES = ['Westgate Mall','City Centre','Eastpark','Northgate']
28
- BRANDS = ['Flame & Grill','Pie Palace','Chill Creamery','Sizzle Wings']
29
- COLORS = ['#c9a84c','#2ecc71','#e74c3c','#9b59b6','#1abc9c','#f39c12','#3498db','#e67e22']
30
 
 
31
  def load_data():
32
- if not SUPABASE_URL or not SUPABASE_KEY: print("SUPABASE not configured"); return pd.DataFrame()
 
33
  try:
34
- r = _http.get(SUPABASE_URL+"/rest/v1/daily_input?select=*&order=date&limit=10000", headers={"apikey":SUPABASE_KEY,"Authorization":"Bearer "+SUPABASE_KEY})
35
- if r.status_code!=200: print("HTTP "+str(r.status_code)); return pd.DataFrame()
36
- data=r.json()
37
- if not data: return pd.DataFrame()
38
- df = pd.DataFrame(data)
39
- for c in ['budget_usd','actual_revenue_usd','prior_month_actual','prior_year_actual','customer_count','counters_open','variance_vs_budget','avg_spend_per_cust','revenue_per_counter','is_holiday','variance_pct','vs_prior_month_pct','vs_prior_year_pct']:
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  if c in df.columns: df[c] = pd.to_numeric(df[c], errors='coerce').fillna(0)
41
- if 'date' in df.columns: df['date'] = pd.to_datetime(df['date'], errors='coerce')
42
- df = df.dropna(subset=['date','actual_revenue_usd']).copy()
43
- df = df[df['actual_revenue_usd'] > 0].copy()
44
- print("Loaded "+str(len(df))+" rows from Supabase")
45
- return df.sort_values('date').reset_index(drop=True)
46
- except Exception as e: print("Load error: "+str(e)); return pd.DataFrame()
 
 
47
  def get_df():
48
  now = time.time()
49
  if now - _cache['loaded_at'] > CACHE_TTL or _cache['df'].empty:
50
  fresh = load_data()
51
- if not fresh.empty: _cache['df'] = fresh; _cache['loaded_at'] = now
 
 
52
  return _cache['df']
53
- def refresh_data():
54
- _cache['loaded_at'] = 0; fresh = get_df()
55
- if fresh.empty: return build_kpi_html(), "No data"
56
- return build_kpi_html(), "Refreshed: "+str(len(fresh))+" rows ("+fresh['date'].min().strftime('%b %d, %Y')+" to "+fresh['date'].max().strftime('%b %d, %Y')+")"
57
- print("Loading from Supabase..."); _ = get_df()
 
 
 
 
 
 
 
 
 
 
58
  def fmt(v):
59
- if v >= 1e6: return "${:.2f}M".format(v/1e6)
60
- if v >= 1e3: return "${:.0f}K".format(v/1e3)
61
- return "${:,.0f}".format(v)
62
- def dark(title, height=360):
63
- return dict(title=dict(text=title,font=dict(color='#c9a84c',size=14)),paper_bgcolor='#0a1628',plot_bgcolor='#0d1f38',font=dict(color='#c8d8f0',family='Arial',size=11),height=height,xaxis=dict(gridcolor='#1a3a6e',linecolor='#1a3a6e',tickfont=dict(color='#c8d8f0')),yaxis=dict(gridcolor='#1a3a6e',linecolor='#1a3a6e',tickfont=dict(color='#c8d8f0')),legend=dict(bgcolor='rgba(10,22,40,0.85)',bordercolor='#1a3a6e',borderwidth=1,font=dict(color='#c8d8f0')))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def build_kpi_html(dff=None):
65
- if dff is None:
66
- dff = get_df()
67
- if dff.empty:
68
- tr,ap,tc,tb,dr = "--","--","--","--","No data"
69
  else:
70
- tr = fmt(dff['actual_revenue_usd'].sum())
71
  bud = dff['budget_usd'].sum() if 'budget_usd' in dff.columns else 0
72
- ap = "{:.1f}%".format(dff['actual_revenue_usd'].sum()/bud*100) if bud > 0 else "--"
73
- tc = dff.groupby('complex')['actual_revenue_usd'].sum().idxmax()
74
- tb = dff.groupby('brand')['actual_revenue_usd'].sum().idxmax()
75
- dr = dff['date'].min().strftime('%b %d')+" - "+dff['date'].max().strftime('%b %d, %Y')
76
- return '<div style="background:linear-gradient(135deg,#0d1b2a,#1a3a5c);padding:18px 28px 16px;border-radius:12px;margin-bottom:4px;border-left:4px solid #c9a84c;"><div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;"><div><h1 style="color:#fff;margin:0;font-size:22px;">Savanna QSR Intelligence</h1><p style="color:#aed6f1;margin:4px 0 0;font-size:13px;">Live Operations Intelligence - Zimbabwe</p></div><div style="text-align:right;"><p style="color:#c9a84c;margin:0;font-size:10px;font-weight:700;letter-spacing:2px;">NETRISYL INSIGHTS</p></div></div><div style="display:flex;gap:10px;margin-top:14px;flex-wrap:wrap;"><div style="background:rgba(10,22,40,0.7);padding:10px 18px;border-radius:8px;border:1px solid #1a3a6e;text-align:center;"><div style="color:#c9a84c;font-size:18px;font-weight:700;">'+tr+'</div><div style="color:#7fb3d3;font-size:11px;">Total Revenue</div></div><div style="background:rgba(10,22,40,0.7);padding:10px 18px;border-radius:8px;border:1px solid #1a3a6e;text-align:center;"><div style="color:#c9a84c;font-size:18px;font-weight:700;">'+ap+'</div><div style="color:#7fb3d3;font-size:11px;">Budget Achievement</div></div><div style="background:rgba(10,22,40,0.7);padding:10px 18px;border-radius:8px;border:1px solid #1a3a6e;text-align:center;"><div style="color:#c9a84c;font-size:18px;font-weight:700;">'+tc+'</div><div style="color:#7fb3d3;font-size:11px;">Top Complex</div></div><div style="background:rgba(10,22,40,0.7);padding:10px 18px;border-radius:8px;border:1px solid #1a3a6e;text-align:center;"><div style="color:#c9a84c;font-size:18px;font-weight:700;">'+tb+'</div><div style="color:#7fb3d3;font-size:11px;">Top Brand</div></div><div style="background:rgba(10,22,40,0.7);padding:10px 18px;border-radius:8px;border:1px solid #1a3a6e;text-align:center;"><div style="color:#7fb3d3;font-size:16px;font-weight:700;">'+dr+'</div><div style="color:#7fb3d3;font-size:11px;">Data Range</div></div></div></div>'
77
- def build_dashboard(period):
78
- df = get_df()
79
- if df.empty:
80
- e = go.Figure().update_layout(**dark("No data - click Refresh")); return [build_kpi_html()]+[e]*6
81
- dff = df.copy(); latest = dff['date'].max()
82
- if period == 'Last 7 Days': dff = dff[dff['date'] >= latest - timedelta(days=7)]
83
- elif period == 'Last 30 Days': dff = dff[dff['date'] >= latest - timedelta(days=30)]
84
- elif period == 'Last 90 Days': dff = dff[dff['date'] >= latest - timedelta(days=90)]
85
- elif period == 'MTD': dff = dff[(dff['date'].dt.month==latest.month)&(dff['date'].dt.year==latest.year)]
86
- cx = dff.groupby('complex').agg(actual=('actual_revenue_usd','sum'),budget=('budget_usd','sum')).reset_index().sort_values('actual',ascending=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  fig1 = go.Figure()
88
- fig1.add_trace(go.Bar(name='Budget',x=cx['budget'],y=cx['complex'],orientation='h',marker=dict(color='#2a4a8a',line=dict(color='#c9a84c',width=1)),opacity=0.6))
89
- fig1.add_trace(go.Bar(name='Actual',x=cx['actual'],y=cx['complex'],orientation='h',marker=dict(color='#c9a84c',line=dict(color='#1e2d5e',width=1)),text=[fmt(v) for v in cx['actual']],textposition='inside',insidetextanchor='middle',textfont=dict(color='#0a1628',size=12,family='Arial',weight='bold')))
90
- fig1.update_layout(**dark("Revenue by Complex",height=300),barmode='overlay',margin=dict(l=140,r=120,t=50,b=40))
91
- br = dff.groupby('brand')['actual_revenue_usd'].sum().reset_index().sort_values('actual_revenue_usd',ascending=True)
92
- fig2 = go.Figure(go.Bar(x=br['actual_revenue_usd'],y=br['brand'],orientation='h',marker=dict(color=['#1e2d5e','#c9a84c','#1abc9c','#e74c3c','#9b59b6','#2ecc71','#e67e22','#3498db'][:len(br)],line=dict(color='#c9a84c',width=1)),text=[fmt(v) for v in br['actual_revenue_usd']],textposition='inside',insidetextanchor='middle',textfont=dict(color='#ffffff',size=12,family='Arial',weight='bold')))
93
- fig2.update_layout(**dark("Revenue by Brand",height=280),margin=dict(l=140,r=120,t=50,b=40))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  daily = dff.groupby('date')['actual_revenue_usd'].sum().reset_index()
95
  fig3 = go.Figure()
96
- fig3.add_trace(go.Scatter(x=daily['date'],y=daily['actual_revenue_usd'],name='Actual',line=dict(color='#c9a84c',width=2.5),fill='tozeroy',fillcolor='rgba(201,168,76,0.08)'))
97
- fig3.update_layout(**dark("Daily Revenue Trend",height=360),hovermode='x unified',showlegend=False,margin=dict(l=90,r=40,t=50,b=50),yaxis_tickprefix="$",yaxis_tickformat=",.0f")
98
- if 'customer_count' in dff.columns:
99
- avs = dff[dff['customer_count']>0].groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['customer_count'].sum()).reset_index(name='avg').sort_values('avg',ascending=True)
100
- fig4 = go.Figure(go.Bar(x=avs['avg'],y=avs['complex'],orientation='h',marker_color='#2ecc71',text=["${:.2f}".format(v) for v in avs['avg']],textposition='outside',textfont=dict(color='#c8d8f0',size=11)))
101
- fig4.update_layout(**dark("Avg Spend Per Customer",height=280),margin=dict(l=140,r=120,t=50,b=40))
102
- else: fig4 = go.Figure().update_layout(**dark("No customer data",height=280))
103
- try:
104
- heat = dff.groupby(['complex','brand']).apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0).reset_index(name='ach')
105
- pivot = heat.pivot(index='complex',columns='brand',values='ach')
106
- fig5 = go.Figure(go.Heatmap(z=pivot.values,x=pivot.columns.tolist(),y=pivot.index.tolist(),colorscale=[[0,'#c0392b'],[0.8,'#f39c12'],[1,'#2ecc71']],zmid=100,zmin=70,zmax=120,text=[["{:.1f}%".format(v) for v in row] for row in pivot.values],texttemplate="%{text}",textfont=dict(color='white',size=12)))
107
- fig5.update_layout(**dark("Budget Achievement %",height=280),margin=dict(l=130,r=60,t=50,b=80))
108
- except: fig5 = go.Figure().update_layout(**dark("Heatmap error",height=280))
109
- comp_cols = {'actual':'actual_revenue_usd'}
110
- if 'prior_month_actual' in dff.columns: comp_cols['sdlm'] = 'prior_month_actual'
111
- if 'prior_year_actual' in dff.columns: comp_cols['sdly'] = 'prior_year_actual'
112
- comp = dff.groupby('complex')[list(comp_cols.values())].sum().reset_index()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  fig6 = go.Figure()
114
- cmap = {'sdly':'#1e2d5e','sdlm':'#1abc9c','actual':'#c9a84c'}
115
- lmap = {'sdly':'Prior Year','sdlm':'Prior Month','actual':'This Period'}
116
- for key, col in comp_cols.items():
117
- if col in comp.columns: fig6.add_trace(go.Bar(name=lmap[key],x=comp['complex'],y=comp[col],marker_color=cmap[key],text=[fmt(v) for v in comp[col]],textposition='outside',textfont=dict(color='#c8d8f0',size=10)))
118
- fig6.update_layout(**dark("Actual vs Prior Periods",height=340),barmode='group',hovermode='x unified',margin=dict(l=60,r=40,t=50,b=60))
119
- return build_kpi_html(dff), fig1, fig2, fig3, fig4, fig5, fig6
120
- def generate_forecast(seg_type, seg_name, horizon):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  try:
122
- df = get_df()
123
- if df.empty: return go.Figure().update_layout(**dark("No data")), "No data."
124
- horizon = int(horizon)
 
125
  if seg_type == 'Overall':
126
  seg = df.groupby('date')['actual_revenue_usd'].sum().reset_index()
127
- label = 'All Complexes'
128
  elif seg_type == 'By Complex':
129
  seg = df[df['complex']==seg_name].groupby('date')['actual_revenue_usd'].sum().reset_index()
130
  label = seg_name
@@ -133,206 +325,203 @@ def generate_forecast(seg_type, seg_name, horizon):
133
  label = seg_name
134
  else:
135
  parts = seg_name.split(' | ')
136
- if len(parts)==2:
137
- seg = df[(df['complex']==parts[0])&(df['brand']==parts[1])].groupby('date')['actual_revenue_usd'].sum().reset_index()
138
- else:
139
- seg = df.groupby('date')['actual_revenue_usd'].sum().reset_index()
140
  label = seg_name
141
  seg.columns = ['date','revenue']
142
  seg = seg.sort_values('date').reset_index(drop=True)
143
  if len(seg) < 7:
144
- return go.Figure().update_layout(**dark("Need 7+ days of data for this segment")), "Insufficient data for this segment."
145
- last_date = seg['date'].max()
146
- base = seg['revenue'].tail(min(horizon, len(seg))).mean()
147
- if pd.isna(base) or base <= 0: base = seg['revenue'].mean()
148
- DOW = {0:0.85,1:0.90,2:0.92,3:0.95,4:1.05,5:1.20,6:1.15}
149
- fc_dates = [last_date + timedelta(days=i+1) for i in range(horizon)]
150
- fc_vals = [round(float(base) * DOW[d.weekday()] * (1+GROWTH_RATE), 2) for d in fc_dates]
151
- upper = [v*1.15 for v in fc_vals]; lower = [v*0.85 for v in fc_vals]
152
- last_date_str = str(last_date)[:10]
153
  fig = go.Figure()
154
- fig.add_trace(go.Scatter(x=seg['date'],y=seg['revenue'],name='Historical',line=dict(color='#4a7aae',width=1.2),opacity=0.85))
155
- fig.add_trace(go.Scatter(x=fc_dates+fc_dates[::-1],y=upper+lower[::-1],fill='toself',fillcolor='rgba(201,168,76,0.18)',line=dict(color='rgba(0,0,0,0)'),name='Confidence',hoverinfo='skip'))
156
- fig.add_trace(go.Scatter(x=fc_dates,y=fc_vals,name=str(horizon)+'-Day Forecast',line=dict(color='#c9a84c',width=2.5,dash='dash'),mode='lines+markers',marker=dict(size=4,color='#c9a84c')))
157
- fig.add_vline(x=last_date_str,line_dash='dot',line_color='#c9a84c',opacity=0.6)
158
- fig.update_layout(**dark(label+" - "+str(horizon)+"-Day Forecast",height=480),hovermode='x unified',margin=dict(l=70,r=40,t=70,b=50))
159
- total=sum(fc_vals); avg=total/horizon; peak=max(fc_vals); peak_d=fc_dates[fc_vals.index(peak)].strftime('%b %d, %Y')
160
- summary = "**"+str(horizon)+"-Day Forecast β€” "+label+"**\n\n| Metric | Value |\n|---|---|\n| Total | **${:,.2f}".format(total)+"** |\n| Daily Avg | **${:,.2f}".format(avg)+"** |\n| Peak | **${:,.2f}".format(peak)+" on "+peak_d+"** |"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  return fig, summary
162
  except Exception as e:
163
- err_fig = go.Figure().update_layout(**dark("Forecast error: "+str(e),height=480))
164
- return err_fig, "Error: "+str(e)
165
- def update_seg_choices(seg_type):
166
- if seg_type == 'Overall': return gr.update(choices=['All'],value='All')
167
- elif seg_type == 'By Complex': return gr.update(choices=COMPLEXES,value=COMPLEXES[0])
168
- elif seg_type == 'By Brand': return gr.update(choices=BRANDS,value=BRANDS[0])
169
- else:
170
- opts = [cx+" | "+br for cx in COMPLEXES for br in BRANDS]
171
- return gr.update(choices=opts,value=opts[0])
172
- def route_intent(message):
173
- df = get_df()
174
- if df.empty: return None
175
  m = message.lower()
176
- latest = df['date'].max()
 
 
 
 
177
 
178
- # Budget / underperformance
179
- if any(x in m for x in ['underperform','below budget','struggling','worst','attention','concern','risk']):
180
- if 'budget_usd' not in df.columns: return "No budget data available."
181
- recent = df[df['date'] >= latest - timedelta(days=7)]
182
  perf = recent.groupby(['complex','brand']).apply(
183
  lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum() if x['budget_usd'].sum()>0 else 1
184
- ).reset_index(name='ach')
185
- under = perf[perf['ach']<0.90].sort_values('ach')
186
- if under.empty: return "All sites above 90% budget achievement in last 7 days."
187
- return "Below 90% budget (last 7 days):\n" + "\n".join(
188
- ["- {}/{}: {:.1f}%".format(r.complex,r.brand,r.ach*100) for r in under.itertuples()])
189
-
190
- if any(x in m for x in ['budget','achievement','variance','target']):
191
- if 'budget_usd' not in df.columns: return "No budget data."
192
- overall = df['actual_revenue_usd'].sum()/df['budget_usd'].sum()*100 if df['budget_usd'].sum()>0 else 0
193
- cx_ach = df.groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0).sort_values(ascending=False)
194
- br_ach = df.groupby('brand').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0).sort_values(ascending=False)
195
- return "Overall budget achievement: {:.1f}%\nBy complex:\n{}\nBy brand:\n{}".format(
196
- overall,
197
- "\n".join(["- {}: {:.1f}%".format(cx,v) for cx,v in cx_ach.items()]),
198
- "\n".join(["- {}: {:.1f}%".format(br,v) for br,v in br_ach.items()]))
199
-
200
- # Prior period comparisons
201
- if any(x in m for x in ['prior month','last month','sdlm','vs month','month on month']):
202
- if 'prior_month_actual' not in df.columns: return "No prior month data."
203
- act=df['actual_revenue_usd'].sum(); pm=df['prior_month_actual'].sum()
204
- cx = df.groupby('complex').agg(actual=('actual_revenue_usd','sum'),pm=('prior_month_actual','sum'))
205
- lines = ["vs Prior Month β€” Overall: ${:,.0f} vs ${:,.0f} ({:+.1f}%)".format(act,pm,(act-pm)/pm*100 if pm else 0)]
206
- lines += ["- {}: ${:,.0f} vs ${:,.0f} ({:+.1f}%)".format(r.Index,r.actual,r.pm,(r.actual-r.pm)/r.pm*100 if r.pm else 0) for r in cx.itertuples()]
207
  return "\n".join(lines)
208
 
209
- if any(x in m for x in ['prior year','last year','sdly','vs year','year on year']):
210
- if 'prior_year_actual' not in df.columns: return "No prior year data."
211
- act=df['actual_revenue_usd'].sum(); py=df['prior_year_actual'].sum()
212
- cx = df.groupby('complex').agg(actual=('actual_revenue_usd','sum'),py=('prior_year_actual','sum'))
213
- lines = ["vs Prior Year β€” Overall: ${:,.0f} vs ${:,.0f} ({:+.1f}%)".format(act,py,(act-py)/py*100 if py else 0)]
214
- lines += ["- {}: ${:,.0f} vs ${:,.0f} ({:+.1f}%)".format(r.Index,r.actual,r.py,(r.actual-r.py)/r.py*100 if r.py else 0) for r in cx.itertuples()]
 
215
  return "\n".join(lines)
216
 
217
- # Daily / weekly / period summaries
218
- if any(x in m for x in ['yesterday','today','latest day','last day']):
219
- day = df[df['date']==latest]
220
- if day.empty: return "No data for {}.".format(latest.strftime('%b %d'))
221
  rev = day['actual_revenue_usd'].sum()
222
- bud = day['budget_usd'].sum() if 'budget_usd' in day.columns else 0
223
- ach = " ({:.1f}% of budget)".format(rev/bud*100) if bud>0 else ""
224
- cx_b = "\n".join([" - {}: ${:,.0f}".format(r.complex,r.actual_revenue_usd) for r in day.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
225
- return "{} revenue: ${:,.0f}{}\nBy complex:\n{}".format(latest.strftime('%b %d'),rev,ach,cx_b)
226
 
 
227
  if any(x in m for x in ['7-day','7 day','last week','this week','weekly','week']):
228
- w = df[df['date'] >= latest - timedelta(days=7)]
229
- total = w['actual_revenue_usd'].sum(); davg = w.groupby('date')['actual_revenue_usd'].sum().mean()
230
- bud = w['budget_usd'].sum() if 'budget_usd' in w.columns else 0
231
- ach = " ({:.1f}% of budget)".format(total/bud*100) if bud>0 else ""
232
- cx_b = "\n".join([" - {}: ${:,.0f}".format(r.complex,r.actual_revenue_usd) for r in w.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
233
- return "Last 7 days: ${:,.0f} total{}, avg ${:,.0f}/day\nBy complex:\n{}".format(total,ach,davg,cx_b)
234
 
 
235
  if any(x in m for x in ['30-day','30 day','this month','monthly','month to date','mtd']):
236
- w = df[df['date'] >= latest - timedelta(days=30)]
237
  total = w['actual_revenue_usd'].sum()
238
- bud = w['budget_usd'].sum() if 'budget_usd' in w.columns else 0
239
- ach = " ({:.1f}% of budget)".format(total/bud*100) if bud>0 else ""
240
- return "Last 30 days: ${:,.0f} total{}".format(total,ach)
241
 
242
- # Customer metrics
243
  if any(x in m for x in ['customer','spend per','avg spend','average spend','foot traffic','footfall']):
244
- if 'customer_count' not in df.columns or df['customer_count'].sum()==0:
245
- return "No customer count data available."
246
- avs = df[df['customer_count']>0].groupby('complex').apply(
247
  lambda x: x['actual_revenue_usd'].sum()/x['customer_count'].sum()).sort_values(ascending=False)
248
- total_c = int(df['customer_count'].sum())
249
- return "Total customers: {:,}\nAvg spend per customer:\n{}".format(
250
- total_c, "\n".join(["- {}: ${:.2f}".format(cx,v) for cx,v in avs.items()]))
251
 
252
  # Counter / throughput
253
  if any(x in m for x in ['counter','till','throughput','revenue per counter']):
254
- if 'revenue_per_counter' not in df.columns: return "No counter data."
255
- rpc = df[df['revenue_per_counter']>0].groupby('complex')['revenue_per_counter'].mean().sort_values(ascending=False)
256
- return "Revenue per counter:\n" + "\n".join(["- {}: ${:,.0f}".format(cx,v) for cx,v in rpc.items()])
257
 
258
  # Day of week
259
  if any(x in m for x in ['best day','peak day','busiest','day of week','highest day']):
260
- dow = df.groupby(df['date'].dt.day_name())['actual_revenue_usd'].mean()
261
  order = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
262
  dow = dow.reindex([d for d in order if d in dow.index])
263
- return "Average daily revenue by day:\n" + "\n".join(
264
- ["- {}: ${:,.0f}".format(d,v) for d,v in dow.sort_values(ascending=False).items()])
265
 
266
  # Rankings
267
- if any(x in m for x in ['rank','ranking','all complex','all brand','compare all','overview']):
268
- cx = df.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False)
269
- br = df.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False)
270
- bud_cx = df.groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if 'budget_usd' in x.columns and x['budget_usd'].sum()>0 else 0) if 'budget_usd' in df.columns else None
271
- cx_lines = "\n".join(["{}. {}: ${:,.0f}{}".format(i+1,n,v," ({:.0f}% bud)".format(bud_cx[n]) if bud_cx is not None else "") for i,(n,v) in enumerate(cx.items())])
272
- br_lines = "\n".join(["{}. {}: ${:,.0f}".format(i+1,n,v) for i,(n,v) in enumerate(br.items())])
273
- return "Complex ranking:\n{}\n\nBrand ranking:\n{}".format(cx_lines,br_lines)
274
-
275
- # Top / bottom
276
- if any(x in m for x in ['top','best','highest','leading','number one','#1']):
277
- g_cx=df.groupby('complex')['actual_revenue_usd'].sum(); g_br=df.groupby('brand')['actual_revenue_usd'].sum()
278
- return "Top complex: {} (${:,.0f})\nTop brand: {} (${:,.0f})".format(g_cx.idxmax(),g_cx.max(),g_br.idxmax(),g_br.max())
 
279
 
 
280
  if any(x in m for x in ['worst','lowest','bottom','poor','weakest']):
281
- g_cx=df.groupby('complex')['actual_revenue_usd'].sum(); g_br=df.groupby('brand')['actual_revenue_usd'].sum()
282
- return "Lowest complex: {} (${:,.0f})\nLowest brand: {} (${:,.0f})".format(g_cx.idxmin(),g_cx.min(),g_br.idxmin(),g_br.min())
 
283
 
284
- if any(x in m for x in ['total revenue','overall revenue','total']):
285
- bud = df['budget_usd'].sum() if 'budget_usd' in df.columns else 0
286
- ach = " ({:.1f}% of budget)".format(df['actual_revenue_usd'].sum()/bud*100) if bud>0 else ""
287
- return "Total revenue: ${:,.0f}{} across {:,} records".format(df['actual_revenue_usd'].sum(),ach,len(df))
 
288
 
289
- # Complex Γ— Brand cross-query
290
  for cx in COMPLEXES:
291
  for br in BRANDS:
292
  if cx.lower() in m and br.lower() in m:
293
- sub=df[(df['complex']==cx)&(df['brand']==br)]
294
  if not sub.empty:
295
- bud=sub['budget_usd'].sum() if 'budget_usd' in sub.columns else 0
296
- ach=" ({:.1f}% budget)".format(sub['actual_revenue_usd'].sum()/bud*100) if bud>0 else ""
297
- return "{}/{}: ${:,.0f} total{}, ${:,.0f}/day avg".format(
298
- cx,br,sub['actual_revenue_usd'].sum(),ach,sub['actual_revenue_usd'].mean())
299
 
300
  for cx in COMPLEXES:
301
  if cx.lower() in m:
302
- sub=df[df['complex']==cx]
303
- bud=sub['budget_usd'].sum() if 'budget_usd' in sub.columns else 0
304
- ach=" ({:.1f}% of budget)".format(sub['actual_revenue_usd'].sum()/bud*100) if bud>0 else ""
305
- br_b="\n".join([" - {}: ${:,.0f}".format(r.brand,r.actual_revenue_usd) for r in sub.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
306
- return "{}: ${:,.0f} total{}\nBy brand:\n{}".format(cx,sub['actual_revenue_usd'].sum(),ach,br_b)
307
 
308
  for br in BRANDS:
309
  if br.lower() in m:
310
- sub=df[df['brand']==br]
311
- bud=sub['budget_usd'].sum() if 'budget_usd' in sub.columns else 0
312
- ach=" ({:.1f}% of budget)".format(sub['actual_revenue_usd'].sum()/bud*100) if bud>0 else ""
313
- return "{}: ${:,.0f} total{}".format(br,sub['actual_revenue_usd'].sum(),ach)
314
 
315
  return None
316
- def build_system_prompt():
317
- df = get_df()
318
- if df.empty: return "No data loaded. Tell the user to refresh data."
319
- cx_rev = df.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False)
320
- br_rev = df.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False)
321
- has_bud = 'budget_usd' in df.columns and df['budget_usd'].sum() > 0
322
- cx_bud = df.groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0) if has_bud else None
323
- br_bud = df.groupby('brand').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0) if has_bud else None
324
- date_range = df['date'].min().strftime('%b %d, %Y')+" to "+df['date'].max().strftime('%b %d, %Y')
325
- cx_lines = "\n".join(["- "+cx+": ${:,.0f}".format(v)+((" ({:.1f}% of budget)".format(cx_bud[cx])) if cx_bud is not None and cx in cx_bud else "") for cx,v in cx_rev.items()])
326
- br_lines = "\n".join(["- "+br+": ${:,.0f}".format(v)+((" ({:.1f}% of budget)".format(br_bud[br])) if br_bud is not None and br in br_bud else "") for br,v in br_rev.items()])
327
- top_cx = cx_rev.idxmax(); top_br = br_rev.idxmax()
328
- total = df['actual_revenue_usd'].sum()
329
- bud_ach = (total / df['budget_usd'].sum() * 100) if 'budget_usd' in df.columns and df['budget_usd'].sum()>0 else None
330
- return f"""You are a QSR operations intelligence assistant for Savanna QSR Group, Zimbabwe.
331
- You have access to live operational data from {len(df)} records covering {date_range}.
332
-
333
- TOTAL REVENUE: ${total:,.2f}{(" (budget achievement: {:.1f}%)".format(bud_ach)) if bud_ach else ""}
334
- TOP COMPLEX: {top_cx}
335
- TOP BRAND: {top_br}
336
 
337
  REVENUE BY COMPLEX:
338
  {cx_lines}
@@ -340,77 +529,165 @@ REVENUE BY COMPLEX:
340
  REVENUE BY BRAND:
341
  {br_lines}
342
 
343
- COMPLEXES: {', '.join(COMPLEXES)}
344
- BRANDS: {', '.join(BRANDS)}
345
 
346
- Answer questions directly and concisely using the data above. Use $ formatting for all revenue figures. If asked which is best/top/highest, use the data provided to give a specific answer."""
347
 
348
- def chat(message, history):
349
  if not message or not message.strip(): return ""
350
- data_answer = route_intent(message)
351
- system = build_system_prompt()
352
- messages = [{"role":"system","content":system}]
 
353
  for h in (history or []):
354
- if isinstance(h, dict): messages.append({"role":h["role"],"content":h["content"]})
355
- elif isinstance(h, (list,tuple)) and len(h)==2:
356
- if h[0]: messages.append({"role":"user","content":str(h[0])})
357
- if h[1]: messages.append({"role":"assistant","content":str(h[1])})
358
- messages.append({"role":"user","content":message+"\n\n[DATA]: "+str(data_answer) if data_answer else message})
359
  try:
360
- r2 = _http.post("https://api.openai.com/v1/chat/completions", headers={"Authorization":"Bearer "+os.environ.get("OPENAI_API_KEY",""),"Content-Type":"application/json"}, json={"model":"gpt-4o-mini","messages":messages,"temperature":0.2,"max_tokens":600}); resp = r2.json()
361
- return resp["choices"][0]["message"]["content"]
362
- except Exception as e: return "Error: "+str(e)
363
- css = """
364
- body,.gradio-container{background:#050d1a!important;font-family:Arial,sans-serif!important;}
365
- button[class*="tab-"]{color:#7fb3d3!important;background:transparent!important;border:none!important;border-bottom:3px solid transparent!important;padding:10px 18px!important;font-size:13px!important;}
366
- button[class*="tab-"][class*="selected"],div[role="tablist"] button[aria-selected="true"]{color:#c9a84c!important;border-bottom:3px solid #c9a84c!important;font-weight:700!important;}
367
- .gradio-container *{color:#c8d8f0;}
368
- .gradio-container input,.gradio-container textarea{background:#0a1628!important;color:#c8d8f0!important;border:1px solid #1a3a6e!important;border-radius:6px!important;}
369
- button.primary,button[variant="primary"]{background:#c9a84c!important;color:#0a1628!important;font-weight:700!important;border:none!important;border-radius:6px!important;}
370
- button.secondary,button[variant="secondary"]{background:#1a3a6e!important;color:#c8d8f0!important;border:1px solid #c9a84c!important;border-radius:6px!important;}
371
- .gradio-container .block,.gradio-container .form,.gradio-container .panel{background:#0a1628!important;border:1px solid #1a3a6e!important;border-radius:8px!important;}
372
- div[class*="chatbot"],.chatbot{background:#040c1a!important;border-radius:12px!important;}
373
- .gradio-container .prose{color:#c8d8f0!important;}
374
- .gradio-container .prose strong{color:#c9a84c!important;}
375
- footer{display:none!important;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  """
377
- with gr.Blocks(title="Savanna QSR Intelligence", css=css) as demo:
 
 
 
378
  kpi_header = gr.HTML(value=build_kpi_html())
 
 
 
 
 
 
 
 
 
379
  with gr.Tabs():
380
- with gr.TabItem("Dashboard"):
 
 
381
  with gr.Row():
382
- period_sel = gr.Radio(choices=['Last 7 Days','Last 30 Days','Last 90 Days','MTD','All Time'],value='All Time',label="Period")
383
- with gr.Column(scale=0, min_width=200):
384
- dash_btn = gr.Button("Load Dashboard", variant="primary")
385
- refresh_btn = gr.Button("Refresh Data", variant="secondary")
386
- refresh_msg = gr.Markdown()
387
- with gr.Row(): ch1=gr.Plot(show_label=False); ch2=gr.Plot(show_label=False)
388
- with gr.Row(): ch3=gr.Plot(show_label=False); ch4=gr.Plot(show_label=False)
389
- with gr.Row(): ch5=gr.Plot(show_label=False); ch6=gr.Plot(show_label=False)
390
- dash_btn.click(build_dashboard,[period_sel],[kpi_header,ch1,ch2,ch3,ch4,ch5,ch6])
391
- period_sel.change(build_dashboard,[period_sel],[kpi_header,ch1,ch2,ch3,ch4,ch5,ch6])
392
- refresh_btn.click(refresh_data,[],[kpi_header,refresh_msg])
393
- with gr.TabItem("Forecast"):
394
  with gr.Row():
395
- seg_type = gr.Radio(choices=['Overall','By Complex','By Brand','Complex x Brand'],value='Overall',label="Segment")
396
- seg_name = gr.Dropdown(choices=['All'],value='All',label="Name",interactive=True)
397
- horizon = gr.Radio(choices=["7","14","30","60"],value="30",label="Horizon (days)")
398
- fc_btn = gr.Button("Generate", variant="primary")
399
- fc_chart = gr.Plot(show_label=False); fc_summary = gr.Markdown()
400
- seg_type.change(update_seg_choices,[seg_type],[seg_name])
401
- fc_btn.click(generate_forecast,[seg_type,seg_name,horizon],[fc_chart,fc_summary])
402
- with gr.TabItem("Intelligence Chat"):
403
- chatbot_box = gr.Chatbot(height=420,show_label=False)
404
  with gr.Row():
405
- chat_input = gr.Textbox(placeholder="Ask about Savanna QSR...",show_label=False,scale=9,container=False)
406
- chat_send = gr.Button("Send",variant="primary",scale=1)
407
- def respond(message, history):
408
- if not message or not message.strip(): return history or [], ""
409
- reply = chat(message, history or [])
410
- h = list(history or []); h.append((message, reply))
411
- return h, ""
412
- chat_send.click(respond,[chat_input,chatbot_box],[chatbot_box,chat_input])
413
- chat_input.submit(respond,[chat_input,chatbot_box],[chatbot_box,chat_input])
414
- gr.HTML('<div style="text-align:center;margin-top:16px;padding:12px;border-top:1px solid #1a3a6e;"><p style="color:#c9a84c;font-size:11px;font-weight:700;letter-spacing:2px;">NETRISYL INSIGHTS</p><p style="color:#4a6a9e;font-size:11px;">Data - Analytics - Intelligence</p></div>')
415
- demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, time, warnings
2
  import gradio as gr
3
  import pandas as pd
4
  import numpy as np
5
  import plotly.graph_objects as go
 
 
6
  import requests as _http
7
+ from datetime import datetime, timedelta
8
  warnings.filterwarnings('ignore')
9
+
10
+ # ── Gradio 5.x schema bug patch ───────────────────────────────────────────────
11
  try:
12
  import gradio_client.utils as _gcu
13
+ _orig = _gcu._json_schema_to_python_type
14
+ def _safe(s, d):
15
+ if not isinstance(s, dict): return "any"
16
+ try: return _orig(s, d)
17
+ except: return "any"
18
+ _gcu._json_schema_to_python_type = _safe
19
+ except: pass
 
20
 
21
+ # ── Config ────────────────────────────────────────────────────────────────────
22
  SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
23
  SUPABASE_KEY = os.environ.get("SUPABASE_KEY", "")
24
+ OPENAI_KEY = os.environ.get("OPENAI_API_KEY", "")
25
+ COMPLEXES = ['Westgate Mall', 'City Centre', 'Eastpark', 'Northgate']
26
+ BRANDS = ['Flame & Grill', 'Pie Palace', 'Chill Creamery', 'Sizzle Wings']
27
+
28
+ # Stores Intelligence colour palette
29
+ C_GOLD = '#c9a84c'
30
+ C_NAVY = '#1e2d5e'
31
+ C_TEAL = '#1abc9c'
32
+ C_RED = '#e74c3c'
33
+ C_PURPLE = '#9b59b6'
34
+ C_BG = '#0a1628'
35
+ C_PLOT = '#0d1f38'
36
+ C_GRID = '#1a3a6e'
37
+ C_TEXT = '#c8d8f0'
38
+ BAR_COLS = [C_GOLD, C_NAVY, C_TEAL, C_RED, C_PURPLE, '#2ecc71', '#e67e22', '#3498db']
39
+
40
  _cache = {'df': pd.DataFrame(), 'loaded_at': 0}
41
+ CACHE_TTL = 300
 
 
42
 
43
+ # ── Data layer β€” paginated so we get ALL rows ─────────────────────────────────
44
  def load_data():
45
+ if not SUPABASE_URL or not SUPABASE_KEY:
46
+ print("Supabase not configured"); return pd.DataFrame()
47
  try:
48
+ all_rows, offset, batch = [], 0, 1000
49
+ while True:
50
+ r = _http.get(
51
+ f"{SUPABASE_URL}/rest/v1/daily_input?select=*&order=date&limit={batch}&offset={offset}",
52
+ headers={"apikey": SUPABASE_KEY, "Authorization": "Bearer " + SUPABASE_KEY}
53
+ )
54
+ if r.status_code != 200: print("HTTP", r.status_code); break
55
+ rows = r.json()
56
+ if not rows: break
57
+ all_rows.extend(rows)
58
+ if len(rows) < batch: break
59
+ offset += batch
60
+ if not all_rows: return pd.DataFrame()
61
+ df = pd.DataFrame(all_rows)
62
+ nums = ['actual_revenue_usd','budget_usd','customer_count','prior_month_actual',
63
+ 'prior_year_actual','variance_vs_budget','variance_pct',
64
+ 'avg_spend_per_cust','revenue_per_counter','counters_open',
65
+ 'vs_prior_month_pct','vs_prior_year_pct','is_holiday']
66
+ for c in nums:
67
  if c in df.columns: df[c] = pd.to_numeric(df[c], errors='coerce').fillna(0)
68
+ df['date'] = pd.to_datetime(df['date'], errors='coerce')
69
+ df = df.dropna(subset=['date','actual_revenue_usd'])
70
+ df = df[df['actual_revenue_usd'] > 0].sort_values('date').reset_index(drop=True)
71
+ print(f"Loaded {len(df)} rows ({df['date'].min().date()} β†’ {df['date'].max().date()})")
72
+ return df
73
+ except Exception as e:
74
+ print("Load error:", e); return pd.DataFrame()
75
+
76
  def get_df():
77
  now = time.time()
78
  if now - _cache['loaded_at'] > CACHE_TTL or _cache['df'].empty:
79
  fresh = load_data()
80
+ if not fresh.empty:
81
+ _cache['df'] = fresh
82
+ _cache['loaded_at'] = now
83
  return _cache['df']
84
+
85
+ def filter_df(date_from, date_to):
86
+ df = get_df()
87
+ if df.empty: return df
88
+ try:
89
+ if date_from and str(date_from).strip():
90
+ df = df[df['date'] >= pd.to_datetime(str(date_from).strip())]
91
+ if date_to and str(date_to).strip():
92
+ df = df[df['date'] <= pd.to_datetime(str(date_to).strip())]
93
+ except: pass
94
+ return df
95
+
96
+ print("Loading data..."); _ = get_df()
97
+
98
+ # ── Helpers ───────────────────────────────────────────────────────────────────
99
  def fmt(v):
100
+ if v >= 1e6: return f"${v/1e6:.2f}M"
101
+ if v >= 1e3: return f"${v/1e3:.0f}K"
102
+ return f"${v:,.0f}"
103
+
104
+ def dark_layout(title, height=320, margin=None):
105
+ m = margin or dict(l=150, r=30, t=45, b=40)
106
+ return dict(
107
+ title=dict(text=title, font=dict(color=C_GOLD, size=13), x=0),
108
+ paper_bgcolor=C_BG, plot_bgcolor=C_PLOT,
109
+ font=dict(color=C_TEXT, family='Arial', size=11),
110
+ height=height,
111
+ xaxis=dict(gridcolor=C_GRID, linecolor=C_GRID, tickfont=dict(color=C_TEXT), title_font=dict(color=C_TEXT)),
112
+ yaxis=dict(gridcolor=C_GRID, linecolor=C_GRID, tickfont=dict(color=C_TEXT), title_font=dict(color=C_TEXT)),
113
+ legend=dict(bgcolor='rgba(10,22,40,0.85)', bordercolor=C_GRID, borderwidth=1, font=dict(color=C_TEXT)),
114
+ margin=m
115
+ )
116
+
117
+ def horiz_bar(x_vals, y_labels, colors, texts, title, height=280):
118
+ """Horizontal bar with values inside, matching Stores Intelligence style."""
119
+ fig = go.Figure()
120
+ # Pick text color: dark for gold, white for navy/dark
121
+ text_colors = []
122
+ for c in (colors if isinstance(colors, list) else [colors]*len(x_vals)):
123
+ text_colors.append('#0a1628' if c in (C_GOLD, C_TEAL, '#2ecc71') else '#ffffff')
124
+ fig.add_trace(go.Bar(
125
+ x=x_vals, y=y_labels, orientation='h',
126
+ marker=dict(color=colors if isinstance(colors, list) else [colors]*len(x_vals),
127
+ line=dict(color=C_GRID, width=1)),
128
+ text=texts,
129
+ textposition='inside',
130
+ insidetextanchor='middle',
131
+ textfont=dict(color=text_colors if len(set(text_colors))>1 else text_colors[0],
132
+ size=12, family='Arial')
133
+ ))
134
+ fig.update_layout(**dark_layout(title, height=height))
135
+ return fig
136
+
137
+ # ── KPI header ────────────────────────────────────────────────────────────────
138
  def build_kpi_html(dff=None):
139
+ if dff is None: dff = get_df()
140
+ if dff is not None and not isinstance(dff, pd.DataFrame): dff = get_df()
141
+ if dff is None or dff.empty:
142
+ rev, ach, tc, tb, dr = "--", "--", "--", "--", "No data"
143
  else:
144
+ rev = fmt(dff['actual_revenue_usd'].sum())
145
  bud = dff['budget_usd'].sum() if 'budget_usd' in dff.columns else 0
146
+ ach = f"{dff['actual_revenue_usd'].sum()/bud*100:.1f}%" if bud > 0 else "--"
147
+ tc = dff.groupby('complex')['actual_revenue_usd'].sum().idxmax()
148
+ tb = dff.groupby('brand')['actual_revenue_usd'].sum().idxmax()
149
+ dr = f"{dff['date'].min().strftime('%b %d, %Y')} β†’ {dff['date'].max().strftime('%b %d, %Y')}"
150
+ return f'''<div style="background:linear-gradient(135deg,#0d1b2a,#1a3a5c);
151
+ padding:16px 24px;border-radius:10px;border-left:4px solid {C_GOLD};margin-bottom:6px;">
152
+ <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
153
+ <div>
154
+ <h2 style="color:#fff;margin:0;font-size:19px;font-weight:700;">πŸ” Savanna QSR Intelligence</h2>
155
+ <p style="color:#aed6f1;margin:3px 0 0;font-size:12px;">Live Operations Intelligence Β· Zimbabwe Β· Powered by Supabase</p>
156
+ </div>
157
+ <p style="color:{C_GOLD};margin:0;font-size:10px;font-weight:700;letter-spacing:2px;">NETRISYL INSIGHTS</p>
158
+ </div>
159
+ <div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;">
160
+ {''.join([f'<div style="background:rgba(10,22,40,0.75);padding:8px 16px;border-radius:7px;border:1px solid {C_GRID};text-align:center;min-width:80px;"><div style="color:{C_GOLD};font-size:16px;font-weight:700;">{v}</div><div style="color:#7fb3d3;font-size:10px;">{l}</div></div>'
161
+ for v,l in [(rev,"Total Revenue"),(ach,"Budget Ach."),(tc,"Top Complex"),(tb,"Top Brand"),(dr,"Date Range")]])}
162
+ </div>
163
+ </div>'''
164
+
165
+ # ── Dashboard ─────────────────────────────────────────────────────────────────
166
+ def build_dashboard(date_from, date_to):
167
+ dff = filter_df(date_from, date_to)
168
+ kpi = build_kpi_html(dff)
169
+ if dff.empty:
170
+ e = go.Figure().update_layout(**dark_layout("No data β€” click Refresh"))
171
+ return kpi, e, e, e, e, e, e
172
+
173
+ # 1. Revenue by Complex β€” gold actual bar + navy budget overlay
174
+ cx = dff.groupby('complex').agg(
175
+ actual=('actual_revenue_usd','sum'), budget=('budget_usd','sum')
176
+ ).reset_index().sort_values('actual', ascending=True)
177
  fig1 = go.Figure()
178
+ fig1.add_trace(go.Bar(
179
+ name='Budget', x=cx['budget'], y=cx['complex'], orientation='h',
180
+ marker=dict(color='#2a4a8a', line=dict(color=C_GRID, width=1)), opacity=0.55
181
+ ))
182
+ fig1.add_trace(go.Bar(
183
+ name='Actual', x=cx['actual'], y=cx['complex'], orientation='h',
184
+ marker=dict(color=C_GOLD, line=dict(color=C_NAVY, width=1)),
185
+ text=[fmt(v) for v in cx['actual']], textposition='inside',
186
+ insidetextanchor='middle', textfont=dict(color='#0a1628', size=12, family='Arial')
187
+ ))
188
+ fig1.update_layout(**dark_layout("Revenue by Complex β€” Actual vs Budget", height=300),
189
+ barmode='overlay',
190
+ xaxis_tickprefix='$', xaxis_tickformat=',.0f')
191
+
192
+ # 2. Revenue by Brand
193
+ br = dff.groupby('brand')['actual_revenue_usd'].sum().reset_index().sort_values('actual_revenue_usd', ascending=True)
194
+ bud_br = dff.groupby('brand')['budget_usd'].sum() if 'budget_usd' in dff.columns else None
195
+ texts = []
196
+ for _, row in br.iterrows():
197
+ bv = bud_br[row['brand']] if bud_br is not None and bud_br.sum() > 0 else 0
198
+ ach = f" {row['actual_revenue_usd']/bv*100:.0f}%" if bv > 0 else ""
199
+ texts.append(f"{fmt(row['actual_revenue_usd'])}{ach}")
200
+ fig2 = go.Figure(go.Bar(
201
+ x=br['actual_revenue_usd'], y=br['brand'], orientation='h',
202
+ marker=dict(color=BAR_COLS[:len(br)], line=dict(color=C_GRID, width=1)),
203
+ text=texts, textposition='inside', insidetextanchor='middle',
204
+ textfont=dict(color='#ffffff', size=12, family='Arial')
205
+ ))
206
+ fig2.update_layout(**dark_layout("Revenue by Brand", height=280),
207
+ xaxis_tickprefix='$', xaxis_tickformat=',.0f')
208
+
209
+ # 3. Daily Revenue Trend
210
  daily = dff.groupby('date')['actual_revenue_usd'].sum().reset_index()
211
  fig3 = go.Figure()
212
+ fig3.add_trace(go.Scatter(
213
+ x=daily['date'], y=daily['actual_revenue_usd'], name='Actual',
214
+ line=dict(color=C_GOLD, width=2.5), fill='tozeroy',
215
+ fillcolor='rgba(201,168,76,0.10)'
216
+ ))
217
+ if 'budget_usd' in dff.columns:
218
+ daily_b = dff.groupby('date')['budget_usd'].sum().reset_index()
219
+ fig3.add_trace(go.Scatter(
220
+ x=daily_b['date'], y=daily_b['budget_usd'], name='Budget',
221
+ line=dict(color='#4a6a9e', width=1.5, dash='dot')
222
+ ))
223
+ fig3.update_layout(**dark_layout("Daily Revenue Trend", height=340, margin=dict(l=80,r=30,t=45,b=50)),
224
+ hovermode='x unified',
225
+ yaxis_tickprefix='$', yaxis_tickformat=',.0f')
226
+
227
+ # 4. Avg Spend Per Customer
228
+ if 'customer_count' in dff.columns and dff['customer_count'].sum() > 0:
229
+ avs = dff[dff['customer_count']>0].groupby('complex').apply(
230
+ lambda x: x['actual_revenue_usd'].sum()/x['customer_count'].sum()
231
+ ).reset_index(name='avg').sort_values('avg', ascending=True)
232
+ fig4 = go.Figure(go.Bar(
233
+ x=avs['avg'], y=avs['complex'], orientation='h',
234
+ marker=dict(color=C_TEAL, line=dict(color=C_NAVY, width=1)),
235
+ text=[f"${v:.2f}" for v in avs['avg']], textposition='inside',
236
+ insidetextanchor='middle', textfont=dict(color='#0a1628', size=12, family='Arial')
237
+ ))
238
+ fig4.update_layout(**dark_layout("Avg Spend Per Customer", height=280),
239
+ xaxis_tickprefix='$', xaxis_tickformat=',.2f')
240
+ else:
241
+ fig4 = go.Figure().update_layout(**dark_layout("No customer data", height=280))
242
+
243
+ # 5. Budget Achievement Heatmap
244
+ if 'budget_usd' in dff.columns and dff['budget_usd'].sum() > 0:
245
+ try:
246
+ heat = dff.groupby(['complex','brand']).apply(
247
+ lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100
248
+ if x['budget_usd'].sum()>0 else 0
249
+ ).reset_index(name='ach')
250
+ pivot = heat.pivot(index='complex', columns='brand', values='ach').fillna(0)
251
+ fig5 = go.Figure(go.Heatmap(
252
+ z=pivot.values, x=pivot.columns.tolist(), y=pivot.index.tolist(),
253
+ colorscale=[[0,'#c0392b'],[0.8,'#f39c12'],[1,'#2ecc71']],
254
+ zmid=100, zmin=70, zmax=130,
255
+ text=[[f"{v:.0f}%" for v in row] for row in pivot.values],
256
+ texttemplate="%{text}", textfont=dict(color='white', size=12),
257
+ colorbar=dict(tickfont=dict(color=C_TEXT))
258
+ ))
259
+ fig5.update_layout(**dark_layout("Budget Achievement % (Complex Γ— Brand)", height=280,
260
+ margin=dict(l=130,r=30,t=45,b=80)))
261
+ except:
262
+ fig5 = go.Figure().update_layout(**dark_layout("Budget heatmap unavailable", height=280))
263
+ else:
264
+ fig5 = go.Figure().update_layout(**dark_layout("No budget data", height=280))
265
+
266
+ # 6. Actual vs Prior Month vs Prior Year
267
+ has_pm = 'prior_month_actual' in dff.columns and dff['prior_month_actual'].sum() > 0
268
+ has_py = 'prior_year_actual' in dff.columns and dff['prior_year_actual'].sum() > 0
269
+ comp = dff.groupby('complex').agg(
270
+ actual=('actual_revenue_usd','sum'),
271
+ **({'pm':('prior_month_actual','sum')} if has_pm else {}),
272
+ **({'py':('prior_year_actual','sum')} if has_py else {})
273
+ ).reset_index()
274
  fig6 = go.Figure()
275
+ if has_py:
276
+ fig6.add_trace(go.Bar(name='Prior Year', x=comp['complex'], y=comp['py'],
277
+ marker=dict(color=C_NAVY, line=dict(color=C_GRID,width=1)),
278
+ text=[fmt(v) for v in comp['py']], textposition='inside',
279
+ insidetextanchor='middle', textfont=dict(color='#ffffff',size=11)))
280
+ if has_pm:
281
+ fig6.add_trace(go.Bar(name='Prior Month', x=comp['complex'], y=comp['pm'],
282
+ marker=dict(color=C_TEAL, line=dict(color=C_GRID,width=1)),
283
+ text=[fmt(v) for v in comp['pm']], textposition='inside',
284
+ insidetextanchor='middle', textfont=dict(color='#0a1628',size=11)))
285
+ fig6.add_trace(go.Bar(name='This Period', x=comp['complex'], y=comp['actual'],
286
+ marker=dict(color=C_GOLD, line=dict(color=C_NAVY,width=1)),
287
+ text=[fmt(v) for v in comp['actual']], textposition='inside',
288
+ insidetextanchor='middle', textfont=dict(color='#0a1628',size=11)))
289
+ fig6.update_layout(**dark_layout("Actual vs Prior Month vs Prior Year", height=340,
290
+ margin=dict(l=60,r=30,t=45,b=60)),
291
+ barmode='group', hovermode='x unified',
292
+ yaxis_tickprefix='$', yaxis_tickformat=',.0f')
293
+
294
+ return kpi, fig1, fig2, fig3, fig4, fig5, fig6
295
+
296
+ # ── Forecast ──────────────────────────────────────────────────────────────────
297
+ GROWTH = 0.05
298
+ DOW = {0:0.85,1:0.90,2:0.92,3:0.95,4:1.05,5:1.20,6:1.15}
299
+
300
+ def update_seg_choices(seg_type):
301
+ if seg_type == 'Overall':
302
+ return gr.update(choices=['All Complexes & Brands'], value='All Complexes & Brands')
303
+ elif seg_type == 'By Complex':
304
+ return gr.update(choices=COMPLEXES, value=COMPLEXES[0])
305
+ elif seg_type == 'By Brand':
306
+ return gr.update(choices=BRANDS, value=BRANDS[0])
307
+ else:
308
+ opts = [f"{cx} | {br}" for cx in COMPLEXES for br in BRANDS]
309
+ return gr.update(choices=opts, value=opts[0])
310
+
311
+ def generate_forecast(seg_type, seg_name, horizon, date_from, date_to):
312
  try:
313
+ df = filter_df(date_from, date_to)
314
+ if df.empty:
315
+ return go.Figure().update_layout(**dark_layout("No data for selected range")), "No data."
316
+ h = int(horizon)
317
  if seg_type == 'Overall':
318
  seg = df.groupby('date')['actual_revenue_usd'].sum().reset_index()
319
+ label = 'All Complexes & Brands'
320
  elif seg_type == 'By Complex':
321
  seg = df[df['complex']==seg_name].groupby('date')['actual_revenue_usd'].sum().reset_index()
322
  label = seg_name
 
325
  label = seg_name
326
  else:
327
  parts = seg_name.split(' | ')
328
+ seg = df[(df['complex']==parts[0])&(df['brand']==parts[1])].groupby('date')['actual_revenue_usd'].sum().reset_index() if len(parts)==2 else df.groupby('date')['actual_revenue_usd'].sum().reset_index()
 
 
 
329
  label = seg_name
330
  seg.columns = ['date','revenue']
331
  seg = seg.sort_values('date').reset_index(drop=True)
332
  if len(seg) < 7:
333
+ return go.Figure().update_layout(**dark_layout("Need at least 7 days of data for this segment")), "Insufficient data."
334
+ last = seg['date'].max()
335
+ base = float(seg['revenue'].tail(min(h, len(seg))).mean())
336
+ if np.isnan(base) or base <= 0: base = float(seg['revenue'].mean())
337
+ fc_dates = [last + timedelta(days=i+1) for i in range(h)]
338
+ fc_vals = [round(base * DOW[d.weekday()] * (1+GROWTH), 2) for d in fc_dates]
339
+ upper = [v*1.15 for v in fc_vals]
340
+ lower = [v*0.85 for v in fc_vals]
 
341
  fig = go.Figure()
342
+ fig.add_trace(go.Scatter(x=seg['date'], y=seg['revenue'], name='Historical',
343
+ line=dict(color='#4a7aae', width=1.5), opacity=0.9,
344
+ hovertemplate='%{x|%b %d}<br>$%{y:,.0f}<extra>Historical</extra>'))
345
+ fig.add_trace(go.Scatter(
346
+ x=fc_dates+fc_dates[::-1], y=upper+lower[::-1],
347
+ fill='toself', fillcolor='rgba(201,168,76,0.15)',
348
+ line=dict(color='rgba(0,0,0,0)'), name='Confidence Band', hoverinfo='skip'))
349
+ fig.add_trace(go.Scatter(x=fc_dates, y=fc_vals, name=f'{h}-Day Forecast',
350
+ line=dict(color=C_GOLD, width=2.5, dash='dash'), mode='lines+markers',
351
+ marker=dict(size=5, color=C_GOLD),
352
+ hovertemplate='%{x|%b %d}<br>$%{y:,.0f}<extra>Forecast</extra>'))
353
+ fig.add_vline(x=str(last)[:10], line_dash='dot', line_color=C_GOLD, opacity=0.5)
354
+ layout = dark_layout(f"{label} β€” {h}-Day Forecast", height=460,
355
+ margin=dict(l=80,r=30,t=60,b=50))
356
+ layout['hovermode'] = 'x unified'
357
+ layout['yaxis_tickprefix'] = '$'
358
+ layout['yaxis_tickformat'] = ',.0f'
359
+ fig.update_layout(**layout)
360
+ total = sum(fc_vals); avg = total/h
361
+ peak = max(fc_vals); peak_d = fc_dates[fc_vals.index(peak)].strftime('%b %d, %Y')
362
+ summary = f"**{h}-Day Forecast β€” {label}**\n\n| Metric | Value |\n|---|---|\n| Predicted Total | **{fmt(total)}** |\n| Daily Average | **{fmt(avg)}** |\n| Peak Day | **{fmt(peak)}** on {peak_d} |\n| Period | {fc_dates[0].strftime('%b %d')} β†’ {fc_dates[-1].strftime('%b %d, %Y')} |\n\n> *Day-of-week adjusted moving average with 5% growth factor.*"
363
  return fig, summary
364
  except Exception as e:
365
+ return go.Figure().update_layout(**dark_layout(f"Error: {e}", height=460)), f"Error: {e}"
366
+
367
+ # ── Intelligence Chat ─────────────────────────────────────────────────────────
368
+ def route_intent(message, dff):
369
+ if dff is None or dff.empty: return None
 
 
 
 
 
 
 
370
  m = message.lower()
371
+ latest = dff['date'].max()
372
+ has_bud = 'budget_usd' in dff.columns and dff['budget_usd'].sum() > 0
373
+
374
+ def ach_str(actual, budget):
375
+ return f" ({actual/budget*100:.1f}% of budget)" if budget > 0 else ""
376
 
377
+ # Underperformance
378
+ if any(x in m for x in ['underperform','below budget','struggling','worst','attention','concern','risk','flag']):
379
+ if not has_bud: return "No budget data available."
380
+ recent = dff[dff['date'] >= latest - timedelta(days=7)]
381
  perf = recent.groupby(['complex','brand']).apply(
382
  lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum() if x['budget_usd'].sum()>0 else 1
383
+ ).reset_index(name='ach').sort_values('ach')
384
+ under = perf[perf['ach'] < 0.90]
385
+ if under.empty: return "All sites above 90% budget achievement in the last 7 days. No underperformers."
386
+ return "Sites below 90% budget (last 7 days):\n" + "\n".join(
387
+ [f"- {r.complex} / {r.brand}: {r.ach*100:.1f}%" for r in under.itertuples()])
388
+
389
+ # Budget achievement
390
+ if any(x in m for x in ['budget','achievement','target','variance']):
391
+ if not has_bud: return "No budget data."
392
+ overall = dff['actual_revenue_usd'].sum()/dff['budget_usd'].sum()*100
393
+ cx_ach = dff.groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0).sort_values(ascending=False)
394
+ br_ach = dff.groupby('brand').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if x['budget_usd'].sum()>0 else 0).sort_values(ascending=False)
395
+ return f"Overall budget achievement: {overall:.1f}%\nBy complex:\n" + "\n".join([f" - {cx}: {v:.1f}%" for cx,v in cx_ach.items()]) + "\nBy brand:\n" + "\n".join([f" - {br}: {v:.1f}%" for br,v in br_ach.items()])
396
+
397
+ # Prior month
398
+ if any(x in m for x in ['prior month','last month','sdlm','month on month']):
399
+ if 'prior_month_actual' not in dff.columns or dff['prior_month_actual'].sum()==0: return "No prior month data."
400
+ act = dff['actual_revenue_usd'].sum(); pm = dff['prior_month_actual'].sum()
401
+ cx = dff.groupby('complex').agg(a=('actual_revenue_usd','sum'),p=('prior_month_actual','sum'))
402
+ lines = [f"vs Prior Month β€” Overall: {fmt(act)} vs {fmt(pm)} ({(act-pm)/pm*100:+.1f}%)"]
403
+ lines += [f" - {r.Index}: {fmt(r.a)} vs {fmt(r.p)} ({(r.a-r.p)/r.p*100:+.1f}%)" for r in cx.itertuples() if r.p>0]
 
 
404
  return "\n".join(lines)
405
 
406
+ # Prior year
407
+ if any(x in m for x in ['prior year','last year','sdly','year on year']):
408
+ if 'prior_year_actual' not in dff.columns or dff['prior_year_actual'].sum()==0: return "No prior year data."
409
+ act = dff['actual_revenue_usd'].sum(); py = dff['prior_year_actual'].sum()
410
+ cx = dff.groupby('complex').agg(a=('actual_revenue_usd','sum'),p=('prior_year_actual','sum'))
411
+ lines = [f"vs Prior Year β€” Overall: {fmt(act)} vs {fmt(py)} ({(act-py)/py*100:+.1f}%)"]
412
+ lines += [f" - {r.Index}: {fmt(r.a)} vs {fmt(r.p)} ({(r.a-r.p)/r.p*100:+.1f}%)" for r in cx.itertuples() if r.p>0]
413
  return "\n".join(lines)
414
 
415
+ # Yesterday / latest day
416
+ if any(x in m for x in ['yesterday','today','latest day','last day','daily']):
417
+ day = dff[dff['date']==latest]
418
+ if day.empty: return f"No data for {latest.strftime('%b %d')}."
419
  rev = day['actual_revenue_usd'].sum()
420
+ bud = day['budget_usd'].sum() if has_bud else 0
421
+ cx_b = "\n".join([f" - {r.complex}: {fmt(r.actual_revenue_usd)}" for r in day.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
422
+ return f"{latest.strftime('%b %d, %Y')} revenue: {fmt(rev)}{ach_str(rev,bud)}\nBy complex:\n{cx_b}"
 
423
 
424
+ # 7-day / weekly
425
  if any(x in m for x in ['7-day','7 day','last week','this week','weekly','week']):
426
+ w = dff[dff['date'] >= latest - timedelta(days=7)]
427
+ total = w['actual_revenue_usd'].sum()
428
+ bud = w['budget_usd'].sum() if has_bud else 0
429
+ davg = w.groupby('date')['actual_revenue_usd'].sum().mean()
430
+ cx_b = "\n".join([f" - {r.complex}: {fmt(r.actual_revenue_usd)}" for r in w.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
431
+ return f"Last 7 days: {fmt(total)} total{ach_str(total,bud)}, avg {fmt(davg)}/day\nBy complex:\n{cx_b}"
432
 
433
+ # 30-day / MTD
434
  if any(x in m for x in ['30-day','30 day','this month','monthly','month to date','mtd']):
435
+ w = dff[dff['date'] >= latest - timedelta(days=30)]
436
  total = w['actual_revenue_usd'].sum()
437
+ bud = w['budget_usd'].sum() if has_bud else 0
438
+ return f"Last 30 days: {fmt(total)} total{ach_str(total,bud)}"
 
439
 
440
+ # Customer / spend
441
  if any(x in m for x in ['customer','spend per','avg spend','average spend','foot traffic','footfall']):
442
+ if 'customer_count' not in dff.columns or dff['customer_count'].sum()==0: return "No customer count data."
443
+ avs = dff[dff['customer_count']>0].groupby('complex').apply(
 
444
  lambda x: x['actual_revenue_usd'].sum()/x['customer_count'].sum()).sort_values(ascending=False)
445
+ tc = int(dff['customer_count'].sum())
446
+ return f"Total customers: {tc:,}\nAvg spend per customer:\n" + "\n".join([f" - {cx}: ${v:.2f}" for cx,v in avs.items()])
 
447
 
448
  # Counter / throughput
449
  if any(x in m for x in ['counter','till','throughput','revenue per counter']):
450
+ if 'revenue_per_counter' not in dff.columns or dff['revenue_per_counter'].sum()==0: return "No counter data."
451
+ rpc = dff[dff['revenue_per_counter']>0].groupby('complex')['revenue_per_counter'].mean().sort_values(ascending=False)
452
+ return "Revenue per counter:\n" + "\n".join([f" - {cx}: {fmt(v)}" for cx,v in rpc.items()])
453
 
454
  # Day of week
455
  if any(x in m for x in ['best day','peak day','busiest','day of week','highest day']):
456
+ dow = dff.groupby(dff['date'].dt.day_name())['actual_revenue_usd'].mean()
457
  order = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
458
  dow = dow.reindex([d for d in order if d in dow.index])
459
+ return "Avg daily revenue by day of week:\n" + "\n".join([f" - {d}: {fmt(v)}" for d,v in dow.sort_values(ascending=False).items()])
 
460
 
461
  # Rankings
462
+ if any(x in m for x in ['rank','ranking','all complex','all brand','compare all','overview','summary']):
463
+ cx = dff.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False)
464
+ br = dff.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False)
465
+ cx_ach = dff.groupby('complex').apply(lambda x: x['actual_revenue_usd'].sum()/x['budget_usd'].sum()*100 if has_bud and x['budget_usd'].sum()>0 else None)
466
+ cx_lines = "\n".join([f" {i+1}. {n}: {fmt(v)}{f' ({cx_ach[n]:.0f}% bud)' if cx_ach[n] else ''}" for i,(n,v) in enumerate(cx.items())])
467
+ br_lines = "\n".join([f" {i+1}. {n}: {fmt(v)}" for i,(n,v) in enumerate(br.items())])
468
+ return f"Complex ranking:\n{cx_lines}\n\nBrand ranking:\n{br_lines}"
469
+
470
+ # Top / best
471
+ if any(x in m for x in ['top','best','highest','leading','number one']):
472
+ g_cx = dff.groupby('complex')['actual_revenue_usd'].sum()
473
+ g_br = dff.groupby('brand')['actual_revenue_usd'].sum()
474
+ return f"Top complex: {g_cx.idxmax()} ({fmt(g_cx.max())})\nTop brand: {g_br.idxmax()} ({fmt(g_br.max())})"
475
 
476
+ # Worst / lowest
477
  if any(x in m for x in ['worst','lowest','bottom','poor','weakest']):
478
+ g_cx = dff.groupby('complex')['actual_revenue_usd'].sum()
479
+ g_br = dff.groupby('brand')['actual_revenue_usd'].sum()
480
+ return f"Lowest complex: {g_cx.idxmin()} ({fmt(g_cx.min())})\nLowest brand: {g_br.idxmin()} ({fmt(g_br.min())})"
481
 
482
+ # Total
483
+ if any(x in m for x in ['total','overall revenue']):
484
+ total = dff['actual_revenue_usd'].sum()
485
+ bud = dff['budget_usd'].sum() if has_bud else 0
486
+ return f"Total revenue: {fmt(total)}{ach_str(total,bud)} across {len(dff):,} records"
487
 
488
+ # Complex Γ— Brand
489
  for cx in COMPLEXES:
490
  for br in BRANDS:
491
  if cx.lower() in m and br.lower() in m:
492
+ sub = dff[(dff['complex']==cx)&(dff['brand']==br)]
493
  if not sub.empty:
494
+ bud = sub['budget_usd'].sum() if has_bud else 0
495
+ return f"{cx} / {br}: {fmt(sub['actual_revenue_usd'].sum())} total{ach_str(sub['actual_revenue_usd'].sum(),bud)}, {fmt(sub['actual_revenue_usd'].mean())}/day avg"
 
 
496
 
497
  for cx in COMPLEXES:
498
  if cx.lower() in m:
499
+ sub = dff[dff['complex']==cx]
500
+ bud = sub['budget_usd'].sum() if has_bud else 0
501
+ br_b = "\n".join([f" - {r.brand}: {fmt(r.actual_revenue_usd)}" for r in sub.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
502
+ return f"{cx}: {fmt(sub['actual_revenue_usd'].sum())} total{ach_str(sub['actual_revenue_usd'].sum(),bud)}\nBy brand:\n{br_b}"
 
503
 
504
  for br in BRANDS:
505
  if br.lower() in m:
506
+ sub = dff[dff['brand']==br]
507
+ bud = sub['budget_usd'].sum() if has_bud else 0
508
+ cx_b = "\n".join([f" - {r.complex}: {fmt(r.actual_revenue_usd)}" for r in sub.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False).reset_index().itertuples()])
509
+ return f"{br}: {fmt(sub['actual_revenue_usd'].sum())} total{ach_str(sub['actual_revenue_usd'].sum(),bud)}\nBy complex:\n{cx_b}"
510
 
511
  return None
512
+
513
+ def build_chat_context(dff):
514
+ if dff is None or dff.empty: return "No data loaded."
515
+ cx_rev = dff.groupby('complex')['actual_revenue_usd'].sum().sort_values(ascending=False)
516
+ br_rev = dff.groupby('brand')['actual_revenue_usd'].sum().sort_values(ascending=False)
517
+ has_bud = 'budget_usd' in dff.columns and dff['budget_usd'].sum() > 0
518
+ total = dff['actual_revenue_usd'].sum()
519
+ bud = dff['budget_usd'].sum() if has_bud else 0
520
+ dr = f"{dff['date'].min().strftime('%b %d, %Y')} to {dff['date'].max().strftime('%b %d, %Y')}"
521
+ cx_lines = "\n".join([f"- {cx}: {fmt(v)}{f' ({v/dff[dff.complex==cx].budget_usd.sum()*100:.0f}% bud)' if has_bud and dff[dff.complex==cx].budget_usd.sum()>0 else ''}" for cx,v in cx_rev.items()])
522
+ br_lines = "\n".join([f"- {br}: {fmt(v)}" for br,v in br_rev.items()])
523
+ return f"""You are the Savanna QSR Intelligence assistant for Netrisyl Insights, Zimbabwe.
524
+ Data range: {dr} | Records: {len(dff):,} | Total revenue: {fmt(total)}{f" ({total/bud*100:.1f}% of budget)" if has_bud else ""}
 
 
 
 
 
 
 
525
 
526
  REVENUE BY COMPLEX:
527
  {cx_lines}
 
529
  REVENUE BY BRAND:
530
  {br_lines}
531
 
532
+ Complexes: {', '.join(COMPLEXES)}
533
+ Brands: {', '.join(BRANDS)}
534
 
535
+ Answer directly and concisely. Always cite figures. Use $ for amounts. Be honest when data is insufficient."""
536
 
537
+ def chat(message, history, date_from, date_to):
538
  if not message or not message.strip(): return ""
539
+ dff = filter_df(date_from, date_to)
540
+ data_ctx = route_intent(message, dff)
541
+ system = build_chat_context(dff)
542
+ msgs = [{"role":"system","content":system}]
543
  for h in (history or []):
544
+ if isinstance(h,(list,tuple)) and len(h)==2:
545
+ if h[0]: msgs.append({"role":"user","content":str(h[0])})
546
+ if h[1]: msgs.append({"role":"assistant","content":str(h[1])})
547
+ user_msg = f"{message}\n\n[COMPUTED DATA]: {data_ctx}" if data_ctx else message
548
+ msgs.append({"role":"user","content":user_msg})
549
  try:
550
+ r = _http.post("https://api.openai.com/v1/chat/completions",
551
+ headers={"Authorization":f"Bearer {OPENAI_KEY}","Content-Type":"application/json"},
552
+ json={"model":"gpt-4o-mini","messages":msgs,"temperature":0.2,"max_tokens":700})
553
+ return r.json()["choices"][0]["message"]["content"]
554
+ except Exception as e: return f"⚠️ {e}"
555
+
556
+ def refresh_and_apply(date_from, date_to):
557
+ _cache['loaded_at'] = 0
558
+ dff = filter_df(date_from, date_to)
559
+ if dff.empty: return build_kpi_html(), "⚠️ No data β€” check Supabase connection"
560
+ full = get_df()
561
+ return build_kpi_html(dff), f"βœ… {len(full):,} rows loaded Β· Showing {len(dff):,} rows for selected range"
562
+
563
+ # ── CSS ───────────────────────────────────────────────────────────────────────
564
+ CSS = f"""
565
+ body,.gradio-container{{background:{C_BG}!important;font-family:Arial,sans-serif!important;}}
566
+ .tab-nav{{background:#0d1628!important;border-bottom:2px solid {C_GRID}!important;padding:0 8px!important;}}
567
+ button[class*="tab-"]{{color:#7fb3d3!important;background:transparent!important;border:none!important;
568
+ border-bottom:3px solid transparent!important;padding:10px 18px!important;font-size:13px!important;font-weight:500!important;}}
569
+ button[class*="tab-"]:hover{{color:#fff!important;background:rgba(201,168,76,0.06)!important;}}
570
+ button[class*="tab-"][class*="selected"],div[role="tablist"] button[aria-selected="true"]{{
571
+ color:{C_GOLD}!important;border-bottom:3px solid {C_GOLD}!important;font-weight:700!important;}}
572
+ .gradio-container *{{color:{C_TEXT};}}
573
+ .gradio-container input,.gradio-container textarea{{
574
+ background:#0d1628!important;color:{C_TEXT}!important;border:1px solid {C_GRID}!important;border-radius:6px!important;}}
575
+ .gradio-container label,.gradio-container .label-wrap span{{color:#a8c8f0!important;}}
576
+ input[type="radio"]{{accent-color:{C_GOLD}!important;}}
577
+ button.primary,button[variant="primary"]{{background:{C_GOLD}!important;color:#0a1628!important;
578
+ font-weight:700!important;border:none!important;border-radius:6px!important;font-size:13px!important;}}
579
+ button.primary:hover{{background:#e0be6a!important;}}
580
+ button.secondary,button[variant="secondary"]{{background:{C_NAVY}!important;color:{C_TEXT}!important;
581
+ border:1px solid {C_GOLD}!important;border-radius:6px!important;}}
582
+ .gradio-container .block,.gradio-container .form{{background:#0d1628!important;
583
+ border:1px solid {C_GRID}!important;border-radius:8px!important;}}
584
+ ul[role="listbox"]{{background:#0d1628!important;border:1px solid {C_GOLD}!important;border-radius:6px!important;}}
585
+ ul[role="listbox"] li{{color:#fff!important;background:#0d1628!important;}}
586
+ ul[role="listbox"] li:hover,ul[role="listbox"] li[aria-selected="true"]{{background:{C_GOLD}!important;color:#0a1628!important;}}
587
+ div[class*="chatbot"],.chatbot{{background:#040c1a!important;border-radius:10px!important;}}
588
+ .gradio-container .prose{{color:{C_TEXT}!important;}}
589
+ .gradio-container .prose strong{{color:{C_GOLD}!important;}}
590
+ .gradio-container .prose th{{background:#0d1628!important;color:{C_GOLD}!important;}}
591
+ .gradio-container .prose td{{border-color:{C_GRID}!important;}}
592
+ ::-webkit-scrollbar{{width:5px;height:5px;}}
593
+ ::-webkit-scrollbar-thumb{{background:{C_GOLD};border-radius:4px;}}
594
+ footer{{display:none!important;}}
595
  """
596
+
597
+ # ── UI ────────────────────────────────────────────────────────────────────────
598
+ with gr.Blocks(title="Savanna QSR Intelligence | Netrisyl Insights", css=CSS) as demo:
599
+
600
  kpi_header = gr.HTML(value=build_kpi_html())
601
+
602
+ # ── Global date filter ────────────────────────────────────────────────────
603
+ with gr.Row():
604
+ date_from = gr.Textbox(label="From Date", placeholder="YYYY-MM-DD", scale=2)
605
+ date_to = gr.Textbox(label="To Date", placeholder="YYYY-MM-DD", scale=2)
606
+ apply_btn = gr.Button("Apply Filter", variant="primary", scale=1)
607
+ refresh_btn = gr.Button("Refresh Data", variant="secondary", scale=1)
608
+ filter_msg = gr.Markdown(scale=3)
609
+
610
  with gr.Tabs():
611
+
612
+ # ── Dashboard ─────────────────────────────────────────────────────────
613
+ with gr.TabItem("πŸ“Š Dashboard"):
614
  with gr.Row():
615
+ ch1 = gr.Plot(show_label=False)
616
+ ch2 = gr.Plot(show_label=False)
 
 
 
 
 
 
 
 
 
 
617
  with gr.Row():
618
+ ch3 = gr.Plot(show_label=False)
619
+ ch4 = gr.Plot(show_label=False)
 
 
 
 
 
 
 
620
  with gr.Row():
621
+ ch5 = gr.Plot(show_label=False)
622
+ ch6 = gr.Plot(show_label=False)
623
+
624
+ # ── Forecast ──────────────────────────────────────────────────────────
625
+ with gr.TabItem("πŸ“ˆ Forecast"):
626
+ gr.HTML(f"<p style='color:#7fb3d3;font-size:12px;margin:8px 0;'>Day-of-week adjusted moving average Β· 5% growth Β· Uses the date range selected above.</p>")
627
+ with gr.Row():
628
+ seg_type = gr.Radio(choices=['Overall','By Complex','By Brand','Complex Γ— Brand'],
629
+ value='Overall', label="Segment Type")
630
+ seg_name = gr.Dropdown(choices=['All Complexes & Brands'],
631
+ value='All Complexes & Brands', label="Segment", interactive=True)
632
+ horizon = gr.Radio(choices=["7","14","30","60"], value="30", label="Horizon (days)")
633
+ fc_btn = gr.Button("⚑ Generate Forecast", variant="primary")
634
+ fc_chart = gr.Plot(show_label=False)
635
+ fc_summary = gr.Markdown()
636
+
637
+ # ── Chat ──────────────────────────────────────────────────────────────
638
+ with gr.TabItem("πŸ’¬ Intelligence Chat"):
639
+ gr.HTML(f"""<div style="background:#0d1628;border:1px solid {C_GRID};border-radius:8px;
640
+ padding:12px 16px;margin:8px 0 12px;">
641
+ <p style="color:{C_GOLD};font-weight:700;margin:0 0 5px;font-size:13px;">
642
+ πŸ’‘ Ask anything about Savanna QSR Group operations</p>
643
+ <p style="color:#7fb3d3;font-size:12px;margin:0;">
644
+ "Which complex is below budget?" Β· "Compare prior month revenue" Β·
645
+ "What's the 7-day trend?" Β· "Avg spend per customer?" Β·
646
+ "Rank all brands" Β· "Which site needs attention?"</p></div>""")
647
+ chatbot_box = gr.Chatbot(height=440, show_label=False)
648
+ with gr.Row():
649
+ chat_input = gr.Textbox(placeholder="Ask about operations...",
650
+ show_label=False, scale=9, container=False)
651
+ send_btn = gr.Button("Send ➀", variant="primary", scale=1)
652
+
653
+ gr.HTML(f'<div style="text-align:center;margin-top:14px;padding:10px;border-top:1px solid {C_GRID};"><p style="color:{C_GOLD};font-size:10px;font-weight:700;letter-spacing:2px;margin:0;">NETRISYL INSIGHTS</p><p style="color:#4a6a9e;font-size:10px;margin:4px 0 0;">Data Β· Analytics Β· Intelligence Β· <a href="https://netrisyl.com" style="color:#7fb3d3;">netrisyl.com</a></p></div>')
654
+
655
+ # ── Wiring ────────────────────────────────────────────────────────────────
656
+ dash_outputs = [kpi_header, ch1, ch2, ch3, ch4, ch5, ch6]
657
 
658
+ apply_btn.click(
659
+ fn=lambda df, dt: (refresh_and_apply(df, dt)[0], f"Showing filtered range") + build_dashboard(df, dt)[1:],
660
+ inputs=[date_from, date_to],
661
+ outputs=[kpi_header, filter_msg] + [ch1,ch2,ch3,ch4,ch5,ch6]
662
+ )
663
+
664
+ def apply_filter(df, dt):
665
+ kpi, msg = refresh_and_apply(df, dt) if False else (build_kpi_html(filter_df(df,dt)), "")
666
+ dash = build_dashboard(df, dt)
667
+ return [dash[0]] + [msg] + list(dash[1:])
668
+
669
+ apply_btn.click(fn=lambda df, dt: [build_kpi_html(filter_df(df,dt)), ""] + list(build_dashboard(df,dt)[1:]),
670
+ inputs=[date_from, date_to],
671
+ outputs=[kpi_header, filter_msg, ch1, ch2, ch3, ch4, ch5, ch6])
672
+
673
+ refresh_btn.click(fn=refresh_and_apply, inputs=[date_from, date_to],
674
+ outputs=[kpi_header, filter_msg])
675
+
676
+ seg_type.change(fn=update_seg_choices, inputs=[seg_type], outputs=[seg_name])
677
+ fc_btn.click(fn=generate_forecast,
678
+ inputs=[seg_type, seg_name, horizon, date_from, date_to],
679
+ outputs=[fc_chart, fc_summary])
680
+
681
+ def respond(message, history, df, dt):
682
+ if not message or not message.strip(): return history or [], ""
683
+ reply = chat(message, history or [], df, dt)
684
+ h = list(history or [])
685
+ h.append((message, reply))
686
+ return h, ""
687
+
688
+ send_btn.click(fn=respond, inputs=[chat_input, chatbot_box, date_from, date_to],
689
+ outputs=[chatbot_box, chat_input])
690
+ chat_input.submit(fn=respond, inputs=[chat_input, chatbot_box, date_from, date_to],
691
+ outputs=[chatbot_box, chat_input])
692
+
693
+ demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)