import gradio as gr import pandas as pd import os from datetime import datetime, timedelta # ---------------- CONFIG ---------------- # STAFF_FILE = "staff_details.xlsx" PERMISSION_FILE = "permissions.xlsx" ADMIN_USER = "admin" ADMIN_PASS = "admin123" # ---------------- INIT ---------------- # if not os.path.exists(PERMISSION_FILE): df = pd.DataFrame(columns=[ "StaffID", "Name", "Department", "Date", "FromTime", "ToTime", "Reason", "SubmittedOn" ]) df.to_excel(PERMISSION_FILE, index=False) # ---------------- LOADERS ---------------- # def load_staff(): return pd.read_excel(STAFF_FILE) def load_permissions(): return pd.read_excel(PERMISSION_FILE) # ---------------- VALIDATORS ---------------- # # Date: Only Today / Tomorrow / Day after Tomorrow def validate_date_range(date_str): try: d = datetime.strptime(date_str, "%d/%m/%Y").date() except: return False, "❌ Date format must be DD/MM/YYYY" today = datetime.today().date() max_day = today + timedelta(days=2) if d < today: return False, "❌ Past date not allowed" if d > max_day: return False, "❌ Apply only within 2 days" return True, "" # Time: 08:45 - 17:20 and exactly 1 hour def validate_time_range(f, t): try: f_time = datetime.strptime(f, "%H:%M") t_time = datetime.strptime(t, "%H:%M") except: return False, "❌ Time format must be HH:MM (24-hour)" min_time = datetime.strptime("08:45", "%H:%M") max_time = datetime.strptime("17:20", "%H:%M") # Check range if f_time < min_time or t_time > max_time: return False, "❌ Time allowed: 08:45 to 17:20 only" # Check 1 hour duration diff = (t_time - f_time).total_seconds() / 3600 if diff != 1: return False, "❌ Permission must be exactly 1 hour" return True, "" # ---------------- STAFF FUNCTIONS ---------------- # def fetch_staff(staff_id): df = load_staff() row = df[df["StaffID"] == staff_id] if row.empty: return "Not Found", "Not Found", "0" name = row.iloc[0]["Name"] dept = row.iloc[0]["Department"] perms = load_permissions() count = len(perms[perms["StaffID"] == staff_id]) return name, dept, str(count) def submit_permission(staff_id, date, f, t, reason): # Basic validation if staff_id.strip() == "": return "❌ Staff ID Required" if date.strip() == "": return "❌ Date Required" if f.strip() == "" or t.strip() == "": return "❌ Time Required" if reason.strip() == "": return "❌ Reason Required" # Date validation ok, msg = validate_date_range(date) if not ok: return msg # Time validation ok, msg = validate_time_range(f, t) if not ok: return msg # Staff validation staff = load_staff() row = staff[staff["StaffID"] == staff_id] if row.empty: return "❌ Invalid Staff ID" perms = load_permissions() # Same day check (max 2) same_day = perms[ (perms["StaffID"] == staff_id) & (perms["Date"] == date) ] if len(same_day) == 1: return "⚠️ Second permission today → Apply Leave" if len(same_day) >= 2: return "❌ Daily limit reached" # Monthly limit (2 only) m = date.split("/")[1] y = date.split("/")[2] same_month = perms[ (perms["StaffID"] == staff_id) & (perms["Date"].str.contains(f"/{m}/{y}", na=False)) ] if len(same_month) >= 2: return "❌ Monthly limit reached (2 only)" # Save name = row.iloc[0]["Name"] dept = row.iloc[0]["Department"] now = datetime.now().strftime("%d/%m/%Y %H:%M") new_row = { "StaffID": staff_id, "Name": name, "Department": dept, "Date": date, "FromTime": f, "ToTime": t, "Reason": reason, "SubmittedOn": now } perms = pd.concat([perms, pd.DataFrame([new_row])], ignore_index=True) perms.to_excel(PERMISSION_FILE, index=False) return "✅ Permission Submitted Successfully" def delete_permission(staff_id, date): perms = load_permissions() before = len(perms) perms = perms[ ~((perms["StaffID"] == staff_id) & (perms["Date"] == date)) ] perms.to_excel(PERMISSION_FILE, index=False) if len(perms) == before: return "❌ No Record Found" else: return "✅ Deleted" def clear_form(): return "", "", "", "", "" # ---------------- ADMIN ---------------- # def admin_login(user, pwd): if user == ADMIN_USER and pwd == ADMIN_PASS: return gr.update(visible=True), "✅ Login Successful" return gr.update(visible=False), "❌ Invalid Login" def get_all_data(): return load_permissions() def download_excel(): return PERMISSION_FILE def monthly_report(month, year): perms = load_permissions() return perms[ perms["Date"].str.contains(f"/{month}/{year}", na=False) ] def dept_report(dept): perms = load_permissions() return perms[perms["Department"] == dept] def reset_data(): df = pd.DataFrame(columns=[ "StaffID", "Name", "Department", "Date", "FromTime", "ToTime", "Reason", "SubmittedOn" ]) df.to_excel(PERMISSION_FILE, index=False) return "✅ All Data Cleared" # ================= UI ================= # with gr.Blocks() as app: gr.HTML("""