VsinghiAssociates's picture
Update app.py
4f9365e verified
Raw History Blame Contribute Delete
10.6 kB
import io
from datetime import datetime
import pandas as pd
import streamlit as st
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
def clean(x: object) -> str:
return (
str(x)
.strip()
.lower()
.replace("\xa0", "")
.replace(" ", " ")
)
def build_report(
reg_file: io.BytesIO,
leave_file: io.BytesIO,
holidays_ddmm: list[str],
) -> bytes:
# ===== LOAD REGULAR SHEET =====
raw = pd.read_excel(reg_file, header=None)
reg_df = raw.copy()
reg_df.columns = reg_df.iloc[0]
reg_df = reg_df[1:]
reg_df.reset_index(drop=True, inplace=True)
# ===== REMOVE UNNAMED COLUMNS =====
reg_df = reg_df.loc[:, ~reg_df.columns.astype(str).str.contains("Unnamed")]
# ===== LOAD LEAVE SHEET =====
leave_df = pd.read_excel(leave_file)
leave_df.columns = leave_df.columns.str.strip().str.lower()
# ===== NAME COLUMN =====
name_col = "Name"
leave_name_col = [col for col in leave_df.columns if "name" in col][0]
reg_df[name_col] = reg_df[name_col].apply(clean)
leave_df[leave_name_col] = leave_df[leave_name_col].apply(clean)
# ===== FIX LEAVE DATES =====
if "start date" not in leave_df.columns or "till date" not in leave_df.columns:
raise ValueError("Leave file must have 'Start Date' and 'Till Date' columns.")
leave_df["start date"] = pd.to_datetime(leave_df["start date"], errors="coerce")
leave_df["till date"] = pd.to_datetime(leave_df["till date"], errors="coerce")
# ===== DATE COLUMNS =====
date_cols = [c for c in reg_df.columns if isinstance(c, (datetime, pd.Timestamp))]
if not date_cols:
raise ValueError("No date columns found in regular sheet header row.")
# ===== LEAVE FUNCTION =====
def get_leave(name: str, current_date: datetime) -> str | None:
emp = leave_df[leave_df[leave_name_col] == name]
for _, r in emp.iterrows():
if pd.isna(r["start date"]) or pd.isna(r["till date"]):
continue
if r["start date"].date() <= current_date.date() <= r["till date"].date():
t = str(r.get("type", "")).lower()
if "work from home - 100" in t:
return "W100"
if "work from home - 50" in t:
return "W50"
if "work from home" in t:
return "W"
return "A"
return None
# ===== APPLY LOGIC =====
final_df = reg_df.copy()
extra_rows: list[list[object]] = []
valid_codes = ["P", "A", "L", "W", "W100", "W50", ""]
for i, row in final_df.iterrows():
name = row[name_col]
for col in date_cols:
val = str(row[col]).strip()
if val.lower() in ["nan", "nat", "none"]:
val = ""
val_upper = val.upper()
leave_val = get_leave(name, col)
if leave_val:
final_df.at[i, col] = leave_val
else:
final_df.at[i, col] = val_upper
if val_upper not in valid_codes and val_upper != "":
extra_rows.append([name, col.strftime("%d-%m-%Y"), val])
# ===== HOLIDAY PARSE =====
year = date_cols[0].year
holidays: list[datetime] = []
for d in holidays_ddmm:
d = d.strip()
if not d:
continue
try:
holidays.append(datetime.strptime(f"{d}-{year}", "%d-%m-%Y"))
except ValueError:
raise ValueError(f"Invalid holiday format: '{d}'. Use dd-mm (e.g. 26-01).")
# ===== SHEET 3 (SUMMARY) =====
summary_data: list[list[object]] = []
for _, row in final_df.iterrows():
name = row[name_col]
values = [str(row[col]).upper() for col in date_cols]
summary_data.append(
[
name,
values.count("P"),
values.count("A"),
values.count("W100"),
values.count("W50"),
values.count("L"),
len([v for v in values if v not in valid_codes and v != ""]),
]
)
summary_df = pd.DataFrame(
summary_data,
columns=["Name", "Present", "Absent", "W100", "W50", "Late", "Other Reason"],
)
# ===== SHEET 4 (LEAVE LEDGER) =====
designation_map = {
"naveen kankaria": "Partner",
"shyam sundar khuntia": "Partner",
"himanshu agarwal": "CA",
"alankriti nigam": "CA",
"arun kumar kesharwani": "CA",
"supriya kumari": "CA",
"kirti bokaria": "CA",
"piyush kumar": "Employee",
"poonam bhandari": "Employee",
"savita gupta": "Employee",
"rounak verma": "Employee",
"monica rawat": "Employee",
"poonam umesh chauhan": "CA Article",
"wilson kumar": "Employee",
"sambhav jain": "CA",
"khushi": "CA Article",
"piyush saini": "CA Article",
"gurjaap kaur": "CA Article",
"ekta": "CA Article",
"aryan raj": "CA Article",
"anirudh soni": "CMA",
"ritik kumar": "CMA Article",
"rahul sharma": "CA Article",
"mansha kuamri": "CA Article",
"shubh jyoti kumar": "CA Article",
"anjali bansal": "CA Article",
"kuldeep gupta": "CA Article",
"ujjwal singhi": "Employee",
"rachna gupta": "CA Article",
"aryan baranwal": "CA Article",
"larsh gola": "CA Article",
"mrinal vatsa": "CA Article",
"ankit gupta": "CA Article",
"anuradha aggarwal": "CA Article",
}
ledger_rows: list[list[object]] = []
total_days = len(date_cols)
for _, row in final_df.iterrows():
name = row[name_col]
desig = designation_map.get(name, "Employee")
values = [str(row[col]).upper() for col in date_cols]
leave_taken = values.count("A")
late_days = values.count("L")
late_deduct = late_days // 3
w50_deduct = values.count("W50") // 2
sandwich = 0
for j in range(1, len(values) - 1):
if values[j - 1] == "A" and values[j + 1] == "A":
if date_cols[j].weekday() == 6 or any(
date_cols[j].date() == h.date() for h in holidays
):
sandwich += 1
leave_accrued = 0 if "article" in desig.lower() else 2
net_leave = max(0, leave_taken - leave_accrued)
paid_days = total_days - (net_leave + late_deduct + w50_deduct + sandwich)
carried_forward = max(0, leave_accrued - leave_taken)
ledger_rows.append(
[
name,
0,
leave_accrued,
0,
leave_taken,
late_days,
late_deduct,
w50_deduct,
sandwich,
paid_days,
carried_forward,
]
)
ledger_df = pd.DataFrame(
ledger_rows,
columns=[
"Name",
"Opening Balance",
"Leave Accrued",
"Comp Off",
"Leave Taken",
"Late Days",
"Late Deduct",
"W50 Deduct",
"Sandwich Deduct",
"Paid Days",
"Carried Forward",
],
)
# ===== WRITE EXCEL (ALL SHEETS) =====
output = io.BytesIO()
with pd.ExcelWriter(output, engine="openpyxl") as writer:
final_df.to_excel(writer, index=False, sheet_name="Final")
if extra_rows:
extra_df = pd.DataFrame(extra_rows, columns=["Name", "Date", "Remark"])
extra_df = extra_df.sort_values(by=["Name", "Date"])
extra_df.to_excel(writer, sheet_name="Remarks", index=False)
summary_df.to_excel(writer, sheet_name="Summary", index=False)
ledger_df.to_excel(writer, sheet_name="Leave Ledger", index=False)
# ===== FORMATTING =====
output.seek(0)
wb = load_workbook(output)
ws = wb["Final"]
red = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
green = PatternFill(start_color="C6EFCE", end_color="C6EFCE", fill_type="solid")
# Find first date col index in Final sheet.
# Excel columns are 1-based. final_df columns start at col=1 in sheet.
date_col_start_excel = (
final_df.columns.get_loc(date_cols[0]) + 1
)
date_col_count = len(date_cols)
for offset in range(date_col_count):
current_date = date_cols[offset]
col_idx = date_col_start_excel + offset
for row_idx in range(2, len(final_df) + 2):
cell = ws.cell(row=row_idx, column=col_idx)
if current_date.weekday() == 6:
cell.fill = red
if any(current_date.date() == h.date() for h in holidays):
cell.fill = green
out2 = io.BytesIO()
wb.save(out2)
return out2.getvalue()
st.set_page_config(page_title="Attendance + Leave Report", layout="wide")
st.title("Attendance + Leave Report Generator")
st.markdown(
"Upload the **Regular ** Excel and **Leave form response** Excel, then download the final report."
)
col1, col2 = st.columns(2)
with col1:
reg_upload = st.file_uploader(
"Upload Regular Sheet ",
type=["xlsx", "xls"],
accept_multiple_files=False,
)
with col2:
leave_upload = st.file_uploader(
"Upload Leave Form Response (leave form response.xlsx)",
type=["xlsx", "xls"],
accept_multiple_files=False,
)
holidays_text = st.text_input(
"Holiday dates (optional, dd-mm). Example: 26-01, 29-03",
value="",
)
holidays_ddmm = [x.strip() for x in holidays_text.split(",")] if holidays_text else []
process = st.button("Process & Generate Report", type="primary", use_container_width=True)
if process:
if not reg_upload or not leave_upload:
st.error("Please upload both files.")
else:
try:
report_bytes = build_report(
io.BytesIO(reg_upload.getvalue()),
io.BytesIO(leave_upload.getvalue()),
holidays_ddmm,
)
except Exception as e:
st.exception(e)
else:
st.success("Report generated.")
st.download_button(
"Download final report (.xlsx)",
data=report_bytes,
file_name="final_output.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
use_container_width=True,
)