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("""

SRC, SASTRA

Staff Permission Management System


""") # ---------------- STAFF TAB ---------------- # with gr.Tab("Staff Panel"): with gr.Row(): with gr.Column(): staff_id = gr.Textbox(label="Staff ID") name = gr.Textbox(label="Name", interactive=False) dept = gr.Textbox(label="Department", interactive=False) count = gr.Textbox(label="Permission Count", interactive=False) fetch = gr.Button("Fetch Details") with gr.Column(): date = gr.Textbox(label="Date (DD/MM/YYYY)") f = gr.Textbox(label="From (HH:MM 24-hr)") t = gr.Textbox(label="To (HH:MM 24-hr)") reason = gr.Textbox(label="Reason", lines=3) with gr.Row(): submit = gr.Button("Submit", variant="primary") delete = gr.Button("Delete", variant="stop") clear = gr.Button("Clear") status = gr.Textbox(label="Status", interactive=False) # ---------------- ADMIN TAB ---------------- # with gr.Tab("Admin Panel"): admin_user = gr.Textbox(label="Username") admin_pwd = gr.Textbox(label="Password", type="password") login = gr.Button("Login") msg = gr.Textbox(interactive=False) admin_box = gr.Column(visible=False) with admin_box: gr.Markdown("### 📊 All Records") table = gr.Dataframe(interactive=False) refresh = gr.Button("Refresh") gr.Markdown("### 📅 Monthly Report") month = gr.Textbox(label="Month (MM)") year = gr.Textbox(label="Year (YYYY)") month_btn = gr.Button("Generate") month_table = gr.Dataframe() gr.Markdown("### 🏢 Department Report") dept_name = gr.Textbox(label="Department") dept_btn = gr.Button("Generate") dept_table = gr.Dataframe() gr.Markdown("### 📥 Download") down = gr.Button("Download Excel") file = gr.File() gr.Markdown("### ⚠️ Reset") reset = gr.Button("Reset All", variant="stop") reset_msg = gr.Textbox(interactive=False) # ---------------- EVENTS ---------------- # fetch.click(fetch_staff, staff_id, [name, dept, count]) submit.click( submit_permission, [staff_id, date, f, t, reason], status ) delete.click(delete_permission, [staff_id, date], status) clear.click(clear_form, outputs=[date, f, t, reason, status]) login.click(admin_login, [admin_user, admin_pwd], [admin_box, msg]) refresh.click(get_all_data, outputs=table) month_btn.click(monthly_report, [month, year], month_table) dept_btn.click(dept_report, dept_name, dept_table) down.click(download_excel, outputs=file) reset.click(reset_data, outputs=reset_msg) app.launch()