162 lines
6.1 KiB
Python
162 lines
6.1 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@Module: hrbp.ehr.attendance
|
||
@FileName: attendance_stat_export.py
|
||
@Description: 考勤统计报表逐日出勤导出:
|
||
调用「考勤统计报表」接口分页抓取某月全集团数据(每人一行,含 v_1~v_最后一天),
|
||
导出 Excel,列为「工号/姓名/部门/岗位 + 1日~最后一日」(默认上月,可按参数指定月份)。
|
||
底层复用:hr_api.attendance_stat(报表抓取)、hr_session(会话管理)。
|
||
@Version: 1.0.0
|
||
|
||
使用说明:
|
||
1. 从项目根目录用模块方式运行(依赖打包为 app 包):
|
||
python -m app.service.hrbp.ehr.attendance.attendance_stat_export
|
||
2. 可选参数:<保存目录> <月份 YYYYMM>(默认上月)。
|
||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||
"""
|
||
|
||
import calendar
|
||
import os
|
||
import sys
|
||
from datetime import date, datetime, timedelta
|
||
from typing import Dict, List
|
||
|
||
from app.utils.logger import get_logger, setup_logging
|
||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import fetch_all_attendance_stat
|
||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError, refresh_hr_session
|
||
|
||
logger = get_logger(__name__)
|
||
|
||
# ===================== 配置区(自行修改) =====================
|
||
# 默认保存目录
|
||
SAVE_DIR = r"D:\资料\人资\考勤统计"
|
||
|
||
# 身份信息列(对应报文 datas 里的字段)
|
||
IDENTITY_COLS: List[Dict[str, str]] = [
|
||
{"key": "base_code", "title": "工号"},
|
||
{"key": "staff_name", "title": "姓名"},
|
||
{"key": "dept_org_name", "title": "部门"},
|
||
{"key": "post_name", "title": "岗位"},
|
||
]
|
||
|
||
|
||
def _clean(v) -> str:
|
||
"""转字符串并去掉常见杂质(None、浮点 .0 尾缀)。"""
|
||
if v is None:
|
||
return ""
|
||
s = str(v).strip()
|
||
if s.endswith(".0"):
|
||
s = s[:-2]
|
||
return s
|
||
|
||
|
||
def last_month_ym(today: date = None) -> str:
|
||
"""返回上月月份 "YYYYMM"。"""
|
||
today = today or date.today()
|
||
this_first = today.replace(day=1)
|
||
last_end = this_first - timedelta(days=1)
|
||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||
|
||
|
||
def _build_rows(records: List[Dict], days_in_month: int) -> List[Dict]:
|
||
"""把报表 datas 转成导出行:身份信息 + 1日~最终日(v_1~v_N),缺失留空。"""
|
||
rows: List[Dict] = []
|
||
for rec in records:
|
||
row = {item["title"]: _clean(rec.get(item["key"])) for item in IDENTITY_COLS}
|
||
for day in range(1, days_in_month + 1):
|
||
row[f"{day}日"] = _clean(rec.get(f"v_{day}"))
|
||
rows.append(row)
|
||
return rows
|
||
|
||
|
||
def export_month_attendance(save_dir: str = None, month: str = None) -> str:
|
||
"""导出某月考勤统计逐日出勤 Excel,返回文件路径。
|
||
|
||
Args:
|
||
save_dir: 保存目录,默认 SAVE_DIR
|
||
month: 查询月份 "YYYYMM"(默认上月)
|
||
|
||
Returns:
|
||
导出文件路径
|
||
"""
|
||
save_dir = save_dir or SAVE_DIR
|
||
os.makedirs(save_dir, exist_ok=True)
|
||
|
||
if not month:
|
||
month = last_month_ym()
|
||
year, mon = int(month[:4]), int(month[4:6])
|
||
days_in_month = calendar.monthrange(year, mon)[1]
|
||
logger.info("===== 考勤统计报表导出,月份:%s(%d 天) =====", month, days_in_month)
|
||
|
||
# 1. 会话校验 + 取当前用户 userId
|
||
session = build_hr_session()
|
||
try:
|
||
info = fetch_cur_user_info(session)
|
||
except HRSessionExpiredError:
|
||
logger.warning("cookies 已失效,正在重新登录")
|
||
session = refresh_hr_session()
|
||
info = fetch_cur_user_info(session)
|
||
user_id = info.get("userId", "")
|
||
if not user_id:
|
||
raise RuntimeError(f"getCurUserInfo 未返回 userId:{info}")
|
||
logger.info("cookies 校验通过,user_id=%s", user_id)
|
||
|
||
# 2. 分页抓取全集团考勤统计报表明细
|
||
records = fetch_all_attendance_stat(session, user_id, month)
|
||
logger.info("考勤统计报表共 %d 人", len(records))
|
||
if not records:
|
||
logger.error("考勤统计报表无数据,请检查月份或权限")
|
||
return ""
|
||
|
||
# 3. 组装导出行并输出 Excel
|
||
columns = [item["title"] for item in IDENTITY_COLS] + [f"{d}日" for d in range(1, days_in_month + 1)]
|
||
rows = _build_rows(records, days_in_month)
|
||
|
||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤统计报表_{month}_{ts}.xlsx"))
|
||
try:
|
||
import pandas as pd
|
||
except ImportError:
|
||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||
|
||
df = pd.DataFrame(rows, columns=columns)
|
||
try:
|
||
df.to_excel(save_path, index=False)
|
||
except PermissionError:
|
||
raise RuntimeError(
|
||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||
)
|
||
|
||
logger.info("导出明细:%d 人 × %d 列", len(rows), len(columns))
|
||
logger.info("文件已保存:%s", save_path)
|
||
logger.info("=" * 60)
|
||
logger.info("【考勤统计报表汇总】")
|
||
logger.info(" 月份:%s", month)
|
||
logger.info(" 人数:%d 人", len(rows))
|
||
logger.info(" 导出文件:%s", save_path)
|
||
logger.info("=" * 60)
|
||
return save_path
|
||
|
||
|
||
def main() -> None:
|
||
setup_logging()
|
||
# 参数:<保存目录> <月份 YYYYMM>
|
||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||
try:
|
||
out = export_month_attendance(save_dir, month)
|
||
if out:
|
||
logger.info("===== 考勤统计报表导出完成 =====")
|
||
except Exception as e: # noqa: BLE001
|
||
if "正被占用" in str(e):
|
||
logger.error("=========== 提醒 ===========")
|
||
logger.error(str(e))
|
||
logger.error("请关闭该 Excel 文件后重新运行即可。")
|
||
return
|
||
logger.error("考勤统计报表导出失败:%s", e)
|
||
raise
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |