Permission / app.py
SanthiSastra's picture
format
7424a92 verified
raw
history blame
8.22 kB
# app.py
# Staff Permission Management System (HF + Gradio Ready)
import gradio as gr
import pandas as pd
import os
from datetime import datetime
# ---------------- CONFIG ---------------- #
STAFF_FILE = "staff_details.xlsx"
PERMISSION_FILE = "permissions.xlsx"
LOGO_FILE = "logo.jpg"
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 ---------------- #
def validate_date(d):
try:
datetime.strptime(d, "%d/%m/%Y")
return True
except:
return False
def validate_time(t):
try:
datetime.strptime(t, "%H:%M")
return True
except:
return False
# ---------------- 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):
if staff_id.strip() == "":
return "❌ Staff ID Required"
if not validate_date(date):
return "❌ Date format: DD/MM/YYYY"
if not validate_time(f) or not validate_time(t):
return "❌ Time format: HH:MM"
if reason.strip() == "":
return "❌ Reason Required"
staff = load_staff()
row = staff[staff["StaffID"] == staff_id]
if row.empty:
return "❌ Invalid Staff ID"
perms = load_permissions()
# ---------- RULE 1: SAME DAY ---------- #
same_day = perms[
(perms["StaffID"] == staff_id) &
(perms["Date"] == date)
]
if len(same_day) == 1:
return "⚠️ Apply Leave (Second permission same day)"
if len(same_day) >= 2:
return "❌ Daily limit reached"
# ---------- RULE 2: MONTHLY LIMIT ---------- #
month = date.split("/")[1]
year = date.split("/")[2]
same_month = perms[
(perms["StaffID"] == staff_id) &
(perms["Date"].str.contains(f"/{month}/{year}", na=False))
]
if len(same_month) >= 2:
return "❌ Monthly limit (Only 2 allowed)"
# ---------- 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 Successfully"
def clear_form():
return "", "", "", "", ""
# ---------------- ADMIN ---------------- #
def admin_login(u, p):
if u == ADMIN_USER and p == ADMIN_PASS:
return gr.update(visible=True), "βœ… Login Success"
return gr.update(visible=False), "❌ Invalid Login"
def get_all_data():
return load_permissions()
def download_excel():
return PERMISSION_FILE
def monthly_report(m, y):
perms = load_permissions()
return perms[
perms["Date"].str.contains(f"/{m}/{y}", na=False)
]
def dept_report(d):
perms = load_permissions()
return perms[perms["Department"] == d]
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 Reset"
# ================= UI ================= #
with gr.Blocks() as app:
# ---------- CSS ---------- #
gr.HTML("""
<style>
.center-text {
text-align: center;
}
</style>
""")
# ---------- HEADER ---------- #
with gr.Column():
gr.Image(
LOGO_FILE,
show_label=False,
height=120,
container=True
)
gr.Markdown(
"## SRC, SASTRA\n"
"### Staff Permission Management System",
elem_classes=["center-text"]
)
gr.Markdown("---")
# ================= 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 Time (HH:MM)")
t = gr.Textbox(label="To Time (HH:MM)")
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 Table")
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 System")
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)
# ================= LAUNCH ================= #
if __name__ == "__main__":
app.launch()