# -*- coding: utf-8 -*- """ @FileName: unsealed_check.py @Author: 小布丁 @CreateTime: 2026-08-31 @UpdateTime: 2026-09-07 @Description: 考勤月报封存检查 - 检查5「未封存名单」(影刀单文件,自包含)。 当月考勤封存完毕后执行,检查范围为「上月完整月份」。识别当月有在职记录的员工是否都有 考勤月报封存记录;有在职记录但无封存记录者输出异常名单,异常类型 = 「考勤月报未封存,请处理」。 数据来源: 1) 在职记录(花名册):由「37du花名册导出」共享指令导出到固定路径,本脚本只读取。 导出参数:在职状态 = 在职 + 离职(离职需设置离职时间范围 = 检查月月初 至今天), 模板 = 员工基础信息。这样才能把「检查月内仍在职 / 检查月内离职」的人全部覆盖到。 口径与封存表保持一致:仅检查所属单位白名单单位员工 (财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部)。 2) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选), 保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。 判定口径(对应需求文档 XQ0011 检查5): - 花名册逐人取 入职时间 / 离职时间,判定其「在检查月是否在职」: 在职 =(入职时间 ≤ 月末)且(无离职时间 或 离职时间 ≥ 月初)。 - 仅统计所属单位在白名单内的员工; - 有在职记录但工号不在当月封存记录集合里 → 异常。 输出: 未封存名单_{月份}_{时间戳}.xlsx 异常名单(含 37工号/姓名/月报检查月份/异常类型/所属单位/一~五级部门)。 依赖安装(启动校验:必须预先装齐): pip install requests pandas openpyxl python-dotenv 运行前置: 1. 需先运行「seal_data_export.py」导出并预处理当月封存数据; 2. 需先运行「37du花名册导出」指令导出花名册到固定路径。 环境变量(可选): monthly_unsealed_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常) monthly_unsealed_roster_path 花名册文件路径(默认 D:\\资料\\人资\\考勤异常\\员工花名册.xlsx) @Version: 1.1.0 """ # ==================== 标准库导入 ==================== import os import sys import traceback from datetime import date, datetime from typing import List, Optional, Set, Tuple # 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from seal_data_export import SEAL_UNIT_WHITELIST, load_seal_rows # noqa: E402 # ==================== 第三方库(启动校验:全部装齐,不懒加载) ==================== try: from dotenv import load_dotenv import pandas as pd except ImportError as _import_err: raise RuntimeError( "缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n" "请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n" f"缺失依赖详情: {_import_err}" ) load_dotenv() # ==================== 日志(print 替代 logging,保持单文件无外部依赖) ==================== class _PrintLogger: @staticmethod def debug(msg, *args): if args: msg = msg % args print(f"[DEBUG] {msg}") @staticmethod def info(msg, *args): if args: msg = msg % args print(f"[INFO] {msg}") @staticmethod def warning(msg, *args): if args: msg = msg % args print(f"[WARN] {msg}") @staticmethod def error(msg, *args): if args: msg = msg % args print(f"[ERROR] {msg}") logger = _PrintLogger() # ==================== 共享路径 & 常量配置 ==================== SAVE_DIR = os.getenv("monthly_unsealed_save_dir") or r"D:\资料\人资\考勤异常" # 花名册固定路径:由「37du花名册导出」共享指令导出(在职 + 离职,离职时间范围 = 检查月月初至今) DEFAULT_ROSTER_PATH = os.getenv("monthly_unsealed_roster_path") or r"D:\资料\人资\考勤异常\员工花名册.xlsx" # 异常类型(对应需求文档检查5) ABNORMAL_TYPE = "考勤月报未封存,请处理" # 封存记录工号字段 SEAL_CODE_FIELDS = ("base_code", "seal_base_code") # 花名册字段(与「37du花名册导出」指令导出的列名一致) ROSTER_CODE_COL = "工号" ROSTER_NAME_COL = "姓名" ROSTER_UNIT_COL = "所属单位" ROSTER_DEPT_COLS = ["一级部门", "二级部门", "三级部门", "四级部门", "五级部门"] ROSTER_JOIN_COL = "入职时间" ROSTER_LEAVE_COL = "离职时间" # 输出列(对应需求文档检查5输出字段) OUTPUT_COLUMNS = [ "37工号", "姓名", "月报检查月份", "异常类型", "所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门", ] # ==================== 通用工具 ==================== def _clean(v) -> str: if v is None: return "" try: if pd.isna(v): return "" except (TypeError, ValueError): pass s = str(v).strip() if s.lower() in ("nan", "none", "nat"): return "" if s.endswith(".0"): s = s[:-2] return s def _parse_date(v) -> Optional[date]: s = _clean(v)[:10] if not s: return None try: return datetime.strptime(s, "%Y-%m-%d").date() except (TypeError, ValueError): return None def _prev_month(year: int, month: int) -> Tuple[int, int]: if month == 1: return year - 1, 12 return year, month - 1 def _month_range(ym: str) -> Tuple[date, date]: y, m = int(ym[:4]), int(ym[5:7]) total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth return date(y, m, 1), date(y, m, total_days) def _seal_code_set(rows: List[dict]) -> Set[str]: """取当月封存记录的全部工号集合。""" codes: Set[str] = set() for rec in rows: for f in SEAL_CODE_FIELDS: code = _clean(rec.get(f)) if code: codes.add(code) break return codes # ==================== 花名册在职判定 ==================== def _load_roster(roster_path: str) -> "pd.DataFrame": """读取花名册(由「37du花名册导出」指令导出,表头在第 1 行)。""" roster_path = roster_path or DEFAULT_ROSTER_PATH if not os.path.exists(roster_path): raise RuntimeError( f"未找到花名册文件:{roster_path}\n" "请先在影刀流程中拖入「37du花名册导出」指令导出花名册" f"(在职状态=在职+离职,离职时间范围=检查月月初至今,模板=员工基础信息),再运行本流程;" "或通过 roster_path 参数指定已有花名册文件。") df = pd.read_excel(roster_path, dtype=str) df.columns = [str(c).strip() for c in df.columns] logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df)) return df def _in_month(join: Optional[date], leave: Optional[date], first: date, last: date) -> bool: """判断员工检查月是否在职:入职 ≤ 月末 且(未离职 或 离职 ≥ 月初)。""" if join is None or join > last: return False if leave is None or leave >= first: return True return False # ==================== 主流程 ==================== def _build_unsealed_rows(df, seal_codes: Set[str], ym: str, first: date, last: date) -> List[dict]: """遍历花名册,找出检查月在职、所属单位在白名单内但无封存记录的员工,返回名单行列表。""" abnormal: List[dict] = [] seen: Set[str] = set() for _, row in df.iterrows(): code = _clean(row.get(ROSTER_CODE_COL)) if not code or code in seen: continue # 花名册在职/离职同一工号可能多行,取一行即可 seen.add(code) unit = _clean(row.get(ROSTER_UNIT_COL)) if unit not in SEAL_UNIT_WHITELIST: continue # 与封存表预处理口径一致:仅检查白名单单位员工 join = _parse_date(row.get(ROSTER_JOIN_COL)) leave = _parse_date(row.get(ROSTER_LEAVE_COL)) if not _in_month(join, leave, first, last): continue # 检查月不在职(尚未入职或已离职早于月初) if code in seal_codes: continue # 已有封存记录,正常 abnormal.append({ "37工号": code, "姓名": _clean(row.get(ROSTER_NAME_COL)), "月报检查月份": ym, "异常类型": ABNORMAL_TYPE, "所属单位": unit, **{f"第{chn}级部门": _clean(row.get(c)) for chn, c in zip( ["一", "二", "三", "四", "五"], ROSTER_DEPT_COLS)}, }) return abnormal def run_unsealed_check(roster_path: str = None, month: str = None) -> List[dict]: """执行检查5「未封存名单」,返回异常名单行列表(并写 Excel 留档)。 Args: roster_path: 花名册文件路径,默认 DEFAULT_ROSTER_PATH。 month: 检查月份 "YYYY-MM",默认上月。 Returns: 异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。 """ today = date.today() if month: try: first, last = _month_range(month) except (ValueError, IndexError, TypeError): raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}") ym = month else: py, pm = _prev_month(today.year, today.month) first, last = _month_range(f"{py:04d}-{pm:02d}") ym = f"{py:04d}-{pm:02d}" logger.info("===== 检查5「未封存名单」月份:%s(%s ~ %s) =====", ym, first, last) # 1. 读花名册(在职记录) df = _load_roster(roster_path) # 2. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存) seal_rows = load_seal_rows(ym) seal_codes = _seal_code_set(seal_rows) logger.info("考勤封存记录共 %d 人:%s", len(seal_codes), ym) # 3. 找出在册未封存 abnormal = _build_unsealed_rows(df, seal_codes, ym, first, last) logger.info("检查5命中异常 %d 人(在册未封存)", len(abnormal)) # 4. 导出异常名单 os.makedirs(SAVE_DIR, exist_ok=True) ts = datetime.now().strftime("%Y%m%d_%H%M%S") save_path = os.path.join(SAVE_DIR, f"未封存名单_{ym}_{ts}.xlsx") try: pd.DataFrame(abnormal if abnormal else [], columns=OUTPUT_COLUMNS).to_excel(save_path, index=False) except PermissionError: raise RuntimeError( f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试") logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal)) return abnormal def main(args=None) -> dict: """影刀「调用模块」入口;也可作为脚本直接运行。 args: dict,可选字段: roster_path(花名册文件路径)、month("YYYY-MM",默认上月)。 """ if args is None: args = {} roster_path = args.get("roster_path") or ( os.getenv("monthly_unsealed_roster_path") or (sys_argv_if(2))) month = args.get("month") or os.getenv("monthly_unsealed_month") or (sys_argv_if(3)) try: rows = run_unsealed_check(roster_path, month) logger.info("=" * 60) logger.info("【检查5 考勤月报未封存名单完成】") logger.info(" 检查月份:%s | 未封存人数:%d", month or "默认上月", len(rows)) logger.info(" 输出目录:%s", SAVE_DIR) logger.info("=" * 60) return {"success": True, "count": len(rows)} except Exception as e: if "正被占用" in str(e): logger.error("=========== 提醒 ===========") logger.error(str(e)) return {"success": False, "message": str(e)} logger.error("检查5执行失败:%s\n%s", e, traceback.format_exc()) return {"success": False, "message": str(e)} def sys_argv_if(idx): """读取命令行第 idx 个参数(index from 1);不存在返回 None。""" import sys return sys.argv[idx] if len(sys.argv) > idx else None if __name__ == "__main__": main()