Dhom1 commited on
Commit
6ca30c7
·
verified ·
1 Parent(s): 72ba855

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +374 -348
src/streamlit_app.py CHANGED
@@ -1,33 +1,32 @@
1
 
2
  # -*- coding: utf-8 -*-
3
  """
4
- Health Matrix — AI Shortage Detection & Auto‑Fill (Styled, API‑Ready, Improved UI)
5
- ----------------------------------------------------------------------------------
6
- - Business Case section at top (from attachment)
7
- - Upgraded Timeline (progress fill + better badges)
8
- - Beautiful HTML tables for Summary & Reasoning
9
- - Custom API/UKG/Mock data sources (priority: Custom API)
 
10
  """
11
 
12
  from __future__ import annotations
13
 
14
- import os, math, random, datetime as dt
15
  from io import StringIO
16
- from typing import Dict, Any, List, Iterable, Optional, Tuple
17
 
18
  import pandas as pd
19
  import requests
20
  import streamlit as st
21
  import streamlit.components.v1 as components
22
 
23
- # =========[ Env ]=========
24
  APP_TITLE = "Health Matrix — AI Shortage & Auto‑Fill"
25
  random.seed(42)
26
 
27
- def env(n,d=""): return os.environ.get(n,d)
 
28
  UKG_APP_KEY, UKG_AUTH_TOKEN = env("UKG_APP_KEY"), env("UKG_AUTH_TOKEN")
29
- OPENAI_API_KEY = env("OPENAI_API_KEY")
30
-
31
  CUSTOM_API_BASE = env("CUSTOM_API_BASE")
32
  CUSTOM_API_TOKEN = env("CUSTOM_API_TOKEN")
33
  CUSTOM_API_SHIFTS = env("CUSTOM_API_SHIFTS", "/open_shifts")
@@ -37,305 +36,334 @@ CUSTOM_API_METHOD_SHIFTS = env("CUSTOM_API_METHOD_SHIFTS", "GET").upper()
37
  CUSTOM_API_METHOD_EMPLOYEES = env("CUSTOM_API_METHOD_EMPLOYEES", "GET").upper()
38
  CUSTOM_API_METHOD_HISTORY = env("CUSTOM_API_METHOD_HISTORY", "GET").upper()
39
 
40
- DATA_SOURCE = "custom" if CUSTOM_API_BASE else ("ukg" if (UKG_APP_KEY and UKG_AUTH_TOKEN) else "mock")
41
-
42
- SHIFT_FIELD_MAP = {"id":"id","department":"department","start":"start","end":"end","required_skill":"required_skill","required_cert":"required_cert"}
43
- EMP_FIELD_MAP = {"personNumber":"personNumber","fullName":"fullName","phoneNumber":"phoneNumber","organizationPath":"organizationPath","certifications":"Certifications","ot_7d":"OT_Hours_7d","availability":"Availability"}
44
-
45
- # =========[ CSS / Theme ]=========
46
- BASE_CSS = r"""
47
- html, body { margin:0; padding:0; height:100%; font-family:'Segoe UI','Tajawal','Noto Sans Arabic',sans-serif;
48
- background:linear-gradient(145deg,#002d5b 0%,#001a33 100%); color:#eaf4ff; overflow-x:hidden; }
49
- a { color:#7fd1ff; text-decoration:none } a:hover{ text-decoration:underline }
50
- .stButton>button{ background:linear-gradient(90deg,#004c97,#36BA01); color:#fff; border:none; border-radius:14px;
51
- padding:.9rem 1.2rem; font-size:1rem; font-weight:700; box-shadow:0 10px 28px rgba(0,0,0,.18); transition:transform .2s }
52
- .stButton>button:hover{ transform:translateY(-1px) }
53
- .hm-card{ background:rgba(255,255,255,.04); padding:1rem; border-radius:16px; border:1px solid rgba(255,255,255,.08); backdrop-filter: blur(6px); }
54
- .hm-title{ font-size:1.1rem; font-weight:800; color:#eaf4ff; margin:0 0 .6rem; display:flex; gap:.5rem; align-items:center }
55
- .hm-chip{ display:inline-flex; align-items:center; gap:.35rem; padding:.25rem .6rem; border-radius:999px; border:1px solid rgba(255,255,255,.14); font-size:.8rem }
56
- .hm-chip.ok{ background:#eaf8ef; color:#0a5a2b; border-color:#cbeed6 } .hm-chip.info{ background:#eef6ff; color:#124a86; border-color:#d7e9ff }
57
- """
58
-
59
- EXTRA_CSS = r"""
60
- /* Soft background dots */
61
- .hm-bg{ position:fixed; inset:0; overflow:hidden; z-index:0 }
62
- .hm-dot{ position:absolute; width:280px; height:280px; border-radius:50%; opacity:.12; filter:blur(18px) }
63
- .hm-dot.a{ top:10%; left:20%; background:radial-gradient(circle,#004c97,#36ba01); animation:floatAround 12s ease-in-out infinite }
64
- .hm-dot.b{ top:60%; left:70%; background:radial-gradient(circle,#36ba01,#004c97); animation:floatAround 14s ease-in-out infinite }
65
- .hm-dot.c{ top:80%; left:30%; background:radial-gradient(circle,#004c97,#36ba01); animation:floatAround 16s ease-in-out infinite }
66
- @keyframes floatAround{0%{transform:translate(0,0) scale(1)}25%{transform:translate(50px,-30px) scale(1.2)}50%{transform:translate(-40px,60px) scale(1.1)}75%{transform:translate(30px,-50px) scale(1.25)}100%{transform:translate(0,0) scale(1)}}
67
-
68
- /* Upgraded timeline */
69
- .hm-flow{ position:relative; margin:1rem 0 .5rem; padding:1rem; border-radius:16px; background:rgba(0,0,0,.18); border:1px solid rgba(255,255,255,.06) }
70
- .hm-track{ position:relative; height:6px; background:#2a3e55; border-radius:999px; overflow:hidden; margin:0 .4rem 1.1rem }
71
- .hm-fill{ position:absolute; inset:0; width:0%; height:100%; background:linear-gradient(90deg,#36ba01,#60d65e); transition:width .6s ease }
72
- .hm-steps{ display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:.8rem }
73
- .hm-step{ background:#0f2337; border:1px solid #1b3a58; border-radius:14px; padding:.55rem .7rem; color:#d7eaff }
74
- .hm-step.active{ outline:2px solid #36ba01 }
75
- .hm-step .title{ font-weight:800; font-size:.92rem; display:flex; gap:.4rem; align-items:center }
76
- .hm-step .desc{ font-size:.8rem; opacity:.9; margin-top:.2rem }
77
-
78
- /* HTML Tables: Summary + Reasoning */
79
- .hm-table{ width:100%; border-collapse:separate; border-spacing:0; overflow:hidden; border-radius:12px; border:1px solid rgba(255,255,255,.10); }
80
- .hm-table thead th{ background:#093356; color:#eaf4ff; text-align:left; padding:.65rem .7rem; font-weight:700; border-bottom:1px solid rgba(255,255,255,.12) }
81
- .hm-table tbody td{ padding:.6rem .7rem; border-bottom:1px solid rgba(255,255,255,.06); color:#e9f4ff; }
82
- .hm-table tbody tr:nth-child(even){ background:rgba(255,255,255,.03) }
83
- .badge{ display:inline-flex; align-items:center; gap:.3rem; padding:.2rem .5rem; border-radius:999px; font-size:.78rem; border:1px solid }
84
  .badge.ok{ background:#eaf8ef; color:#0a5a2b; border-color:#cbeed6 } .badge.warn{ background:#fff7e6; color:#985f00; border-color:#ffe1a3 }
85
- .badge.no{ background:#ffeded; color:#9d2b2b; border-color:#ffc4c4 } .badge.yes{ background:#eaf8ef; color:#0a5a2b; border-color:#cbeed6 }
 
 
 
 
 
 
 
86
  """
87
 
88
- # =========[ Small helpers ]=========
89
- def _render_bg():
90
- st.markdown(f"<style>{BASE_CSS}</style>", unsafe_allow_html=True)
91
- st.markdown(f"<style>{EXTRA_CSS}</style>", unsafe_allow_html=True)
92
- st.markdown('''
93
- <div class="hm-bg">
94
- <div class="hm-dot a"></div><div class="hm-dot b"></div><div class="hm-dot c"></div>
 
 
 
 
 
 
 
 
 
 
 
 
95
  </div>''', unsafe_allow_html=True)
96
 
97
- def _api_headers()->Dict[str,str]:
98
- h={"Content-Type":"application/json"}
99
- if CUSTOM_API_TOKEN: h["Authorization"]=f"Bearer {CUSTOM_API_TOKEN}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  return h
101
 
102
- def _api_call(path:str, method:str="GET", params:Dict[str,Any]|None=None, payload:Dict[str,Any]|None=None)->Any:
103
- url=(CUSTOM_API_BASE or "").rstrip("/")+"/"+path.lstrip("/")
104
- r=requests.request(method.upper(), url, headers=_api_headers(), params=params, json=payload, timeout=30)
105
  r.raise_for_status()
106
  try: return r.json()
107
  except Exception: return r.text
108
 
109
- def custom_fetch_open_shifts(start_date:str, end_date:str)->pd.DataFrame:
110
- data=_api_call(CUSTOM_API_SHIFTS, CUSTOM_API_METHOD_SHIFTS, params={"start_date":start_date,"end_date":end_date})
111
- rows=[]
112
- for s in data or []:
113
  rows.append({
114
- "ShiftID": s.get(SHIFT_FIELD_MAP["id"]) or s.get("ShiftID") or s.get("id"),
115
- "Department": s.get(SHIFT_FIELD_MAP["department"]) or s.get("department") or s.get("dept") or s.get("unit"),
116
- "Start": s.get(SHIFT_FIELD_MAP["start"]) or s.get("startDateTime") or s.get("start"),
117
- "End": s.get(SHIFT_FIELD_MAP["end"]) or s.get("endDateTime") or s.get("end"),
118
- "RequiredSkill": s.get(SHIFT_FIELD_MAP["required_skill"]) or s.get("requiredSkill") or s.get("jobRole"),
119
- "RequiredCert": s.get(SHIFT_FIELD_MAP["required_cert"]) or s.get("requiredCert") or "BLS",
120
  })
121
  return pd.DataFrame(rows)
122
 
123
- def custom_fetch_employees(employee_ids: Optional[List[int]]=None)->pd.DataFrame:
124
- params={"ids":",".join(map(str,employee_ids or []))} if CUSTOM_API_METHOD_EMPLOYEES=="GET" else None
125
- payload={"ids":employee_ids or []} if CUSTOM_API_METHOD_EMPLOYEES=="POST" else None
126
- data=_api_call(CUSTOM_API_EMPLOYEES, CUSTOM_API_METHOD_EMPLOYEES, params=params, payload=payload)
127
- rows=[]
128
- for e in data or []:
129
- org=e.get(EMP_FIELD_MAP["organizationPath"]) or e.get("organizationPath") or ""
130
  rows.append({
131
- "personNumber": e.get(EMP_FIELD_MAP["personNumber"]) or e.get("personNumber"),
132
- "fullName": e.get(EMP_FIELD_MAP["fullName"]) or e.get("fullName"),
133
- "phoneNumber": e.get(EMP_FIELD_MAP["phoneNumber"]) or e.get("phoneNumber"),
134
  "organizationPath": org,
135
- "Certifications": e.get(EMP_FIELD_MAP["certifications"]) or e.get("Certifications") or e.get("certifications") or [],
136
- "OT_Hours_7d": e.get(EMP_FIELD_MAP["ot_7d"]) or e.get("OT_Hours_7d") or 0,
137
- "Availability": e.get(EMP_FIELD_MAP["availability"]) or e.get("Availability") or [],
138
  "JobRole": org.split("/")[-1] if isinstance(org,str) and org else ""
139
  })
140
  return pd.DataFrame(rows)
141
 
142
- def mock_open_shifts()->pd.DataFrame:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  return pd.DataFrame([
144
  {"ShiftID":"S-1001","Department":"ICU","Start":"2025-08-16 07:00","End":"2025-08-16 19:00","RequiredSkill":"ICU RN","RequiredCert":"ACLS"},
145
  {"ShiftID":"S-1002","Department":"ER","Start":"2025-08-16 19:00","End":"2025-08-17 07:00","RequiredSkill":"ER RN","RequiredCert":"BLS"},
146
  ])
147
 
148
- def mock_employees()->pd.DataFrame:
149
- df=pd.DataFrame([
150
- {"personNumber":850,"fullName":"Amal AlHarbi","phoneNumber":"+966500000001","organizationPath":"Hospital/Nursing/ICU/ICU RN","Certifications":["ACLS","BLS"],"OT_Hours_7d":4,"Availability":["2025-08-16 07:00-19:00"]},
151
- {"personNumber":825,"fullName":"Saud AlQahtani","phoneNumber":"+966500000002","organizationPath":"Hospital/Nursing/ER/ER RN","Certifications":["BLS"],"OT_Hours_7d":10,"Availability":["2025-08-16 19:00-07:00"]},
152
- {"personNumber":811,"fullName":"Nora AlQahtani","phoneNumber":"+966500000003","organizationPath":"Hospital/Nursing/MedSurg/MedSurg RN","Certifications":["BLS"],"OT_Hours_7d":2,"Availability":["2025-08-16 07:00-19:00"]},
153
  ])
154
- df["JobRole"]=df["organizationPath"].apply(lambda p: p.split("/")[-1] if isinstance(p,str) else "")
155
  return df
156
 
157
- # History helpers
158
- def prepare_history(df:pd.DataFrame)->pd.DataFrame:
159
- df=df.copy()
160
- df["date"]=pd.to_datetime(df["date"]).dt.date
161
- df["dow"]=pd.to_datetime(df["date"]).map(lambda d: dt.date.fromisoformat(str(d)).weekday())
162
- for c in ["demand","scheduled_staff","absences"]:
163
- if c in df.columns: df[c]=pd.to_numeric(df[c],errors="coerce").fillna(0).astype(int)
164
- return df
165
-
166
- def forecast_next(df:pd.DataFrame, dep:str)->float:
167
- sub=df[df["department"]==dep].sort_values("date")
168
- if sub.empty: return 0.0
169
- last_dow=sub.iloc[-1]["dow"]
170
- same=sub[sub["dow"]==last_dow].tail(4)
171
- return float((same["demand"].mean() if not same.empty else sub["demand"].tail(7).mean()))
172
-
173
- def staff_required(demand:float, ratio:float)->int:
174
- if ratio<=0: ratio=4.0
175
- return int(math.ceil(demand/ratio))
176
-
177
- REQUIRED_SKILL_BY_DEP={"ICU":"ICU RN","ER":"ER RN","MedSurg":"MedSurg RN"}
178
- REQUIRED_CERT_BY_DEP={"ICU":"ACLS","ER":"BLS","MedSurg":"BLS"}
179
-
180
- def detect_shortages(hist:pd.DataFrame, deps:List[str], params:Dict[str,Any])->pd.DataFrame:
181
- def uplift(x:float)->float:
182
- fac=1.0
183
- if params.get("holiday"): fac*=params["uplift"].get("holidays",1.15)
184
- if params.get("event"): fac*=params["uplift"].get("events",1.08)
185
- if params.get("weather"): fac*=params["uplift"].get("weather",1.05)
186
- return x*fac
187
- rows=[]
188
- for dep in deps:
189
- base=forecast_next(hist, dep); adj=uplift(base)
190
- need=staff_required(adj, params.get("patients_per_nurse",4.0))
191
- scheduled=int(hist[hist["department"]==dep]["scheduled_staff"].tail(1).values[0]) if not hist[hist["department"]==dep].empty else 0
192
- shortage=max(0, need-scheduled)
193
- for i in range(shortage):
194
- rows.append({
195
- "ShiftID": f"GEN-{dep[:2].upper()}-{i+1:03d}",
196
- "Department": dep,
197
- "Start": params.get("start_time","2025-08-16 07:00"),
198
- "End": params.get("end_time","2025-08-16 19:00"),
199
- "RequiredSkill": REQUIRED_SKILL_BY_DEP.get(dep,"MedSurg RN"),
200
- "RequiredCert": REQUIRED_CERT_BY_DEP.get(dep,"BLS"),
201
- })
202
- return pd.DataFrame(rows)
203
-
204
- # Eligibility & ranking
205
- def is_eligible(emp:pd.Series, shift:pd.Series, ot_threshold:int, labor_max:int)->Tuple[bool,List[str]]:
206
- reasons=[]
207
- role_ok=emp.get("JobRole","").lower()==shift["RequiredSkill"].lower(); reasons.append("Role✔" if role_ok else "Role✖")
208
- cert_ok=shift["RequiredCert"].lower() in [c.lower() for c in emp.get("Certifications",[])]; reasons.append("Cert✔" if cert_ok else "Cert✖")
209
- av_list=emp.get("Availability",[]) or []; start,end=str(shift["Start"]), str(shift["End"])
210
- avail_ok=(not av_list) or any(start in a or end in a for a in av_list); reasons.append("Avail✔" if avail_ok else "Avail✖")
211
- ot_ok=int(emp.get("OT_Hours_7d",0))<=int(ot_threshold); reasons.append("OT✔" if ot_ok else "OT✖")
212
- labor_ok=(int(emp.get("OT_Hours_7d",0))+12)<=int(labor_max); reasons.append("Labor✔" if labor_ok else "Labor✖")
213
- return all([role_ok,cert_ok,avail_ok,ot_ok, labor_ok]), reasons
214
-
215
- def rank_candidates(df_emp:pd.DataFrame, shift:pd.Series, ot_threshold:int, labor_max:int)->pd.DataFrame:
216
- rows=[]
217
- for _,emp in df_emp.iterrows():
218
- ok, reasons = is_eligible(emp, shift, ot_threshold, labor_max)
219
- score=sum(x in reasons for x in ["Role✔","Cert✔","Avail✔","OT✔","Labor✔"])
220
  rows.append({
221
  "ShiftID": shift["ShiftID"], "Employee": emp.get("fullName",""), "Phone": emp.get("phoneNumber",""),
222
  "personNumber": emp.get("personNumber",""), "JobRole": emp.get("JobRole",""),
223
  "Certifications": ",".join(emp.get("Certifications",[])), "Reasons": " | ".join(reasons),
224
  "Eligible": "Yes" if ok else "No", "Score": int(score)
225
  })
226
- return pd.DataFrame(rows).sort_values(["Eligible","Score"], ascending=[True,False])
227
-
228
- # =========[ UI bits ]=========
229
- def business_case_block():
230
- html = '''
231
- <div class="hm-card" dir="ltr" style="margin-top:1rem">
232
- <div class="hm-title">📌 Business Case</div>
233
- <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px">
234
- <div>
235
- <div class="hm-chip info">Use Case</div>
236
- <p style="margin:.5rem 0 0;line-height:1.5">
237
- Manager can’t predict the shortage of staff in specific departments and occasions, and can’t fill in open shifts automatically.
238
- </p>
239
- </div>
240
- <div>
241
- <div class="hm-chip info">AI Solution</div>
242
- <ul style="margin:.5rem 0 0;line-height:1.5">
243
- <li>Detect shortage, then identify eligible employees by skills, certifications, availability, OT thresholds, and labor rules.</li>
244
- <li>Auto‑suggest or send shift offers via SMS, app, or email.</li>
245
- <li>Auto‑fill open shifts based on acceptance/rejection.</li>
246
- <li>Notify relevant employees of the assignments.</li>
247
- </ul>
248
- </div>
249
- <div>
250
- <div class="hm-chip info">Prerequisites</div>
251
- <p style="margin:.5rem 0 0;line-height:1.5">
252
- Historical scheduling data, absentee trends, labor demand forecasts, and external factors (holidays, events, weather) are available in WFM.
253
- </p>
254
- </div>
255
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  </div>
257
- '''
258
- st.markdown(html, unsafe_allow_html=True)
259
-
260
- def flow_timeline(steps: List[Dict[str,str]], progress: float):
261
- width = max(0,min(100,int(progress*100)))
262
- grid = ''.join([f'''\
263
- <div class="hm-step {'active' if i==int(progress*(len(steps))) else ''}">\
264
- <div class="title">{s.get('icon','⏺')} {s.get('title','')}</div>\
265
- <div class="desc">{s.get('desc','')}</div>\
266
- </div>''' for i,s in enumerate(steps)])
267
- html = f'''\
268
- <div class="hm-flow">\
269
- <div class="hm-track"><div class="hm-fill" style="width:{width}%"></div></div>\
270
- <div class="hm-steps">{grid}</div>\
271
- </div>\
272
- '''
273
- components.html(html, height=220, scrolling=False)
274
 
275
- def html_table(df: pd.DataFrame, title: str, icon: str="📊"):
276
- if df is None or df.empty:
277
- st.info("No data")
278
- return
279
- df = df.copy()
280
- ths=''.join([f'<th>{c}</th>' for c in df.columns])
281
- def fmt_cell(cname,val):
282
- if cname.lower() in ("eligible","status"):
283
- if str(val).lower() in ("yes","✅ filled","filled"):
284
- return f'<span class="badge yes">✅ {val}</span>'
285
- if "unfilled" in str(val).lower() or str(val).lower() in ("no","not eligible"):
286
- return f'<span class="badge no">✖ {val}</span>'
287
- if "skipp" in str(val).lower() or "notify" in str(val).lower():
288
- return f'<span class="badge warn">⚠ {val}</span>'
289
- return str(val)
290
- rows=''
291
- for _,r in df.iterrows():
292
- tds=''.join([f'<td>{fmt_cell(c,r[c])}</td>' for c in df.columns])
293
- rows+=f'<tr>{tds}</tr>'
294
- html=f'''\
295
- <div class="hm-card" style="margin-top:.8rem">\
296
- <div class="hm-title">{icon} {title}</div>\
297
- <div style="overflow:auto">\
298
- <table class="hm-table">\
299
- <thead><tr>{ths}</tr></thead>\
300
- <tbody>{rows}</tbody>\
301
- </table>\
302
- </div>\
303
- </div>'''
304
- st.markdown(html, unsafe_allow_html=True)
305
-
306
- # =========[ Main ]=========
307
  def main():
308
  st.set_page_config(page_title=APP_TITLE, layout="wide")
309
- _render_bg()
310
-
311
- st.markdown('<div style="text-align:center; margin-top:2.2rem;"><h1 style="color:#36ba01;margin:0">AI Shortage Detection & Auto‑Fill</h1><p style="opacity:.9;margin:.3rem 0 0">by Health Matrix</p></div>', unsafe_allow_html=True)
312
 
313
- # Business Case at top
314
- business_case_block()
315
 
316
- # Sidebar controls
317
  with st.sidebar:
318
- st.markdown("### ⚙️ Settings")
319
- st.write("Data Source:", "Custom API" if CUSTOM_API_BASE else ("UKG" if (UKG_APP_KEY and UKG_AUTH_TOKEN) else "Mock"))
320
- c1,c2,c3 = st.columns(3)
321
- with c1: holiday=st.checkbox("Holidays", True)
322
- with c2: event=st.checkbox("Events", False)
323
- with c3: weather=st.checkbox("Weather", False)
324
- uplifts={"holidays": st.number_input("Holiday uplift",1.0,2.5,1.15,0.01),
325
- "events": st.number_input("Event uplift",1.0,2.5,1.08,0.01),
326
- "weather": st.number_input("Weather uplift",1.0,2.5,1.05,0.01)}
327
- ratio = st.number_input("Patients per Nurse",1.0,10.0,4.0,0.5)
328
- ot_threshold = st.number_input("OT Max 7d (h)",0,40,12,1)
329
- labor_max = st.number_input("Labor weekly max +12h",20,80,60,1)
 
 
 
 
330
  st.markdown("---")
 
 
 
 
 
 
331
  start_time = st.text_input("Shift Start", "2025-08-16 07:00")
332
  end_time = st.text_input("Shift End", "2025-08-16 19:00")
 
333
 
334
- # History (mock CSV inside app for quick check)
335
  st.markdown('<div class="hm-card">', unsafe_allow_html=True)
336
  st.markdown('<div class="hm-title">🧾 Scheduling History</div>', unsafe_allow_html=True)
337
- sample = st.toggle("Use sample history", True)
338
- if sample:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  sample_csv = """date,department,demand,scheduled_staff,absences
340
  2025-07-20,ICU,28,7,1
341
  2025-07-27,ICU,30,7,1
@@ -351,95 +379,93 @@ def main():
351
  2025-08-10,MedSurg,131,28,5
352
  """
353
  hist_df = pd.read_csv(StringIO(sample_csv))
354
- else:
355
- up = st.file_uploader("Upload CSV (date, department, demand, scheduled_staff, absences)", type=["csv"])
356
- if up is None: st.stop()
357
- hist_df = pd.read_csv(up)
358
- hist_df = prepare_history(hist_df)
359
- st.dataframe(hist_df, use_container_width=True)
360
  st.markdown('</div>', unsafe_allow_html=True)
361
 
362
- # Detect
363
- deps = sorted(hist_df["department"].unique().tolist())
364
- target_deps = st.multiselect("Target departments", options=deps, default=deps)
365
- if st.button("🔎 Detect Shortages"):
366
- params={"holiday":holiday,"event":event,"weather":weather,"uplift":uplifts,"patients_per_nurse":ratio,"start_time":start_time,"end_time":end_time}
367
- if CUSTOM_API_BASE:
368
- open_api = custom_fetch_open_shifts("2025-08-15","2025-08-18")
369
- elif UKG_APP_KEY and UKG_AUTH_TOKEN:
370
- open_api = pd.DataFrame()
371
- else:
372
- open_api = mock_open_shifts()
373
- gen_df = detect_shortages(hist_df, target_deps, params)
374
- open_df = pd.concat([open_api, gen_df], ignore_index=True).drop_duplicates(subset=["ShiftID"], keep="first")
375
- st.session_state["open_shifts"] = open_df
376
- flow_timeline([
377
- {"icon":"📊","title":"Forecast","desc":"Estimate demand & staffing"},
378
- {"icon":"🚨","title":"Shortage","desc":"Generate open shifts"},
379
- {"icon":"🗂️","title":"Merge","desc":"Combine with API/UKG open shifts"},
380
- ], progress=0.66)
381
- html_table(open_df, "Open Shifts")
382
-
383
- # Employees, offers
384
- colA, colB = st.columns([2,3])
385
- with colA:
386
- emp_ids_txt = st.text_input("Employee IDs (comma separated)", "850,825,811")
387
- load = st.button("📥 Load Employees")
388
- with colB:
389
- st.info("Will evaluate Role/Cert/Availability/OT/Labor rules → rank → send offers (SMS/App/Email).")
390
-
391
- if load:
392
- if CUSTOM_API_BASE:
393
- emp_df = custom_fetch_employees([int(x) for x in emp_ids_txt.split(",") if x.strip().isdigit()])
394
- else:
395
- emp_df = mock_employees()
396
- st.session_state["employees"] = emp_df
397
- st.dataframe(emp_df, use_container_width=True)
398
-
399
- if st.button("📤 Auto‑Suggest Offers"):
400
- open_df = st.session_state.get("open_shifts", pd.DataFrame())
401
- emp_df = st.session_state.get("employees", mock_employees())
402
  if open_df.empty:
403
- st.error("No open shifts yet.")
404
- else:
405
- offers=[]
406
- for _,s in open_df.iterrows():
407
- ranked = rank_candidates(emp_df, s, ot_threshold=ot_threshold, labor_max=labor_max)
408
- top = ranked.head(3) if not ranked.empty else pd.DataFrame()
409
- for _, r in top.iterrows():
410
- ch = random.choice(["SMS","App","Email"])
411
- offers.append({"ShiftID": r["ShiftID"], "Employee": r["Employee"], "Channel": ch, "Result": f"{ch}→{r.get('Phone') or r['Employee']} (simulated)"})
412
- offers_df = pd.DataFrame(offers)
413
- st.session_state["offers"]=offers_df
414
- flow_timeline([
415
- {"icon":"🧮","title":"Evaluate","desc":"Rank candidates"},
416
- {"icon":"🤝","title":"Suggest","desc":"Send top offers"},
417
- ], progress=0.82)
418
- html_table(offers_df, "Offers Sent", "📨")
419
-
420
- if st.button("⚙️ Run Auto‑Fill (simulate responses)"):
421
- offers_df = st.session_state.get("offers", pd.DataFrame())
422
- open_df = st.session_state.get("open_shifts", pd.DataFrame())
423
- if offers_df.empty or open_df.empty:
424
- st.error("No offers/open shifts to process.")
425
  else:
426
- grouped = offers_df.groupby("ShiftID")
427
- assigned, notices = [], []
428
- for sid, grp in grouped:
429
- emp = grp.sample(1)["Employee"].iloc[0]
430
- assigned.append({"ShiftID":sid,"Employee":emp,"Status":"✅ Filled"})
431
- notices.append({"To":emp,"Message":f"You are assigned to shift {sid}","Channel":"App"})
432
- st.session_state["assigned"]=pd.DataFrame(assigned)
433
- st.session_state["notices"]=pd.DataFrame(notices)
434
- flow_timeline([
435
- {"icon":"📬","title":"Offers","desc":"Waiting for responses"},
436
- {"icon":"✅","title":"Auto‑Fill","desc":"Assign accepted employees"},
437
- {"icon":"🔔","title":"Notify","desc":"Send notifications"},
438
- ], progress=1.0)
439
- html_table(st.session_state["assigned"], "Shift Fulfillment Summary", "📈")
440
- html_table(st.session_state["notices"], "Notifications", "🔔")
441
-
442
- st.markdown("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
  st.caption("© 2025 Health Matrix — Digital Health Transformation")
444
 
445
  if __name__ == "__main__":
 
1
 
2
  # -*- coding: utf-8 -*-
3
  """
4
+ Health Matrix — AI Shortage Detection & Auto‑Fill (Business KPIs, API/UKG-ready)
5
+ -------------------------------------------------------------------------------
6
+ - Business KPIs at top (value over text) + concise Business Case.
7
+ - Sidebar = Data Source / Labor Rules / Cost Model / Channels / Advanced.
8
+ - Robust datetime parsing (fixes 'Invalid isoformat string').
9
+ - Data preflight validation & clear warnings (no tracebacks).
10
+ - One-click end‑to‑end run (Forecast → Offers → Auto‑Fill).
11
  """
12
 
13
  from __future__ import annotations
14
 
15
+ import os, math, random, json, datetime as dt
16
  from io import StringIO
17
+ from typing import Dict, Any, List, Optional, Tuple
18
 
19
  import pandas as pd
20
  import requests
21
  import streamlit as st
22
  import streamlit.components.v1 as components
23
 
 
24
  APP_TITLE = "Health Matrix — AI Shortage & Auto‑Fill"
25
  random.seed(42)
26
 
27
+ # ---------- Environment (can be overridden from UI) ----------
28
+ def env(k, d=""): return os.environ.get(k, d)
29
  UKG_APP_KEY, UKG_AUTH_TOKEN = env("UKG_APP_KEY"), env("UKG_AUTH_TOKEN")
 
 
30
  CUSTOM_API_BASE = env("CUSTOM_API_BASE")
31
  CUSTOM_API_TOKEN = env("CUSTOM_API_TOKEN")
32
  CUSTOM_API_SHIFTS = env("CUSTOM_API_SHIFTS", "/open_shifts")
 
36
  CUSTOM_API_METHOD_EMPLOYEES = env("CUSTOM_API_METHOD_EMPLOYEES", "GET").upper()
37
  CUSTOM_API_METHOD_HISTORY = env("CUSTOM_API_METHOD_HISTORY", "GET").upper()
38
 
39
+ # ---------- Styling ----------
40
+ BASE_CSS = r"""html, body { margin:0; padding:0; height:100%; font-family:'Inter','Segoe UI','Tajawal','Noto Sans Arabic',sans-serif; background:#f7fbff; color:#0d2236; }
41
+ .stApp { background: radial-gradient(90% 60% at 10% 10%, #e9f5ff 0, transparent 60%), radial-gradient(80% 60% at 90% 5%, #ecfff0 0, transparent 60%); }
42
+ h1, h2, h3 { letter-spacing: .2px }
43
+ .kpi-grid { display:grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap:14px; margin: 1rem 0; }
44
+ .kpi { background:#fff; border:1px solid #e8eef5; border-radius:14px; padding:14px; box-shadow:0 10px 20px rgba(13,34,54,.04) }
45
+ .kpi .big { font-size:28px; font-weight:900; color:#0f7a1a }
46
+ .kpi .sub { font-size:13px; color:#567; margin-top:4px }
47
+ .kpi .delta { font-size:12px; padding:2px 8px; border-radius:999px; border:1px solid #dce8f5; display:inline-block; margin-top:8px; background:#f6fbff }
48
+ .hm-card { background:#fff; border:1px solid #e8eef5; border-radius:14px; padding:14px; box-shadow:0 10px 20px rgba(13,34,54,.04); margin-top:12px }
49
+ .hm-title{ font-weight:800; color:#0d2236; margin:0 0 .4rem; display:flex; align-items:center; gap:.5rem }
50
+ .badge { display:inline-flex; align-items:center; gap:.3rem; padding:.2rem .5rem; border-radius:999px; font-size:.78rem; border:1px solid }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  .badge.ok{ background:#eaf8ef; color:#0a5a2b; border-color:#cbeed6 } .badge.warn{ background:#fff7e6; color:#985f00; border-color:#ffe1a3 }
52
+ .badge.no{ background:#ffeded; color:#9d2b2b; border-color:#ffc4c4 } .badge.info{ background:#eef6ff; color:#124a86; border-color:#d7e9ff }
53
+ .tbl { width:100%; border-collapse:separate; border-spacing:0; overflow:hidden; border-radius:12px; border:1px solid #e8eef5; }
54
+ .tbl thead th{ background:#f3f8fe; color:#17324a; text-align:left; padding:.6rem .65rem; font-weight:800; border-bottom:1px solid #e8eef5 }
55
+ .tbl tbody td{ padding:.55rem .65rem; border-bottom:1px solid #f1f5fa; }
56
+ .tbl tbody tr:nth-child(even){ background:#fcfeff }
57
+ .stepper { position:relative; padding: 10px; border-radius:12px; background:#f6fbff; border:1px solid #e1edf9; margin: 10px 0; }
58
+ .track { height:6px; background:#e1edf9; border-radius:999px; overflow:hidden; margin-bottom:10px }
59
+ .fill { height:100%; width:0%; background:linear-gradient(90deg,#1ab04b,#6bd47d) }
60
  """
61
 
62
+ def html_table(df: pd.DataFrame, title: str, icon: str="📊"):
63
+ if df is None or df.empty:
64
+ st.info("No data")
65
+ return
66
+ ths=''.join([f'<th>{c}</th>' for c in df.columns])
67
+ def fmt(c,v):
68
+ if c.lower() in ("eligible","status"):
69
+ s=str(v).lower()
70
+ if s in ("yes","✅ filled","filled"): return f'<span class="badge ok">✅ {v}</span>'
71
+ if "unfilled" in s or s in ("no","not eligible"): return f'<span class="badge no">✖ {v}</span>'
72
+ if "skip" in s or "notify" in s: return f'<span class="badge warn">⚠ {v}</span>'
73
+ return str(v)
74
+ rows=''.join(['<tr>'+''.join([f'<td>{fmt(c,r[c])}</td>' for c in df.columns])+'</tr>' for _,r in df.iterrows()])
75
+ st.markdown(f'''
76
+ <div class="hm-card">
77
+ <div class="hm-title">{icon} {title}</div>
78
+ <div style="overflow:auto">
79
+ <table class="tbl"><thead><tr>{ths}</tr></thead><tbody>{rows}</tbody></table>
80
+ </div>
81
  </div>''', unsafe_allow_html=True)
82
 
83
+ # ---------- Data helpers ----------
84
+ def to_dt_series(v) -> pd.Series:
85
+ # Robust conversion: supports "YYYY-MM-DD", "YYYY-MM-DD HH:MM:SS", etc.
86
+ s = pd.to_datetime(v, errors="coerce", infer_datetime_format=True, utc=False)
87
+ return s
88
+
89
+ def prepare_history(df: pd.DataFrame) -> pd.DataFrame:
90
+ if df is None or df.empty: return pd.DataFrame()
91
+ df = df.copy()
92
+ # normalize columns
93
+ cols_lower = {c.lower(): c for c in df.columns}
94
+ for need in ["date","department","demand","scheduled_staff"]:
95
+ if need not in cols_lower:
96
+ raise ValueError(f"Missing required column: {need}")
97
+ dt_series = to_dt_series(df[cols_lower["date"]])
98
+ if dt_series.isna().all():
99
+ raise ValueError("All date values are invalid. Please check date format.")
100
+ df["date"] = dt_series.dt.date
101
+ df["week"] = dt_series.dt.isocalendar().week.astype(int)
102
+ df["dow"] = dt_series.dt.dayofweek.astype(int) # 0=Mon
103
+ for c in ["demand","scheduled_staff","absences"]:
104
+ if c in cols_lower: df[c] = pd.to_numeric(df[cols_lower[c]], errors="coerce").fillna(0).astype(int)
105
+ elif c not in df.columns and c in ["absences"]:
106
+ df[c] = 0
107
+ return df
108
+
109
+ def staff_required(demand: float, ratio: float) -> int:
110
+ ratio = max(0.1, float(ratio or 4.0))
111
+ return int(math.ceil(demand / ratio))
112
+
113
+ def forecast_next(df: pd.DataFrame, department: str) -> float:
114
+ sub = df[df["department"]==department].sort_values("date")
115
+ if sub.empty: return 0.0
116
+ last_dow = sub.iloc[-1]["dow"]
117
+ same = sub[sub["dow"]==last_dow].tail(4)
118
+ return float((same["demand"].mean() if not same.empty else sub["demand"].tail(7).mean()))
119
+
120
+ REQUIRED_SKILL_BY_DEP = {"ICU":"ICU RN","ER":"ER RN","MedSurg":"MedSurg RN"}
121
+ REQUIRED_CERT_BY_DEP = {"ICU":"ACLS","ER":"BLS","MedSurg":"BLS"}
122
+
123
+ def detect_shortages(history_df: pd.DataFrame, departments: List[str], params: Dict[str,Any]) -> pd.DataFrame:
124
+ def uplift(x: float) -> float:
125
+ fac = 1.0
126
+ if params.get("holiday"): fac *= params["uplift"].get("holidays",1.15)
127
+ if params.get("event"): fac *= params["uplift"].get("events",1.08)
128
+ if params.get("weather"): fac *= params["uplift"].get("weather",1.05)
129
+ return x * fac
130
+ rows = []
131
+ for dep in departments:
132
+ base = forecast_next(history_df, dep)
133
+ adj = uplift(base)
134
+ need = staff_required(adj, params.get("patients_per_nurse", 4.0))
135
+ scheduled = int(history_df[history_df["department"]==dep]["scheduled_staff"].tail(1).values[0]) if not history_df[history_df["department"]==dep].empty else 0
136
+ shortage = max(0, need - scheduled)
137
+ for i in range(shortage):
138
+ rows.append({
139
+ "ShiftID": f"GEN-{dep[:2].upper()}-{i+1:03d}",
140
+ "Department": dep,
141
+ "Start": params.get("start_time","2025-08-16 07:00"),
142
+ "End": params.get("end_time","2025-08-16 19:00"),
143
+ "RequiredSkill": REQUIRED_SKILL_BY_DEP.get(dep,"MedSurg RN"),
144
+ "RequiredCert": REQUIRED_CERT_BY_DEP.get(dep,"BLS"),
145
+ })
146
+ return pd.DataFrame(rows)
147
+
148
+ # ---------- Integration (Custom API / UKG / Mock) ----------
149
+ def _api_headers() -> Dict[str,str]:
150
+ h = {"Content-Type":"application/json"}
151
+ if CUSTOM_API_TOKEN: h["Authorization"] = f"Bearer {CUSTOM_API_TOKEN}"
152
  return h
153
 
154
+ def _api_call(path: str, method: str="GET", params: Dict[str,Any]|None=None, payload: Dict[str,Any]|None=None):
155
+ url = (CUSTOM_API_BASE or "").rstrip("/") + "/" + path.lstrip("/")
156
+ r = requests.request(method.upper(), url, headers=_api_headers(), params=params, json=payload, timeout=30)
157
  r.raise_for_status()
158
  try: return r.json()
159
  except Exception: return r.text
160
 
161
+ def custom_fetch_open_shifts(start_date: str, end_date: str) -> pd.DataFrame:
162
+ data = _api_call(CUSTOM_API_SHIFTS, CUSTOM_API_METHOD_SHIFTS, params={"start_date":start_date,"end_date":end_date})
163
+ rows = []
164
+ for s in (data or []):
165
  rows.append({
166
+ "ShiftID": s.get("id") or s.get("ShiftID") or s.get("shiftId"),
167
+ "Department": s.get("department") or s.get("dept") or s.get("unit"),
168
+ "Start": s.get("start") or s.get("startDateTime"),
169
+ "End": s.get("end") or s.get("endDateTime"),
170
+ "RequiredSkill": s.get("required_skill") or s.get("requiredSkill") or s.get("jobRole"),
171
+ "RequiredCert": s.get("required_cert") or s.get("requiredCert") or "BLS",
172
  })
173
  return pd.DataFrame(rows)
174
 
175
+ def custom_fetch_employees(ids: Optional[List[int]]=None) -> pd.DataFrame:
176
+ params = {"ids": ",".join(map(str,ids or []))} if CUSTOM_API_METHOD_EMPLOYEES=="GET" else None
177
+ payload= {"ids": ids or []} if CUSTOM_API_METHOD_EMPLOYEES=="POST" else None
178
+ data = _api_call(CUSTOM_API_EMPLOYEES, CUSTOM_API_METHOD_EMPLOYEES, params=params, payload=payload)
179
+ rows = []
180
+ for e in (data or []):
181
+ org = e.get("organizationPath") or ""
182
  rows.append({
183
+ "personNumber": e.get("personNumber"),
184
+ "fullName": e.get("fullName"),
185
+ "phoneNumber": e.get("phoneNumber"),
186
  "organizationPath": org,
187
+ "Certifications": e.get("Certifications") or e.get("certifications") or [],
188
+ "OT_Hours_7d": e.get("OT_Hours_7d") or 0,
189
+ "Availability": e.get("Availability") or [],
190
  "JobRole": org.split("/")[-1] if isinstance(org,str) and org else ""
191
  })
192
  return pd.DataFrame(rows)
193
 
194
+ def _ukg_headers() -> Dict[str,str]:
195
+ return {"Content-Type":"application/json", "appkey": UKG_APP_KEY or "", "Authorization": f"Bearer {UKG_AUTH_TOKEN}" if UKG_AUTH_TOKEN else ""}
196
+
197
+ def ukg_fetch_open_shifts(start_date: str, end_date: str) -> pd.DataFrame:
198
+ try:
199
+ url = "https://partnerdemo-019.cfn.mykronos.com/api/v1/scheduling/schedule/multi_read"
200
+ payload = {"select":["OPENSHIFTS"],"where":{"locations":{"dateRange":{"startDate":start_date,"endDate":end_date},"includeEmployeeTransfer":False,"locations":{"ids":["2401","2402"]}}}}
201
+ r = requests.post(url, headers=_ukg_headers(), json=payload, timeout=30); r.raise_for_status(); data = r.json()
202
+ rows = []
203
+ for s in data.get("openShifts", []):
204
+ rows.append({
205
+ "ShiftID": s.get("id"),
206
+ "Department": (s.get("label") or "").split("-")[0],
207
+ "Start": s.get("startDateTime"), "End": s.get("endDateTime"),
208
+ "RequiredSkill": (s.get("segments", [{}])[0].get("orgJobRef",{}).get("qualifier","")) if s.get("segments") else "",
209
+ "RequiredCert": "BLS"
210
+ })
211
+ return pd.DataFrame(rows)
212
+ except Exception as e:
213
+ st.warning(f"UKG open_shifts error: {e}")
214
+ return pd.DataFrame()
215
+
216
+ def mock_open_shifts() -> pd.DataFrame:
217
  return pd.DataFrame([
218
  {"ShiftID":"S-1001","Department":"ICU","Start":"2025-08-16 07:00","End":"2025-08-16 19:00","RequiredSkill":"ICU RN","RequiredCert":"ACLS"},
219
  {"ShiftID":"S-1002","Department":"ER","Start":"2025-08-16 19:00","End":"2025-08-17 07:00","RequiredSkill":"ER RN","RequiredCert":"BLS"},
220
  ])
221
 
222
+ def mock_employees() -> pd.DataFrame:
223
+ df = pd.DataFrame([
224
+ {"personNumber":850,"fullName":"Amal Al-Harbi","phoneNumber":"+966500000001","organizationPath":"Hospital/Nursing/ICU/ICU RN","Certifications":["ACLS","BLS"],"OT_Hours_7d":4,"Availability":["2025-08-16 07:00-19:00"]},
225
+ {"personNumber":825,"fullName":"Saud Al-Qahtani","phoneNumber":"+966500000002","organizationPath":"Hospital/Nursing/ER/ER RN","Certifications":["BLS"],"OT_Hours_7d":10,"Availability":["2025-08-16 19:00-07:00"]},
226
+ {"personNumber":811,"fullName":"Nora Al-Qahtani","phoneNumber":"+966500000003","organizationPath":"Hospital/Nursing/MedSurg/MedSurg RN","Certifications":["BLS"],"OT_Hours_7d":2,"Availability":["2025-08-16 07:00-19:00"]},
227
  ])
228
+ df["JobRole"] = df["organizationPath"].apply(lambda p: p.split("/")[-1] if isinstance(p,str) else "")
229
  return df
230
 
231
+ # ---------- Eligibility & Offers ----------
232
+ def is_eligible(emp: pd.Series, shift: pd.Series, ot_threshold: int, labor_max_hours: int) -> Tuple[bool, List[str]]:
233
+ reasons = []
234
+ role_ok = emp.get("JobRole","").strip().lower() == (shift.get("RequiredSkill","") or "").strip().lower(); reasons.append("Role✔" if role_ok else "Role✖")
235
+ cert_ok = (shift.get("RequiredCert","") or "").lower() in [str(c).lower() for c in (emp.get("Certifications",[]) or [])]; reasons.append("Cert✔" if cert_ok else "Cert✖")
236
+ avail_list = emp.get("Availability", []) or []
237
+ start, end = str(shift.get("Start","")), str(shift.get("End",""))
238
+ avail_ok = (not avail_list) or any(start in a or end in a for a in avail_list); reasons.append("Avail✔" if avail_ok else "Avail✖")
239
+ ot_ok = int(emp.get("OT_Hours_7d",0)) <= int(ot_threshold); reasons.append("OT✔" if ot_ok else "OT✖")
240
+ labor_ok = (int(emp.get("OT_Hours_7d",0)) + 12) <= int(labor_max_hours); reasons.append("Labor✔" if labor_ok else "Labor✖")
241
+ return all([role_ok, cert_ok, avail_ok, ot_ok, labor_ok]), reasons
242
+
243
+ def rank_candidates(df_emp: pd.DataFrame, shift: pd.Series, ot_threshold: int, labor_max_hours: int) -> pd.DataFrame:
244
+ rows = []
245
+ for _, emp in df_emp.iterrows():
246
+ ok, reasons = is_eligible(emp, shift, ot_threshold, labor_max_hours)
247
+ score = sum(x in reasons for x in ["Role✔","Cert✔","Avail✔","OT✔","Labor✔"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  rows.append({
249
  "ShiftID": shift["ShiftID"], "Employee": emp.get("fullName",""), "Phone": emp.get("phoneNumber",""),
250
  "personNumber": emp.get("personNumber",""), "JobRole": emp.get("JobRole",""),
251
  "Certifications": ",".join(emp.get("Certifications",[])), "Reasons": " | ".join(reasons),
252
  "Eligible": "Yes" if ok else "No", "Score": int(score)
253
  })
254
+ return pd.DataFrame(rows).sort_values(["Eligible","Score"], ascending=[True, False])
255
+
256
+ def estimate_time_to_fill(total_offers: int, accept_rate: float) -> float:
257
+ if accept_rate <= 0: return float("inf")
258
+ return round(1.0 / accept_rate, 2)
259
+
260
+ # ---------- UI Blocks ----------
261
+ def business_kpis(open_df: pd.DataFrame, ranked_map: Dict[str,pd.DataFrame], cost_ot: float, cost_agency: float) -> None:
262
+ shifts = int(len(open_df)) if open_df is not None else 0
263
+ eligible_per_shift = {sid: int((df["Eligible"]=="Yes").sum()) for sid, df in (ranked_map or {}).items()}
264
+ shifts_with_coverage = sum(1 for sid,c in eligible_per_shift.items() if c>0)
265
+ coverage = round((shifts_with_coverage / shifts * 100.0), 1) if shifts else 0.0
266
+ accept_rate = 0.35 if shifts_with_coverage else 0.05
267
+ ttf = estimate_time_to_fill(3, accept_rate)
268
+ saved = int(max(0.0, (cost_agency - cost_ot) * 12.0 * shifts_with_coverage))
269
+ ineligible = sum(int((df["Eligible"]=="No").sum()) for df in (ranked_map or {}).values())
270
+ st.markdown('<div class="kpi-grid">', unsafe_allow_html=True)
271
+ st.markdown(f'''
272
+ <div class="kpi"><div class="big">{shifts}</div><div class="sub">Shifts at Risk / Open</div><div class="delta badge info">based on forecast & source</div></div>
273
+ <div class="kpi"><div class="big">{coverage}%</div><div class="sub">Eligible Coverage</div><div class="delta badge ok">{shifts_with_coverage} of {shifts} shifts have eligible</div></div>
274
+ <div class="kpi"><div class="big">{ttf} h</div><div class="sub">Est. Time-to-Fill</div><div class="delta badge info">with parallel offers</div></div>
275
+ <div class="kpi"><div class="big">{saved:,} SAR</div><div class="sub">Cost Impact (savings)</div><div class="delta badge ok">vs agency for filled shifts</div></div>
276
+ <div class="kpi"><div class="big">{ineligible}</div><div class="sub">Compliance Risks Avoided</div><div class="delta badge warn">filtered by OT/Cert/Labor</div></div>
277
+ ''', unsafe_allow_html=True)
278
+ st.markdown('</div>', unsafe_allow_html=True)
279
+
280
+ def business_case_brief():
281
+ st.markdown('''
282
+ <div class="hm-card">
283
+ <div class="hm-title">📌 Business Case (concise)</div>
284
+ <ul style="margin:.2rem 0 0; color:#3a556f;">
285
+ <li>Predict and detect staffing shortages per department/occasion.</li>
286
+ <li>Auto-identify eligible employees (skills, certs, availability, OT, labor rules).</li>
287
+ <li>Auto-suggest/sent offers via SMS/App/Email, then auto-fill on acceptance.</li>
288
+ <li>Notify assigned employees; track cost vs agency and compliance benefits.</li>
289
+ </ul>
290
+ </div>
291
+ ''', unsafe_allow_html=True)
292
+
293
+ def stepper(progress: float, labels: List[str]):
294
+ pct = max(0, min(100, int(progress*100)))
295
+ steps_html = ''.join([f'<span class="badge {"ok" if i<pct/100*len(labels) else "info"}">{labels[i]}</span> ' for i in range(len(labels))])
296
+ st.markdown(f'''
297
+ <div class="stepper">
298
+ <div class="track"><div class="fill" style="width:{pct}%"></div></div>
299
+ {steps_html}
300
  </div>
301
+ ''', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
+ # ---------- Main ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  def main():
305
  st.set_page_config(page_title=APP_TITLE, layout="wide")
306
+ st.markdown(f"<style>{BASE_CSS}</style>", unsafe_allow_html=True)
 
 
307
 
308
+ st.markdown('<div style="text-align:center; margin-top:1.2rem;"><h1 style="color:#1ab04b;margin:0">AI Shortage Detection & Auto‑Fill</h1><p style="opacity:.8;margin:.3rem 0 0">by Health Matrix</p></div>', unsafe_allow_html=True)
309
+ business_case_brief()
310
 
311
+ # Sidebar with value-oriented controls
312
  with st.sidebar:
313
+ st.markdown("### 🔌 Data Source")
314
+ default_idx = 0 if CUSTOM_API_BASE else (1 if UKG_APP_KEY and UKG_AUTH_TOKEN else 2)
315
+ source = st.radio("", ["Custom API","UKG","Sample/CSV"], index=default_idx)
316
+ if source == "Custom API":
317
+ base = st.text_input("Base URL", value=CUSTOM_API_BASE)
318
+ token= st.text_input("Auth Token (Bearer)", value=CUSTOM_API_TOKEN, type="password")
319
+ else:
320
+ base = CUSTOM_API_BASE; token = CUSTOM_API_TOKEN
321
+ st.markdown("---")
322
+ st.markdown("### 🧭 Labor Rules")
323
+ ot_threshold = st.number_input("OT Max (7d) hours", 0, 40, 12, 1)
324
+ labor_max = st.number_input("Weekly Max incl. +12h", 20, 80, 60, 1)
325
+ st.markdown("---")
326
+ st.markdown("### 💰 Cost Model")
327
+ cost_ot = st.number_input("Internal OT hourly (SAR)", 0.0, 500.0, 85.0, 1.0)
328
+ cost_agency = st.number_input("Agency hourly (SAR)", 0.0, 800.0, 150.0, 1.0)
329
  st.markdown("---")
330
+ st.markdown("### 📣 Channels")
331
+ ch_sms = st.checkbox("SMS", True); ch_app = st.checkbox("App", True); ch_email = st.checkbox("Email", False)
332
+ st.markdown("---")
333
+ with st.expander("Advanced (external factors)"):
334
+ holiday = st.checkbox("Holidays", True); event = st.checkbox("Events", False); weather = st.checkbox("Weather", False)
335
+ uplifts = {"holidays": st.number_input("Holiday uplift",1.0,2.5,1.15,0.01), "events": st.number_input("Event uplift",1.0,2.5,1.08,0.01), "weather": st.number_input("Weather uplift",1.0,2.5,1.05,0.01)}
336
  start_time = st.text_input("Shift Start", "2025-08-16 07:00")
337
  end_time = st.text_input("Shift End", "2025-08-16 19:00")
338
+ run_all = st.button("▶️ Run end‑to‑end")
339
 
340
+ # History block (Sample or CSV)
341
  st.markdown('<div class="hm-card">', unsafe_allow_html=True)
342
  st.markdown('<div class="hm-title">🧾 Scheduling History</div>', unsafe_allow_html=True)
343
+ if source == "Sample/CSV":
344
+ sample = st.toggle("Use sample history", True)
345
+ if sample:
346
+ sample_csv = """date,department,demand,scheduled_staff,absences
347
+ 2025-07-20,ICU,28,7,1
348
+ 2025-07-27,ICU,30,7,1
349
+ 2025-08-03,ICU,32,7,0
350
+ 2025-08-10,ICU,34,7,1
351
+ 2025-07-20,ER,90,18,3
352
+ 2025-07-27,ER,92,18,2
353
+ 2025-08-03,ER,95,18,2
354
+ 2025-08-10,ER,110,18,4
355
+ 2025-07-20,MedSurg,120,28,4
356
+ 2025-07-27,MedSurg,118,28,3
357
+ 2025-08-03,MedSurg,125,28,3
358
+ 2025-08-10,MedSurg,131,28,5
359
+ """
360
+ hist_df = pd.read_csv(StringIO(sample_csv))
361
+ else:
362
+ up = st.file_uploader("Upload CSV (date, department, demand, scheduled_staff[, absences])", type=["csv"])
363
+ if up is None: st.stop()
364
+ hist_df = pd.read_csv(up)
365
+ else:
366
+ # For API/UKG, we won't fetch history remotely; we assume demand baseline is captured elsewhere; sample stays for forecast baseline.
367
  sample_csv = """date,department,demand,scheduled_staff,absences
368
  2025-07-20,ICU,28,7,1
369
  2025-07-27,ICU,30,7,1
 
379
  2025-08-10,MedSurg,131,28,5
380
  """
381
  hist_df = pd.read_csv(StringIO(sample_csv))
382
+ try:
383
+ hist_df = prepare_history(hist_df)
384
+ st.dataframe(hist_df, use_container_width=True)
385
+ except Exception as e:
386
+ st.error(f"History preprocessing error: {e}")
387
+ st.stop()
388
  st.markdown('</div>', unsafe_allow_html=True)
389
 
390
+ # Run pipeline
391
+ if run_all:
392
+ params = {"holiday":holiday, "event":event, "weather":weather, "uplift":uplifts, "patients_per_nurse":4.0, "start_time":start_time, "end_time":end_time}
393
+
394
+ # Fetch open shifts according to the chosen source
395
+ open_df = pd.DataFrame()
396
+ if source == "Custom API" and base:
397
+ try:
398
+ global CUSTOM_API_BASE, CUSTOM_API_TOKEN
399
+ CUSTOM_API_BASE, CUSTOM_API_TOKEN = base, token
400
+ open_df = custom_fetch_open_shifts("2025-08-15","2025-08-18")
401
+ except Exception as e:
402
+ st.warning(f"Custom API shifts error: {e}")
403
+ elif source == "UKG":
404
+ open_df = ukg_fetch_open_shifts("2025-08-15","2025-08-18")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  if open_df.empty:
406
+ st.info("No open shifts from source → generating from forecast.")
407
+ gen_df = detect_shortages(hist_df, sorted(hist_df['department'].unique().tolist()), params)
408
+ open_df = pd.concat([open_df, gen_df], ignore_index=True).drop_duplicates(subset=["ShiftID"], keep="first")
409
+ if open_df.empty:
410
+ st.warning("No open shifts available. Adjust parameters or provide source.")
411
+ st.stop()
412
+
413
+ # Employees
414
+ if source == "Custom API" and base:
415
+ try:
416
+ employees = custom_fetch_employees([])
417
+ except Exception as e:
418
+ st.warning(f"Custom API employees error: {e}")
419
+ employees = mock_employees()
 
 
 
 
 
 
 
 
420
  else:
421
+ employees = mock_employees()
422
+ st.session_state["open_shifts"], st.session_state["employees"] = open_df, employees
423
+
424
+ # Rank per shift
425
+ ranked_map = {}
426
+ for _, s in open_df.iterrows():
427
+ ranked_map[s["ShiftID"]] = rank_candidates(employees, s, ot_threshold, labor_max)
428
+
429
+ # KPIs
430
+ st.markdown('<style>'+BASE_CSS+'</style>', unsafe_allow_html=True)
431
+ business_kpis(open_df, ranked_map, cost_ot, cost_agency)
432
+
433
+ # Timeline
434
+ stepper(0.66, ["Forecast","Offers","Auto‑Fill"])
435
+
436
+ # Show open shifts
437
+ html_table(open_df, "Open Shifts", "🗂️")
438
+
439
+ # Prepare offers (top‑3 per shift)
440
+ offers = []
441
+ for sid, ranked in ranked_map.items():
442
+ top = ranked[ranked["Eligible"]=="Yes"].head(3) if not ranked.empty else pd.DataFrame()
443
+ for _, r in top.iterrows():
444
+ ch = ("SMS" if ch_sms else ("App" if ch_app else "Email"))
445
+ offers.append({"ShiftID": sid, "Employee": r["Employee"], "Channel": ch, "Result": f"{ch}→{r.get('Phone') or r['Employee']} (simulated)"})
446
+ offers_df = pd.DataFrame(offers)
447
+ html_table(offers_df, "Offers Sent", "📨")
448
+
449
+ # Auto‑fill simulate: first candidate per shift accepts
450
+ assigned, notices = [], []
451
+ for sid, group in offers_df.groupby("ShiftID"):
452
+ if not group.empty:
453
+ emp = group.iloc[0]["Employee"]
454
+ assigned.append({"ShiftID": sid, "Employee": emp, "Status": "✅ Filled"})
455
+ notices.append({"To": emp, "Message": f"You are assigned to shift {sid}", "Channel": "App"})
456
+ else:
457
+ assigned.append({"ShiftID": sid, "Employee": "—", "Status": "⚠️ Unfilled"})
458
+ assigned_df, notices_df = pd.DataFrame(assigned), pd.DataFrame(notices)
459
+
460
+ stepper(1.0, ["Forecast","Offers","Auto‑Fill"])
461
+ html_table(assigned_df, "Shift Fulfillment Summary", "📈")
462
+ if not notices_df.empty:
463
+ html_table(notices_df, "Notifications", "🔔")
464
+
465
+ # Download results
466
+ csv = assigned_df.to_csv(index=False).encode("utf-8")
467
+ st.download_button("Download Fulfillment CSV", csv, "fulfillment_summary.csv", "text/csv")
468
+
469
  st.caption("© 2025 Health Matrix — Digital Health Transformation")
470
 
471
  if __name__ == "__main__":