# -*- coding: utf-8 -*- """XQ0011 考勤月报封存检查 插件 - 汇总执行与单工作簿输出(由影刀版移植)。 依次运行检查1~检查6,将各异常名单合并写入一个 Excel 工作簿(每个检查一个 sheet), 并生成「汇总」sheet 概览各检查异常人数。各检查模块不再单独落盘(单工作簿统一输出)。 插件化改造点: 1. save_dir / roster_path / transfer_path 由 run() 解析注入; 2. 各检查 run_fn 统一签名 (month=..., save_dir=..., **kwargs); 3. 某检查失败不阻断其余检查(记 rows=[]),汇总仍输出。 """ import os from datetime import date, datetime from typing import Callable, Dict, List, Tuple import pandas as pd from ..config import logger, DEFAULT_SAVE_DIR from ..logic.working_days_shift_check import ( run_working_days_shift_check, OUTPUT_COLUMNS as COL_CHECK1, ) from ..logic.attendance_rest_check import ( run_attendance_rest_check, OUTPUT_COLUMNS as COL_CHECK2, ) from ..logic.latest_seal_check import ( run_latest_seal_check, OUTPUT_COLUMNS as COL_CHECK3, ) from ..logic.full_attendance_check import ( run_full_attendance_check, OUTPUT_COLUMNS as COL_CHECK4, ) from ..logic.unsealed_check import ( run_unsealed_check, OUTPUT_COLUMNS as COL_CHECK5, ) from ..logic.overtime_compensation_check import ( run_overtime_compensation_check, OUTPUT_COLUMNS as COL_CHECK6, ) # 检查元信息:(编号, sheet 名, 异常类型标签, run 函数, 输出列, run 额外 kwargs) CHECK_META: List[Tuple[str, str, str, Callable, List[str], Dict]] = [ ("检查1", "检查1-在职天数排班异常", "在职天数 ≠ 应勤工作日 + 休息天", run_working_days_shift_check, COL_CHECK1, {}), ("检查2", "检查2-出勤及排休天数异常", "出勤/正休天数与应勤天标准不符", run_attendance_rest_check, COL_CHECK2, {}), ("检查3", "检查3-封存非最新值", "考勤封存非最新值,请重新封存", run_latest_seal_check, COL_CHECK3, {}), ("检查4", "检查4-全勤验证异常", "晋升当月要求全勤 / 迟到早退", run_full_attendance_check, COL_CHECK4, {}), ("检查5", "检查5-未封存名单", "考勤月报未封存,请处理", run_unsealed_check, COL_CHECK5, {}), ("检查6", "检查6-延时加班异常", "经营系管理岗不应享受延时加班,请核对", run_overtime_compensation_check, COL_CHECK6, {}), ] # ==================== 通用工具 ==================== def _prev_month(year: int, month: int) -> Tuple[int, int]: if month == 1: return year - 1, 12 return year, month - 1 def _normalize_month(month) -> str: """月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。""" if not month: py, pm = _prev_month(date.today().year, date.today().month) return f"{py:04d}-{pm:02d}" s = str(month).strip() if len(s) == 6 and s.isdigit(): return f"{s[:4]}-{s[4:]}" return s # ==================== 主流程 ==================== def run_all_checks(month: str = None, save_dir: str = None, roster_path: str = None, transfer_path: str = None, checks: List[str] = None) -> Dict[str, object]: """依次运行检查1~6,返回各检查异常名单行列表(每项含编号/sheet/类型/列/行列表)。 checks:需要执行的检查编号列表(如 ["检查1", "检查3"]);为空/None = 全部执行。 """ ym = _normalize_month(month) save_dir = save_dir or DEFAULT_SAVE_DIR metas = CHECK_META if checks: want = {str(c).strip() for c in checks} metas = [m for m in CHECK_META if m[0] in want] if not metas: raise RuntimeError(f"未选择任何有效检查项:{checks}") logger.info("===== 考勤月报封存检查(汇总)月份:%s,检查项:%s =====", ym, "、".join(m[0] for m in metas)) results: List[dict] = [] total = 0 notes: List[str] = [] for no, sheet_name, label, run_fn, cols, kwargs in metas: kw = dict(kwargs) if no == "检查1": kw["roster_path"] = roster_path if no == "检查4": kw["transfer_path"] = transfer_path if no in ("检查5", "检查6"): kw["roster_path"] = roster_path try: rows = run_fn(month=ym, save_dir=save_dir, **kw) except Exception as e: logger.error("%s 执行失败:%s", no, e) notes.append(f"{no} 执行失败:{e}") rows = [] results.append({ "no": no, "sheet_name": sheet_name, "label": label, "cols": cols, "rows": rows, }) total += len(rows) logger.info("%s 完成:异常 %d 人", no, len(rows)) return {"ym": ym, "results": results, "total": total, "notes": notes} def write_workbook(result: Dict[str, object], save_dir: str = None) -> str: """将各检查异常名单写入单工作簿(汇总 + 每检查一个 sheet),返回文件路径。""" ym = result["ym"] save_dir = save_dir or DEFAULT_SAVE_DIR 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") # 汇总 sheet 行 summary_rows = [{ "序号": i + 1, "检查编号": it["no"], "异常类型": it["label"], "异常人数": len(it["rows"]), } for i, it in enumerate(result["results"])] summary_rows.append({ "序号": len(summary_rows) + 1, "检查编号": "合计", "异常类型": "", "异常人数": result["total"], }) try: with pd.ExcelWriter(save_path, engine="openpyxl") as writer: pd.DataFrame(summary_rows).to_excel( writer, sheet_name="汇总", index=False) for it in result["results"]: rows = it["rows"] cols = it["cols"] sheet_name = it["sheet_name"] if not rows: # 空结果也保留 sheet,便于人工核对 pd.DataFrame(columns=cols).to_excel( writer, sheet_name=sheet_name, index=False) continue pd.DataFrame(rows, columns=cols).to_excel( writer, sheet_name=sheet_name, index=False) except PermissionError: raise RuntimeError( f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试") logger.info("汇总工作簿已保存:%s(共 %d 人异常)", save_path, result["total"]) return save_path