visa25/Permission
0
1import gradio as gr2import pandas as pd3import os4from datetime import datetime, timedelta5 6 7# ---------------- CONFIG ---------------- #8 9STAFF_FILE = "staff_details.xlsx"10PERMISSION_FILE = "permissions.xlsx"11 12ADMIN_USER = "admin"13ADMIN_PASS = "admin123"14 15 16# ---------------- INIT ---------------- #17 18if not os.path.exists(PERMISSION_FILE):19 df = pd.DataFrame(columns=[20 "StaffID",21 "Name",22 "Department",23 "Date",24 "FromTime",25 "ToTime",26 "Reason",27 "SubmittedOn"28 ])29 df.to_excel(PERMISSION_FILE, index=False)30 31 32# ---------------- LOADERS ---------------- #33 34def load_staff():35 return pd.read_excel(STAFF_FILE)36 37 38def load_permissions():39 return pd.read_excel(PERMISSION_FILE)40 41 42# ---------------- VALIDATORS ---------------- #43 44# Date: Only Today / Tomorrow / Day after Tomorrow45def validate_date_range(date_str):46 47 try:48 d = datetime.strptime(date_str, "%d/%m/%Y").date()49 except:50 return False, "❌ Date format must be DD/MM/YYYY"51 52 today = datetime.today().date()53 max_day = today + timedelta(days=2)54 55 if d < today:56 return False, "❌ Past date not allowed"57 58 if d > max_day:59 return False, "❌ Apply only within 2 days"60 61 return True, ""62 63 64# Time: 08:45 - 17:20 and exactly 1 hour65def validate_time_range(f, t):66 67 try:68 f_time = datetime.strptime(f, "%H:%M")69 t_time = datetime.strptime(t, "%H:%M")70 except:71 return False, "❌ Time format must be HH:MM (24-hour)"72 73 min_time = datetime.strptime("08:45", "%H:%M")74 max_time = datetime.strptime("17:20", "%H:%M")75 76 # Check range77 if f_time < min_time or t_time > max_time:78 return False, "❌ Time allowed: 08:45 to 17:20 only"79 80 # Check 1 hour duration81 diff = (t_time - f_time).total_seconds() / 360082 83 if diff != 1:84 return False, "❌ Permission must be exactly 1 hour"85 86 return True, ""87 88 89# ---------------- STAFF FUNCTIONS ---------------- #90 91def fetch_staff(staff_id):92 93 df = load_staff()94 row = df[df["StaffID"] == staff_id]95 96 if row.empty:97 return "Not Found", "Not Found", "0"98 99 name = row.iloc[0]["Name"]100 dept = row.iloc[0]["Department"]101 102 perms = load_permissions()103 count = len(perms[perms["StaffID"] == staff_id])104 105 return name, dept, str(count)106 107 108def submit_permission(staff_id, date, f, t, reason):109 110 # Basic validation111 if staff_id.strip() == "":112 return "❌ Staff ID Required"113 114 if date.strip() == "":115 return "❌ Date Required"116 117 if f.strip() == "" or t.strip() == "":118 return "❌ Time Required"119 120 if reason.strip() == "":121 return "❌ Reason Required"122 123 124 # Date validation125 ok, msg = validate_date_range(date)126 if not ok:127 return msg128 129 130 # Time validation131 ok, msg = validate_time_range(f, t)132 if not ok:133 return msg134 135 136 # Staff validation137 staff = load_staff()138 row = staff[staff["StaffID"] == staff_id]139 140 if row.empty:141 return "❌ Invalid Staff ID"142 143 144 perms = load_permissions()145 146 147 # Same day check (max 2)148 same_day = perms[149 (perms["StaffID"] == staff_id) &150 (perms["Date"] == date)151 ]152 153 if len(same_day) == 1:154 return "⚠️ Second permission today → Apply Leave"155 156 if len(same_day) >= 2:157 return "❌ Daily limit reached"158 159 160 # Monthly limit (2 only)161 m = date.split("/")[1]162 y = date.split("/")[2]163 164 same_month = perms[165 (perms["StaffID"] == staff_id) &166 (perms["Date"].str.contains(f"/{m}/{y}", na=False))167 ]168 169 if len(same_month) >= 2:170 return "❌ Monthly limit reached (2 only)"171 172 173 # Save174 name = row.iloc[0]["Name"]175 dept = row.iloc[0]["Department"]176 177 now = datetime.now().strftime("%d/%m/%Y %H:%M")178 179 new_row = {180 "StaffID": staff_id,181 "Name": name,182 "Department": dept,183 "Date": date,184 "FromTime": f,185 "ToTime": t,186 "Reason": reason,187 "SubmittedOn": now188 }189 190 perms = pd.concat([perms, pd.DataFrame([new_row])], ignore_index=True)191 perms.to_excel(PERMISSION_FILE, index=False)192 193 return "✅ Permission Submitted Successfully"194 195 196def delete_permission(staff_id, date):197 198 perms = load_permissions()199 before = len(perms)200 201 perms = perms[202 ~((perms["StaffID"] == staff_id) &203 (perms["Date"] == date))204 ]205 206 perms.to_excel(PERMISSION_FILE, index=False)207 208 if len(perms) == before:209 return "❌ No Record Found"210 else:211 return "✅ Deleted"212 213 214def clear_form():215 return "", "", "", "", ""216 217 218# ---------------- ADMIN ---------------- #219 220def admin_login(user, pwd):221 222 if user == ADMIN_USER and pwd == ADMIN_PASS:223 return gr.update(visible=True), "✅ Login Successful"224 225 return gr.update(visible=False), "❌ Invalid Login"226 227 228def get_all_data():229 return load_permissions()230 231 232def download_excel():233 return PERMISSION_FILE234 235 236def monthly_report(month, year):237 238 perms = load_permissions()239 240 return perms[241 perms["Date"].str.contains(f"/{month}/{year}", na=False)242 ]243 244 245def dept_report(dept):246 247 perms = load_permissions()248 249 return perms[perms["Department"] == dept]250 251 252def reset_data():253 254 df = pd.DataFrame(columns=[255 "StaffID",256 "Name",257 "Department",258 "Date",259 "FromTime",260 "ToTime",261 "Reason",262 "SubmittedOn"263 ])264 265 df.to_excel(PERMISSION_FILE, index=False)266 267 return "✅ All Data Cleared"268 269 270# ================= UI ================= #271 272with gr.Blocks() as app:273 274 gr.HTML("""275 <center>276 <h2>SRC, SASTRA</h2>277 <h3>Staff Permission Management System</h3>278 <hr>279 </center>280 """)281 282 283 # ---------------- STAFF TAB ---------------- #284 285 with gr.Tab("Staff Panel"):286 287 with gr.Row():288 289 with gr.Column():290 291 staff_id = gr.Textbox(label="Staff ID")292 293 name = gr.Textbox(label="Name", interactive=False)294 dept = gr.Textbox(label="Department", interactive=False)295 count = gr.Textbox(label="Permission Count", interactive=False)296 297 fetch = gr.Button("Fetch Details")298 299 300 with gr.Column():301 302 date = gr.Textbox(label="Date (DD/MM/YYYY)")303 f = gr.Textbox(label="From (HH:MM 24-hr)")304 t = gr.Textbox(label="To (HH:MM 24-hr)")305 306 reason = gr.Textbox(label="Reason", lines=3)307 308 with gr.Row():309 submit = gr.Button("Submit", variant="primary")310 delete = gr.Button("Delete", variant="stop")311 clear = gr.Button("Clear")312 313 status = gr.Textbox(label="Status", interactive=False)314 315 316 # ---------------- ADMIN TAB ---------------- #317 318 with gr.Tab("Admin Panel"):319 320 admin_user = gr.Textbox(label="Username")321 admin_pwd = gr.Textbox(label="Password", type="password")322 323 login = gr.Button("Login")324 325 msg = gr.Textbox(interactive=False)326 327 admin_box = gr.Column(visible=False)328 329 with admin_box:330 331 gr.Markdown("### 📊 All Records")332 333 table = gr.Dataframe(interactive=False)334 335 refresh = gr.Button("Refresh")336 337 338 gr.Markdown("### 📅 Monthly Report")339 340 month = gr.Textbox(label="Month (MM)")341 year = gr.Textbox(label="Year (YYYY)")342 343 month_btn = gr.Button("Generate")344 345 month_table = gr.Dataframe()346 347 348 gr.Markdown("### 🏢 Department Report")349 350 dept_name = gr.Textbox(label="Department")351 352 dept_btn = gr.Button("Generate")353 354 dept_table = gr.Dataframe()355 356 357 gr.Markdown("### 📥 Download")358 359 down = gr.Button("Download Excel")360 361 file = gr.File()362 363 364 gr.Markdown("### ⚠️ Reset")365 366 reset = gr.Button("Reset All", variant="stop")367 368 reset_msg = gr.Textbox(interactive=False)369 370 371 # ---------------- EVENTS ---------------- #372 373 fetch.click(fetch_staff, staff_id, [name, dept, count])374 375 submit.click(376 submit_permission,377 [staff_id, date, f, t, reason],378 status379 )380 381 delete.click(delete_permission, [staff_id, date], status)382 383 clear.click(clear_form, outputs=[date, f, t, reason, status])384 385 386 login.click(admin_login, [admin_user, admin_pwd], [admin_box, msg])387 388 refresh.click(get_all_data, outputs=table)389 390 month_btn.click(monthly_report, [month, year], month_table)391 392 dept_btn.click(dept_report, dept_name, dept_table)393 394 down.click(download_excel, outputs=file)395 396 reset.click(reset_data, outputs=reset_msg)397 398 399app.launch()400 